Compare commits
259 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 3b8dd87c4b | |||
| fe346c9036 | |||
| 697cd27cde | |||
| d733298bd9 | |||
| 4b515404a8 | |||
| 3f7dd4b2e5 | |||
| c930788bf8 | |||
| 6c94b1fb85 | |||
| d5154cf59d | |||
| 0205f32f28 | |||
| 76252cb5d0 | |||
| 67a560e3fd | |||
| b4f984fd5b | |||
| b74c054c02 | |||
| 2b5032d8c9 | |||
| 75823d6c82 | |||
| 0906cf7094 | |||
| 4088923a45 | |||
| c626ee4e27 | |||
| 633df7a02b | |||
| fad1567e54 | |||
| 67c836388b | |||
| dd9e177420 | |||
| 3524d8bbb6 | |||
| 8caeeb3d78 | |||
| a348da32da | |||
| 5ddb7453ec | |||
| 4210552cb8 | |||
| 181e5a030c | |||
| 6f01e9ef0a | |||
| d185df5fd1 | |||
| 000e9ef9b9 | |||
| 92b820b234 | |||
| 697ab32715 | |||
| bbee996f84 | |||
| 3b925231d5 | |||
| 0f9923d230 | |||
| b0fce88a51 | |||
| 8f3b59b5f2 | |||
| 652dcfc7b1 | |||
| 87e4305889 | |||
| 751ce6d54a | |||
| f4a0064342 | |||
| bde8a830df | |||
| ba73721d51 | |||
| eed068bd22 | |||
| 7def1fd840 | |||
| 86723750d3 | |||
| 82bac1a3ab | |||
| 0f0bace29e | |||
| 2180aa868e | |||
| bf4e2329ec | |||
| bd1c714935 | |||
| f625674a68 | |||
| 9797f43dc4 | |||
| b5c6638538 | |||
| ec67496569 | |||
| d99fac23e9 | |||
| a3c74188be | |||
| 7dcc9a37c7 | |||
| 68ce3e5a3b | |||
| b00bc41b65 | |||
| fcec6357ff | |||
| 13e1c21386 | |||
| 80a610a5c2 | |||
| d02b9ffeb8 | |||
| 0269648429 | |||
| bd693ca31b | |||
| d8ec9389e0 | |||
| 10028c4abb | |||
| 8e897d7b3e | |||
| a8ffa89011 | |||
| bf07bed2ae | |||
| 373f7a69cd | |||
| b1ce5bf976 | |||
| 23203f235c | |||
| 37d6209aec | |||
| ee72566263 | |||
| e0019abe31 | |||
| 2a7bed87db | |||
| dfaa652098 | |||
| cd08a2892a | |||
| 16d1c072e3 | |||
| 363f7cd513 | |||
| cd274512e7 | |||
| 3b8bacf114 | |||
| 781341a0ba | |||
| 109596bc3b | |||
| 6fc140d8dc | |||
| 993866c1d7 | |||
| 19a14bfeb6 | |||
| 648c87bb8a | |||
| 04db23705a | |||
| 9a7b9b9301 | |||
| d2b1329095 | |||
| 0d19a5546f | |||
| da1839c6d2 | |||
| 957e75524c | |||
| 0ef135bfda | |||
| 3280f734ef | |||
| 599ad81bec | |||
| 6915a86132 | |||
| 4afdd9b826 | |||
| fb5947ea3a | |||
| 2a04938a96 | |||
| b11c6d1788 | |||
| 1ddeb2c6dc | |||
| 4dff8086ab | |||
| 447b42a1cd | |||
| 58656dea45 | |||
| 58c20fa863 | |||
| f73f0c1b6a | |||
| bff4ed8a8b | |||
| e0bf5ca57a | |||
| 691926d839 | |||
| 6fab30337a | |||
| e736166a39 | |||
| a2d75c462c | |||
| 31f9e48219 | |||
| 473670185c | |||
| c8fa165dc9 | |||
| 2f95753d9c | |||
| 9dc87ae996 | |||
| d9c97fd915 | |||
| 1d40fb7ac0 | |||
| 03ee83e8a5 | |||
| 9cb48a70b7 | |||
| 2b23574ece | |||
| 76676ee5a6 | |||
| 23b3a3d340 | |||
| ef47356541 | |||
| 0666b68ff6 | |||
| 6f2e62bea3 | |||
| aa57fee4de | |||
| 92c95ef031 | |||
| 595745c7b1 | |||
| 9c02ed769b | |||
| 94aedacf05 | |||
| 7e6e0cc7d1 | |||
| aecab00ff6 | |||
| a1dc705be7 | |||
| b5b3f09599 | |||
| 6f7e43b097 | |||
| 91f25c452c | |||
| 083bc83331 | |||
| 5e6db4de76 | |||
| b345bc0ec4 | |||
| 3d7a691338 | |||
| 3754242969 | |||
| 9545bb0bfc | |||
| 620c832477 | |||
| 812c24de9e | |||
| 1b39e71e81 | |||
| d884ad731d | |||
| dd0a557ad3 | |||
| b633ee8b4c | |||
| fcd2e57887 | |||
| 66f5884ab4 | |||
| 5d5653bfc3 | |||
| 1ad6ddc198 | |||
| 67963102d9 | |||
| d368bb32f9 | |||
| 9fa440726e | |||
| 28a4144b49 | |||
| b91a0d1914 | |||
| abbab3c8ce | |||
| 05f1b472fc | |||
| 5aba4c6c87 | |||
| b47202a2e9 | |||
| 0632aa5901 | |||
| 730e6380c8 | |||
| 59bb0745e7 | |||
| 303385a5ee | |||
| 899e7f1bfc | |||
| 31f5327255 | |||
| 3f00ad2754 | |||
| e42cad7b1a | |||
| eb61b40f08 | |||
| b72af69baf | |||
| 078db6cbcb | |||
| 9376bafaa2 | |||
| 6bed1cd691 | |||
| 7b5c1285a2 | |||
| e5512d50b0 | |||
| 627d524aa2 | |||
| 370fe3a9f5 | |||
| 72de18744b | |||
| cbdba90014 | |||
| c3f6eeb6df | |||
| 2e617db23c | |||
| b350c71246 | |||
| 88a79c3561 | |||
| ddac9e3c73 | |||
| 02bd120aed | |||
| 201af83d95 | |||
| 61a07bc950 | |||
| aa03a78476 | |||
| 9d6952a772 | |||
| 44823ce323 | |||
| 71746f437e | |||
| 2700bd18cb | |||
| ac78e7db73 | |||
| 792bfc4eca | |||
| 6650b639e1 | |||
| a1cac0898e | |||
| 3b803d558b | |||
| 56a86d6d49 | |||
| f97edeb830 | |||
| 7d033c5ca1 | |||
| f076da99b6 | |||
| 3f2a1a1052 | |||
| 2d5a8110c6 | |||
| d42727b038 | |||
| 059a79525a | |||
| 6176971307 | |||
| 8f6e72b0b8 | |||
| b96262eb0c | |||
| 5a0bc6f78b | |||
| f27abcb53e | |||
| 6c7b77970b | |||
| 80d88a0352 | |||
| c0a3f55f12 | |||
| 7216fb5f98 | |||
| 6b0b8ce6de | |||
| 8112a001d2 | |||
| 8552f92ddb | |||
| c09c7a2ac7 | |||
| 54cc6baf95 | |||
| 7eebbbbfc3 | |||
| c8eb64adec | |||
| 9333573cd8 | |||
| d44ff1260d | |||
| f059fef320 | |||
| 7555d3e6c9 | |||
| 750632f80e | |||
| 90559fe01b | |||
| b49c1f379e | |||
| cd828dc06d | |||
| c9879cffa2 | |||
| c0cc50b127 | |||
| f837871b77 | |||
| d06b62efe2 | |||
| 926b74bc0b | |||
| fdce017aff | |||
| 8350cbf9c9 | |||
| 02896b6e12 | |||
| 3a99536f9c | |||
| fa34cbaff3 | |||
| 3e516d0ac1 | |||
| f99fb59cd4 | |||
| dbfae9ea81 | |||
| f33023f8e0 | |||
| 5847f40ab5 | |||
| f656a2d2e9 | |||
| 578503c1ca | |||
| 39dca97f9b | |||
| 283f62813f | |||
| f89bdf7edf | |||
| 86c1da2cf5 |
34
README.md
34
README.md
@@ -2,12 +2,24 @@
|
||||
|
||||
ReleaseKit is an opinionated Go library and executable for a shared release
|
||||
process. The Go module, root `releasekit` facade, `buildinfo` runtime package,
|
||||
local candidate check, source-tag publication API, selected-target build API,
|
||||
tagged-source delivery API, and the `version`, `check`, `publish`, `build`,
|
||||
`deliver`, and `ci-deliver` commands are implemented. ReleaseKit's source-only
|
||||
local candidate check, source-tag publication, selected-target build, tagged
|
||||
delivery, readiness, and rehearsal APIs and commands are implemented. ReleaseKit's source-only
|
||||
maintainer procedure and prepared Woodpecker workflow for hosted note-page
|
||||
delivery are documented. ReleaseKit does not declare binary deliverables.
|
||||
|
||||
The Go module is `go.maximumdirect.net/releasekit`. The
|
||||
[adoption guide](docs/consumers/adoption.md#migrating-from-the-original-module-path)
|
||||
explains the v0.5.0 migration from the original Gitea module path.
|
||||
The [v0.6.0 release note](docs/releases/v0.6.0.md) describes the delivery API
|
||||
and profile migration.
|
||||
|
||||
Release operations can select a Go module or a general source directory within a
|
||||
repository. The repository root remains the default; the selected publication
|
||||
mode determines the complete Git tag and release-note location. See the
|
||||
[candidate check](docs/consumers/check.md),
|
||||
[publication](docs/consumers/publish.md), and
|
||||
[multi-module example](examples/multi-module/).
|
||||
|
||||
See the [consumer adoption guide](docs/consumers/adoption.md) to add ReleaseKit
|
||||
as a versioned Go tool or package dependency, and the
|
||||
[v0.1.0 release note](docs/releases/v0.1.0.md) for the initial baseline.
|
||||
@@ -18,15 +30,16 @@ Run the offline Go test suite from the repository root with:
|
||||
go test ./...
|
||||
```
|
||||
|
||||
The version command prints ReleaseKit's version:
|
||||
The version command prints ReleaseKit's version. For the `go run` examples
|
||||
below, [select the Go host target](docs/consumers/adoption.md#select-the-go-host-target)
|
||||
if your shell is set to cross-compile.
|
||||
|
||||
```sh
|
||||
go run ./cmd/releasekit version
|
||||
```
|
||||
|
||||
The local candidate check validates a committed release note, runs the standard
|
||||
offline Go suite with any selected shared validation checks, and then runs
|
||||
configured product checks:
|
||||
offline Go suite when Go is selected, and runs selected shared and product checks:
|
||||
|
||||
```sh
|
||||
go run ./cmd/releasekit check v1.2.3
|
||||
@@ -47,8 +60,8 @@ failure recovery.
|
||||
dependencies, upgrades, and CI adoption.
|
||||
- [Contributor guide](docs/development.md): orientation, validation, and selective
|
||||
policy reading.
|
||||
- [CLI contract](docs/cli.md): the `version`, `check`, `publish`, `build`,
|
||||
`deliver`, and `ci-deliver` commands.
|
||||
- [CLI contract](docs/cli.md): candidate, publication, delivery, readiness,
|
||||
rehearsal, and recovery commands.
|
||||
- [Configuration](docs/config.md): profile fields and child-command settings.
|
||||
- [Runtime version guidance](docs/consumers/runtime-version.md): how applications
|
||||
read their embedded version through `buildinfo`.
|
||||
@@ -56,6 +69,9 @@ failure recovery.
|
||||
injected application version.
|
||||
- [Delivery guidance](docs/consumers/delivery.md): deliver tagged source and
|
||||
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
|
||||
operations and their failure behavior.
|
||||
- [Candidate check guidance](docs/consumers/check.md): local candidate validation
|
||||
@@ -68,6 +84,8 @@ failure recovery.
|
||||
components and their responsibilities.
|
||||
- [Architecture policy](docs/policy/architecture.md): responsibility and dependency
|
||||
boundaries for development.
|
||||
- [ADR 0006](docs/adr/0006-neutral-forge-delivery-and-preflight.md): neutral
|
||||
delivery policy and credential preflight.
|
||||
- [ADR 0001](docs/adr/0001-public-facade.md): the accepted public facade decision.
|
||||
- [Policy provenance](docs/policy/meta.md): adopted policy sources and update
|
||||
guidance.
|
||||
|
||||
120
build.go
120
build.go
@@ -2,9 +2,15 @@ package releasekit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
internalbuild "gitea.maximumdirect.net/eric/ReleaseKit/internal/build"
|
||||
"go.maximumdirect.net/releasekit/internal/artifact"
|
||||
internalbuild "go.maximumdirect.net/releasekit/internal/build"
|
||||
"go.maximumdirect.net/releasekit/internal/git"
|
||||
"go.maximumdirect.net/releasekit/internal/releaseidentity"
|
||||
"go.maximumdirect.net/releasekit/internal/versioncontract"
|
||||
)
|
||||
|
||||
// Target identifies one explicit Go operating-system and architecture pair.
|
||||
@@ -22,11 +28,17 @@ type BuildSpec struct {
|
||||
|
||||
// BuildRequest contains the source and output settings for Build.
|
||||
type BuildRequest struct {
|
||||
RepositoryDir string // source repository whose current HEAD is recorded.
|
||||
Version string // stable vMAJOR.MINOR.PATCH value injected at link time.
|
||||
Spec BuildSpec // application package, artifact name, and targets.
|
||||
OutputDir string // output location; empty selects <repository>/dist.
|
||||
Output io.Writer // optional build progress destination.
|
||||
RepositoryDir string // directory within the source Git checkout whose HEAD is recorded.
|
||||
// ModuleDir selects a repository-relative module directory; empty selects
|
||||
// the repository root.
|
||||
ModuleDir string
|
||||
// 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.
|
||||
OutputDir string // output location; relative paths use ModuleDir and empty selects <module>/dist.
|
||||
Output io.Writer // optional build progress destination.
|
||||
}
|
||||
|
||||
// BuildArtifact identifies one generated binary and its SHA-256 digest.
|
||||
@@ -39,8 +51,19 @@ type BuildArtifact struct {
|
||||
|
||||
// BuildResult describes the source and artifacts reached by Build.
|
||||
type BuildResult struct {
|
||||
RepositoryDir string // absolute source repository path.
|
||||
CandidateCommit string // Git HEAD observed when the build started.
|
||||
RepositoryDir string // absolute source repository path.
|
||||
SourceDir string // absolute selected source directory.
|
||||
SourceSubdir string // repository-relative selected source directory.
|
||||
GoEnabled bool // whether Go capability was selected.
|
||||
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
|
||||
// after a completed build. It is required for binary delivery, not an attestation.
|
||||
SourceVerified bool
|
||||
@@ -53,33 +76,72 @@ type BuildResult struct {
|
||||
Compiler string // output of the selected local Go toolchain's version command.
|
||||
}
|
||||
|
||||
// Build compiles the selected targets with Version injected through buildinfo.
|
||||
// It uses the available compatible local Go toolchain, applies ReleaseKit's
|
||||
// readonly offline build settings, preserves effective cache and tool settings,
|
||||
// and verifies the version command on the Go host before succeeding. An empty
|
||||
// target set records source identity without running the Go toolchain. Errors
|
||||
// return partial build facts in the result.
|
||||
// Build resolves the selected module's working-tree identity, then compiles the
|
||||
// selected targets with Version injected through buildinfo. It uses the
|
||||
// available compatible local Go toolchain, applies ReleaseKit's readonly
|
||||
// offline build settings, preserves effective cache and tool settings, and
|
||||
// verifies the version command on the Go host before succeeding. Relative
|
||||
// output paths use ModuleDir; an empty path selects its dist directory. An
|
||||
// empty target set records source identity without running the Go toolchain.
|
||||
// Errors return partial build facts in the result.
|
||||
func Build(ctx context.Context, request BuildRequest) (BuildResult, error) {
|
||||
result, err := internalbuild.Build(ctx, internalbuild.Request{
|
||||
RepositoryDir: request.RepositoryDir,
|
||||
Version: request.Version,
|
||||
Spec: *internalBuildSpec(&request.Spec),
|
||||
OutputDir: request.OutputDir,
|
||||
Output: request.Output,
|
||||
spec := *internalBuildSpec(&request.Spec)
|
||||
result := internalbuild.Result{Version: request.Version}
|
||||
failure := func(err error) (BuildResult, error) {
|
||||
result.Settings = artifact.NormalizeSettings(spec.MainPackage, spec.BinaryName, spec.Targets)
|
||||
return publicBuildResult(result), err
|
||||
}
|
||||
if request.Source == nil && !versioncontract.ValidStableVersion(request.Version) {
|
||||
return failure(fmt.Errorf("%w: %q", ErrInvalidVersion, request.Version))
|
||||
}
|
||||
repositoryDir, err := git.RepositoryRoot(ctx, request.RepositoryDir)
|
||||
if err != nil {
|
||||
return failure(err)
|
||||
}
|
||||
result.RepositoryDir = repositoryDir
|
||||
identity, err := releaseidentity.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
|
||||
if err != nil {
|
||||
if errors.Is(err, versioncontract.ErrInvalidIdentifier) {
|
||||
return failure(fmt.Errorf("%w: %q", ErrInvalidVersion, request.Version))
|
||||
}
|
||||
return failure(err)
|
||||
}
|
||||
result, err = internalbuild.BuildResolved(ctx, internalbuild.Request{
|
||||
Identity: identity,
|
||||
Spec: spec,
|
||||
OutputDir: request.OutputDir,
|
||||
Output: request.Output,
|
||||
})
|
||||
return publicBuildResult(result), err
|
||||
}
|
||||
|
||||
func publicBuildResult(result internalbuild.Result) BuildResult {
|
||||
public := BuildResult{
|
||||
RepositoryDir: result.RepositoryDir,
|
||||
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,
|
||||
ModulePath: result.ModulePath,
|
||||
Tag: result.Tag,
|
||||
CandidateCommit: result.CandidateCommit,
|
||||
SourceVerified: result.SourceVerified,
|
||||
Version: result.Version,
|
||||
MainPackage: result.MainPackage,
|
||||
BinaryName: result.BinaryName,
|
||||
MainPackage: result.Settings.MainPackage,
|
||||
BinaryName: result.Settings.BinaryName,
|
||||
OutputDir: result.OutputDir,
|
||||
Compiler: result.Compiler,
|
||||
Targets: make([]Target, 0, len(result.Targets)),
|
||||
Targets: make([]Target, 0, len(result.Settings.Targets)),
|
||||
Artifacts: make([]BuildArtifact, 0, len(result.Artifacts)),
|
||||
}
|
||||
for _, target := range result.Targets {
|
||||
for _, target := range result.Settings.Targets {
|
||||
public.Targets = append(public.Targets, Target{OS: target.OS, Arch: target.Arch})
|
||||
}
|
||||
for _, artifact := range result.Artifacts {
|
||||
@@ -90,7 +152,7 @@ func Build(ctx context.Context, request BuildRequest) (BuildResult, error) {
|
||||
SHA256: artifact.SHA256,
|
||||
})
|
||||
}
|
||||
return public, err
|
||||
return public
|
||||
}
|
||||
|
||||
func internalBuildSpec(spec *BuildSpec) *internalbuild.Spec {
|
||||
@@ -105,10 +167,10 @@ func internalBuildSpec(spec *BuildSpec) *internalbuild.Spec {
|
||||
}
|
||||
|
||||
func internalBuildResult(result BuildResult) *internalbuild.Result {
|
||||
converted := &internalbuild.Result{RepositoryDir: result.RepositoryDir, CandidateCommit: result.CandidateCommit, SourceVerified: result.SourceVerified, Version: result.Version, MainPackage: result.MainPackage, BinaryName: result.BinaryName, OutputDir: result.OutputDir, Compiler: result.Compiler}
|
||||
for _, target := range result.Targets {
|
||||
converted.Targets = append(converted.Targets, internalbuild.Target{OS: target.OS, Arch: target.Arch})
|
||||
}
|
||||
input := internalBuildSpec(&BuildSpec{MainPackage: result.MainPackage, BinaryName: result.BinaryName, Targets: result.Targets})
|
||||
settings := artifact.NormalizeSettings(input.MainPackage, input.BinaryName, input.Targets)
|
||||
converted := &internalbuild.Result{RepositoryDir: result.RepositoryDir, ModuleDir: result.ModuleDir, ModulePath: result.ModulePath, Tag: result.Tag, CandidateCommit: result.CandidateCommit, SourceVerified: result.SourceVerified, Settings: settings, Version: result.Version, 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 {
|
||||
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})
|
||||
}
|
||||
|
||||
150
build_source_cancellation_test.go
Normal file
150
build_source_cancellation_test.go
Normal file
@@ -0,0 +1,150 @@
|
||||
package releasekit_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
releasekit "go.maximumdirect.net/releasekit"
|
||||
)
|
||||
|
||||
// inspectionDeadlineContext models deadline expiration at the readiness signal,
|
||||
// so unrelated setup time cannot consume the source-inspection test's deadline.
|
||||
type inspectionDeadlineContext struct{ context.Context }
|
||||
|
||||
func (ctx inspectionDeadlineContext) Err() error {
|
||||
return context.Cause(ctx.Context)
|
||||
}
|
||||
|
||||
func TestBuildSourceInspectionCancellation(t *testing.T) {
|
||||
const source = `package main
|
||||
import("fmt";"os";"go.maximumdirect.net/releasekit/buildinfo")
|
||||
func main(){ if len(os.Args)>1 && os.Args[1]=="version" {fmt.Println("fixture",buildinfo.Version())} }
|
||||
`
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
status int
|
||||
deadline bool
|
||||
binary bool
|
||||
}{
|
||||
{"initial", 1, false, false}, {"deadline", 1, true, false}, {"final", 2, false, true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
repo := newBuildConsumer(t, source)
|
||||
realGit, err := exec.LookPath("git")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bin := t.TempDir()
|
||||
count := filepath.Join(t.TempDir(), "count")
|
||||
ready := filepath.Join(t.TempDir(), "ready")
|
||||
script := `#!/bin/sh
|
||||
for arg in "$@"; do
|
||||
if [ "$arg" = status ]; then
|
||||
count=0
|
||||
if [ -f "$INSPECT_COUNT" ]; then count=$(/bin/cat "$INSPECT_COUNT"); fi
|
||||
count=$((count+1)); printf '%s' "$count" > "$INSPECT_COUNT"
|
||||
if [ "$count" = "$INSPECT_BLOCK" ]; then : > "$INSPECT_READY"; exec /bin/sleep 60; fi
|
||||
fi
|
||||
done
|
||||
exec "$INSPECT_GIT" "$@"
|
||||
`
|
||||
if err := os.WriteFile(filepath.Join(bin, "git"), []byte(script), 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||
t.Setenv("INSPECT_GIT", realGit)
|
||||
t.Setenv("INSPECT_COUNT", count)
|
||||
t.Setenv("INSPECT_READY", ready)
|
||||
t.Setenv("INSPECT_BLOCK", fmt.Sprint(tc.status))
|
||||
var ctx context.Context
|
||||
var cancel context.CancelFunc
|
||||
if tc.deadline {
|
||||
parent, expire := context.WithCancelCause(context.Background())
|
||||
ctx = inspectionDeadlineContext{parent}
|
||||
cancel = func() { expire(context.DeadlineExceeded) }
|
||||
} else {
|
||||
ctx, cancel = context.WithCancel(context.Background())
|
||||
}
|
||||
defer cancel()
|
||||
request := releasekit.BuildRequest{RepositoryDir: repo, Version: "v1.2.3", OutputDir: t.TempDir()}
|
||||
if tc.binary {
|
||||
request.Spec = releasekit.BuildSpec{MainPackage: "./cmd/app", BinaryName: "fixture", Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}}}
|
||||
}
|
||||
type outcome struct {
|
||||
result releasekit.BuildResult
|
||||
err error
|
||||
}
|
||||
done := make(chan outcome, 1)
|
||||
go func() { result, err := releasekit.Build(ctx, request); done <- outcome{result, err} }()
|
||||
timer := time.NewTimer(45 * time.Second)
|
||||
defer timer.Stop()
|
||||
ticker := time.NewTicker(10 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
waiting := true
|
||||
for waiting {
|
||||
if _, err := os.Stat(ready); err == nil {
|
||||
waiting = false
|
||||
break
|
||||
}
|
||||
select {
|
||||
case result := <-done:
|
||||
t.Fatalf("build ended before inspection: %#v, %v", result.result, result.err)
|
||||
case <-timer.C:
|
||||
cancel()
|
||||
result := <-done
|
||||
t.Fatalf("inspection did not start: %#v, %v", result.result, result.err)
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
cancel()
|
||||
var result outcome
|
||||
select {
|
||||
case result = <-done:
|
||||
case <-timer.C:
|
||||
t.Fatal("build did not stop after source inspection interruption")
|
||||
}
|
||||
want := context.Canceled
|
||||
if tc.deadline {
|
||||
want = context.DeadlineExceeded
|
||||
}
|
||||
if !errors.Is(result.err, want) || result.result.SourceVerified {
|
||||
t.Fatalf("result = %#v, error = %v", result.result, result.err)
|
||||
}
|
||||
if tc.binary {
|
||||
if len(result.result.Artifacts) != 1 || result.result.Artifacts[0].SHA256 == "" {
|
||||
t.Fatalf("completed artifact missing: %#v", result.result.Artifacts)
|
||||
}
|
||||
if _, err := os.Stat(result.result.Artifacts[0].Path); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildSourceInspectionPreservesGitFailure(t *testing.T) {
|
||||
repo := newBuildConsumer(t, "package main\nfunc main() {}\n")
|
||||
realGit, err := exec.LookPath("git")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bin := t.TempDir()
|
||||
script := "#!/bin/sh\nfor arg do if [ \"$arg\" = status ]; then exit 37; fi; done\nexec \"$INSPECT_GIT\" \"$@\"\n"
|
||||
if err := os.WriteFile(filepath.Join(bin, "git"), []byte(script), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||
t.Setenv("INSPECT_GIT", realGit)
|
||||
result, err := releasekit.Build(context.Background(), releasekit.BuildRequest{RepositoryDir: repo, Version: "v1.2.3"})
|
||||
var exitErr *exec.ExitError
|
||||
if !errors.As(err, &exitErr) || exitErr.ExitCode() != 37 || result.SourceVerified {
|
||||
t.Fatalf("result = %#v, error = %v", result, err)
|
||||
}
|
||||
}
|
||||
327
build_test.go
327
build_test.go
@@ -15,9 +15,67 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
releasekit "gitea.maximumdirect.net/eric/ReleaseKit"
|
||||
releasekit "go.maximumdirect.net/releasekit"
|
||||
)
|
||||
|
||||
func TestBuildReplacementDerivedSourceIsNotEligibleForDelivery(t *testing.T) {
|
||||
repository := newTaggedDeliveryConsumer(t)
|
||||
original := buildGit(t, repository, "rev-parse", "HEAD")
|
||||
mainPath := filepath.Join(repository, "cmd/app/main.go")
|
||||
main, err := os.ReadFile(mainPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writeBuildFixture(t, repository, "cmd/app/main.go", string(main)+"\n// replacement source\n")
|
||||
buildGit(t, repository, "add", "cmd/app/main.go")
|
||||
buildGit(t, repository, "commit", "-m", "Replacement source")
|
||||
replacement := buildGit(t, repository, "rev-parse", "HEAD")
|
||||
buildGit(t, repository, "reset", "--hard", original)
|
||||
buildGit(t, repository, "replace", original, replacement)
|
||||
buildGit(t, repository, "reset", "--hard", original)
|
||||
result, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||
RepositoryDir: repository, Version: "v1.2.3", OutputDir: t.TempDir(),
|
||||
Spec: releasekit.BuildSpec{MainPackage: "./cmd/app", BinaryName: "fixture", Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}}},
|
||||
})
|
||||
if err != nil || result.SourceVerified || len(result.Artifacts) != 1 || result.CandidateCommit != original {
|
||||
t.Fatalf("replacement build = %#v, error = %v", result, err)
|
||||
}
|
||||
buildGit(t, repository, "replace", "-d", original)
|
||||
buildGit(t, repository, "reset", "--hard", original)
|
||||
server, remote := newFacadeDeliveryServer(t, repository)
|
||||
defer server.Close()
|
||||
delivery, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
|
||||
RepositoryDir: repository, Product: "Fixture", Version: "v1.2.3",
|
||||
Destination: facadeDeliveryDestination(server.URL), Prebuilt: &result,
|
||||
})
|
||||
if err == nil || delivery.State != releasekit.DeliveryNotAttempted || remote.snapshot().writes != 0 {
|
||||
t.Fatalf("delivery of replacement build = %#v, error = %v", delivery, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildPreservesInvalidVersionAndDeclarationFailureEvidence(t *testing.T) {
|
||||
spec := releasekit.BuildSpec{MainPackage: "./cmd/app", BinaryName: "widget", Targets: []releasekit.Target{{OS: "linux", Arch: "amd64"}, {OS: "linux", Arch: "amd64"}}}
|
||||
invalid, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||
RepositoryDir: filepath.Join(t.TempDir(), "absent"), Version: "bad-version", Spec: spec,
|
||||
})
|
||||
if !errors.Is(err, releasekit.ErrInvalidVersion) || invalid.Version != "bad-version" || invalid.MainPackage != spec.MainPackage || invalid.BinaryName != spec.BinaryName || len(invalid.Targets) != 1 {
|
||||
t.Fatalf("invalid version result = %#v, error = %v", invalid, err)
|
||||
}
|
||||
repo := newPublishFixture(t)
|
||||
writeFile(t, repo.work, "nested/go.mod", "go 1.26.0\n")
|
||||
failed, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||
RepositoryDir: repo.work, ModuleDir: "nested", Version: "v1.2.3", Spec: spec,
|
||||
})
|
||||
if err == nil || failed.RepositoryDir != repo.work || failed.ModuleDir != filepath.Join(repo.work, "nested") || failed.Version != "v1.2.3" || failed.MainPackage != spec.MainPackage || failed.BinaryName != spec.BinaryName || len(failed.Targets) != 1 || failed.SourceVerified {
|
||||
t.Fatalf("declaration failure = %#v, error = %v", failed, err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if _, err := releasekit.Build(ctx, releasekit.BuildRequest{RepositoryDir: repo.work, Version: "v1.2.3", Spec: spec}); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("canceled build error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildCreatesSelectedTargetsAndInjectsVersion(t *testing.T) {
|
||||
repository := newBuildConsumer(t, `package main
|
||||
|
||||
@@ -25,7 +83,7 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo"
|
||||
"go.maximumdirect.net/releasekit/buildinfo"
|
||||
)
|
||||
|
||||
func main() {
|
||||
@@ -104,7 +162,7 @@ func TestBuildUsesGoHostDespiteAmbientTargetEnvironment(t *testing.T) {
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo"
|
||||
"go.maximumdirect.net/releasekit/buildinfo"
|
||||
)
|
||||
|
||||
func main() {
|
||||
@@ -115,7 +173,7 @@ func main() {
|
||||
t.Setenv("GOARCH", "arm64")
|
||||
result, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||
RepositoryDir: repository,
|
||||
Version: "v2.3.4",
|
||||
Version: "v1.2.3",
|
||||
Spec: releasekit.BuildSpec{
|
||||
MainPackage: "./cmd/app",
|
||||
BinaryName: "fixture",
|
||||
@@ -126,7 +184,7 @@ func main() {
|
||||
if err != nil {
|
||||
t.Fatalf("Build() error = %v; partial result = %#v", err, result)
|
||||
}
|
||||
if len(result.Artifacts) != 1 || result.Artifacts[0].Filename != "fixture-v2.3.4-windows-arm64.exe" {
|
||||
if len(result.Artifacts) != 1 || result.Artifacts[0].Filename != "fixture-v1.2.3-windows-arm64.exe" {
|
||||
t.Fatalf("build artifacts = %#v", result.Artifacts)
|
||||
}
|
||||
}
|
||||
@@ -136,7 +194,7 @@ func TestBuildIgnoresAmbientAndPersistentArchitectureTuning(t *testing.T) {
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo"
|
||||
"go.maximumdirect.net/releasekit/buildinfo"
|
||||
)
|
||||
func main() { if len(os.Args) == 2 && os.Args[1] == "version" { fmt.Printf("fixture %s\n", buildinfo.Version()) } }
|
||||
`)
|
||||
@@ -166,7 +224,7 @@ func main() { if len(os.Args) == 2 && os.Args[1] == "version" { fmt.Printf("fixt
|
||||
|
||||
result, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||
RepositoryDir: repository,
|
||||
Version: "v2.3.4",
|
||||
Version: "v1.2.3",
|
||||
Spec: releasekit.BuildSpec{
|
||||
MainPackage: "./cmd/app",
|
||||
BinaryName: "fixture",
|
||||
@@ -242,9 +300,148 @@ func main() {}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildUsesNestedWorkingTreeModuleAndModuleRelativeOutput(t *testing.T) {
|
||||
repository := newBuildConsumer(t, "package main\nfunc main() {}\n")
|
||||
moduleDir := filepath.Join(repository, "integrations", "nested")
|
||||
writeNestedBuildConsumer(t, repository, "integrations/nested", "example.com/nestedbuild", `package main
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"go.maximumdirect.net/releasekit/buildinfo"
|
||||
)
|
||||
func main() {
|
||||
if len(os.Args) == 2 && os.Args[1] == "version" {
|
||||
if logPath := os.Getenv("RELEASEKIT_SMOKE_LOG"); logPath != "" {
|
||||
if executable, err := os.Executable(); err == nil {
|
||||
_ = os.WriteFile(logPath, []byte(executable), 0o600)
|
||||
}
|
||||
}
|
||||
fmt.Printf("nested-app %s\n", buildinfo.Version())
|
||||
}
|
||||
}
|
||||
`)
|
||||
outputDirectory := "artifacts"
|
||||
crossTarget := releasekit.Target{OS: "darwin", Arch: "arm64"}
|
||||
if runtime.GOOS == "darwin" && runtime.GOARCH == "arm64" {
|
||||
crossTarget = releasekit.Target{OS: "linux", Arch: "amd64"}
|
||||
}
|
||||
nativeTarget := releasekit.Target{OS: runtime.GOOS, Arch: runtime.GOARCH}
|
||||
result, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||
RepositoryDir: repository,
|
||||
ModuleDir: "integrations/nested",
|
||||
Version: "v1.2.3",
|
||||
Spec: releasekit.BuildSpec{
|
||||
MainPackage: "./cmd/app",
|
||||
BinaryName: "nested-app",
|
||||
Targets: []releasekit.Target{nativeTarget, crossTarget},
|
||||
},
|
||||
OutputDir: outputDirectory,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Build() error = %v; result = %#v", err, result)
|
||||
}
|
||||
if result.ModuleDir != moduleDir || result.ModulePath != "example.com/nestedbuild" || result.Tag != "integrations/nested/v1.2.3" {
|
||||
t.Fatalf("nested build identity = %#v", result)
|
||||
}
|
||||
wantOutput := filepath.Join(moduleDir, outputDirectory)
|
||||
if result.OutputDir != wantOutput || len(result.Artifacts) != 2 {
|
||||
t.Fatalf("nested build output = %#v, want directory %q and two artifacts", result, wantOutput)
|
||||
}
|
||||
var native string
|
||||
for _, artifact := range result.Artifacts {
|
||||
if filepath.Dir(artifact.Path) != wantOutput || !strings.Contains(artifact.Filename, "nested-app-v1.2.3-") {
|
||||
t.Fatalf("nested artifact = %#v", artifact)
|
||||
}
|
||||
if artifact.Target == nativeTarget {
|
||||
native = artifact.Path
|
||||
}
|
||||
}
|
||||
if native == "" {
|
||||
t.Fatalf("native artifact missing from %#v", result.Artifacts)
|
||||
}
|
||||
if output, err := exec.Command(native, "version").CombinedOutput(); err != nil || string(output) != "nested-app v1.2.3\n" {
|
||||
t.Fatalf("nested native version = %q, error = %v", output, err)
|
||||
}
|
||||
|
||||
localTemporary := filepath.Join(repository, "source-temporary")
|
||||
if err := os.Mkdir(localTemporary, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
crossOutput := filepath.Join(t.TempDir(), "cross-artifacts")
|
||||
smokeLog := filepath.Join(t.TempDir(), "smoke-executable")
|
||||
t.Setenv("RELEASEKIT_SMOKE_LOG", smokeLog)
|
||||
t.Setenv("TMPDIR", localTemporary)
|
||||
smokeResult, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||
RepositoryDir: repository,
|
||||
ModuleDir: "integrations/nested",
|
||||
Version: "v1.2.3",
|
||||
Spec: releasekit.BuildSpec{
|
||||
MainPackage: "./cmd/app",
|
||||
BinaryName: "nested-app",
|
||||
Targets: []releasekit.Target{crossTarget},
|
||||
},
|
||||
OutputDir: crossOutput,
|
||||
})
|
||||
if err != nil || len(smokeResult.Artifacts) != 1 {
|
||||
t.Fatalf("nested cross build with source-local TMPDIR = %#v, %v", smokeResult, err)
|
||||
}
|
||||
smokePathBytes, err := os.ReadFile(smokeLog)
|
||||
if err != nil {
|
||||
t.Fatalf("read native smoke executable path: %v", err)
|
||||
}
|
||||
smokePath := string(smokePathBytes)
|
||||
relativeSmokePath, err := filepath.Rel(repository, smokePath)
|
||||
if err != nil || relativeSmokePath == "." || (!filepath.IsAbs(relativeSmokePath) && relativeSmokePath != ".." && !strings.HasPrefix(relativeSmokePath, ".."+string(filepath.Separator))) {
|
||||
t.Fatalf("native smoke output path %q is inside repository %q (relative %q, error %v)", smokePath, repository, relativeSmokePath, err)
|
||||
}
|
||||
if _, err := os.Stat(smokePath); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("native smoke output %q was not removed: %v", smokePath, err)
|
||||
}
|
||||
remaining, err := os.ReadDir(localTemporary)
|
||||
if err != nil || len(remaining) != 0 {
|
||||
t.Fatalf("native smoke output remained in source-local TMPDIR: %v %v", remaining, err)
|
||||
}
|
||||
|
||||
emptyResult, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||
RepositoryDir: repository,
|
||||
ModuleDir: "integrations/nested",
|
||||
Version: "v1.2.3",
|
||||
})
|
||||
if err != nil || emptyResult.Compiler != "" || emptyResult.OutputDir != filepath.Join(moduleDir, "dist") {
|
||||
t.Fatalf("nested empty build = %#v, %v", emptyResult, err)
|
||||
}
|
||||
if _, err := os.Stat(emptyResult.OutputDir); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("empty nested build created dist: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildResolvesDirtyWorkingTreeDeclaration(t *testing.T) {
|
||||
repository := newBuildConsumer(t, "package main\nfunc main() {}\n")
|
||||
declarationPath := filepath.Join(repository, "go.mod")
|
||||
contents, err := os.ReadFile(declarationPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
updated := strings.Replace(string(contents), "module example.com/buildfixture", "module example.com/changedbuild", 1)
|
||||
if updated == string(contents) {
|
||||
t.Fatal("fixture module declaration was not replaced")
|
||||
}
|
||||
writeBuildFixture(t, repository, "go.mod", updated)
|
||||
result, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||
RepositoryDir: repository,
|
||||
Version: "v1.2.3",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result.ModulePath != "example.com/changedbuild" || result.Tag != "v1.2.3" {
|
||||
t.Fatalf("dirty declaration identity = %#v", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildRegeneratesOwnedOutputsAndPreservesUnrelatedFiles(t *testing.T) {
|
||||
const source = `package main
|
||||
import("fmt";"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo")
|
||||
import("fmt";"go.maximumdirect.net/releasekit/buildinfo")
|
||||
func main(){fmt.Println("fixture",buildinfo.Version())}
|
||||
`
|
||||
repository := newBuildConsumer(t, source)
|
||||
@@ -324,6 +521,61 @@ func TestBuildReportsMissingMainPackage(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildRetainsOnlyHashedArtifactsAfterReadFailure(t *testing.T) {
|
||||
repository := newBuildConsumer(t, "package main\nfunc main() {}\n")
|
||||
realGo, err := exec.LookPath("go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bin := t.TempDir()
|
||||
count := filepath.Join(t.TempDir(), "count")
|
||||
script := `#!/bin/sh
|
||||
if [ "$1" != build ]; then exec "$RELEASEKIT_REAL_GO" "$@"; fi
|
||||
output=
|
||||
previous=
|
||||
for arg in "$@"; do
|
||||
if [ "$previous" = -o ]; then output=$arg; fi
|
||||
previous=$arg
|
||||
done
|
||||
"$RELEASEKIT_REAL_GO" "$@" || exit $?
|
||||
if [ -f "$RELEASEKIT_BUILD_COUNT" ]; then
|
||||
rm "$output"
|
||||
mkdir "$output"
|
||||
else
|
||||
: > "$RELEASEKIT_BUILD_COUNT"
|
||||
fi
|
||||
`
|
||||
if err := os.WriteFile(filepath.Join(bin, "go"), []byte(script), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||
t.Setenv("RELEASEKIT_REAL_GO", realGo)
|
||||
t.Setenv("RELEASEKIT_BUILD_COUNT", count)
|
||||
secondArch := "arm64"
|
||||
if runtime.GOARCH == secondArch {
|
||||
secondArch = "amd64"
|
||||
}
|
||||
result, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||
RepositoryDir: repository, Version: "v1.2.3", OutputDir: t.TempDir(),
|
||||
Spec: releasekit.BuildSpec{MainPackage: "./cmd/app", BinaryName: "fixture", Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}, {OS: runtime.GOOS, Arch: secondArch}}},
|
||||
})
|
||||
var pathErr *os.PathError
|
||||
if !errors.As(err, &pathErr) || !strings.Contains(err.Error(), "hash build output") || len(result.Artifacts) != 1 || len(result.Targets) != 2 || result.MainPackage != "./cmd/app" || result.BinaryName != "fixture" || result.CandidateCommit == "" || result.SourceVerified {
|
||||
t.Fatalf("partial build = %#v, error = %v", result, err)
|
||||
}
|
||||
contents, readErr := os.ReadFile(result.Artifacts[0].Path)
|
||||
if readErr != nil {
|
||||
t.Fatal(readErr)
|
||||
}
|
||||
digest := sha256.Sum256(contents)
|
||||
if result.Artifacts[0].SHA256 != hex.EncodeToString(digest[:]) {
|
||||
t.Fatalf("completed artifact digest = %q", result.Artifacts[0].SHA256)
|
||||
}
|
||||
if info, statErr := os.Stat(pathErr.Path); statErr != nil || !info.IsDir() {
|
||||
t.Fatalf("failed output was not retained: %v", statErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildReportsIncorrectVersionOutputAndRetainsBinary(t *testing.T) {
|
||||
repository := newBuildConsumer(t, `package main
|
||||
import (
|
||||
@@ -432,6 +684,21 @@ func TestBuildCancellationReturnsCompletedArtifacts(t *testing.T) {
|
||||
|
||||
func TestCheckBuildsAfterValidationAndKeepsOutputOutsideWorktree(t *testing.T) {
|
||||
repository := newPublishFixture(t)
|
||||
realGo, err := exec.LookPath("go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
goShimDir := t.TempDir()
|
||||
goLog := filepath.Join(goShimDir, "go-commands")
|
||||
goShim := filepath.Join(goShimDir, "go")
|
||||
shimSource := "#!/bin/sh\nset -eu\nprintf '%s\\n' \"$*\" >> \"$RELEASEKIT_REAL_GO_LOG\"\nexec \"$RELEASEKIT_REAL_GO\" \"$@\"\n"
|
||||
if err := os.WriteFile(goShim, []byte(shimSource), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("RELEASEKIT_REAL_GO", realGo)
|
||||
t.Setenv("RELEASEKIT_REAL_GO_LOG", goLog)
|
||||
t.Setenv("GOENV", "off")
|
||||
t.Setenv("PATH", goShimDir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||
writeFile(t, repository.work, "guide.md", "# Guide\n[section](#guide)\n")
|
||||
gitRun(t, repository.work, "add", "guide.md")
|
||||
gitRun(t, repository.work, "commit", "-m", "add Markdown guide")
|
||||
@@ -439,7 +706,7 @@ func TestCheckBuildsAfterValidationAndKeepsOutputOutsideWorktree(t *testing.T) {
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo"
|
||||
"go.maximumdirect.net/releasekit/buildinfo"
|
||||
)
|
||||
func main() { if len(os.Args) == 2 && os.Args[1] == "version" { fmt.Printf("fixture %s\n", buildinfo.Version()) } }
|
||||
`)
|
||||
@@ -465,6 +732,26 @@ func main() { if len(os.Args) == 2 && os.Args[1] == "version" { fmt.Printf("fixt
|
||||
if validations != 1 || candidate.Commit != gitText(t, repository.work, "rev-parse", "HEAD") {
|
||||
t.Fatalf("candidate = %#v, validation calls = %d", candidate, validations)
|
||||
}
|
||||
goCommands, err := os.ReadFile(goLog)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var discoveries, suites, builds, versions int
|
||||
for _, command := range strings.Split(strings.TrimSpace(string(goCommands)), "\n") {
|
||||
switch {
|
||||
case strings.HasPrefix(command, "env "):
|
||||
discoveries++
|
||||
case strings.HasPrefix(command, "test "):
|
||||
suites++
|
||||
case strings.HasPrefix(command, "build "):
|
||||
builds++
|
||||
case command == "version":
|
||||
versions++
|
||||
}
|
||||
}
|
||||
if discoveries != 2 || suites != 1 || builds != 1 || versions != 1 {
|
||||
t.Fatalf("Go commands = %q; discovery=%d suite=%d build=%d version=%d, want 2, 1, 1, 1", goCommands, discoveries, suites, builds, versions)
|
||||
}
|
||||
if got := gitText(t, repository.work, "status", "--porcelain"); got != "" {
|
||||
t.Fatalf("candidate build dirtied worktree: %s", got)
|
||||
}
|
||||
@@ -516,7 +803,7 @@ func newBuildConsumer(t *testing.T, mainSource string) string {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
module := fmt.Sprintf("module example.com/buildfixture\n\ngo 1.26.0\n\nrequire gitea.maximumdirect.net/eric/ReleaseKit v0.0.0\n\nreplace gitea.maximumdirect.net/eric/ReleaseKit => %s\n", filepath.ToSlash(root))
|
||||
module := fmt.Sprintf("module example.com/buildfixture\n\ngo 1.27.0\n\nrequire go.maximumdirect.net/releasekit v0.0.0\n\nreplace go.maximumdirect.net/releasekit => %s\n", filepath.ToSlash(root))
|
||||
writeBuildFixture(t, repository, "go.mod", module)
|
||||
writeBuildFixture(t, repository, "cmd/app/main.go", mainSource)
|
||||
writeBuildFixture(t, repository, "cmd/app/main_test.go", "package main\nimport \"testing\"\nfunc TestCandidateFixture(t *testing.T) {}\n")
|
||||
@@ -528,13 +815,25 @@ func newBuildConsumer(t *testing.T, mainSource string) string {
|
||||
return repository
|
||||
}
|
||||
|
||||
func writeNestedBuildConsumer(t *testing.T, repository, moduleDir, modulePath, mainSource string) string {
|
||||
t.Helper()
|
||||
root, err := filepath.Abs(".")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
module := fmt.Sprintf("module %s\n\ngo 1.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, "cmd/app/main.go")), mainSource)
|
||||
return filepath.Join(repository, filepath.FromSlash(moduleDir))
|
||||
}
|
||||
|
||||
func prepareCandidateBuild(t *testing.T, repository, mainSource string) {
|
||||
t.Helper()
|
||||
root, err := filepath.Abs(".")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
module := fmt.Sprintf("module example.com/candidatebuild\n\ngo 1.26.0\n\nrequire gitea.maximumdirect.net/eric/ReleaseKit v0.0.0\n\nreplace gitea.maximumdirect.net/eric/ReleaseKit => %s\n", filepath.ToSlash(root))
|
||||
module := fmt.Sprintf("module example.com/candidatebuild\n\ngo 1.27.0\n\nrequire go.maximumdirect.net/releasekit v0.0.0\n\nreplace go.maximumdirect.net/releasekit => %s\n", filepath.ToSlash(root))
|
||||
writeFile(t, repository, "go.mod", module)
|
||||
writeFile(t, repository, ".gitignore", "dist/\n")
|
||||
writeFile(t, repository, "cmd/app/main.go", mainSource)
|
||||
@@ -568,7 +867,7 @@ func buildGit(t *testing.T, directory string, args ...string) string {
|
||||
|
||||
func TestBuildSourceEligibilitySurvivesLaterCheckoutCleanup(t *testing.T) {
|
||||
const source = `package main
|
||||
import("fmt";"os";"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo")
|
||||
import("fmt";"os";"go.maximumdirect.net/releasekit/buildinfo")
|
||||
func main(){ if len(os.Args)>1 && os.Args[1]=="version" {fmt.Println("fixture",buildinfo.Version())} }
|
||||
`
|
||||
for _, mode := range []string{"clean", "dirty before build", "changed during build", "commit during build"} {
|
||||
@@ -606,7 +905,7 @@ func main(){ if len(os.Args)>1 && os.Args[1]=="version" {fmt.Println("fixture",b
|
||||
}
|
||||
buildGit(t, repository, "restore", "cmd/app/main.go")
|
||||
buildGit(t, repository, "checkout", "--detach", "v1.2.3")
|
||||
delivered, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{RepositoryDir: repository, Product: "Fixture", Version: "v1.2.3", Prebuilt: &result})
|
||||
delivered, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{RepositoryDir: repository, Product: "Fixture", Version: "v1.2.3", Destination: releasekit.DeliveryDestination{Forge: releasekit.ForgeGitea}, Prebuilt: &result})
|
||||
if err == nil || !strings.Contains(err.Error(), "build source") || delivered.State != releasekit.DeliveryNotAttempted {
|
||||
t.Fatalf("dirty source delivered: %#v %v", delivered, err)
|
||||
}
|
||||
@@ -629,7 +928,7 @@ func TestCandidateBuildDoesNotRequireWritableRepositoryParent(t *testing.T) {
|
||||
t.Skip("requires ordinary Unix permission checks")
|
||||
}
|
||||
repository := newBuildConsumer(t, `package main
|
||||
import("fmt";"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo")
|
||||
import("fmt";"go.maximumdirect.net/releasekit/buildinfo")
|
||||
func main(){fmt.Println("fixture",buildinfo.Version())}
|
||||
`)
|
||||
writeBuildFixture(t, repository, "docs/releases/v1.2.3.md", "# Fixture v1.2.3\n")
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// built with ReleaseKit.
|
||||
package buildinfo
|
||||
|
||||
import "gitea.maximumdirect.net/eric/ReleaseKit/internal/runtimeinfo"
|
||||
import "go.maximumdirect.net/releasekit/internal/runtimeinfo"
|
||||
|
||||
// Version returns the injected release identifier when available. Otherwise,
|
||||
// it returns the executable's main module version, or "dev" when that metadata
|
||||
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"gitea.maximumdirect.net/eric/ReleaseKit/internal/versioncontract"
|
||||
"go.maximumdirect.net/releasekit/internal/versioncontract"
|
||||
)
|
||||
|
||||
func TestVersionInConsumerExecutable(t *testing.T) {
|
||||
@@ -19,11 +19,11 @@ func TestVersionInConsumerExecutable(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
module := fmt.Sprintf(`module example.com/versionfixture
|
||||
|
||||
go 1.26.0
|
||||
go 1.27.0
|
||||
|
||||
require gitea.maximumdirect.net/eric/ReleaseKit v0.0.0
|
||||
require go.maximumdirect.net/releasekit v0.0.0
|
||||
|
||||
replace gitea.maximumdirect.net/eric/ReleaseKit => %s
|
||||
replace go.maximumdirect.net/releasekit => %s
|
||||
`, filepath.ToSlash(repo))
|
||||
if err := os.WriteFile(filepath.Join(dir, "go.mod"), []byte(module), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -32,7 +32,7 @@ replace gitea.maximumdirect.net/eric/ReleaseKit => %s
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo"
|
||||
"go.maximumdirect.net/releasekit/buildinfo"
|
||||
)
|
||||
|
||||
func main() { fmt.Print(buildinfo.Version()) }
|
||||
|
||||
156
check.go
156
check.go
@@ -4,13 +4,13 @@ import (
|
||||
"context"
|
||||
"io"
|
||||
|
||||
internalbuild "gitea.maximumdirect.net/eric/ReleaseKit/internal/build"
|
||||
"gitea.maximumdirect.net/eric/ReleaseKit/internal/candidate"
|
||||
"gitea.maximumdirect.net/eric/ReleaseKit/internal/publish"
|
||||
"gitea.maximumdirect.net/eric/ReleaseKit/internal/validation"
|
||||
internalbuild "go.maximumdirect.net/releasekit/internal/build"
|
||||
"go.maximumdirect.net/releasekit/internal/candidate"
|
||||
"go.maximumdirect.net/releasekit/internal/publish"
|
||||
"go.maximumdirect.net/releasekit/internal/validation"
|
||||
)
|
||||
|
||||
// ErrInvalidVersion reports a version that is not stable vMAJOR.MINOR.PATCH.
|
||||
// ErrInvalidVersion reports an identifier that does not match its selected format.
|
||||
var ErrInvalidVersion = candidate.ErrInvalidVersion
|
||||
|
||||
// ErrUnexpectedPushURL reports that the effective publication push URL does
|
||||
@@ -18,25 +18,49 @@ var ErrInvalidVersion = candidate.ErrInvalidVersion
|
||||
var ErrUnexpectedPushURL = publish.ErrUnexpectedPushURL
|
||||
|
||||
// Candidate identifies one committed local source revision selected for
|
||||
// validation.
|
||||
// validation. SourceDir is the absolute selected source directory. ModuleDir
|
||||
// and ModulePath identify a selected Go module and are empty for source-only
|
||||
// releases. Tag is the complete derived Git tag.
|
||||
type Candidate struct {
|
||||
RepositoryDir string
|
||||
SourceDir string
|
||||
SourceSubdir string
|
||||
GoEnabled bool
|
||||
Publication PublicationMode
|
||||
VersionFormat VersionFormat
|
||||
VersionPrefix string
|
||||
ModuleDir string
|
||||
ModulePath string
|
||||
Tag string
|
||||
Commit string
|
||||
Version string
|
||||
Version string // selected production identifier.
|
||||
}
|
||||
|
||||
// ReleaseRequest contains the inputs used to validate and optionally build one
|
||||
// local candidate. Remote is retained for publication operations; Check makes
|
||||
// no remote availability claim.
|
||||
type ReleaseRequest struct {
|
||||
// RepositoryDir names a directory within the source Git checkout. Operations
|
||||
// resolve its root before applying repository-relative selections.
|
||||
RepositoryDir string
|
||||
Product string
|
||||
Version string
|
||||
Remote string
|
||||
// ModuleDir selects a repository-relative module directory; empty selects
|
||||
// the repository root.
|
||||
ModuleDir string
|
||||
// Source selects explicit source and publication capabilities. Nil retains
|
||||
// the ModuleDir Go-module shorthand.
|
||||
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
|
||||
// this string exactly before validation or tag creation. Check ignores this
|
||||
// publication-only expectation. A mismatch returns ErrUnexpectedPushURL.
|
||||
ExpectedPushURL string
|
||||
// PublicationRecordDir optionally overrides Publish's private attempt-record
|
||||
// directory. Relative paths are resolved from the source repository root;
|
||||
// Check ignores this publication-only setting. Recording failure is returned
|
||||
// separately on PublicationResult and does not change publication status.
|
||||
PublicationRecordDir string
|
||||
// Validation selects optional checks run against the captured candidate.
|
||||
Validation ValidationSpec
|
||||
// AdditionalChecks optionally runs product checks after shared validation.
|
||||
@@ -46,9 +70,24 @@ type ReleaseRequest struct {
|
||||
}
|
||||
|
||||
// ValidationSpec selects optional shared validation checks. Its zero value
|
||||
// preserves the current validation behavior.
|
||||
// preserves the current validation behavior. File checks inspect the selected
|
||||
// module and shared-file inputs. Independent nested modules form automatic
|
||||
// input boundaries; vendored files remain included. Referenced destinations
|
||||
// remain available for targeted inspection without expanding the input set.
|
||||
// ForbiddenFiles checks explicitly selected repository paths independently of
|
||||
// those file inputs.
|
||||
type ValidationSpec struct {
|
||||
Go GoValidationSpec
|
||||
// SharedFiles adds repository-relative committed files to optional file
|
||||
// checks. Nil selects the optional root COPYRIGHT, LICENSE, and
|
||||
// docs/oss/attribution.md defaults; an empty non-nil slice selects none.
|
||||
// Explicit files replace the defaults and must exist even when file checks
|
||||
// are off.
|
||||
SharedFiles []string
|
||||
// ForbiddenFiles lists literal repository-relative file paths that must be
|
||||
// absent from the captured commit, independently of module/shared inputs.
|
||||
// An empty list disables the check. File contents and history are not read.
|
||||
ForbiddenFiles []string
|
||||
Go GoValidationSpec
|
||||
// GoFormat checks the formatting of committed regular Go source files. It
|
||||
// does not modify repository contents and is disabled when false.
|
||||
GoFormat bool
|
||||
@@ -76,7 +115,7 @@ type FileSizeValidationSpec struct {
|
||||
// LimitBytes is the maximum decimal byte count. Nil selects 1,000,000;
|
||||
// zero is a zero-byte limit, and negative values are invalid.
|
||||
LimitBytes *int64
|
||||
// Exclusions are literal repository-relative file or directory paths.
|
||||
// Exclusions are literal module-relative file or directory paths.
|
||||
// A directory exclusion includes committed descendants.
|
||||
Exclusions []string
|
||||
}
|
||||
@@ -88,7 +127,8 @@ type ModuleDistributionValidationSpec struct {
|
||||
// nested paths and symlink entries. It does not select Go's test workspace.
|
||||
WorkspaceFiles bool
|
||||
// LocalReplacements rejects filesystem replacements in committed go.mod
|
||||
// declarations, including nested modules. It does not select Go's workspace.
|
||||
// declarations in the selected inputs, including vendor and explicit shared
|
||||
// files. It does not select Go's workspace.
|
||||
LocalReplacements bool
|
||||
}
|
||||
|
||||
@@ -107,21 +147,24 @@ type GoValidationSpec struct {
|
||||
}
|
||||
|
||||
// Check validates one local, committed release candidate. It requires a clean
|
||||
// worktree and index on main, a committed note matching Product and Version,
|
||||
// and an unused local tag. It always runs the offline Go test suite with the
|
||||
// available compatible local Go toolchain and Go host target, then calls
|
||||
// worktree and index on main, a committed source-local note matching Product
|
||||
// and Version, and an unused local tag. A Go selection also requires a module
|
||||
// declaration. Nil Source retains the ModuleDir Go-module shorthand. Check
|
||||
// runs the offline Go test suite when Go is enabled, then calls
|
||||
// AdditionalChecks when supplied. Validation.Go.Race runs that one suite with
|
||||
// the race detector, Validation.Go.FullVet runs go vet after the suite instead
|
||||
// of test-time vet, and Validation.Go.CompileTargets compiles all packages for
|
||||
// each selected GOOS/GOARCH pair after tests and vet with cgo disabled. Package
|
||||
// compilation produces no artifacts and does not execute target binaries.
|
||||
// Validation.ForbiddenFiles checks that selected repository-relative files are
|
||||
// absent from the captured commit after Go checks and before other file checks.
|
||||
// Validation.GoFormat checks regular committed Go source after those selected
|
||||
// Go checks and before AdditionalChecks. Its zero value disables formatting.
|
||||
// Validation.ModuleDistribution.WorkspaceFiles rejects committed workspace
|
||||
// files after formatting. Its zero value disables that distribution check and
|
||||
// does not change Go's workspace environment.
|
||||
// Validation.ModuleDistribution.LocalReplacements parses committed go.mod
|
||||
// declarations, including nested modules, and rejects filesystem replacements
|
||||
// declarations in the selected inputs and rejects filesystem replacements
|
||||
// after workspace-file inspection. Its zero value disables that check.
|
||||
// Validation.FileSize checks each selected committed blob after module
|
||||
// distribution checks. Its nil value disables size checks; an empty object
|
||||
@@ -131,7 +174,7 @@ type GoValidationSpec struct {
|
||||
// Nil disables the check; an empty object enables it. Outside-checkout
|
||||
// destinations are reported as out of scope unless the selected specification
|
||||
// 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
|
||||
// storage outside the worktree, then rechecks
|
||||
// branch, HEAD, worktree, index, and local tag state. Success establishes local
|
||||
@@ -139,43 +182,72 @@ type GoValidationSpec struct {
|
||||
func Check(ctx context.Context, request ReleaseRequest) (Candidate, error) {
|
||||
checked, err := candidate.Check(ctx, candidateRequest(request))
|
||||
if err != nil {
|
||||
return Candidate{}, convertValidationError(err)
|
||||
return publicCandidate(checked), convertValidationError(err)
|
||||
}
|
||||
return publicCandidate(checked), nil
|
||||
}
|
||||
|
||||
func publicCandidate(checked candidate.Candidate) Candidate {
|
||||
return Candidate{
|
||||
RepositoryDir: checked.RepositoryDir,
|
||||
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,
|
||||
ModulePath: checked.ModulePath,
|
||||
Tag: checked.Tag,
|
||||
Commit: checked.Commit,
|
||||
Version: checked.Version,
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
func candidateRequest(request ReleaseRequest) candidate.Request {
|
||||
fileSize := internalFileSizeSettings(request.Validation.FileSize)
|
||||
result := candidate.Request{
|
||||
RepositoryDir: request.RepositoryDir,
|
||||
Product: request.Product,
|
||||
Version: request.Version,
|
||||
Validation: validation.Settings{
|
||||
Race: request.Validation.Go.Race,
|
||||
FullVet: request.Validation.Go.FullVet,
|
||||
CompileTargets: make([]validation.Target, len(request.Validation.Go.CompileTargets)),
|
||||
GoFormat: request.Validation.GoFormat,
|
||||
Markdown: internalMarkdownSettings(request.Validation.Markdown),
|
||||
ModuleDistribution: validation.ModuleDistributionSettings{
|
||||
WorkspaceFiles: request.Validation.ModuleDistribution.WorkspaceFiles,
|
||||
LocalReplacements: request.Validation.ModuleDistribution.LocalReplacements,
|
||||
},
|
||||
FileSize: fileSize,
|
||||
},
|
||||
RepositoryDir: request.RepositoryDir,
|
||||
ModuleDir: request.ModuleDir,
|
||||
Source: internalSourceSpec(request.Source),
|
||||
BuildTargets: request.Build != nil && len(request.Build.Targets) != 0,
|
||||
Product: request.Product,
|
||||
Version: request.Version,
|
||||
Validation: internalValidationSpec(request.Validation),
|
||||
AdditionalChecks: candidateChecks(request.AdditionalChecks),
|
||||
AfterValidate: internalbuild.CandidateCallback(internalBuildSpec(request.Build), request.Output),
|
||||
Output: request.Output,
|
||||
}
|
||||
for index, target := range request.Validation.Go.CompileTargets {
|
||||
result.Validation.CompileTargets[index] = validation.Target{OS: target.OS, Arch: target.Arch}
|
||||
return result
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
func copyStringSlice(values []string) []string {
|
||||
if values == nil {
|
||||
return nil
|
||||
}
|
||||
return append(make([]string, 0, len(values)), values...)
|
||||
}
|
||||
|
||||
func internalMarkdownSettings(spec *MarkdownValidationSpec) *validation.MarkdownSettings {
|
||||
if spec == nil {
|
||||
return nil
|
||||
@@ -203,10 +275,6 @@ func candidateChecks(checks func(context.Context, Candidate) error) func(context
|
||||
return nil
|
||||
}
|
||||
return func(ctx context.Context, captured candidate.Candidate) error {
|
||||
return checks(ctx, Candidate{
|
||||
RepositoryDir: captured.RepositoryDir,
|
||||
Commit: captured.Commit,
|
||||
Version: captured.Version,
|
||||
})
|
||||
return checks(ctx, publicCandidate(captured))
|
||||
}
|
||||
}
|
||||
|
||||
38
check_request_test.go
Normal file
38
check_request_test.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package releasekit
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestCandidateRequestPreservesSharedFileSelection(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
input []string
|
||||
wantNil bool
|
||||
wantValues []string
|
||||
}{
|
||||
{name: "omitted defaults", input: nil, wantNil: true},
|
||||
{name: "explicit empty", input: []string{}, wantValues: []string{}},
|
||||
{name: "explicit paths", input: []string{"LICENSE", "docs/shared.md"}, wantValues: []string{"LICENSE", "docs/shared.md"}},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
request := ReleaseRequest{Validation: ValidationSpec{SharedFiles: tt.input}}
|
||||
mapped := candidateRequest(request).Validation.SharedFiles
|
||||
if (mapped == nil) != tt.wantNil {
|
||||
t.Fatalf("mapped shared files nil=%t, want %t", mapped == nil, tt.wantNil)
|
||||
}
|
||||
if len(mapped) != len(tt.wantValues) {
|
||||
t.Fatalf("mapped shared files = %#v, want %#v", mapped, tt.wantValues)
|
||||
}
|
||||
for index, value := range tt.wantValues {
|
||||
if mapped[index] != value {
|
||||
t.Fatalf("mapped shared files = %#v, want %#v", mapped, tt.wantValues)
|
||||
}
|
||||
}
|
||||
if len(tt.input) != 0 {
|
||||
request.Validation.SharedFiles[0] = "changed"
|
||||
if mapped[0] != tt.wantValues[0] {
|
||||
t.Fatal("mapped shared-file selection aliases the caller's slice")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
381
cmd/releasekit/assembled_rehearsal_test.go
Normal file
381
cmd/releasekit/assembled_rehearsal_test.go
Normal 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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
103
cmd/releasekit/assets_test.go
Normal file
103
cmd/releasekit/assets_test.go
Normal file
@@ -0,0 +1,103 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
|
||||
)
|
||||
|
||||
func TestBuildAndPrebuiltDeliveryUseSameDirectoryBase(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name, module string
|
||||
absolute bool
|
||||
alias bool
|
||||
}{
|
||||
{name: "root relative"},
|
||||
{name: "nested relative", module: "apps/widget"},
|
||||
{name: "nested absolute", module: "apps/widget", absolute: true},
|
||||
{name: "nested checkout alias", module: "apps/widget", absolute: true, alias: true},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
repository := newDeliveryBuildRepository(t)
|
||||
moduleDirectory := repository
|
||||
tag := "v1.2.3"
|
||||
if tt.module != "" {
|
||||
moduleDirectory = filepath.Join(repository, filepath.FromSlash(tt.module))
|
||||
tag = tt.module + "/v1.2.3"
|
||||
for _, name := range []string{"go.mod", "main.go", "docs/releases/v1.2.3.md"} {
|
||||
contents, err := os.ReadFile(filepath.Join(repository, filepath.FromSlash(name)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writeRepositoryFile(t, repository, tt.module+"/"+name, string(contents))
|
||||
}
|
||||
}
|
||||
writeRepositoryFile(t, repository, ".gitignore", "dist/\n")
|
||||
state := &deliveryServerState{data: deliveryServerData{tag: tag}}
|
||||
server := newDeliveryServer(t, state)
|
||||
defer server.Close()
|
||||
settings := cli.Settings{Product: "Example Product", ModuleDir: tt.module,
|
||||
Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}},
|
||||
Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example"},
|
||||
}
|
||||
writeDeliveryProfile(t, repository, settings)
|
||||
cliGitRun(t, repository, "add", ".")
|
||||
cliGitRun(t, repository, "commit", "-m", "Prepare module source and output exclusion")
|
||||
state.update(func(state *deliveryServerData) { state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") })
|
||||
cliGitRun(t, repository, "tag", tag)
|
||||
output, resolved := "dist", filepath.Join(moduleDirectory, "dist")
|
||||
if tt.absolute {
|
||||
output = filepath.Join(t.TempDir(), "assets")
|
||||
resolved = output
|
||||
}
|
||||
var stdout, stderr bytes.Buffer
|
||||
invocationRepository := repository
|
||||
if tt.alias {
|
||||
invocationRepository = filepath.Join(t.TempDir(), "checkout-alias")
|
||||
if err := os.Symlink(repository, invocationRepository); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if status := run(context.Background(), []string{"build", "--repo", invocationRepository, "--output", output, "v1.2.3"}, &stdout, &stderr); status != 0 {
|
||||
t.Fatalf("build status=%d, stderr=%s", status, stderr.String())
|
||||
}
|
||||
receipt, err := cli.LoadBuildReceipt(filepath.Join(resolved, cli.BuildReceiptName))
|
||||
if err != nil || receipt.ModuleDir != moduleDirectory || receipt.Tag != tag {
|
||||
t.Fatalf("build receipt=%#v, error=%v", receipt, err)
|
||||
}
|
||||
t.Setenv("RELEASEKIT_GITEA_TOKEN", "fixture-token")
|
||||
args := []string{"deliver", "--repo", invocationRepository, "--assets", output, "v1.2.3"}
|
||||
stdout.Reset()
|
||||
stderr.Reset()
|
||||
if status := run(context.Background(), args, &stdout, &stderr); status != 0 || state.snapshot().releaseCreates != 1 || state.snapshot().assetUploads != 2 {
|
||||
t.Fatalf("delivery status=%d, creates=%d, uploads=%d, stderr=%s", status, state.snapshot().releaseCreates, state.snapshot().assetUploads, stderr.String())
|
||||
}
|
||||
if tt.alias {
|
||||
if status := run(context.Background(), []string{"deliver", "--repo", repository, "--assets", output, "v1.2.3"}, &stdout, &stderr); status != 0 || state.snapshot().assetUploads != 2 {
|
||||
t.Fatalf("physical-path retry status=%d, uploads=%d, stderr=%s", status, state.snapshot().assetUploads, stderr.String())
|
||||
}
|
||||
}
|
||||
if tt.module != "" {
|
||||
cliGitRun(t, repository, "tag", "v1.2.3")
|
||||
wrongModule := settings
|
||||
wrongModule.ModuleDir = ""
|
||||
invocation := cli.Invocation{Repository: repository, AssetsDir: resolved, Version: "v1.2.3"}
|
||||
requestsBefore := state.snapshot().apiRequests
|
||||
if status := deliverWithSettings(context.Background(), invocation, wrongModule, &stdout, &stderr); status != 1 || state.snapshot().apiRequests != requestsBefore {
|
||||
t.Fatalf("wrong module status=%d, requests=%d->%d, stderr=%s", status, requestsBefore, state.snapshot().apiRequests, stderr.String())
|
||||
}
|
||||
}
|
||||
if err := os.WriteFile(receipt.Artifacts[0].Path, []byte("changed"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writesBefore := state.snapshot().writes
|
||||
if status := run(context.Background(), args, &stdout, &stderr); status != 1 || state.snapshot().writes != writesBefore {
|
||||
t.Fatalf("changed content status=%d, writes=%d->%d, stderr=%s", status, writesBefore, state.snapshot().writes, stderr.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
60
cmd/releasekit/ci_identity_test.go
Normal file
60
cmd/releasekit/ci_identity_test.go
Normal file
@@ -0,0 +1,60 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
|
||||
)
|
||||
|
||||
func TestCIDeliveryRejectsModuleTagMismatchBeforePreparation(t *testing.T) {
|
||||
for _, binary := range []bool{false, true} {
|
||||
name := "page-only"
|
||||
if binary {
|
||||
name = "binary"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
repository := newDeliveryBuildRepository(t)
|
||||
writeRepositoryFile(t, repository, "child/go.mod", "module example.com/tagged-app/child\n\ngo 1.26.0\n")
|
||||
writeRepositoryFile(t, repository, "child/docs/releases/v1.2.3.md", "# Example Product v1.2.3\n\nChild release.\n")
|
||||
cliGitRun(t, repository, "add", "child")
|
||||
cliGitRun(t, repository, "commit", "-m", "add child module")
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
t.Errorf("mismatched module tag reached forge: %s", r.URL.Path)
|
||||
http.Error(w, "unexpected request", http.StatusInternalServerError)
|
||||
}))
|
||||
defer server.Close()
|
||||
settings := cli.Settings{
|
||||
Product: "Example Product", ModuleDir: "child",
|
||||
Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example"},
|
||||
}
|
||||
if binary {
|
||||
settings.Build = &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}}
|
||||
}
|
||||
writeDeliveryProfile(t, repository, settings)
|
||||
commit := pushTaggedCLIRepository(t, repository)
|
||||
t.Setenv("RELEASEKIT_GITEA_TOKEN", "fixture-token")
|
||||
shimDir := t.TempDir()
|
||||
marker := filepath.Join(shimDir, "go-invoked")
|
||||
if err := os.WriteFile(filepath.Join(shimDir, "go"), []byte("#!/bin/sh\n: > \"$RELEASEKIT_GO_MARKER\"\nexit 99\n"), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("RELEASEKIT_GO_MARKER", marker)
|
||||
t.Setenv("PATH", shimDir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||
var stdout, stderr bytes.Buffer
|
||||
status := run(context.Background(), []string{"ci-deliver", "--repo", repository, "--prepared", "--commit", commit, "--expected-module", "child", "v1.2.3"}, &stdout, &stderr)
|
||||
if status != 1 || !strings.Contains(stderr.String(), `expected delivery tag "v1.2.3"`) || !strings.Contains(stderr.String(), `selected source tag "child/v1.2.3"`) {
|
||||
t.Fatalf("status=%d stderr=%q, want module tag mismatch", status, stderr.String())
|
||||
}
|
||||
if _, err := os.Stat(marker); !os.IsNotExist(err) {
|
||||
t.Fatalf("dependency/build work ran before tag comparison: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
71
cmd/releasekit/committed_identity_test.go
Normal file
71
cmd/releasekit/committed_identity_test.go
Normal file
@@ -0,0 +1,71 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
|
||||
)
|
||||
|
||||
func TestCandidateCheckUsesCommittedDeclarationSymlink(t *testing.T) {
|
||||
repository := newCLIRepository(t)
|
||||
if err := os.Rename(filepath.Join(repository, "go.mod"), filepath.Join(repository, "module.txt")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink("module.txt", filepath.Join(repository, "go.mod")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writeDeliveryProfile(t, repository, cli.Settings{Product: "Example Product"})
|
||||
cliGitRun(t, repository, "add", ".")
|
||||
cliGitRun(t, repository, "commit", "-m", "Use committed declaration symlink")
|
||||
var stdout, stderr bytes.Buffer
|
||||
if status := run(context.Background(), []string{"check", "--repo", repository, "v1.2.3"}, &stdout, &stderr); status != 0 {
|
||||
t.Fatalf("linked declaration check status=%d stderr=%s", status, stderr.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestPageOnlyDeliveryUsesCommittedModuleInSparseCheckout(t *testing.T) {
|
||||
repository := newCLIRepository(t)
|
||||
const module = "apps/widget"
|
||||
writeRepositoryFile(t, repository, module+"/go.mod", "module example.com/widget\n\ngo 1.26.0\n")
|
||||
writeRepositoryFile(t, repository, module+"/docs/releases/v1.2.3.md", "# Example Product v1.2.3\n\nNested release note.\n")
|
||||
cliGitRun(t, repository, "add", ".")
|
||||
cliGitRun(t, repository, "commit", "-m", "Add sparse release module")
|
||||
state := &deliveryServerState{data: deliveryServerData{tag: module + "/v1.2.3"}}
|
||||
server := newDeliveryServer(t, state)
|
||||
defer server.Close()
|
||||
writeDeliveryProfile(t, repository, cli.Settings{Product: "Example Product", ModuleDir: module,
|
||||
Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example"},
|
||||
})
|
||||
state.update(func(state *deliveryServerData) { state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") })
|
||||
cliGitRun(t, repository, "tag", state.snapshot().tag)
|
||||
cliGitRun(t, repository, "checkout", "--detach", state.snapshot().tag)
|
||||
cliGitRun(t, repository, "sparse-checkout", "set", "--cone", "docs")
|
||||
if _, err := os.Stat(filepath.Join(repository, filepath.FromSlash(module))); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("module fixture is materialized: %v", err)
|
||||
}
|
||||
t.Setenv("RELEASEKIT_GITEA_TOKEN", "fixture-token")
|
||||
gitOnly := t.TempDir()
|
||||
gitPath, err := exec.LookPath("git")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(gitPath, filepath.Join(gitOnly, "git")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("PATH", gitOnly)
|
||||
for _, args := range [][]string{
|
||||
{"deliver", "--repo", repository, "v1.2.3"},
|
||||
{"ci-deliver", "--repo", repository, "--prepared", "--expected-module", module, "--commit", state.snapshot().commit, state.snapshot().tag},
|
||||
} {
|
||||
var stdout, stderr bytes.Buffer
|
||||
if status := run(context.Background(), args, &stdout, &stderr); status != 0 || state.snapshot().releaseCreates != 1 || state.snapshot().assetUploads != 0 {
|
||||
t.Fatalf("%s sparse delivery status=%d creates=%d uploads=%d stderr=%s", args[0], status, state.snapshot().releaseCreates, state.snapshot().assetUploads, stderr.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
71
cmd/releasekit/delivery_status_test.go
Normal file
71
cmd/releasekit/delivery_status_test.go
Normal file
@@ -0,0 +1,71 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
|
||||
)
|
||||
|
||||
func TestDeliveryFailureStatusesRespectPhase(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name, rejectedPath, state string
|
||||
cancelWrite bool
|
||||
status int
|
||||
}{
|
||||
{name: "preflight authorization", rejectedPath: "/api/v1/repos/owner/example", state: "not_attempted", status: 2},
|
||||
{name: "later authorization", rejectedPath: "/api/v1/repos/owner/example/tags/v1.2.3", state: "not_attempted", status: 1},
|
||||
{name: "canceled unresolved write", cancelWrite: true, state: "unknown", status: 3},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
repository := newCLIRepository(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
var commit string
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == test.rejectedPath {
|
||||
http.Error(w, "rejected credential", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
switch r.URL.Path {
|
||||
case "/api/v1/repos/owner/example", "/api/v1/repositories/1":
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"id": 1, "name": "example", "full_name": "owner/example", "owner": map[string]string{"login": "owner"}})
|
||||
case "/api/v1/repos/owner/example/tags/v1.2.3":
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"commit": map[string]string{"sha": commit}})
|
||||
case "/api/v1/repos/owner/example/releases/tags/v1.2.3":
|
||||
http.NotFound(w, r)
|
||||
case "/api/v1/repos/owner/example/releases":
|
||||
if r.Method != http.MethodPost || !test.cancelWrite {
|
||||
t.Errorf("unexpected release write: %s", r.Method)
|
||||
}
|
||||
cancel()
|
||||
http.Error(w, "unacknowledged write", http.StatusServiceUnavailable)
|
||||
default:
|
||||
t.Errorf("unexpected request: %s", r.URL.Path)
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
writeDeliveryProfile(t, repository, cli.Settings{
|
||||
Product: "Example Product",
|
||||
Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example"},
|
||||
})
|
||||
commit = cliGitOutput(t, repository, "rev-parse", "HEAD")
|
||||
cliGitRun(t, repository, "tag", "v1.2.3")
|
||||
t.Setenv("RELEASEKIT_GITEA_TOKEN", "fixture-token")
|
||||
var stdout, stderr bytes.Buffer
|
||||
status := run(ctx, []string{"deliver", "--repo", repository, "v1.2.3"}, &stdout, &stderr)
|
||||
if status != test.status || !strings.Contains(stderr.String(), "state="+test.state) {
|
||||
t.Fatalf("status=%d stderr=%q, want status %d and state %s", status, stderr.String(), test.status, test.state)
|
||||
}
|
||||
if test.cancelWrite && !strings.Contains(stderr.String(), context.Canceled.Error()) {
|
||||
t.Fatalf("cancellation cause missing: %s", stderr.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
64
cmd/releasekit/destination_test.go
Normal file
64
cmd/releasekit/destination_test.go
Normal file
@@ -0,0 +1,64 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
|
||||
)
|
||||
|
||||
func TestInvalidDeliveryDestinationStopsBeforePreparation(t *testing.T) {
|
||||
for _, command := range []string{"deliver", "ci-deliver"} {
|
||||
for _, setting := range []string{"URL", "owner", "repository"} {
|
||||
t.Run(command+"/"+setting, func(t *testing.T) {
|
||||
repository := newDeliveryBuildRepository(t)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
t.Errorf("invalid destination made a hosted request: %s", r.URL.Path)
|
||||
http.Error(w, "unexpected request", http.StatusInternalServerError)
|
||||
}))
|
||||
defer server.Close()
|
||||
destination := &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example", Credentials: &cli.DeliveryCredentials{CI: &cli.CICredential{TokenEnvironmentVariable: "RELEASEKIT_TEST_DELIVERY_TOKEN"}}}
|
||||
switch setting {
|
||||
case "URL":
|
||||
destination.BaseURL = "ssh://forge.example"
|
||||
case "owner":
|
||||
destination.Owner = "owner/child"
|
||||
case "repository":
|
||||
destination.Repository = "repo/child"
|
||||
}
|
||||
writeDeliveryProfile(t, repository, cli.Settings{
|
||||
Product: "Example Product", Delivery: destination,
|
||||
Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}},
|
||||
})
|
||||
commit := pushTaggedCLIRepository(t, repository)
|
||||
t.Setenv("RELEASEKIT_TEST_DELIVERY_TOKEN", "fixture-token")
|
||||
shimDir := t.TempDir()
|
||||
marker := filepath.Join(shimDir, "go-invoked")
|
||||
if err := os.WriteFile(filepath.Join(shimDir, "go"), []byte("#!/bin/sh\n: > \"$RELEASEKIT_GO_MARKER\"\nexit 99\n"), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("RELEASEKIT_GO_MARKER", marker)
|
||||
t.Setenv("PATH", shimDir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||
args := []string{command, "--repo", repository}
|
||||
if command == "ci-deliver" {
|
||||
args = append(args, "--prepared", "--commit", commit)
|
||||
}
|
||||
args = append(args, "v1.2.3")
|
||||
var stdout, stderr bytes.Buffer
|
||||
status := run(context.Background(), args, &stdout, &stderr)
|
||||
if status != 2 || !strings.Contains(stderr.String(), "invalid_destination") {
|
||||
t.Fatalf("status=%d stderr=%q, want destination configuration error", status, stderr.String())
|
||||
}
|
||||
if _, err := os.Stat(marker); !os.IsNotExist(err) {
|
||||
t.Fatalf("preparation/build ran for invalid destination: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
97
cmd/releasekit/diagnostic.go
Normal file
97
cmd/releasekit/diagnostic.go
Normal 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
|
||||
}
|
||||
256
cmd/releasekit/diagnostic_test.go
Normal file
256
cmd/releasekit/diagnostic_test.go
Normal 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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
54
cmd/releasekit/example_source_test.go
Normal file
54
cmd/releasekit/example_source_test.go
Normal file
@@ -0,0 +1,54 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMultiModuleExampleSetupUsesCurrentSourceTool(t *testing.T) {
|
||||
root := cliRepositoryRoot(t)
|
||||
repository := newCLIRepository(t)
|
||||
copyExampleTree(t, filepath.Join(root, "examples", "multi-module"), repository)
|
||||
const module = "go.maximumdirect.net/releasekit"
|
||||
environment := append(os.Environ(), "GOTOOLCHAIN=local", "GOWORK=off", "GOPROXY=off", "GOSUMDB=off", "GOFLAGS=")
|
||||
goCommand := func(directory string, args ...string) string {
|
||||
t.Helper()
|
||||
command := exec.Command("go", args...)
|
||||
command.Dir, command.Env = directory, environment
|
||||
output, err := command.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("go %q: %v\n%s", args, err, output)
|
||||
}
|
||||
return string(output)
|
||||
}
|
||||
selections := []struct {
|
||||
directory, profile, product, version string
|
||||
}{
|
||||
{".", "releasekit-root.json", "Example Consumer", "v1.2.3"},
|
||||
{"integrations/ckconfig", "releasekit-ckconfig.json", "Example Consumer Integration", "v1.2.3"},
|
||||
{"integrations/core/v2", "releasekit-core-v2.json", "Example Consumer Core v2", "v2.1.0"},
|
||||
}
|
||||
for _, selected := range selections {
|
||||
directory := filepath.Join(repository, filepath.FromSlash(selected.directory))
|
||||
if selected.directory != "integrations/core/v2" {
|
||||
writeRepositoryFile(t, repository, selected.directory+"/source.go", "package candidate\n")
|
||||
}
|
||||
goCommand(directory, "mod", "edit", "-require="+module+"@v0.0.0", "-replace="+module+"="+root, "-tool="+module+"/cmd/releasekit")
|
||||
goCommand(directory, "mod", "tidy")
|
||||
writeRepositoryFile(t, repository, selected.directory+"/docs/releases/"+selected.version+".md", "# "+selected.product+" "+selected.version+"\n\nSource verification fixture.\n")
|
||||
}
|
||||
cliGitRun(t, repository, "add", ".")
|
||||
cliGitRun(t, repository, "commit", "-m", "Select current source in disposable example")
|
||||
for _, selected := range selections {
|
||||
output := goCommand(filepath.Join(repository, filepath.FromSlash(selected.directory)), "tool", "releasekit", "check", "--config", selected.profile, selected.version)
|
||||
if !strings.Contains(output, "is valid") {
|
||||
t.Fatalf("source-selected check output=%s", output)
|
||||
}
|
||||
}
|
||||
if status := cliGitOutput(t, repository, "status", "--porcelain"); status != "" {
|
||||
t.Fatalf("source verification changed committed fixture: %s", status)
|
||||
}
|
||||
}
|
||||
62
cmd/releasekit/internal/cli/committed_profile.go
Normal file
62
cmd/releasekit/internal/cli/committed_profile.go
Normal 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
|
||||
}
|
||||
84
cmd/releasekit/internal/cli/committed_profile_test.go
Normal file
84
cmd/releasekit/internal/cli/committed_profile_test.go
Normal 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)
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
@@ -12,33 +13,74 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.maximumdirect.net/eric/ReleaseKit/internal/process"
|
||||
"go.maximumdirect.net/releasekit/internal/process"
|
||||
"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] VERSION\n releasekit build [--repo DIR] [--config FILE] [--output DIR] VERSION\n releasekit deliver [--repo DIR] [--config FILE] [--assets DIR] VERSION\n releasekit ci-deliver [--repo DIR] [--config FILE] [--remote NAME] --commit OID VERSION"
|
||||
const Usage = "usage: releasekit version\n releasekit 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
|
||||
|
||||
const (
|
||||
VersionCommand Command = "version"
|
||||
CheckAction Command = "check"
|
||||
PublishAction Command = "publish"
|
||||
BuildAction Command = "build"
|
||||
DeliveryAction Command = "deliver"
|
||||
CIDeliveryAction Command = "ci-deliver"
|
||||
VersionCommand Command = "version"
|
||||
ValidateAction Command = "validate"
|
||||
CheckAction Command = "check"
|
||||
PublishAction Command = "publish"
|
||||
BuildAction Command = "build"
|
||||
DeliveryAction Command = "deliver"
|
||||
CIDeliveryAction Command = "ci-deliver"
|
||||
ReconcileAction Command = "reconcile"
|
||||
PublicationAttemptsAction Command = "publication-attempts"
|
||||
TestAction Command = "test"
|
||||
TestResumeAction Command = "test-resume"
|
||||
TestCleanupAction Command = "test-cleanup"
|
||||
)
|
||||
|
||||
// Invocation contains parsed command settings owned by the CLI adapter.
|
||||
type Invocation struct {
|
||||
Command Command
|
||||
Repository string
|
||||
ConfigPath string
|
||||
OutputDir string
|
||||
AssetsDir string
|
||||
Remote string
|
||||
Commit string
|
||||
Version string
|
||||
Command Command
|
||||
Repository string
|
||||
ConfigPath string
|
||||
OutputDir string
|
||||
AssetsDir string
|
||||
Remote string
|
||||
Commit string
|
||||
Version string
|
||||
ExpectedModule string
|
||||
ExpectedSource string
|
||||
ExpectedTag string
|
||||
Prepared bool
|
||||
RecordPath string
|
||||
RecordDir string
|
||||
JSON bool
|
||||
Context string
|
||||
Operations []string
|
||||
Offline bool
|
||||
Ref string
|
||||
TokenFile string
|
||||
WoodpeckerTokenFile string
|
||||
Timeout time.Duration
|
||||
CleanupTimeout time.Duration
|
||||
}
|
||||
|
||||
type operationFlags []string
|
||||
|
||||
func (values *operationFlags) String() string { return strings.Join(*values, ",") }
|
||||
func (values *operationFlags) Set(value string) error {
|
||||
switch value {
|
||||
case "publication", "go", "build", "delivery", "rehearsal":
|
||||
default:
|
||||
return fmt.Errorf("unknown validation operation %q", value)
|
||||
}
|
||||
for _, existing := range *values {
|
||||
if existing == value {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
*values = append(*values, value)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Parse accepts only commands that have been implemented by the executable.
|
||||
@@ -47,6 +89,87 @@ func Parse(args []string) (Invocation, error) {
|
||||
return Invocation{}, errors.New("a command is required")
|
||||
}
|
||||
switch args[0] {
|
||||
case string(TestAction), string(TestResumeAction), string(TestCleanupAction):
|
||||
action := Command(args[0])
|
||||
flags := flag.NewFlagSet(string(action), flag.ContinueOnError)
|
||||
flags.SetOutput(io.Discard)
|
||||
invocation := Invocation{Command: action, Timeout: 30 * time.Minute, CleanupTimeout: 2 * time.Minute}
|
||||
if action == TestAction {
|
||||
flags.StringVar(&invocation.Repository, "repo", ".", "repository directory")
|
||||
flags.StringVar(&invocation.ConfigPath, "config", "", "committed profile path")
|
||||
flags.StringVar(&invocation.Ref, "ref", "", "source commit")
|
||||
flags.StringVar(&invocation.RecordDir, "record-dir", "", "attempt record directory")
|
||||
} else {
|
||||
flags.StringVar(&invocation.RecordPath, "record", "", "attempt record file")
|
||||
flags.StringVar(&invocation.TokenFile, "token-file", "", "delivery token file override")
|
||||
flags.StringVar(&invocation.WoodpeckerTokenFile, "woodpecker-token-file", "", "Woodpecker token file override")
|
||||
}
|
||||
if action != TestCleanupAction {
|
||||
flags.DurationVar(&invocation.Timeout, "timeout", 30*time.Minute, "CI observation timeout")
|
||||
}
|
||||
flags.DurationVar(&invocation.CleanupTimeout, "cleanup-timeout", 2*time.Minute, "cleanup timeout")
|
||||
flags.BoolVar(&invocation.JSON, "json", false, "write structured JSON")
|
||||
if err := flags.Parse(args[1:]); err != nil {
|
||||
return Invocation{}, err
|
||||
}
|
||||
if flags.NArg() != 0 {
|
||||
return Invocation{}, fmt.Errorf("%s takes no positional arguments", action)
|
||||
}
|
||||
if action != TestAction && strings.TrimSpace(invocation.RecordPath) == "" {
|
||||
return Invocation{}, fmt.Errorf("%s requires --record FILE", action)
|
||||
}
|
||||
if invocation.Timeout < 0 {
|
||||
return Invocation{}, errors.New("--timeout must not be negative")
|
||||
}
|
||||
if invocation.CleanupTimeout <= 0 {
|
||||
return Invocation{}, errors.New("--cleanup-timeout must be positive")
|
||||
}
|
||||
return invocation, nil
|
||||
case string(ValidateAction):
|
||||
flags := flag.NewFlagSet(string(ValidateAction), flag.ContinueOnError)
|
||||
flags.SetOutput(io.Discard)
|
||||
repository := flags.String("repo", ".", "repository directory")
|
||||
configPath := flags.String("config", "", "profile path")
|
||||
credentialContext := flags.String("context", "local", "credential context")
|
||||
var operations operationFlags
|
||||
flags.Var(&operations, "operation", "selected readiness operation")
|
||||
offline := flags.Bool("offline", false, "omit remote observations")
|
||||
assets := flags.String("assets", "", "existing build assets directory")
|
||||
structured := flags.Bool("json", false, "write structured JSON")
|
||||
if err := flags.Parse(args[1:]); err != nil {
|
||||
return Invocation{}, err
|
||||
}
|
||||
if flags.NArg() != 0 {
|
||||
return Invocation{}, errors.New("validate takes no positional arguments")
|
||||
}
|
||||
if *credentialContext != "local" && *credentialContext != "ci" {
|
||||
return Invocation{}, errors.New("validate --context must be local or ci")
|
||||
}
|
||||
return Invocation{Command: ValidateAction, Repository: *repository, ConfigPath: *configPath, Context: *credentialContext, Operations: operations, Offline: *offline, AssetsDir: *assets, JSON: *structured}, nil
|
||||
case string(ReconcileAction), string(PublicationAttemptsAction):
|
||||
action := Command(args[0])
|
||||
flags := flag.NewFlagSet(string(action), flag.ContinueOnError)
|
||||
flags.SetOutput(io.Discard)
|
||||
record := ""
|
||||
recordDir := ""
|
||||
repository := "."
|
||||
if action == ReconcileAction {
|
||||
flags.StringVar(&record, "record", "", "attempt record file")
|
||||
} else {
|
||||
flags.StringVar(&repository, "repo", ".", "repository directory")
|
||||
flags.StringVar(&recordDir, "record-dir", "", "attempt-record directory")
|
||||
}
|
||||
structured := flags.Bool("json", false, "write structured JSON")
|
||||
if err := flags.Parse(args[1:]); err != nil {
|
||||
return Invocation{}, err
|
||||
}
|
||||
if flags.NArg() != 0 {
|
||||
return Invocation{}, fmt.Errorf("%s takes no positional arguments", action)
|
||||
}
|
||||
if action == ReconcileAction && record == "" {
|
||||
return Invocation{}, errors.New("reconcile requires --record FILE")
|
||||
}
|
||||
return Invocation{Command: action, Repository: repository, RecordPath: record, RecordDir: recordDir, JSON: *structured}, nil
|
||||
case string(VersionCommand):
|
||||
if len(args) != 1 {
|
||||
return Invocation{}, errors.New("version takes no arguments")
|
||||
@@ -67,10 +190,22 @@ func Parse(args []string) (Invocation, error) {
|
||||
flags.StringVar(&assetsDir, "assets", "", "verified build assets directory")
|
||||
}
|
||||
var remote *string
|
||||
expectedModule := ""
|
||||
expectedSource := ""
|
||||
if action == PublishAction || action == CIDeliveryAction {
|
||||
flags.StringVar(&expectedModule, "expected-module", "", "expected module directory from a launcher mapping")
|
||||
flags.StringVar(&expectedSource, "expected-source", "", "expected source directory from a launcher mapping")
|
||||
}
|
||||
recordDir := ""
|
||||
if action == PublishAction {
|
||||
flags.StringVar(&recordDir, "record-dir", "", "publication attempt-record directory")
|
||||
}
|
||||
expectedCommit := ""
|
||||
prepared := false
|
||||
if action == CIDeliveryAction {
|
||||
remote = flags.String("remote", "origin", "Git remote")
|
||||
flags.StringVar(&expectedCommit, "commit", "", "expected tagged commit")
|
||||
flags.BoolVar(&prepared, "prepared", false, "verify an already prepared tagged checkout without fetching or checkout")
|
||||
}
|
||||
if err := flags.Parse(args[1:]); err != nil {
|
||||
return Invocation{}, err
|
||||
@@ -84,11 +219,19 @@ func Parse(args []string) (Invocation, error) {
|
||||
if action == CIDeliveryAction && !validGitObjectID(expectedCommit) {
|
||||
return Invocation{}, errors.New("ci-deliver --commit must be a full Git object ID")
|
||||
}
|
||||
version := flags.Arg(0)
|
||||
expectedTag := ""
|
||||
if action == CIDeliveryAction {
|
||||
expectedTag = version
|
||||
if slash := strings.LastIndex(version, "/"); slash >= 0 {
|
||||
version = version[slash+1:]
|
||||
}
|
||||
}
|
||||
parsedRemote := ""
|
||||
if remote != nil {
|
||||
parsedRemote = *remote
|
||||
}
|
||||
return Invocation{Command: action, Repository: *repository, ConfigPath: *configPath, OutputDir: outputDir, AssetsDir: assetsDir, Remote: parsedRemote, Commit: expectedCommit, Version: flags.Arg(0)}, nil
|
||||
return Invocation{Command: action, Repository: *repository, ConfigPath: *configPath, OutputDir: outputDir, AssetsDir: assetsDir, Remote: parsedRemote, Commit: expectedCommit, Version: version, ExpectedModule: expectedModule, ExpectedSource: expectedSource, ExpectedTag: expectedTag, Prepared: prepared, RecordDir: recordDir}, nil
|
||||
default:
|
||||
return Invocation{}, fmt.Errorf("unknown command %q", args[0])
|
||||
}
|
||||
@@ -115,18 +258,89 @@ type CheckCommand struct {
|
||||
// Settings contains the product, remote, publication expectation, shared
|
||||
// validation selections, and check commands read from a releasekit.json profile.
|
||||
type Settings struct {
|
||||
Product string `json:"product"`
|
||||
Remote string `json:"remote,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"`
|
||||
Product string `json:"product"`
|
||||
ModuleDir string `json:"module_dir,omitempty"`
|
||||
Source *SourceSettings `json:"source,omitempty"`
|
||||
Go *struct{} `json:"go,omitempty"`
|
||||
Publication *PublicationSettings `json:"publication,omitempty"`
|
||||
Version *VersionSettings `json:"version,omitempty"`
|
||||
Remote string `json:"remote,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.
|
||||
type ValidationSettings struct {
|
||||
Go GoValidationSettings `json:"go,omitempty"`
|
||||
// SharedFiles selects committed files relative to the repository root.
|
||||
// Nil uses optional defaults; a non-nil empty slice selects no shared files.
|
||||
SharedFiles []string `json:"shared_files"`
|
||||
ForbiddenFiles []string `json:"forbidden_files,omitempty"`
|
||||
Go GoValidationSettings `json:"go,omitempty"`
|
||||
// GoFormat checks the formatting of committed regular Go source files.
|
||||
// Omitted or false disables the check.
|
||||
GoFormat bool `json:"go_format,omitempty"`
|
||||
@@ -167,12 +381,28 @@ type GoValidationSettings struct {
|
||||
CompileTargets []string `json:"compile_targets,omitempty"`
|
||||
}
|
||||
|
||||
// DeliverySettings selects the hosted Gitea release destination.
|
||||
// DeliverySettings selects the hosted forge release destination.
|
||||
type DeliverySettings struct {
|
||||
BaseURL string `json:"base_url"`
|
||||
Owner string `json:"owner"`
|
||||
Repository string `json:"repository"`
|
||||
TokenEnv string `json:"token_env,omitempty"`
|
||||
Forge string `json:"forge,omitempty"`
|
||||
BaseURL string `json:"base_url"`
|
||||
Owner string `json:"owner"`
|
||||
Repository string `json:"repository"`
|
||||
Credentials *DeliveryCredentials `json:"credentials,omitempty"`
|
||||
LegacyTokenEnv json.RawMessage `json:"token_env,omitempty"`
|
||||
LegacyTokenFile json.RawMessage `json:"token_file,omitempty"`
|
||||
}
|
||||
|
||||
type DeliveryCredentials struct {
|
||||
Local *LocalCredential `json:"local,omitempty"`
|
||||
CI *CICredential `json:"ci,omitempty"`
|
||||
}
|
||||
|
||||
type LocalCredential struct {
|
||||
TokenFile string `json:"token_file"`
|
||||
}
|
||||
|
||||
type CICredential struct {
|
||||
TokenEnvironmentVariable string `json:"token_environment_variable,omitempty"`
|
||||
}
|
||||
|
||||
// BuildSettings selects the Go application package, artifact name, and targets.
|
||||
@@ -201,9 +431,17 @@ func LoadSettings(repoDir, configPath string) (Settings, error) {
|
||||
return Settings{}, fmt.Errorf("open profile %q: %w", configPath, err)
|
||||
}
|
||||
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
|
||||
decoder := json.NewDecoder(file)
|
||||
decoder := json.NewDecoder(input)
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&settings); err != nil {
|
||||
return Settings{}, fmt.Errorf("decode profile %q: %w", configPath, err)
|
||||
@@ -219,6 +457,20 @@ func LoadSettings(repoDir, configPath string) (Settings, error) {
|
||||
if strings.TrimSpace(settings.Product) == "" {
|
||||
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 == "" {
|
||||
settings.Remote = "origin"
|
||||
}
|
||||
@@ -269,9 +521,9 @@ func LoadSettings(repoDir, configPath string) (Settings, error) {
|
||||
return settings, nil
|
||||
}
|
||||
|
||||
// RunChecks runs configured argument vectors in repoDir. Each command receives
|
||||
// RunChecks runs configured argument vectors in dir. Each command receives
|
||||
// its own environment overlay and inherits the remaining process environment.
|
||||
func RunChecks(ctx context.Context, repoDir string, checks []CheckCommand, ownedEnv map[string]string, stdout, stderr io.Writer) error {
|
||||
func RunChecks(ctx context.Context, dir string, checks []CheckCommand, ownedEnv map[string]string, stdout, stderr io.Writer) error {
|
||||
for i, check := range checks {
|
||||
environment := make(map[string]string, len(check.Env)+len(ownedEnv))
|
||||
for key, value := range check.Env {
|
||||
@@ -282,7 +534,7 @@ func RunChecks(ctx context.Context, repoDir string, checks []CheckCommand, owned
|
||||
}
|
||||
if err := process.Run(ctx, process.Invocation{
|
||||
Args: check.Args,
|
||||
Dir: repoDir,
|
||||
Dir: dir,
|
||||
Env: environment,
|
||||
Stdout: stdout,
|
||||
Stderr: stderr,
|
||||
|
||||
@@ -19,6 +19,33 @@ func TestParse(t *testing.T) {
|
||||
if invocation.Command != VersionCommand {
|
||||
t.Fatalf("Parse() command = %q, want %q", invocation.Command, VersionCommand)
|
||||
}
|
||||
reconcile, err := Parse([]string{"reconcile", "--record", "records/release record's.json", "--json"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if reconcile.Command != ReconcileAction || reconcile.RecordPath != "records/release record's.json" || !reconcile.JSON {
|
||||
t.Fatalf("Parse(reconcile) = %#v", reconcile)
|
||||
}
|
||||
attempts, err := Parse([]string{"publication-attempts", "--repo", "repository with spaces", "--record-dir", "records with spaces", "--json"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if attempts.Command != PublicationAttemptsAction || attempts.Repository != "repository with spaces" || attempts.RecordDir != "records with spaces" || !attempts.JSON {
|
||||
t.Fatalf("Parse(publication-attempts) = %#v", attempts)
|
||||
}
|
||||
for _, args := range [][]string{
|
||||
{"reconcile"},
|
||||
{"reconcile", "record.json"},
|
||||
{"reconcile", "--record", "record.json", "--repo", "."},
|
||||
{"reconcile", "--record", "record.json", "--record-dir", "records"},
|
||||
{"reconcile", "--record", "record.json", "VERSION"},
|
||||
{"publication-attempts", "--record", "record.json"},
|
||||
{"publication-attempts", "VERSION"},
|
||||
} {
|
||||
if _, err := Parse(args); err == nil {
|
||||
t.Errorf("Parse(%q) succeeded, want a usage error", args)
|
||||
}
|
||||
}
|
||||
check, err := Parse([]string{"check", "--repo", "repository with spaces", "--config", "profiles/release config.json", "v1.2.3"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -26,13 +53,24 @@ func TestParse(t *testing.T) {
|
||||
if check.Command != CheckAction || check.Repository != "repository with spaces" || check.ConfigPath != "profiles/release config.json" || check.Version != "v1.2.3" {
|
||||
t.Fatalf("Parse(check) = %#v", check)
|
||||
}
|
||||
publish, err := Parse([]string{"publish", "--repo", "candidate", "--config", "releasekit.json", "v1.2.4"})
|
||||
publish, err := Parse([]string{"publish", "--repo", "candidate", "--config", "releasekit.json", "--record-dir", "attempt records", "v1.2.4"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if publish.Command != PublishAction || publish.Repository != "candidate" || publish.ConfigPath != "releasekit.json" || publish.Version != "v1.2.4" {
|
||||
if publish.Command != PublishAction || publish.Repository != "candidate" || publish.ConfigPath != "releasekit.json" || publish.RecordDir != "attempt records" || publish.Version != "v1.2.4" {
|
||||
t.Fatalf("Parse(publish) = %#v", publish)
|
||||
}
|
||||
if _, err := Parse([]string{"check", "--record-dir", "attempt records", "v1.2.4"}); err == nil {
|
||||
t.Fatal("Parse(check) accepted the publication-only record directory")
|
||||
}
|
||||
publishMapped, err := Parse([]string{"publish", "--repo", "candidate", "--expected-module", "integrations/ckconfig", "v1.2.4"})
|
||||
if err != nil || publishMapped.ExpectedModule != "integrations/ckconfig" {
|
||||
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"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -47,11 +85,11 @@ func TestParse(t *testing.T) {
|
||||
if deliver.Command != DeliveryAction || deliver.Repository != "candidate" || deliver.ConfigPath != "releasekit.json" || deliver.AssetsDir != "assets with spaces" || deliver.Version != "v1.2.6" {
|
||||
t.Fatalf("Parse(deliver) = %#v", deliver)
|
||||
}
|
||||
ciDelivery, err := Parse([]string{"ci-deliver", "--repo", "candidate", "--config", "profiles/release config.json", "--remote", "upstream", "--commit", "0123456789abcdef0123456789abcdef01234567", "v1.2.7"})
|
||||
ciDelivery, err := Parse([]string{"ci-deliver", "--repo", "candidate", "--config", "profiles/release config.json", "--remote", "upstream", "--prepared", "--expected-module", "integrations/ckconfig", "--commit", "0123456789abcdef0123456789abcdef01234567", "integrations/ckconfig/v1.2.7"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ciDelivery.Command != CIDeliveryAction || ciDelivery.Repository != "candidate" || ciDelivery.ConfigPath != "profiles/release config.json" || ciDelivery.Remote != "upstream" || ciDelivery.Commit != "0123456789abcdef0123456789abcdef01234567" || ciDelivery.Version != "v1.2.7" {
|
||||
if ciDelivery.Command != CIDeliveryAction || ciDelivery.Repository != "candidate" || ciDelivery.ConfigPath != "profiles/release config.json" || ciDelivery.Remote != "upstream" || ciDelivery.Commit != "0123456789abcdef0123456789abcdef01234567" || ciDelivery.Version != "v1.2.7" || ciDelivery.ExpectedTag != "integrations/ckconfig/v1.2.7" || ciDelivery.ExpectedModule != "integrations/ckconfig" || !ciDelivery.Prepared {
|
||||
t.Fatalf("Parse(ci-deliver) = %#v", ciDelivery)
|
||||
}
|
||||
ciDefault, err := Parse([]string{"ci-deliver", "--commit", "0123456789abcdef0123456789abcdef01234567", "v1.2.8"})
|
||||
@@ -64,6 +102,10 @@ func TestParse(t *testing.T) {
|
||||
if _, err := Parse([]string{"ci-deliver", "--commit", "abc123", "v1.2.3"}); err == nil || !strings.Contains(err.Error(), "full Git object ID") {
|
||||
t.Fatalf("Parse(ci-deliver with abbreviated commit) error = %v, want full object ID error", err)
|
||||
}
|
||||
calendar, err := Parse([]string{"ci-deliver", "--commit", "0123456789abcdef0123456789abcdef01234567", "config/2026-12-01"})
|
||||
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 {
|
||||
t.Fatal("Parse accepted a flag after the version")
|
||||
}
|
||||
@@ -115,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) {
|
||||
repoDir := t.TempDir()
|
||||
contents := `{"product":"Example"}`
|
||||
@@ -166,6 +238,56 @@ func TestLoadSettingsReadsGoValidation(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadSettingsPreservesSharedFilesSelection(t *testing.T) {
|
||||
repoDir := t.TempDir()
|
||||
profileDir := filepath.Join(repoDir, "profiles")
|
||||
if err := os.MkdirAll(profileDir, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
profile string
|
||||
wantNil bool
|
||||
wantFile string
|
||||
}{
|
||||
{name: "omitted", profile: `{"product":"Example","module_dir":"integrations/ckconfig","validation":{}}`, wantNil: true},
|
||||
{name: "null", profile: `{"product":"Example","module_dir":"integrations/ckconfig","validation":{"shared_files":null}}`, wantNil: true},
|
||||
{name: "empty", profile: `{"product":"Example","module_dir":"integrations/ckconfig","validation":{"shared_files":[]}}`},
|
||||
{name: "selected", profile: `{"product":"Example","module_dir":"integrations/ckconfig","validation":{"shared_files":["../README.md"]}}`, wantFile: "../README.md"},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
path := filepath.Join(profileDir, "release.json")
|
||||
if err := os.WriteFile(path, []byte(test.profile), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
settings, err := LoadSettings(repoDir, filepath.Join("profiles", "release.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if settings.ModuleDir != "integrations/ckconfig" {
|
||||
t.Fatalf("module_dir = %q", settings.ModuleDir)
|
||||
}
|
||||
if settings.Validation == nil || (settings.Validation.SharedFiles == nil) != test.wantNil {
|
||||
t.Fatalf("shared_files = %#v, want nil=%t", settings.Validation, test.wantNil)
|
||||
}
|
||||
if test.wantFile != "" && (len(settings.Validation.SharedFiles) != 1 || settings.Validation.SharedFiles[0] != test.wantFile) {
|
||||
t.Fatalf("shared_files = %#v, want %q", settings.Validation.SharedFiles, test.wantFile)
|
||||
}
|
||||
encoded, err := json.Marshal(settings)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var roundTrip Settings
|
||||
if err := json.Unmarshal(encoded, &roundTrip); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if (roundTrip.Validation.SharedFiles == nil) != test.wantNil {
|
||||
t.Fatalf("serialized shared_files = %#v, want nil=%t; JSON=%s", roundTrip.Validation.SharedFiles, test.wantNil, encoded)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadSettingsPreservesMarkdownObjectSelection(t *testing.T) {
|
||||
repoDir := t.TempDir()
|
||||
profilePath := filepath.Join(repoDir, "releasekit.json")
|
||||
|
||||
81
cmd/releasekit/internal/cli/credentials.go
Normal file
81
cmd/releasekit/internal/cli/credentials.go
Normal 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
|
||||
}
|
||||
@@ -8,14 +8,18 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"gitea.maximumdirect.net/eric/ReleaseKit/internal/artifact"
|
||||
"gitea.maximumdirect.net/eric/ReleaseKit/internal/versioncontract"
|
||||
"go.maximumdirect.net/releasekit/internal/artifact"
|
||||
"go.maximumdirect.net/releasekit/internal/releaseidentity"
|
||||
"go.maximumdirect.net/releasekit/internal/versioncontract"
|
||||
"golang.org/x/mod/module"
|
||||
)
|
||||
|
||||
const BuildReceiptName = ".releasekit-build.json"
|
||||
const BuildReceiptSchemaVersion = 2
|
||||
|
||||
type ReceiptTarget struct {
|
||||
OS string `json:"os"`
|
||||
@@ -31,7 +35,19 @@ type ReceiptArtifact struct {
|
||||
|
||||
// BuildReceipt is private local coordination data for generated binaries.
|
||||
type BuildReceipt struct {
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
RepositoryDir string `json:"repository_dir"`
|
||||
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"`
|
||||
ModulePath string `json:"module_path"`
|
||||
Tag string `json:"tag"`
|
||||
CandidateCommit string `json:"candidate_commit"`
|
||||
SourceVerified bool `json:"source_verified"`
|
||||
Version string `json:"version"`
|
||||
@@ -44,12 +60,16 @@ type BuildReceipt struct {
|
||||
}
|
||||
|
||||
func WriteBuildReceipt(outputDir string, receipt BuildReceipt) (string, error) {
|
||||
return writeBuildReceipt(outputDir, receipt, os.Remove)
|
||||
}
|
||||
|
||||
func writeBuildReceipt(outputDir string, receipt BuildReceipt, remove func(string) error) (resultPath string, resultErr error) {
|
||||
resolvedDir, err := filepath.Abs(outputDir)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("resolve build receipt directory: %w", err)
|
||||
}
|
||||
receipt.OutputDir = resolvedDir
|
||||
if err := validateBuildReceipt(receipt, true); err != nil {
|
||||
if err := validateBuildReceipt(receipt); err != nil {
|
||||
return "", err
|
||||
}
|
||||
contents, err := json.MarshalIndent(receipt, "", " ")
|
||||
@@ -62,7 +82,11 @@ func WriteBuildReceipt(outputDir string, receipt BuildReceipt) (string, error) {
|
||||
return "", fmt.Errorf("create temporary build receipt: %w", err)
|
||||
}
|
||||
temporaryPath := temporary.Name()
|
||||
defer os.Remove(temporaryPath)
|
||||
defer func() {
|
||||
if err := remove(temporaryPath); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
resultErr = errors.Join(resultErr, fmt.Errorf("remove temporary build receipt %q: %w", temporaryPath, err))
|
||||
}
|
||||
}()
|
||||
if _, err := temporary.Write(contents); err != nil {
|
||||
_ = temporary.Close()
|
||||
return "", fmt.Errorf("write build receipt: %w", err)
|
||||
@@ -100,7 +124,6 @@ func LoadBuildReceipt(path string) (BuildReceipt, error) {
|
||||
defer file.Close()
|
||||
var receipt BuildReceipt
|
||||
decoder := json.NewDecoder(file)
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&receipt); err != nil {
|
||||
return BuildReceipt{}, fmt.Errorf("decode build receipt: %w", err)
|
||||
}
|
||||
@@ -111,41 +134,59 @@ func LoadBuildReceipt(path string) (BuildReceipt, error) {
|
||||
}
|
||||
return BuildReceipt{}, fmt.Errorf("decode build receipt: %w", err)
|
||||
}
|
||||
if err := validateBuildReceipt(receipt, true); err != nil {
|
||||
if err := validateBuildReceipt(receipt); err != nil {
|
||||
if receipt.SchemaVersion != BuildReceiptSchemaVersion {
|
||||
return BuildReceipt{}, fmt.Errorf("%w; regenerate it with the updated build command", err)
|
||||
}
|
||||
return BuildReceipt{}, err
|
||||
}
|
||||
if filepath.Clean(receipt.OutputDir) != filepath.Dir(resolvedPath) {
|
||||
if !sameDirectory(receipt.OutputDir, filepath.Dir(resolvedPath)) {
|
||||
return BuildReceipt{}, errors.New("build receipt output directory does not match its location")
|
||||
}
|
||||
return receipt, nil
|
||||
}
|
||||
|
||||
func (receipt BuildReceipt) MatchesBuild(repositoryDir, commit, version string, settings BuildSettings) bool {
|
||||
resolvedRepo, err := filepath.Abs(repositoryDir)
|
||||
if err != nil || filepath.Clean(receipt.RepositoryDir) != filepath.Clean(resolvedRepo) {
|
||||
if !sameDirectory(receipt.RepositoryDir, repositoryDir) {
|
||||
return false
|
||||
}
|
||||
if receipt.CandidateCommit != commit || receipt.Version != version || receipt.MainPackage != settings.MainPackage || receipt.BinaryName != settings.BinaryName {
|
||||
if receipt.CandidateCommit != commit || receipt.Version != version {
|
||||
return false
|
||||
}
|
||||
want := normalizeReceiptTargets(settings.Targets)
|
||||
if len(want) != len(receipt.Targets) {
|
||||
want := artifact.NormalizeSettings(settings.MainPackage, settings.BinaryName, parseReceiptTargets(settings.Targets))
|
||||
got := artifact.NormalizeSettings(receipt.MainPackage, receipt.BinaryName, parseStoredTargets(receipt.Targets))
|
||||
if want.MainPackage != got.MainPackage || want.BinaryName != got.BinaryName || len(want.Targets) != len(got.Targets) {
|
||||
return false
|
||||
}
|
||||
for i, target := range want {
|
||||
if target != receipt.Targets[i] {
|
||||
for i, target := range want.Targets {
|
||||
if target != got.Targets[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func validateBuildReceipt(receipt BuildReceipt, verifyFiles bool) error {
|
||||
if !versioncontract.ValidStableVersion(receipt.Version) {
|
||||
return fmt.Errorf("build receipt has invalid version %q", receipt.Version)
|
||||
func sameDirectory(first, second string) bool {
|
||||
firstInfo, err := os.Stat(first)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if !filepath.IsAbs(receipt.RepositoryDir) || !filepath.IsAbs(receipt.OutputDir) {
|
||||
return errors.New("build receipt repository and output directories must be absolute")
|
||||
secondInfo, err := os.Stat(second)
|
||||
return err == nil && os.SameFile(firstInfo, secondInfo)
|
||||
}
|
||||
|
||||
func validateBuildReceipt(receipt BuildReceipt) error {
|
||||
if receipt.SchemaVersion != BuildReceiptSchemaVersion {
|
||||
return fmt.Errorf("unsupported or missing build receipt schema version %d", receipt.SchemaVersion)
|
||||
}
|
||||
if !filepath.IsAbs(receipt.RepositoryDir) || !filepath.IsAbs(receipt.SourceDir) || !filepath.IsAbs(receipt.ModuleDir) || !filepath.IsAbs(receipt.OutputDir) {
|
||||
return errors.New("build receipt repository, source, module, and output directories must be absolute")
|
||||
}
|
||||
if strings.TrimSpace(receipt.ModulePath) == "" || strings.TrimSpace(receipt.Tag) == "" {
|
||||
return errors.New("build receipt is missing module path or full tag")
|
||||
}
|
||||
if err := validateRecordedIdentity(receipt); err != nil {
|
||||
return fmt.Errorf("build receipt has inconsistent module identity: %w", err)
|
||||
}
|
||||
if !validCommitID(receipt.CandidateCommit) {
|
||||
return errors.New("build receipt has invalid candidate commit")
|
||||
@@ -156,32 +197,15 @@ func validateBuildReceipt(receipt BuildReceipt, verifyFiles bool) error {
|
||||
if len(receipt.Targets) == 0 || len(receipt.Artifacts) != len(receipt.Targets) {
|
||||
return errors.New("build receipt target and artifact counts do not match")
|
||||
}
|
||||
seenTargets := make(map[ReceiptTarget]bool, len(receipt.Targets))
|
||||
seenArtifacts := make(map[ReceiptTarget]bool, len(receipt.Artifacts))
|
||||
targets := make([]artifact.Target, 0, len(receipt.Targets))
|
||||
for _, target := range receipt.Targets {
|
||||
if !artifact.ValidComponent(target.OS) || !artifact.ValidComponent(target.Arch) {
|
||||
return fmt.Errorf("build receipt has unsafe target %q/%q", target.OS, target.Arch)
|
||||
}
|
||||
if seenTargets[target] {
|
||||
return fmt.Errorf("build receipt repeats target %s/%s", target.OS, target.Arch)
|
||||
}
|
||||
seenTargets[target] = true
|
||||
targets = append(targets, artifact.Target{OS: target.OS, Arch: target.Arch})
|
||||
declarations := make([]artifact.Declaration, 0, len(receipt.Artifacts))
|
||||
for _, item := range receipt.Artifacts {
|
||||
declarations = append(declarations, artifact.Declaration{Target: artifact.Target{OS: item.Target.OS, Arch: item.Target.Arch}, Filename: item.Filename})
|
||||
}
|
||||
declarations := artifact.ExpectedBuild(receipt.BinaryName, receipt.Version, targets)
|
||||
wantByTarget := make(map[ReceiptTarget]string, len(declarations))
|
||||
for _, declaration := range declarations {
|
||||
target := ReceiptTarget{OS: declaration.Target.OS, Arch: declaration.Target.Arch}
|
||||
wantByTarget[target] = declaration.Filename
|
||||
if err := artifact.ValidateDeclarations(receipt.BinaryName, receipt.Version, parseStoredTargets(receipt.Targets), declarations); err != nil {
|
||||
return fmt.Errorf("build receipt: %w", err)
|
||||
}
|
||||
for _, artifact := range receipt.Artifacts {
|
||||
if !seenTargets[artifact.Target] || seenArtifacts[artifact.Target] {
|
||||
return fmt.Errorf("build receipt has an unexpected artifact target %s/%s", artifact.Target.OS, artifact.Target.Arch)
|
||||
}
|
||||
seenArtifacts[artifact.Target] = true
|
||||
wantName := wantByTarget[artifact.Target]
|
||||
if artifact.Filename != wantName || filepath.Base(artifact.Filename) != artifact.Filename {
|
||||
if filepath.Base(artifact.Filename) != artifact.Filename {
|
||||
return fmt.Errorf("build receipt has invalid artifact filename %q", artifact.Filename)
|
||||
}
|
||||
wantPath := filepath.Join(receipt.OutputDir, artifact.Filename)
|
||||
@@ -191,39 +215,87 @@ func validateBuildReceipt(receipt BuildReceipt, verifyFiles bool) error {
|
||||
if !validSHA256(artifact.SHA256) {
|
||||
return fmt.Errorf("build receipt has invalid SHA-256 for %q", artifact.Filename)
|
||||
}
|
||||
if verifyFiles {
|
||||
if err := verifyReceiptArtifact(artifact); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateRecordedIdentity(receipt BuildReceipt) error {
|
||||
repositoryDir := filepath.Clean(receipt.RepositoryDir)
|
||||
moduleDir := filepath.Clean(receipt.ModuleDir)
|
||||
sourceDir := filepath.Clean(receipt.SourceDir)
|
||||
relative, err := filepath.Rel(repositoryDir, sourceDir)
|
||||
if err != nil {
|
||||
return fmt.Errorf("relate module directory to repository: %w", err)
|
||||
}
|
||||
if relative == ".." || strings.HasPrefix(relative, ".."+string(filepath.Separator)) || filepath.IsAbs(relative) {
|
||||
return errors.New("source directory is outside repository")
|
||||
}
|
||||
if 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{
|
||||
RepositoryDir: repositoryDir,
|
||||
ModuleDir: moduleDir,
|
||||
ModuleSubdir: filepath.ToSlash(relative),
|
||||
}, []byte("module "+receipt.ModulePath+"\n"), receipt.Version)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if identity.Tag != receipt.Tag {
|
||||
return fmt.Errorf("full tag %q does not match module selection and version; want %q", receipt.Tag, identity.Tag)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func verifyReceiptArtifact(artifact ReceiptArtifact) error {
|
||||
info, err := os.Lstat(artifact.Path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("inspect build artifact %q: %w", artifact.Path, err)
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return fmt.Errorf("build artifact %q is not a regular file", artifact.Path)
|
||||
}
|
||||
file, err := os.Open(artifact.Path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("open build artifact %q: %w", artifact.Path, err)
|
||||
}
|
||||
defer file.Close()
|
||||
hash := sha256.New()
|
||||
if _, err := io.Copy(hash, file); err != nil {
|
||||
return fmt.Errorf("hash build artifact %q: %w", artifact.Path, err)
|
||||
}
|
||||
if actual := hex.EncodeToString(hash.Sum(nil)); actual != artifact.SHA256 {
|
||||
return fmt.Errorf("build artifact %q hash changed: got %s, expected %s", artifact.Path, actual, artifact.SHA256)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func normalizeReceiptTargets(targets []string) []ReceiptTarget {
|
||||
func parseReceiptTargets(targets []string) []artifact.Target {
|
||||
parsed := make([]artifact.Target, 0, len(targets))
|
||||
for _, value := range targets {
|
||||
goos, goarch, ok := strings.Cut(value, "/")
|
||||
@@ -232,12 +304,15 @@ func normalizeReceiptTargets(targets []string) []ReceiptTarget {
|
||||
}
|
||||
parsed = append(parsed, artifact.Target{OS: goos, Arch: goarch})
|
||||
}
|
||||
normalized := artifact.NormalizeTargets(parsed)
|
||||
result := make([]ReceiptTarget, 0, len(normalized))
|
||||
for _, target := range normalized {
|
||||
result = append(result, ReceiptTarget{OS: target.OS, Arch: target.Arch})
|
||||
return parsed
|
||||
}
|
||||
|
||||
func parseStoredTargets(targets []ReceiptTarget) []artifact.Target {
|
||||
parsed := make([]artifact.Target, 0, len(targets))
|
||||
for _, target := range targets {
|
||||
parsed = append(parsed, artifact.Target{OS: target.OS, Arch: target.Arch})
|
||||
}
|
||||
return result
|
||||
return parsed
|
||||
}
|
||||
|
||||
func validCommitID(value string) bool {
|
||||
|
||||
@@ -3,72 +3,197 @@ package cli
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBuildReceiptRoundTripBindsFilesAndBuildInputs(t *testing.T) {
|
||||
outputDir := t.TempDir()
|
||||
repositoryDir := t.TempDir()
|
||||
filename := "example-v1.2.3-linux-amd64"
|
||||
artifactPath := filepath.Join(outputDir, filename)
|
||||
contents := []byte("built application")
|
||||
if err := os.WriteFile(artifactPath, contents, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
digest := sha256.Sum256(contents)
|
||||
receipt := BuildReceipt{
|
||||
RepositoryDir: repositoryDir,
|
||||
CandidateCommit: strings.Repeat("a", 40),
|
||||
Version: "v1.2.3",
|
||||
MainPackage: "./cmd/example",
|
||||
BinaryName: "example",
|
||||
Targets: []ReceiptTarget{{OS: "linux", Arch: "amd64"}},
|
||||
Compiler: "go version go1.25.0 linux/amd64",
|
||||
Artifacts: []ReceiptArtifact{{
|
||||
Path: artifactPath,
|
||||
Filename: filename,
|
||||
Target: ReceiptTarget{OS: "linux", Arch: "amd64"},
|
||||
SHA256: hex.EncodeToString(digest[:]),
|
||||
}},
|
||||
}
|
||||
path, err := WriteBuildReceipt(outputDir, receipt)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
loaded, err := LoadBuildReceipt(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
settings := BuildSettings{
|
||||
MainPackage: "./cmd/example",
|
||||
BinaryName: "example",
|
||||
Targets: []string{"linux/amd64", "linux/amd64"},
|
||||
}
|
||||
if !loaded.MatchesBuild(repositoryDir, strings.Repeat("a", 40), "v1.2.3", settings) {
|
||||
t.Fatalf("receipt does not match normalized build settings: %#v", loaded)
|
||||
}
|
||||
settings.BinaryName = "other"
|
||||
if loaded.MatchesBuild(repositoryDir, strings.Repeat("a", 40), "v1.2.3", settings) {
|
||||
t.Fatal("receipt matched changed build settings")
|
||||
}
|
||||
if err := os.WriteFile(artifactPath, []byte("changed artifact"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := LoadBuildReceipt(path); err == nil || !strings.Contains(err.Error(), "hash changed") {
|
||||
t.Fatalf("LoadBuildReceipt() error = %v, want changed-file hash error", err)
|
||||
func TestWriteBuildReceiptReportsTemporaryCleanup(t *testing.T) {
|
||||
for _, mode := range []string{"renamed", "cleanup failure", "install and cleanup failure"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
repository := t.TempDir()
|
||||
output := t.TempDir()
|
||||
name := "app-v1.2.3-linux-amd64"
|
||||
receipt := BuildReceipt{
|
||||
SchemaVersion: BuildReceiptSchemaVersion, RepositoryDir: repository, ModuleDir: repository,
|
||||
SourceDir: repository, SourceSubdir: ".", GoEnabled: true, Publication: "go-module", VersionFormat: "semver", VersionPrefix: "v", IdentityKind: "production", NotePath: "docs/releases/v1.2.3.md",
|
||||
ModulePath: "example.com/receipt", Tag: "v1.2.3", CandidateCommit: strings.Repeat("a", 40),
|
||||
Version: "v1.2.3", MainPackage: ".", BinaryName: "app", Compiler: "go fixture",
|
||||
Targets: []ReceiptTarget{{OS: "linux", Arch: "amd64"}},
|
||||
Artifacts: []ReceiptArtifact{{Path: filepath.Join(output, name), Filename: name, Target: ReceiptTarget{OS: "linux", Arch: "amd64"}, SHA256: strings.Repeat("a", 64)}},
|
||||
}
|
||||
if mode == "install and cleanup failure" {
|
||||
blocked := filepath.Join(output, BuildReceiptName)
|
||||
if err := os.Mkdir(blocked, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(blocked, "keep"), nil, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
cleanupErr := errors.New("cleanup failed")
|
||||
var temporaryPath string
|
||||
remove := func(path string) error {
|
||||
temporaryPath = path
|
||||
err := os.Remove(path)
|
||||
if mode == "renamed" {
|
||||
return err
|
||||
}
|
||||
return cleanupErr
|
||||
}
|
||||
path, err := writeBuildReceipt(output, receipt, remove)
|
||||
if mode == "renamed" {
|
||||
if err != nil || path != filepath.Join(output, BuildReceiptName) {
|
||||
t.Fatalf("renamed receipt = %q, %v", path, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if !errors.Is(err, cleanupErr) || temporaryPath == "" || !strings.Contains(err.Error(), temporaryPath) {
|
||||
t.Fatalf("cleanup path = %q, error = %v", temporaryPath, err)
|
||||
}
|
||||
if mode == "cleanup failure" && path != filepath.Join(output, BuildReceiptName) {
|
||||
t.Fatalf("installed receipt path = %q", path)
|
||||
}
|
||||
if mode == "install and cleanup failure" {
|
||||
var pathErr *os.PathError
|
||||
if !errors.As(err, &pathErr) {
|
||||
t.Fatalf("install cause missing: %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadBuildReceiptRejectsUnknownFieldsAndMultipleValues(t *testing.T) {
|
||||
func TestBuildReceiptRoundTripBindsRootAndNestedModuleIdentity(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
moduleDir string
|
||||
modulePath string
|
||||
tag string
|
||||
}{
|
||||
{name: "root", moduleDir: ".", modulePath: "example.com/receipt", tag: "v1.2.3"},
|
||||
{name: "nested", moduleDir: "integrations/ckconfig", modulePath: "example.com/ckconfig", tag: "integrations/ckconfig/v1.2.3"},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
outputDir := t.TempDir()
|
||||
repositoryDir := t.TempDir()
|
||||
moduleDir := repositoryDir
|
||||
if test.moduleDir != "." {
|
||||
moduleDir = filepath.Join(repositoryDir, filepath.FromSlash(test.moduleDir))
|
||||
if err := os.MkdirAll(moduleDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
filename := "example-v1.2.3-linux-amd64"
|
||||
artifactPath := filepath.Join(outputDir, filename)
|
||||
contents := []byte("built application")
|
||||
if err := os.WriteFile(artifactPath, contents, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
digest := sha256.Sum256(contents)
|
||||
receipt := BuildReceipt{
|
||||
SchemaVersion: BuildReceiptSchemaVersion,
|
||||
RepositoryDir: repositoryDir,
|
||||
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,
|
||||
ModulePath: test.modulePath,
|
||||
Tag: test.tag,
|
||||
CandidateCommit: strings.Repeat("a", 40),
|
||||
Version: "v1.2.3",
|
||||
MainPackage: "./cmd/example",
|
||||
BinaryName: "example",
|
||||
Targets: []ReceiptTarget{{OS: "linux", Arch: "amd64"}},
|
||||
Compiler: "go version go1.25.0 linux/amd64",
|
||||
Artifacts: []ReceiptArtifact{{
|
||||
Path: artifactPath, Filename: filename,
|
||||
Target: ReceiptTarget{OS: "linux", Arch: "amd64"}, SHA256: hex.EncodeToString(digest[:]),
|
||||
}},
|
||||
}
|
||||
path, err := WriteBuildReceipt(outputDir, receipt)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
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)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
settings := BuildSettings{MainPackage: "./cmd/example", BinaryName: "example", Targets: []string{"linux/amd64", "linux/amd64"}}
|
||||
if !loaded.MatchesBuild(repositoryDir, strings.Repeat("a", 40), "v1.2.3", settings) {
|
||||
t.Fatalf("receipt does not match normalized build settings: %#v", loaded)
|
||||
}
|
||||
aliases := t.TempDir()
|
||||
repositoryAlias, outputAlias := filepath.Join(aliases, "repository"), filepath.Join(aliases, "output")
|
||||
if err := os.Symlink(repositoryDir, repositoryAlias); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(outputDir, outputAlias); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !loaded.MatchesBuild(repositoryAlias, receipt.CandidateCommit, receipt.Version, settings) {
|
||||
t.Fatal("receipt rejected an alias of its source repository")
|
||||
}
|
||||
if _, err := LoadBuildReceipt(filepath.Join(outputAlias, BuildReceiptName)); err != nil {
|
||||
t.Fatalf("load receipt through output alias: %v", err)
|
||||
}
|
||||
if loaded.MatchesBuild(t.TempDir(), receipt.CandidateCommit, receipt.Version, settings) {
|
||||
t.Fatal("receipt matched a different repository")
|
||||
}
|
||||
settings.BinaryName = "other"
|
||||
if loaded.MatchesBuild(repositoryDir, strings.Repeat("a", 40), "v1.2.3", settings) {
|
||||
t.Fatal("receipt matched changed build settings")
|
||||
}
|
||||
if err := os.WriteFile(artifactPath, []byte("changed artifact"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := LoadBuildReceipt(path); err != nil {
|
||||
t.Fatalf("receipt loading verified changed artifact bytes: %v", err)
|
||||
}
|
||||
if err := os.Remove(artifactPath); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := LoadBuildReceipt(path); err != nil {
|
||||
t.Fatalf("receipt loading required artifact bytes: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadBuildReceiptRejectsOldSchemasAndMultipleValues(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
body string
|
||||
want string
|
||||
}{
|
||||
{name: "unknown field", body: `{"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: "unknown schema", body: `{"schema_version":3}`, want: "regenerate it with the updated build command"},
|
||||
{name: "multiple values", body: `{} {}`, want: "multiple JSON values"},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
@@ -82,3 +207,91 @@ func TestLoadBuildReceiptRejectsUnknownFieldsAndMultipleValues(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteBuildReceiptRejectsInconsistentRecordedIdentity(t *testing.T) {
|
||||
repositoryDir := t.TempDir()
|
||||
moduleDir := filepath.Join(repositoryDir, "integrations", "ckconfig")
|
||||
if err := os.MkdirAll(moduleDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
outputDir := t.TempDir()
|
||||
receipt := BuildReceipt{
|
||||
SchemaVersion: BuildReceiptSchemaVersion,
|
||||
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",
|
||||
CandidateCommit: strings.Repeat("a", 40), Version: "v1.2.3", MainPackage: ".", BinaryName: "helper",
|
||||
OutputDir: outputDir, Targets: []ReceiptTarget{{OS: "linux", Arch: "amd64"}}, Compiler: "go version fixture",
|
||||
Artifacts: []ReceiptArtifact{{
|
||||
Path: filepath.Join(outputDir, "helper-v1.2.3-linux-amd64"), Filename: "helper-v1.2.3-linux-amd64",
|
||||
Target: ReceiptTarget{OS: "linux", Arch: "amd64"}, SHA256: strings.Repeat("a", 64),
|
||||
}},
|
||||
}
|
||||
if _, err := WriteBuildReceipt(outputDir, receipt); err == nil || !strings.Contains(err.Error(), "full tag") {
|
||||
t.Fatalf("WriteBuildReceipt() error = %v, want inconsistent full tag", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadBuildReceiptRejectsMismatchedModuleIdentity(t *testing.T) {
|
||||
repositoryDir := t.TempDir()
|
||||
outputDir := t.TempDir()
|
||||
artifactPath := filepath.Join(outputDir, "helper-v1.2.3-linux-amd64")
|
||||
contents := []byte("fixture")
|
||||
if err := os.WriteFile(artifactPath, contents, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
digest := sha256.Sum256(contents)
|
||||
receipt := BuildReceipt{
|
||||
SchemaVersion: BuildReceiptSchemaVersion,
|
||||
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",
|
||||
CandidateCommit: strings.Repeat("a", 40), Version: "v1.2.3", MainPackage: ".", BinaryName: "helper",
|
||||
OutputDir: outputDir, Targets: []ReceiptTarget{{OS: "linux", Arch: "amd64"}}, Compiler: "go version fixture",
|
||||
Artifacts: []ReceiptArtifact{{
|
||||
Path: artifactPath, Filename: filepath.Base(artifactPath),
|
||||
Target: ReceiptTarget{OS: "linux", Arch: "amd64"}, SHA256: hex.EncodeToString(digest[:]),
|
||||
}},
|
||||
}
|
||||
contents, err := json.Marshal(receipt)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var fields map[string]any
|
||||
if err := json.Unmarshal(contents, &fields); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fields["module_dir"] = filepath.Join(repositoryDir, "integrations", "ckconfig")
|
||||
contents, err = json.Marshal(fields)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := filepath.Join(outputDir, BuildReceiptName)
|
||||
if err := os.WriteFile(path, contents, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := LoadBuildReceipt(path); err == nil || !strings.Contains(err.Error(), "inconsistent module identity") {
|
||||
t.Fatalf("LoadBuildReceipt() error = %v, want inconsistent module identity", err)
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
45
cmd/releasekit/internal/cli/rehearsal_recovery.go
Normal file
45
cmd/releasekit/internal/cli/rehearsal_recovery.go
Normal 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
|
||||
}
|
||||
56
cmd/releasekit/internal/cli/rehearsal_recovery_test.go
Normal file
56
cmd/releasekit/internal/cli/rehearsal_recovery_test.go
Normal 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)
|
||||
}
|
||||
}
|
||||
51
cmd/releasekit/internal/cli/source_test.go
Normal file
51
cmd/releasekit/internal/cli/source_test.go
Normal 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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
44
cmd/releasekit/local_module_test.go
Normal file
44
cmd/releasekit/local_module_test.go
Normal file
@@ -0,0 +1,44 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
|
||||
)
|
||||
|
||||
func TestMainModuleWithoutDomainSupportsCheckBuildAndPageDelivery(t *testing.T) {
|
||||
repository := newDeliveryBuildRepository(t)
|
||||
writeRepositoryFile(t, repository, "go.mod", "module example\n\ngo 1.26.0\n")
|
||||
cliGitRun(t, repository, "add", ".")
|
||||
cliGitRun(t, repository, "commit", "-m", "Use local main module path")
|
||||
state := &deliveryServerState{}
|
||||
server := newDeliveryServer(t, state)
|
||||
defer server.Close()
|
||||
settings := cli.Settings{Product: "Example Product",
|
||||
Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}},
|
||||
Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example"},
|
||||
}
|
||||
writeDeliveryProfile(t, repository, settings)
|
||||
for _, args := range [][]string{
|
||||
{"check", "--repo", repository, "v1.2.3"},
|
||||
{"build", "--repo", repository, "--output", filepath.Join(t.TempDir(), "assets"), "v1.2.3"},
|
||||
} {
|
||||
var stdout, stderr bytes.Buffer
|
||||
if status := run(context.Background(), args, &stdout, &stderr); status != 0 || !strings.Contains(stdout.String(), "module example version v1.2.3 tag v1.2.3") {
|
||||
t.Fatalf("%s status=%d stdout=%s stderr=%s", args[0], status, stdout.String(), stderr.String())
|
||||
}
|
||||
}
|
||||
settings.Build = nil
|
||||
writeDeliveryProfile(t, repository, settings)
|
||||
state.update(func(state *deliveryServerData) { state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") })
|
||||
cliGitRun(t, repository, "tag", "v1.2.3")
|
||||
t.Setenv("RELEASEKIT_GITEA_TOKEN", "fixture-token")
|
||||
var stdout, stderr bytes.Buffer
|
||||
if status := run(context.Background(), []string{"deliver", "--repo", repository, "v1.2.3"}, &stdout, &stderr); status != 0 || state.snapshot().releaseCreates != 1 || state.snapshot().assetUploads != 0 {
|
||||
t.Fatalf("page delivery status=%d creates=%d uploads=%d stderr=%s", status, state.snapshot().releaseCreates, state.snapshot().assetUploads, stderr.String())
|
||||
}
|
||||
}
|
||||
@@ -10,10 +10,16 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"gitea.maximumdirect.net/eric/ReleaseKit"
|
||||
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo"
|
||||
"gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit/internal/cli"
|
||||
"go.maximumdirect.net/releasekit"
|
||||
"go.maximumdirect.net/releasekit/buildinfo"
|
||||
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
|
||||
"go.maximumdirect.net/releasekit/internal/artifact"
|
||||
"go.maximumdirect.net/releasekit/internal/git"
|
||||
"go.maximumdirect.net/releasekit/internal/gotool"
|
||||
"go.maximumdirect.net/releasekit/internal/releaseidentity"
|
||||
"go.maximumdirect.net/releasekit/internal/versioncontract"
|
||||
)
|
||||
|
||||
func main() {
|
||||
@@ -29,103 +35,31 @@ func run(ctx context.Context, args []string, stdout, stderr io.Writer) int {
|
||||
fmt.Fprintf(stderr, "%v\n%s\n", err, cli.Usage)
|
||||
return 2
|
||||
}
|
||||
if invocation.Command == cli.ReconcileAction || invocation.Command == cli.PublicationAttemptsAction {
|
||||
return runRecovery(ctx, invocation, stdout, stderr)
|
||||
}
|
||||
if invocation.Command == cli.TestAction || invocation.Command == cli.TestResumeAction || invocation.Command == cli.TestCleanupAction {
|
||||
return runRehearsal(ctx, invocation, stdout, stderr)
|
||||
}
|
||||
if invocation.Command == cli.ValidateAction {
|
||||
return runValidate(ctx, invocation, stdout)
|
||||
}
|
||||
if invocation.Command != cli.VersionCommand {
|
||||
invocation.Repository, err = git.RepositoryRoot(ctx, invocation.Repository)
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "%v\n", err)
|
||||
return 1
|
||||
}
|
||||
}
|
||||
|
||||
switch invocation.Command {
|
||||
case cli.VersionCommand:
|
||||
fmt.Fprintf(stdout, "releasekit %s\n", buildinfo.Version())
|
||||
return 0
|
||||
case cli.CheckAction, cli.PublishAction:
|
||||
settings, err := cli.LoadSettings(invocation.Repository, invocation.ConfigPath)
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "load profile: %v\n", err)
|
||||
return 2
|
||||
}
|
||||
request := candidateRequest(invocation, settings, stderr)
|
||||
if invocation.Command == cli.PublishAction {
|
||||
request.ExpectedPushURL = settings.ExpectedPushURL
|
||||
fmt.Fprintf(stderr, "validating and publishing %s\n", invocation.Version)
|
||||
result, err := releasekit.Publish(ctx, request)
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "publication state=%s phase=%s version=%s commit=%s tag-object=%s endpoint=%q: %s\n", result.State, result.Phase, result.Version, result.CandidateCommit, result.TagObject, result.Endpoint, candidateFailureText(err))
|
||||
if errors.Is(err, releasekit.ErrInvalidVersion) {
|
||||
return 2
|
||||
}
|
||||
if result.State == releasekit.PublicationUnknown {
|
||||
return 3
|
||||
}
|
||||
return 1
|
||||
}
|
||||
fmt.Fprintf(stdout, "published %s at %s (tag object %s)\n", result.Version, result.CandidateCommit, result.TagObject)
|
||||
return 0
|
||||
}
|
||||
candidate, err := releasekit.Check(ctx, request)
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "check failed: %s\n", candidateFailureText(err))
|
||||
if errors.Is(err, releasekit.ErrInvalidVersion) {
|
||||
return 2
|
||||
}
|
||||
return 1
|
||||
}
|
||||
fmt.Fprintf(stdout, "local candidate %s at %s is valid\n", candidate.Version, candidate.Commit)
|
||||
return 0
|
||||
return runCheckOrPublish(ctx, invocation, stdout, stderr)
|
||||
case cli.BuildAction:
|
||||
settings, err := cli.LoadSettings(invocation.Repository, invocation.ConfigPath)
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "load profile: %v\n", err)
|
||||
return 2
|
||||
}
|
||||
if settings.Build == nil {
|
||||
fmt.Fprintln(stderr, "build requires build settings in the profile")
|
||||
return 2
|
||||
}
|
||||
result, err := releasekit.Build(ctx, releasekit.BuildRequest{
|
||||
RepositoryDir: invocation.Repository,
|
||||
Version: invocation.Version,
|
||||
Spec: *configuredBuildSpec(settings.Build),
|
||||
OutputDir: invocation.OutputDir,
|
||||
Output: stderr,
|
||||
})
|
||||
if result.OutputDir != "" && len(result.Targets) != 0 {
|
||||
if receiptErr := cli.RemoveBuildReceipt(result.OutputDir); receiptErr != nil {
|
||||
fmt.Fprintf(stderr, "%v\n", receiptErr)
|
||||
return 1
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "build failed at %s: %v\n", result.CandidateCommit, err)
|
||||
for _, artifact := range result.Artifacts {
|
||||
fmt.Fprintf(stderr, "built %s %s\n", artifact.Filename, artifact.SHA256)
|
||||
}
|
||||
if errors.Is(err, releasekit.ErrInvalidVersion) {
|
||||
return 2
|
||||
}
|
||||
return 1
|
||||
}
|
||||
if len(result.Targets) == 0 {
|
||||
fmt.Fprintf(stdout, "no build targets selected for %s at %s\n", result.Version, result.CandidateCommit)
|
||||
return 0
|
||||
}
|
||||
receipt := receiptFromBuild(result)
|
||||
receiptPath, err := cli.WriteBuildReceipt(result.OutputDir, receipt)
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "write build receipt: %v\n", err)
|
||||
return 1
|
||||
}
|
||||
stored, err := cli.LoadBuildReceipt(receiptPath)
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "verify build receipt: %v\n", err)
|
||||
return 1
|
||||
}
|
||||
if !stored.MatchesBuild(result.RepositoryDir, result.CandidateCommit, result.Version, *settings.Build) {
|
||||
fmt.Fprintln(stderr, "build receipt does not match the selected source and build settings")
|
||||
return 1
|
||||
}
|
||||
fmt.Fprintf(stdout, "built %d artifacts for %s at %s with %s\n", len(result.Artifacts), result.Version, result.CandidateCommit, result.Compiler)
|
||||
for _, artifact := range result.Artifacts {
|
||||
fmt.Fprintf(stdout, "%s %s\n", artifact.Filename, artifact.SHA256)
|
||||
}
|
||||
fmt.Fprintf(stdout, "build receipt: %s\n", receiptPath)
|
||||
return 0
|
||||
return runBuild(ctx, invocation, stdout, stderr)
|
||||
case cli.DeliveryAction:
|
||||
return runDelivery(ctx, invocation, stdout, stderr)
|
||||
case cli.CIDeliveryAction:
|
||||
@@ -134,9 +68,218 @@ func run(ctx context.Context, args []string, stdout, stderr io.Writer) int {
|
||||
return 2
|
||||
}
|
||||
|
||||
func runCheckOrPublish(ctx context.Context, invocation cli.Invocation, stdout, stderr io.Writer) int {
|
||||
settings, err := cli.LoadSettings(invocation.Repository, invocation.ConfigPath)
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "load profile: %v\n", err)
|
||||
return 2
|
||||
}
|
||||
request := candidateRequest(invocation, settings, stderr)
|
||||
if invocation.Command == cli.PublishAction {
|
||||
if err := checkExpectedSelection(ctx, invocation.Repository, invocation.ExpectedModule, invocation.ExpectedSource, settings); err != nil {
|
||||
fmt.Fprintf(stderr, "%s: %v\n", selectionErrorLabel(invocation.ExpectedSource), err)
|
||||
return 2
|
||||
}
|
||||
request.ExpectedPushURL = settings.ExpectedPushURL
|
||||
request.PublicationRecordDir = invocation.RecordDir
|
||||
fmt.Fprintf(stderr, "validating and publishing module %s version %s\n", selectedModuleLabel(settings.ModuleDir), invocation.Version)
|
||||
result, err := releasekit.Publish(ctx, request)
|
||||
reportPublicationRecord(ctx, result, err, stderr)
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "publication state=%s phase=%s module=%s module-dir=%s version=%s tag=%s commit=%s tag-object=%s endpoint=%q: %s\n", result.State, result.Phase, result.ModulePath, result.ModuleDir, result.Version, result.Tag, result.CandidateCommit, result.TagObject, git.DisplayURL(result.Endpoint), candidateFailureText(err))
|
||||
if errors.Is(err, releasekit.ErrInvalidVersion) {
|
||||
return 2
|
||||
}
|
||||
if result.State == releasekit.PublicationUnknown {
|
||||
return 3
|
||||
}
|
||||
return 1
|
||||
}
|
||||
fmt.Fprintf(stdout, "published %s as %s at %s (tag object %s)\n", result.Version, result.Tag, result.CandidateCommit, result.TagObject)
|
||||
return 0
|
||||
}
|
||||
candidate, err := releasekit.Check(ctx, request)
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "check failed module=%s module-dir=%s version=%s tag=%s commit=%s: %s\n", candidate.ModulePath, candidate.ModuleDir, candidate.Version, candidate.Tag, candidate.Commit, candidateFailureText(err))
|
||||
if errors.Is(err, releasekit.ErrInvalidVersion) {
|
||||
return 2
|
||||
}
|
||||
return 1
|
||||
}
|
||||
fmt.Fprintf(stdout, "local candidate module %s version %s tag %s at %s is valid\n", candidate.ModulePath, candidate.Version, candidate.Tag, candidate.Commit)
|
||||
return 0
|
||||
}
|
||||
|
||||
func reportPublicationRecord(ctx context.Context, result releasekit.PublicationResult, publicationErr error, stderr io.Writer) {
|
||||
if result.RecordError != nil {
|
||||
fmt.Fprintf(stderr, "publication record warning: %s\n", git.DisplayError(result.RecordError))
|
||||
}
|
||||
if result.RecordPath == "" {
|
||||
return
|
||||
}
|
||||
fmt.Fprintf(stderr, "publication record saved: %s\n", git.DisplayDiagnostic(result.RecordPath))
|
||||
if publicationErr == nil || !publicationOffersRecovery(result.Phase) {
|
||||
return
|
||||
}
|
||||
// Handoff preparation follows the failed publication and has its own bounded
|
||||
// lifetime, including when publication's context was canceled.
|
||||
handoffContext, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
|
||||
defer cancel()
|
||||
command, err := selectedPublicationRecoveryCommand(handoffContext, result)
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "recovery tool preparation warning: %s\n", git.DisplayError(err))
|
||||
command, err = publicationRecoveryCommand(result.RecordPath)
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "recovery command unavailable: %s\n", git.DisplayError(err))
|
||||
fmt.Fprintln(stderr, "Use your selected supported ReleaseKit CLI with this record if the original executable is unavailable.")
|
||||
return
|
||||
}
|
||||
}
|
||||
fmt.Fprintf(stderr, "recovery command: %s\n", git.DisplayDiagnostic(command))
|
||||
fmt.Fprintln(stderr, "If this entry point is unavailable, use your selected supported ReleaseKit CLI with the same record.")
|
||||
}
|
||||
|
||||
func selectedPublicationRecoveryCommand(ctx context.Context, result releasekit.PublicationResult) (string, error) {
|
||||
if result.Evidence.ModuleDir != "" {
|
||||
common, err := git.CommonDirectory(ctx, result.RepositoryDir)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
args, err := gotool.RecoveryTool(ctx, result.Evidence.ModuleDir, filepath.Join(common, "releasekit", "publication-recovery"))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if args != nil {
|
||||
prefix := "env go -C " + shellQuote(git.DisplayDiagnostic(args.Directory))
|
||||
command := "(export GOWORK=off GOTOOLCHAIN=local && releasekit_host_os=$(" + prefix + " env GOHOSTOS) && releasekit_host_arch=$(" + prefix + " env GOHOSTARCH) && GOOS=\"$releasekit_host_os\" GOARCH=\"$releasekit_host_arch\" " + prefix
|
||||
for _, arg := range args.Args {
|
||||
command += " " + shellQuote(git.DisplayDiagnostic(arg))
|
||||
}
|
||||
path, err := filepath.Abs(git.DisplayDiagnostic(result.RecordPath))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return command + " reconcile --record " + shellQuote(path) + ")", nil
|
||||
}
|
||||
}
|
||||
return publicationRecoveryCommand(result.RecordPath)
|
||||
}
|
||||
|
||||
func publicationOffersRecovery(phase releasekit.PublicationPhase) bool {
|
||||
switch phase {
|
||||
case releasekit.PublicationTagCreation, releasekit.PublicationPush, releasekit.PublicationReconciliation:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func publicationRecoveryCommand(recordPath string) (string, error) {
|
||||
return executableRecoveryCommand(recordPath, "reconcile")
|
||||
}
|
||||
|
||||
func executableRecoveryCommand(recordPath, command string) (string, error) {
|
||||
executable, err := os.Executable()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("find current executable: %w", err)
|
||||
}
|
||||
executable, err = filepath.Abs(executable)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("resolve current executable path: %w", err)
|
||||
}
|
||||
if gotool.TemporaryExecutable(executable) {
|
||||
return "", fmt.Errorf("current executable belongs to a temporary Go build; select a supported ReleaseKit CLI for the saved record")
|
||||
}
|
||||
// Redact before path cleaning can change a pasted URL's recognizable syntax.
|
||||
recordPath, err = filepath.Abs(git.DisplayDiagnostic(recordPath))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("resolve publication record path: %w", err)
|
||||
}
|
||||
return shellQuote(executable) + " " + command + " --record " + shellQuote(recordPath), nil
|
||||
}
|
||||
|
||||
func shellQuote(argument string) string {
|
||||
return "'" + strings.ReplaceAll(argument, "'", "'\"'\"'") + "'"
|
||||
}
|
||||
|
||||
func runBuild(ctx context.Context, invocation cli.Invocation, stdout, stderr io.Writer) int {
|
||||
settings, err := cli.LoadSettings(invocation.Repository, invocation.ConfigPath)
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "load profile: %v\n", err)
|
||||
return 2
|
||||
}
|
||||
if settings.Build == nil {
|
||||
fmt.Fprintln(stderr, "build requires build settings in the profile")
|
||||
return 2
|
||||
}
|
||||
result, err := releasekit.Build(ctx, releasekit.BuildRequest{
|
||||
RepositoryDir: invocation.Repository,
|
||||
ModuleDir: settings.ModuleDir,
|
||||
Source: sourceSpec(settings),
|
||||
Version: invocation.Version,
|
||||
Spec: *configuredBuildSpec(settings.Build),
|
||||
OutputDir: invocation.OutputDir,
|
||||
Output: stderr,
|
||||
})
|
||||
if result.OutputDir != "" && len(result.Targets) != 0 {
|
||||
if receiptErr := cli.RemoveBuildReceipt(result.OutputDir); receiptErr != nil {
|
||||
fmt.Fprintf(stderr, "%v\n", receiptErr)
|
||||
return 1
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "build failed module=%s module-dir=%s version=%s tag=%s commit=%s: %v\n", result.ModulePath, result.ModuleDir, result.Version, result.Tag, result.CandidateCommit, err)
|
||||
for _, artifact := range result.Artifacts {
|
||||
fmt.Fprintf(stderr, "built %s %s\n", artifact.Filename, artifact.SHA256)
|
||||
}
|
||||
if errors.Is(err, releasekit.ErrInvalidVersion) {
|
||||
return 2
|
||||
}
|
||||
return 1
|
||||
}
|
||||
if len(result.Targets) == 0 {
|
||||
fmt.Fprintf(stdout, "no build targets selected for module %s version %s tag %s at %s\n", result.ModulePath, result.Version, result.Tag, result.CandidateCommit)
|
||||
return 0
|
||||
}
|
||||
receipt := receiptFromBuild(result)
|
||||
receiptPath, err := cli.WriteBuildReceipt(result.OutputDir, receipt)
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "write build receipt: %v\n", err)
|
||||
return 1
|
||||
}
|
||||
stored, err := cli.LoadBuildReceipt(receiptPath)
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "verify build receipt: %v\n", err)
|
||||
return 1
|
||||
}
|
||||
if !stored.MatchesBuild(result.RepositoryDir, result.CandidateCommit, result.Version, *settings.Build) {
|
||||
fmt.Fprintln(stderr, "build receipt does not match the selected source and build settings")
|
||||
return 1
|
||||
}
|
||||
fmt.Fprintf(stdout, "built %d artifacts for module %s version %s tag %s at %s with %s\n", len(result.Artifacts), result.ModulePath, result.Version, result.Tag, result.CandidateCommit, result.Compiler)
|
||||
for _, artifact := range result.Artifacts {
|
||||
fmt.Fprintf(stdout, "%s %s\n", artifact.Filename, artifact.SHA256)
|
||||
}
|
||||
fmt.Fprintf(stdout, "build receipt: %s\n", receiptPath)
|
||||
return 0
|
||||
}
|
||||
|
||||
func sourceSpec(settings cli.Settings) *releasekit.SourceSpec {
|
||||
source := settings.SourceSpec()
|
||||
if source == nil {
|
||||
return nil
|
||||
}
|
||||
return &releasekit.SourceSpec{
|
||||
Dir: source.Dir, GoEnabled: source.GoEnabled, Publication: releasekit.PublicationMode(source.Publication),
|
||||
VersionFormat: releasekit.VersionFormat(source.VersionFormat), VersionPrefix: source.VersionPrefix, TagPrefix: source.TagPrefix,
|
||||
}
|
||||
}
|
||||
|
||||
func candidateRequest(invocation cli.Invocation, settings cli.Settings, output io.Writer) releasekit.ReleaseRequest {
|
||||
request := releasekit.ReleaseRequest{
|
||||
RepositoryDir: invocation.Repository,
|
||||
ModuleDir: settings.ModuleDir,
|
||||
Source: sourceSpec(settings),
|
||||
Product: settings.Product,
|
||||
Version: invocation.Version,
|
||||
Remote: settings.Remote,
|
||||
@@ -147,9 +290,14 @@ func candidateRequest(invocation cli.Invocation, settings cli.Settings, output i
|
||||
if len(settings.Checks) != 0 {
|
||||
checks := settings.Checks
|
||||
request.AdditionalChecks = func(ctx context.Context, candidate releasekit.Candidate) error {
|
||||
return cli.RunChecks(ctx, candidate.RepositoryDir, checks, map[string]string{
|
||||
"RELEASEKIT_VERSION": candidate.Version,
|
||||
"RELEASEKIT_CANDIDATE": candidate.Commit,
|
||||
return cli.RunChecks(ctx, candidate.SourceDir, checks, map[string]string{
|
||||
"RELEASEKIT_VERSION": candidate.Version,
|
||||
"RELEASEKIT_CANDIDATE": candidate.Commit,
|
||||
"RELEASEKIT_REPOSITORY_DIR": candidate.RepositoryDir,
|
||||
"RELEASEKIT_SOURCE_DIR": candidate.SourceDir,
|
||||
"RELEASEKIT_MODULE_DIR": candidate.ModuleDir,
|
||||
"RELEASEKIT_MODULE_PATH": candidate.ModulePath,
|
||||
"RELEASEKIT_TAG": candidate.Tag,
|
||||
}, output, output)
|
||||
}
|
||||
}
|
||||
@@ -161,7 +309,9 @@ func validationSpec(settings *cli.ValidationSettings) releasekit.ValidationSpec
|
||||
return releasekit.ValidationSpec{}
|
||||
}
|
||||
result := releasekit.ValidationSpec{
|
||||
GoFormat: settings.GoFormat,
|
||||
SharedFiles: copyStringsPreservingEmpty(settings.SharedFiles),
|
||||
ForbiddenFiles: copyStringsPreservingEmpty(settings.ForbiddenFiles),
|
||||
GoFormat: settings.GoFormat,
|
||||
ModuleDistribution: releasekit.ModuleDistributionValidationSpec{
|
||||
WorkspaceFiles: settings.ModuleDistribution.WorkspaceFiles,
|
||||
LocalReplacements: settings.ModuleDistribution.LocalReplacements,
|
||||
@@ -199,6 +349,54 @@ func candidateFailureText(err error) string {
|
||||
return err.Error()
|
||||
}
|
||||
|
||||
func checkExpectedSelection(ctx context.Context, repositoryDir, expectedModule, expectedSource string, settings cli.Settings) error {
|
||||
if expectedModule == "" && expectedSource == "" {
|
||||
return nil
|
||||
}
|
||||
commit, err := git.CaptureHead(ctx, repositoryDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
selected, err := releaseidentity.ResolveCommittedSource(ctx, repositoryDir, settings.ModuleDir, commit, settings.SourceSpec())
|
||||
if err != nil {
|
||||
return fmt.Errorf("normalize profile source: %w", err)
|
||||
}
|
||||
for _, expectation := range []struct{ kind, dir string }{{"module", expectedModule}, {"source", expectedSource}} {
|
||||
if expectation.dir == "" {
|
||||
continue
|
||||
}
|
||||
expected, err := releaseidentity.ResolveCommittedSelection(ctx, repositoryDir, expectation.dir, commit)
|
||||
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
|
||||
}
|
||||
|
||||
func selectionErrorLabel(expectedSource string) string {
|
||||
if expectedSource != "" {
|
||||
return "profile source selection"
|
||||
}
|
||||
return "profile module selection"
|
||||
}
|
||||
|
||||
func selectedModuleLabel(moduleDir string) string {
|
||||
if moduleDir == "" {
|
||||
return "."
|
||||
}
|
||||
return moduleDir
|
||||
}
|
||||
|
||||
func copyStringsPreservingEmpty(values []string) []string {
|
||||
if values == nil {
|
||||
return nil
|
||||
}
|
||||
return append([]string{}, values...)
|
||||
}
|
||||
|
||||
func runDelivery(ctx context.Context, invocation cli.Invocation, stdout, stderr io.Writer) int {
|
||||
settings, err := cli.LoadSettings(invocation.Repository, invocation.ConfigPath)
|
||||
if err != nil {
|
||||
@@ -211,9 +409,10 @@ func runDelivery(ctx context.Context, invocation cli.Invocation, stdout, stderr
|
||||
func runCIDelivery(ctx context.Context, invocation cli.Invocation, stdout, stderr io.Writer) int {
|
||||
err := releasekit.PrepareTaggedCheckout(ctx, releasekit.TaggedCheckoutRequest{
|
||||
RepositoryDir: invocation.Repository,
|
||||
Version: invocation.Version,
|
||||
Tag: invocation.ExpectedTag,
|
||||
Remote: invocation.Remote,
|
||||
ExpectedCommit: invocation.Commit,
|
||||
VerifyOnly: invocation.Prepared,
|
||||
})
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "prepare tagged checkout: %v\n", err)
|
||||
@@ -223,17 +422,48 @@ func runCIDelivery(ctx context.Context, invocation cli.Invocation, stdout, stder
|
||||
return 1
|
||||
}
|
||||
|
||||
if releaseidentity.IsDiagnosticTag(invocation.ExpectedTag) {
|
||||
return runDiagnosticDelivery(ctx, invocation, stdout, stderr)
|
||||
}
|
||||
|
||||
settings, err := cli.LoadSettings(invocation.Repository, invocation.ConfigPath)
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "load profile: %v\n", err)
|
||||
return 2
|
||||
}
|
||||
destination, status := deliveryDestination(settings, stderr)
|
||||
if err := checkExpectedSelection(ctx, invocation.Repository, invocation.ExpectedModule, invocation.ExpectedSource, settings); err != nil {
|
||||
fmt.Fprintf(stderr, "%s: %v\n", selectionErrorLabel(invocation.ExpectedSource), err)
|
||||
return 2
|
||||
}
|
||||
identity, err := releaseidentity.FromCommittedSource(ctx, invocation.Repository, settings.ModuleDir, invocation.Version, invocation.Commit, settings.SourceSpec())
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "resolve CI release identity: %v\n", err)
|
||||
if errors.Is(err, versioncontract.ErrInvalidIdentifier) {
|
||||
return 2
|
||||
}
|
||||
return 1
|
||||
}
|
||||
if invocation.ExpectedTag != identity.Tag {
|
||||
fmt.Fprintf(stderr, "expected delivery tag %q does not match selected source tag %q\n", invocation.ExpectedTag, identity.Tag)
|
||||
return 1
|
||||
}
|
||||
if !identity.GoEnabled && settings.Build != nil && len(settings.Build.Targets) != 0 {
|
||||
fmt.Fprintln(stderr, "build targets require Go capability")
|
||||
return 2
|
||||
}
|
||||
destination, status := deliveryDestination(invocation.Repository, settings, cli.CICredentials, stderr)
|
||||
if status != 0 {
|
||||
return status
|
||||
}
|
||||
if settings.Build != nil && len(settings.Build.Targets) != 0 {
|
||||
if err := releasekit.PrepareBuildDependencies(ctx, invocation.Repository); err != nil {
|
||||
if err := releasekit.PreflightDelivery(ctx, destination); err != nil {
|
||||
fmt.Fprintf(stderr, "delivery credential preflight: %v\n", err)
|
||||
return deliveryPreflightExitStatus(err)
|
||||
}
|
||||
if err := releasekit.PrepareBuildDependencies(ctx, releasekit.DependencyPreparationRequest{
|
||||
RepositoryDir: invocation.Repository,
|
||||
ModuleDir: identity.ModuleSubdir,
|
||||
}); err != nil {
|
||||
fmt.Fprintf(stderr, "prepare build dependencies: %v\n", err)
|
||||
return 1
|
||||
}
|
||||
@@ -244,32 +474,41 @@ func runCIDelivery(ctx context.Context, invocation cli.Invocation, stdout, stder
|
||||
// deliverWithSettings adapts prepared CLI state to the public delivery facade.
|
||||
// CI entry points can reuse it after preparing the checkout and loading its profile.
|
||||
func deliverWithSettings(ctx context.Context, invocation cli.Invocation, settings cli.Settings, stdout, stderr io.Writer) int {
|
||||
destination, status := deliveryDestination(settings, stderr)
|
||||
destination, status := deliveryDestination(invocation.Repository, settings, cli.LocalCredentials, stderr)
|
||||
if status != 0 {
|
||||
return status
|
||||
}
|
||||
return deliverWithDestination(ctx, invocation, settings, destination, stdout, stderr)
|
||||
}
|
||||
|
||||
func deliveryDestination(settings cli.Settings, stderr io.Writer) (releasekit.GiteaDestination, int) {
|
||||
func deliveryDestination(repositoryDir string, settings cli.Settings, context cli.CredentialContext, stderr io.Writer) (releasekit.DeliveryDestination, int) {
|
||||
delivery := settings.Delivery
|
||||
if delivery == nil || strings.TrimSpace(delivery.BaseURL) == "" || strings.TrimSpace(delivery.Owner) == "" || strings.TrimSpace(delivery.Repository) == "" {
|
||||
if delivery == nil {
|
||||
fmt.Fprintln(stderr, "deliver requires an explicit delivery.forge selection in the profile")
|
||||
return releasekit.DeliveryDestination{}, 2
|
||||
}
|
||||
switch strings.TrimSpace(delivery.Forge) {
|
||||
case "":
|
||||
fmt.Fprintln(stderr, "deliver requires delivery.forge in the profile")
|
||||
return releasekit.DeliveryDestination{}, 2
|
||||
case string(releasekit.ForgeGitea):
|
||||
default:
|
||||
fmt.Fprintf(stderr, "unsupported delivery forge %q\n", delivery.Forge)
|
||||
return releasekit.DeliveryDestination{}, 2
|
||||
}
|
||||
if strings.TrimSpace(delivery.BaseURL) == "" || strings.TrimSpace(delivery.Owner) == "" || strings.TrimSpace(delivery.Repository) == "" {
|
||||
fmt.Fprintln(stderr, "deliver requires base_url, owner, and repository in the profile delivery settings")
|
||||
return releasekit.GiteaDestination{}, 2
|
||||
return releasekit.DeliveryDestination{}, 2
|
||||
}
|
||||
tokenEnv := delivery.TokenEnv
|
||||
if strings.TrimSpace(tokenEnv) == "" {
|
||||
tokenEnv = "RELEASEKIT_GITEA_TOKEN"
|
||||
token, _, err := cli.ResolveDeliveryCredential(repositoryDir, delivery.Credentials, context)
|
||||
if err != nil {
|
||||
fmt.Fprintln(stderr, err)
|
||||
return releasekit.DeliveryDestination{}, 2
|
||||
}
|
||||
token, ok := os.LookupEnv(tokenEnv)
|
||||
if !ok || strings.TrimSpace(token) == "" {
|
||||
fmt.Fprintf(stderr, "deliver requires a non-empty token in environment variable %s\n", tokenEnv)
|
||||
return releasekit.GiteaDestination{}, 2
|
||||
}
|
||||
return releasekit.GiteaDestination{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
|
||||
}
|
||||
|
||||
func deliverWithDestination(ctx context.Context, invocation cli.Invocation, settings cli.Settings, destination releasekit.GiteaDestination, stdout, stderr io.Writer) int {
|
||||
func deliverWithDestination(ctx context.Context, invocation cli.Invocation, settings cli.Settings, destination releasekit.DeliveryDestination, stdout, stderr io.Writer) int {
|
||||
hasTargets := settings.Build != nil && len(settings.Build.Targets) != 0
|
||||
if invocation.AssetsDir != "" && !hasTargets {
|
||||
fmt.Fprintln(stderr, "--assets requires build targets in the profile")
|
||||
@@ -282,10 +521,17 @@ func deliverWithDestination(ctx context.Context, invocation cli.Invocation, sett
|
||||
}
|
||||
if hasTargets {
|
||||
if invocation.AssetsDir != "" {
|
||||
assetsDir := invocation.AssetsDir
|
||||
if !filepath.IsAbs(assetsDir) {
|
||||
assetsDir = filepath.Join(invocation.Repository, assetsDir)
|
||||
commit, err := git.CaptureHead(ctx, invocation.Repository)
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "capture asset source commit: %v\n", err)
|
||||
return 1
|
||||
}
|
||||
selection, err := releaseidentity.ResolveCommittedSource(ctx, invocation.Repository, settings.ModuleDir, commit, settings.SourceSpec())
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "resolve asset module directory: %v\n", err)
|
||||
return 1
|
||||
}
|
||||
assetsDir := artifact.OutputDirectory(selection.ModuleDir, invocation.AssetsDir)
|
||||
receipt, err := cli.LoadBuildReceipt(filepath.Join(assetsDir, cli.BuildReceiptName))
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "load verified build receipt: %v\n", err)
|
||||
@@ -301,26 +547,20 @@ func deliverWithDestination(ctx context.Context, invocation cli.Invocation, sett
|
||||
|
||||
result, err := releasekit.Deliver(ctx, releasekit.DeliveryRequest{
|
||||
RepositoryDir: invocation.Repository,
|
||||
ModuleDir: settings.ModuleDir,
|
||||
Source: sourceSpec(settings),
|
||||
Product: settings.Product,
|
||||
Version: invocation.Version,
|
||||
ExpectedTag: invocation.ExpectedTag,
|
||||
Destination: destination,
|
||||
Build: buildSpec,
|
||||
Prebuilt: prebuilt,
|
||||
Output: stderr,
|
||||
})
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "delivery state=%s version=%s commit=%s url=%s: %v\n", result.State, result.Version, result.CandidateCommit, result.ReleaseURL, err)
|
||||
writeDeliveryAssets(stderr, result)
|
||||
writeDeliveryRecovery(stderr, result)
|
||||
if errors.Is(err, releasekit.ErrInvalidVersion) {
|
||||
return 2
|
||||
}
|
||||
if result.State == releasekit.DeliveryUnknown {
|
||||
return 3
|
||||
}
|
||||
return 1
|
||||
return reportDeliveryFailure(stderr, result, err)
|
||||
}
|
||||
fmt.Fprintf(stdout, "delivered %s at %s (state %s)\n", result.Version, result.CandidateCommit, result.State)
|
||||
fmt.Fprintf(stdout, "delivered module %s version %s tag %s at %s (state %s)\n", result.ModulePath, result.Version, result.Tag, result.CandidateCommit, result.State)
|
||||
if result.ReleaseURL != "" {
|
||||
fmt.Fprintf(stdout, "release: %s\n", result.ReleaseURL)
|
||||
}
|
||||
@@ -328,6 +568,46 @@ func deliverWithDestination(ctx context.Context, invocation cli.Invocation, sett
|
||||
return 0
|
||||
}
|
||||
|
||||
func reportDeliveryFailure(output io.Writer, result releasekit.DeliveryResult, err error) int {
|
||||
if result.State == releasekit.DeliveryComplete {
|
||||
fmt.Fprintln(output, "hosted delivery completed; local cleanup failed")
|
||||
}
|
||||
fmt.Fprintf(output, "delivery state=%s module=%s module-dir=%s version=%s tag=%s commit=%s url=%s: %v\n", result.State, result.ModulePath, result.ModuleDir, result.Version, result.Tag, result.CandidateCommit, result.ReleaseURL, err)
|
||||
writeDeliveryAssets(output, result)
|
||||
writeDeliveryRecovery(output, result)
|
||||
if result.State == releasekit.DeliveryComplete {
|
||||
return 1
|
||||
}
|
||||
if errors.Is(err, releasekit.ErrInvalidVersion) {
|
||||
return 2
|
||||
}
|
||||
var preflightErr *releasekit.DeliveryPreflightError
|
||||
if errors.As(err, &preflightErr) {
|
||||
return deliveryPreflightExitStatus(preflightErr)
|
||||
}
|
||||
if result.State == releasekit.DeliveryUnknown {
|
||||
return 3
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
func deliveryPreflightExitStatus(err error) int {
|
||||
var preflightErr *releasekit.DeliveryPreflightError
|
||||
if !errors.As(err, &preflightErr) {
|
||||
return 1
|
||||
}
|
||||
switch preflightErr.Kind {
|
||||
case releasekit.DeliveryPreflightInvalidDestination,
|
||||
releasekit.DeliveryPreflightMissingCredential,
|
||||
releasekit.DeliveryPreflightInvalidCredential,
|
||||
releasekit.DeliveryPreflightInsufficientPermissions,
|
||||
releasekit.DeliveryPreflightInaccessibleDestination:
|
||||
return 2
|
||||
default:
|
||||
return 1
|
||||
}
|
||||
}
|
||||
|
||||
func writeDeliveryAssets(output io.Writer, result releasekit.DeliveryResult) {
|
||||
for _, group := range []struct {
|
||||
label string
|
||||
@@ -342,13 +622,13 @@ func writeDeliveryAssets(output io.Writer, result releasekit.DeliveryResult) {
|
||||
func writeDeliveryRecovery(output io.Writer, result releasekit.DeliveryResult) {
|
||||
switch result.State {
|
||||
case releasekit.DeliveryNotAttempted:
|
||||
fmt.Fprintln(output, "recovery: fix the local or preflight failure before retrying; no remote write was attempted")
|
||||
fmt.Fprintf(output, "recovery: fix the local or preflight failure for module %s version %s tag %s before retrying; no remote write was attempted\n", result.ModulePath, result.Version, result.Tag)
|
||||
case releasekit.DeliveryPartial:
|
||||
fmt.Fprintln(output, "recovery: fix the reported cause, then retry this version")
|
||||
fmt.Fprintf(output, "recovery: fix the reported cause, then retry module %s version %s tag %s\n", result.ModulePath, result.Version, result.Tag)
|
||||
case releasekit.DeliveryConflict:
|
||||
fmt.Fprintln(output, "recovery: investigate conflicting hosted content; use a new version if the source or published contents need correction")
|
||||
fmt.Fprintf(output, "recovery: investigate conflicting hosted content for module %s version %s tag %s; use a new version if the source or published contents need correction\n", result.ModulePath, result.Version, result.Tag)
|
||||
case releasekit.DeliveryUnknown:
|
||||
fmt.Fprintln(output, "recovery: resolve the remote state before retrying")
|
||||
fmt.Fprintf(output, "recovery: resolve the remote state for module %s version %s tag %s before retrying\n", result.ModulePath, result.Version, result.Tag)
|
||||
default:
|
||||
return
|
||||
}
|
||||
@@ -359,7 +639,11 @@ func writeDeliveryRecovery(output io.Writer, result releasekit.DeliveryResult) {
|
||||
|
||||
func buildResultFromReceipt(receipt cli.BuildReceipt) *releasekit.BuildResult {
|
||||
result := &releasekit.BuildResult{
|
||||
RepositoryDir: receipt.RepositoryDir, CandidateCommit: receipt.CandidateCommit, SourceVerified: receipt.SourceVerified,
|
||||
RepositoryDir: receipt.RepositoryDir, ModuleDir: receipt.ModuleDir, ModulePath: receipt.ModulePath, Tag: receipt.Tag,
|
||||
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,
|
||||
Version: receipt.Version, MainPackage: receipt.MainPackage, BinaryName: receipt.BinaryName,
|
||||
OutputDir: receipt.OutputDir, Compiler: receipt.Compiler,
|
||||
}
|
||||
@@ -393,7 +677,19 @@ func configuredBuildSpec(settings *cli.BuildSettings) *releasekit.BuildSpec {
|
||||
|
||||
func receiptFromBuild(result releasekit.BuildResult) cli.BuildReceipt {
|
||||
receipt := cli.BuildReceipt{
|
||||
SchemaVersion: cli.BuildReceiptSchemaVersion,
|
||||
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,
|
||||
ModulePath: result.ModulePath,
|
||||
Tag: result.Tag,
|
||||
CandidateCommit: result.CandidateCommit,
|
||||
SourceVerified: result.SourceVerified,
|
||||
Version: result.Version,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
315
cmd/releasekit/multi_module_example_test.go
Normal file
315
cmd/releasekit/multi_module_example_test.go
Normal file
@@ -0,0 +1,315 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMultiModuleSelectorMapsSelectorsAndTags(t *testing.T) {
|
||||
example := filepath.Join(cliRepositoryRoot(t), "examples", "multi-module")
|
||||
helper := filepath.Join(example, "select-module.sh")
|
||||
for _, test := range []struct {
|
||||
mode string
|
||||
value string
|
||||
want string
|
||||
}{
|
||||
{mode: "selector", value: "root", want: "root\tv[01].*\t.\treleasekit-root.json"},
|
||||
{mode: "selector", value: "ckconfig", want: "ckconfig\tintegrations/ckconfig/v*\tintegrations/ckconfig\treleasekit-ckconfig.json"},
|
||||
{mode: "tag", value: "integrations/ckconfig/v1.2.3", want: "ckconfig\tintegrations/ckconfig/v*\tintegrations/ckconfig\treleasekit-ckconfig.json"},
|
||||
{mode: "tag", value: "integrations/core/v2.3.4", want: "core-v2\tintegrations/core/v2.*\tintegrations/core/v2\treleasekit-core-v2.json"},
|
||||
{mode: "tag", value: "v1.2.3", want: "root\tv[01].*\t.\treleasekit-root.json"},
|
||||
{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) {
|
||||
got := runModuleSelector(t, helper, test.mode, test.value, "")
|
||||
if strings.TrimSpace(got) != test.want {
|
||||
t.Fatalf("selector output = %q, want %q", got, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
mapPath := filepath.Join(t.TempDir(), "release modules.tsv")
|
||||
if err := os.WriteFile(mapPath, []byte("one\tfeature/*\tmodules/one\tprofiles/one.json\ntwo\tfeature/v1.*\tmodules/two\tprofiles/two.json\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if output := runModuleSelectorError(t, helper, "selector", "absent", mapPath); !strings.Contains(output, "no module map row") {
|
||||
t.Fatalf("unknown selector error = %q", output)
|
||||
}
|
||||
if output := runModuleSelectorError(t, helper, "tag", "feature/v1.2.3", mapPath); !strings.Contains(output, "ambiguous") {
|
||||
t.Fatalf("ambiguous event error = %q", output)
|
||||
}
|
||||
if 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 {
|
||||
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)
|
||||
want := "space\tfeature/*\tintegrations/ck config\tprofiles/core release.json"
|
||||
if strings.TrimSpace(got) != want {
|
||||
t.Fatalf("paths with spaces = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMultiModuleLauncherUsesSelectedModuleAndProfile(t *testing.T) {
|
||||
example := filepath.Join(cliRepositoryRoot(t), "examples", "multi-module")
|
||||
repository := newCLIRepository(t)
|
||||
copyExampleTree(t, example, repository)
|
||||
|
||||
rootModule := "module example.com/multi-module-consumer\n\ngo 1.25.0\n\nrequire go.maximumdirect.net/releasekit v0.2.197\n"
|
||||
selectedModule := "module example.com/multi-module-consumer/integrations/ckconfig\n\ngo 1.25.0\n\nrequire go.maximumdirect.net/releasekit v0.2.198\n"
|
||||
writeRepositoryFile(t, repository, "go.mod", rootModule)
|
||||
writeRepositoryFile(t, repository, "integrations/ckconfig/go.mod", selectedModule)
|
||||
spaceModule := "module example.com/multi-module-consumer/integrations/ckconfig\n\ngo 1.25.0\n\nrequire go.maximumdirect.net/releasekit v0.2.299\n"
|
||||
writeRepositoryFile(t, repository, "integrations/ck config/go.mod", spaceModule)
|
||||
writeRepositoryFile(t, repository, "profiles/core release.json", `{"product":"Example Consumer Integration","module_dir":"integrations/ck config"}`)
|
||||
cliGitRun(t, repository, "add", ".")
|
||||
cliGitRun(t, repository, "commit", "-m", "prepare multi-module launcher fixture")
|
||||
|
||||
mapPath := filepath.Join(t.TempDir(), "release modules.tsv")
|
||||
if err := os.WriteFile(mapPath, []byte("with space\tfeature/*\tintegrations/ck config\tprofiles/core release.json\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
shimDir := t.TempDir()
|
||||
goLog := filepath.Join(t.TempDir(), "go commands")
|
||||
argsLog := filepath.Join(t.TempDir(), "tool arguments")
|
||||
shim := `#!/bin/sh
|
||||
set -eu
|
||||
printf 'cwd=%s args=%s\n' "$PWD" "$*" >> "$RELEASEKIT_TEST_GO_LOG"
|
||||
if [ "$1" = env ]; then
|
||||
case "$2" in GOHOSTOS) printf '%s\n' "$RELEASEKIT_TEST_HOST_OS" ;; GOHOSTARCH) printf '%s\n' "$RELEASEKIT_TEST_HOST_ARCH" ;; esac
|
||||
exit 0
|
||||
fi
|
||||
case " $* " in *" -deps "*) printf 'target=%s/%s\n' "$GOOS" "$GOARCH" >> "$RELEASEKIT_TEST_GO_LOG" ;; esac
|
||||
modfile=
|
||||
for argument in "$@"; do
|
||||
case "$argument" in -modfile=*) modfile=${argument#-modfile=} ;; esac
|
||||
done
|
||||
if [ -n "$modfile" ]; then cat "$modfile" >> "$RELEASEKIT_TEST_GO_LOG"; fi
|
||||
if [ "$1" = tool ]; then
|
||||
shift 3
|
||||
printf '<%s>\n' "$@" > "$RELEASEKIT_TEST_TOOL_ARGS"
|
||||
fi
|
||||
`
|
||||
if err := os.WriteFile(filepath.Join(shimDir, "go"), []byte(shim), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("PATH", shimDir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||
t.Setenv("RELEASEKIT_MODULE_MAP", mapPath)
|
||||
t.Setenv("RELEASEKIT_TEST_GO_LOG", goLog)
|
||||
t.Setenv("RELEASEKIT_TEST_TOOL_ARGS", argsLog)
|
||||
t.Setenv("RELEASEKIT_TEST_HOST_OS", runtime.GOOS)
|
||||
t.Setenv("RELEASEKIT_TEST_HOST_ARCH", runtime.GOARCH)
|
||||
foreignOS, foreignArch := foreignTarget()
|
||||
t.Setenv("GOOS", foreignOS)
|
||||
t.Setenv("GOARCH", foreignArch)
|
||||
launcher := filepath.Join(repository, "release.sh")
|
||||
command := exec.Command(launcher, "with space", "v1.2.4")
|
||||
var stdout, stderr bytes.Buffer
|
||||
command.Stdout = &stdout
|
||||
command.Stderr = &stderr
|
||||
if err := command.Run(); err != nil {
|
||||
t.Fatalf("launcher error: %v stdout=%q stderr=%q", err, stdout.String(), stderr.String())
|
||||
}
|
||||
|
||||
goCommands, err := os.ReadFile(goLog)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wantModule := filepath.Join(repository, "integrations", "ck config")
|
||||
if !strings.Contains(string(goCommands), "cwd="+wantModule) || !strings.Contains(string(goCommands), "v0.2.299") || strings.Contains(string(goCommands), "v0.2.197") {
|
||||
t.Fatalf("tool bootstrap did not use selected module metadata: %s", goCommands)
|
||||
}
|
||||
if !strings.Contains(string(goCommands), "target="+runtime.GOOS+"/"+runtime.GOARCH) {
|
||||
t.Fatalf("dependency inspection did not use host target: %s", goCommands)
|
||||
}
|
||||
toolArgs, err := os.ReadFile(argsLog)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, expected := range []string{"<publish>", "<--repo>", "<" + repository + ">", "<--config>", "<profiles/core release.json>", "<--expected-module>", "<integrations/ck config>", "<v1.2.4>"} {
|
||||
if !strings.Contains(string(toolArgs), expected) {
|
||||
t.Errorf("publication arguments %q omit %q", toolArgs, expected)
|
||||
}
|
||||
}
|
||||
if strings.Contains(string(goCommands), repository+"/.releasekit-bootstrap.") {
|
||||
t.Fatalf("temporary tool metadata was placed inside the repository: %s", goCommands)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMultiModuleLauncherRunsToolFromSelectedDependency(t *testing.T) {
|
||||
example := filepath.Join(cliRepositoryRoot(t), "examples", "multi-module")
|
||||
repository := newCLIRepository(t)
|
||||
copyExampleTree(t, example, repository)
|
||||
writeRepositoryFile(t, repository, "go.mod", "module example.com/multi-module-consumer\n\ngo 1.25.0\n\nrequire go.maximumdirect.net/releasekit v0.2.197\n")
|
||||
const otherModule = "example.com/other-tool"
|
||||
other := t.TempDir()
|
||||
writeRepositoryFile(t, other, "go.mod", "module "+otherModule+"\n\ngo 1.25.0\n")
|
||||
writeRepositoryFile(t, other, "cmd/releasekit/main.go", "package main\nfunc main() { println(\"unexpected tool ran\") }\n")
|
||||
writeRepositoryFile(t, repository, "integrations/ckconfig/go.mod", "module example.com/multi-module-consumer/integrations/ckconfig\n\ngo 1.25.0\n\nrequire go.maximumdirect.net/releasekit v0.2.198\nrequire "+otherModule+" v0.0.0\n\nreplace "+otherModule+" => "+strconv.Quote(other)+"\n\ntool "+otherModule+"/cmd/releasekit\n")
|
||||
cliGitRun(t, repository, "add", ".")
|
||||
cliGitRun(t, repository, "commit", "-m", "prepare selected tool module")
|
||||
|
||||
proxy := writeReleaseKitModuleProxy(t)
|
||||
moduleCache := t.TempDir()
|
||||
t.Setenv("GOMODCACHE", moduleCache)
|
||||
t.Cleanup(func() {
|
||||
_ = filepath.WalkDir(moduleCache, func(path string, entry fs.DirEntry, err error) error {
|
||||
if err == nil && entry.IsDir() {
|
||||
_ = os.Chmod(path, 0o700)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
})
|
||||
t.Setenv("GOPROXY", "file://"+filepath.ToSlash(proxy))
|
||||
t.Setenv("GOSUMDB", "off")
|
||||
t.Setenv("GOTOOLCHAIN", "local")
|
||||
foreignOS, foreignArch := foreignTarget()
|
||||
t.Setenv("GOOS", foreignOS)
|
||||
t.Setenv("GOARCH", foreignArch)
|
||||
moduleBefore, err := os.ReadFile(filepath.Join(repository, "integrations", "ckconfig", "go.mod"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, status := range []int{0, 1, 2, 3} {
|
||||
t.Run(strconv.Itoa(status), func(t *testing.T) {
|
||||
command := exec.Command(filepath.Join(repository, "release.sh"), "ckconfig", "v1.2.3")
|
||||
command.Env = setEnvironment(os.Environ(), "RELEASEKIT_TOOL_EXIT", strconv.Itoa(status))
|
||||
output, err := command.CombinedOutput()
|
||||
if status == 0 && err != nil {
|
||||
t.Fatalf("launcher error: %v output=%q", err, output)
|
||||
}
|
||||
if status != 0 {
|
||||
var exitError *exec.ExitError
|
||||
if !errors.As(err, &exitError) || exitError.ExitCode() != status {
|
||||
t.Fatalf("launcher error = %v, want exit %d; output=%q", err, status, output)
|
||||
}
|
||||
}
|
||||
for _, expected := range []string{
|
||||
"tool-version=v0.2.198 helper=tool-only dependency",
|
||||
`"publish"`, `"--repo"`, `"` + repository + `"`,
|
||||
`"--config"`, `"releasekit-ckconfig.json"`,
|
||||
`"--expected-module"`, `"integrations/ckconfig"`, `"v1.2.3"`,
|
||||
} {
|
||||
if !strings.Contains(string(output), expected) {
|
||||
t.Errorf("launcher output %q omits %q", output, expected)
|
||||
}
|
||||
}
|
||||
if strings.Contains(string(output), "tool-version=v0.2.197") {
|
||||
t.Fatalf("launcher ran the root-selected ReleaseKit version: %s", output)
|
||||
}
|
||||
if strings.Contains(string(output), "unexpected tool ran") {
|
||||
t.Fatalf("launcher ran the other tool with the same name: %s", output)
|
||||
}
|
||||
moduleAfter, err := os.ReadFile(filepath.Join(repository, "integrations", "ckconfig", "go.mod"))
|
||||
if err != nil || !bytes.Equal(moduleAfter, moduleBefore) {
|
||||
t.Fatalf("selected module go.mod changed: got %q want %q error=%v", moduleAfter, moduleBefore, err)
|
||||
}
|
||||
if status := cliGitOutput(t, repository, "status", "--porcelain", "--untracked-files=all"); status != "" {
|
||||
t.Fatalf("launcher changed source: %q", status)
|
||||
}
|
||||
entries, err := os.ReadDir(filepath.Dir(repository))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if strings.HasPrefix(entry.Name(), ".releasekit-bootstrap.") {
|
||||
t.Fatalf("temporary bootstrap directory remains: %s", entry.Name())
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func foreignTarget() (string, string) {
|
||||
osName, arch := "windows", "arm64"
|
||||
if runtime.GOOS == osName {
|
||||
osName = "linux"
|
||||
}
|
||||
if runtime.GOARCH == arch {
|
||||
arch = "amd64"
|
||||
}
|
||||
return osName, arch
|
||||
}
|
||||
|
||||
func runModuleSelector(t *testing.T, helper, mode, value, mapPath string) string {
|
||||
t.Helper()
|
||||
command := exec.Command("sh", helper, mode, value)
|
||||
command.Env = os.Environ()
|
||||
if mapPath != "" {
|
||||
command.Env = append(command.Env, "RELEASEKIT_MODULE_MAP="+mapPath)
|
||||
}
|
||||
output, err := command.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("selector %s %q: %v: %s", mode, value, err, output)
|
||||
}
|
||||
return string(output)
|
||||
}
|
||||
|
||||
func runModuleSelectorError(t *testing.T, helper, mode, value, mapPath string) string {
|
||||
t.Helper()
|
||||
command := exec.Command("sh", helper, mode, value)
|
||||
command.Env = append(os.Environ(), "RELEASEKIT_MODULE_MAP="+mapPath)
|
||||
output, err := command.CombinedOutput()
|
||||
if err == nil {
|
||||
t.Fatalf("selector %s %q unexpectedly succeeded: %s", mode, value, output)
|
||||
}
|
||||
return string(output)
|
||||
}
|
||||
|
||||
func copyExampleTree(t *testing.T, source, destination string) {
|
||||
t.Helper()
|
||||
err := filepath.WalkDir(source, func(path string, entry fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
relative, err := filepath.Rel(source, path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if relative == "." {
|
||||
return nil
|
||||
}
|
||||
target := filepath.Join(destination, relative)
|
||||
if entry.IsDir() {
|
||||
return os.MkdirAll(target, 0o700)
|
||||
}
|
||||
contents, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
info, err := entry.Info()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mode := info.Mode().Perm()
|
||||
if err := os.WriteFile(target, contents, mode); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Chmod(target, mode)
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(fmt.Errorf("copy multi-module example: %w", err))
|
||||
}
|
||||
}
|
||||
542
cmd/releasekit/multi_module_woodpecker_test.go
Normal file
542
cmd/releasekit/multi_module_woodpecker_test.go
Normal file
@@ -0,0 +1,542 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"debug/elf"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"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) {
|
||||
root := cliRepositoryRoot(t)
|
||||
example := filepath.Join(root, "examples", "multi-module")
|
||||
contents, err := os.ReadFile(filepath.Join(example, "woodpecker.yml"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
block, err := extractWoodpeckerCommand(string(contents), "deliver")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
command := strings.ReplaceAll(block, "$${", "${")
|
||||
for _, eventTag := range []string{"refs/tags/v[01].*", "refs/tags/integrations/ckconfig/v*", "refs/tags/integrations/core/v2.*", "refs/tags/configuration/20*", "refs/tags/releasekit-test/*/*"} {
|
||||
if !strings.Contains(string(contents), eventTag) {
|
||||
t.Errorf("workflow tag filters omit %q", eventTag)
|
||||
}
|
||||
}
|
||||
toolBinary := buildWorkflowCLI(t, root)
|
||||
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) {
|
||||
const tag = "integrations/ckconfig/v1.2.3"
|
||||
delivery := newMappedDeliveryFixture(t, tag)
|
||||
repository := newWorkflowRepository(t, example)
|
||||
writeMappedProfile(t, repository, "releasekit-ckconfig.json", cli.Settings{
|
||||
Product: "Example Consumer Integration", ModuleDir: "integrations/ckconfig",
|
||||
Delivery: workflowDeliverySettings(delivery.snapshot().URL),
|
||||
})
|
||||
writeRepositoryFile(t, repository, "integrations/ckconfig/docs/releases/v1.2.3.md", "# Example Consumer Integration v1.2.3\n\nTagged integration note.\n")
|
||||
writeRepositoryFile(t, repository, "integrations/ckconfig/go.mod", workflowModuleFile("example.com/multi-module-consumer/integrations/ckconfig", "v0.2.197"))
|
||||
commit := tagAndPushWorkflowRepository(t, repository, tag)
|
||||
delivery.update(func(delivery *mappedDeliveryData) { delivery.commit = commit })
|
||||
env := multiModuleWorkflowEnvironment(t, repository, commit, tag, toolBinary, proxy)
|
||||
env["CI_COMMIT_SHA"] = cliGitOutput(t, repository, "rev-parse", "refs/tags/"+tag)
|
||||
if output := runWoodpeckerBlock(t, command, repository, env); !strings.Contains(output, "state complete") || !strings.Contains(output, "tool-version=v0.2.197") {
|
||||
t.Fatalf("tagged page delivery output = %q", output)
|
||||
}
|
||||
assertGoSelection(t, repository, env["RELEASEKIT_GO_LOG"])
|
||||
if delivery.snapshot().creates != 1 || delivery.snapshot().requests == 0 || delivery.snapshot().tag != tag {
|
||||
t.Fatalf("page delivery fixture = %#v", delivery.snapshot())
|
||||
}
|
||||
|
||||
cliGitRun(t, repository, "checkout", "main")
|
||||
writeRepositoryFile(t, repository, "release-modules.tsv", "# changed after release\nroot\tv[01].*\t.\treleasekit-root.json\n")
|
||||
writeRepositoryFile(t, repository, "integrations/ckconfig/go.mod", workflowModuleFile("example.com/multi-module-consumer/integrations/ckconfig", "v0.2.198"))
|
||||
cliGitRun(t, repository, "add", ".")
|
||||
cliGitRun(t, repository, "commit", "-m", "change default branch release selection")
|
||||
cliGitRun(t, repository, "push", "origin", "main")
|
||||
|
||||
output := runWoodpeckerBlock(t, command, repository, env)
|
||||
if !strings.Contains(output, "tool-version=v0.2.197") || strings.Contains(output, "tool-version=v0.2.198") {
|
||||
t.Fatalf("tag retry did not use its committed tool version: %q", output)
|
||||
}
|
||||
if delivery.snapshot().creates != 1 || delivery.snapshot().tag != tag {
|
||||
t.Fatalf("tag retry did not reuse the tagged mapping: %#v", delivery.snapshot())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("binary delivery from physical major module", func(t *testing.T) {
|
||||
const tag = "integrations/core/v2.1.0"
|
||||
arch, machine := "arm64", elf.EM_AARCH64
|
||||
if runtime.GOOS == "linux" && runtime.GOARCH == arch {
|
||||
arch, machine = "amd64", elf.EM_X86_64
|
||||
}
|
||||
delivery := newMappedDeliveryFixture(t, tag)
|
||||
repository := newWorkflowRepository(t, example)
|
||||
writeMappedProfile(t, repository, "releasekit-core-v2.json", cli.Settings{
|
||||
Product: "Example Consumer Core v2", ModuleDir: "integrations/core/v2",
|
||||
Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "core", Targets: []string{"linux/" + arch}},
|
||||
Delivery: workflowDeliverySettings(delivery.snapshot().URL),
|
||||
})
|
||||
writeRepositoryFile(t, repository, "integrations/core/v2/docs/releases/v2.1.0.md", "# Example Consumer Core v2 v2.1.0\n\nTagged core note.\n")
|
||||
prepareWorkflowModuleSum(t, repository, "integrations/core/v2", proxy)
|
||||
commit := tagAndPushWorkflowRepository(t, repository, tag)
|
||||
delivery.update(func(delivery *mappedDeliveryData) { delivery.commit = commit })
|
||||
env := multiModuleWorkflowEnvironment(t, repository, commit, tag, toolBinary, proxy)
|
||||
output := runWoodpeckerBlock(t, command, repository, env)
|
||||
if !strings.Contains(output, "tool-version=v0.2.197") || !strings.Contains(output, "state complete") {
|
||||
t.Fatalf("binary delivery output = %q", output)
|
||||
}
|
||||
observed := delivery.snapshot()
|
||||
if observed.creates != 1 || observed.uploads != 2 || observed.tag != tag {
|
||||
t.Fatalf("binary delivery fixture = %#v", observed)
|
||||
}
|
||||
name := "core-v2.1.0-linux-" + arch
|
||||
asset, ok := observed.assets[name]
|
||||
if !ok {
|
||||
t.Fatalf("binary asset %q missing", name)
|
||||
}
|
||||
binary, err := elf.NewFile(bytes.NewReader(asset))
|
||||
if err != nil {
|
||||
t.Fatalf("read uploaded %s as ELF: %v", name, err)
|
||||
}
|
||||
if binary.Machine != machine {
|
||||
t.Fatalf("uploaded %s machine = %s, want %s", name, binary.Machine, machine)
|
||||
}
|
||||
if _, ok := observed.assets["SHA256SUMS"]; !ok {
|
||||
t.Fatalf("checksum asset missing: %#v", observed.assets)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("binary delivery from virtual major module", func(t *testing.T) {
|
||||
const tag = "integrations/core/v2.1.0"
|
||||
delivery := newMappedDeliveryFixture(t, tag)
|
||||
repository := newWorkflowRepository(t, example)
|
||||
writeRepositoryFile(t, repository, "release-modules.tsv", strings.ReplaceAll(readWorkflowFile(t, repository, "release-modules.tsv"), "integrations/core/v2\treleasekit-core-v2.json", "integrations/core\treleasekit-core-v2.json"))
|
||||
writeMappedProfile(t, repository, "releasekit-core-v2.json", cli.Settings{
|
||||
Product: "Example Consumer Core v2", ModuleDir: "integrations/core",
|
||||
Delivery: workflowDeliverySettings(delivery.snapshot().URL),
|
||||
})
|
||||
writeRepositoryFile(t, repository, "integrations/core/go.mod", workflowModuleFile("example.com/multi-module-consumer/integrations/core/v2", "v0.2.197"))
|
||||
writeRepositoryFile(t, repository, "integrations/core/main.go", readWorkflowFile(t, example, "integrations/core/v2/main.go"))
|
||||
writeRepositoryFile(t, repository, "integrations/core/docs/releases/v2.1.0.md", "# Example Consumer Core v2 v2.1.0\n\nTagged core note.\n")
|
||||
prepareWorkflowModuleSum(t, repository, "integrations/core", proxy)
|
||||
commit := tagAndPushWorkflowRepository(t, repository, tag)
|
||||
delivery.update(func(delivery *mappedDeliveryData) { delivery.commit = commit })
|
||||
env := multiModuleWorkflowEnvironment(t, repository, commit, tag, toolBinary, proxy)
|
||||
output := runWoodpeckerBlock(t, command, repository, env)
|
||||
if !strings.Contains(output, "tool-version=v0.2.197") || !strings.Contains(output, "state complete") {
|
||||
t.Fatalf("virtual-major delivery output = %q", output)
|
||||
}
|
||||
if delivery.snapshot().creates != 1 || delivery.snapshot().tag != tag {
|
||||
t.Fatalf("virtual-major delivery fixture = %#v", delivery.snapshot())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("inconsistent mapping fails exact event tag check", func(t *testing.T) {
|
||||
const tag = "integrations/ckconfig/v2.1.0"
|
||||
delivery := newMappedDeliveryFixture(t, tag)
|
||||
repository := newWorkflowRepository(t, example)
|
||||
mapping := readWorkflowFile(t, repository, "release-modules.tsv")
|
||||
mapping = strings.Replace(mapping,
|
||||
"ckconfig\tintegrations/ckconfig/v*\tintegrations/ckconfig\treleasekit-ckconfig.json",
|
||||
"ckconfig\tintegrations/ckconfig/v*\tintegrations/core/v2\treleasekit-core-v2.json", 1)
|
||||
writeRepositoryFile(t, repository, "release-modules.tsv", mapping)
|
||||
writeMappedProfile(t, repository, "releasekit-core-v2.json", cli.Settings{
|
||||
Product: "Example Consumer Core v2", ModuleDir: "integrations/core/v2",
|
||||
Delivery: workflowDeliverySettings(delivery.snapshot().URL),
|
||||
})
|
||||
writeRepositoryFile(t, repository, "integrations/core/v2/docs/releases/v2.1.0.md", "# Example Consumer Core v2 v2.1.0\n\nMismatched mapped note.\n")
|
||||
commit := tagAndPushWorkflowRepository(t, repository, tag)
|
||||
delivery.update(func(delivery *mappedDeliveryData) { delivery.commit = commit })
|
||||
env := multiModuleWorkflowEnvironment(t, repository, commit, tag, toolBinary, proxy)
|
||||
if output, err := executeWoodpeckerBlock(command, repository, env); err == nil {
|
||||
t.Fatalf("inconsistent mapping succeeded: %s", output)
|
||||
} else if !strings.Contains(output, tag) || !strings.Contains(output, "integrations/core/v2.1.0") {
|
||||
t.Fatalf("inconsistent mapping did not fail the exact tag comparison: %s", output)
|
||||
}
|
||||
if delivery.snapshot().requests != 0 {
|
||||
t.Fatalf("exact event tag mismatch reached hosted delivery: %#v", delivery.snapshot())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
type mappedDeliveryFixture struct {
|
||||
mu sync.Mutex
|
||||
data mappedDeliveryData
|
||||
}
|
||||
|
||||
func (state *mappedDeliveryFixture) update(change func(*mappedDeliveryData)) {
|
||||
state.mu.Lock()
|
||||
defer state.mu.Unlock()
|
||||
change(&state.data)
|
||||
}
|
||||
|
||||
func (state *mappedDeliveryFixture) snapshot() mappedDeliveryData {
|
||||
state.mu.Lock()
|
||||
defer state.mu.Unlock()
|
||||
result := state.data
|
||||
|
||||
result.assets = make(map[string][]byte, len(state.data.assets))
|
||||
for key, value := range state.data.assets {
|
||||
result.assets[key] = append([]byte(nil), value...)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
type mappedDeliveryData struct {
|
||||
URL string
|
||||
tag string
|
||||
commit string
|
||||
page bool
|
||||
name string
|
||||
body string
|
||||
creates int
|
||||
uploads int
|
||||
requests int
|
||||
assets map[string][]byte
|
||||
}
|
||||
|
||||
func newMappedDeliveryFixture(t *testing.T, tag string) *mappedDeliveryFixture {
|
||||
t.Helper()
|
||||
state := &mappedDeliveryFixture{data: mappedDeliveryData{tag: tag, assets: make(map[string][]byte)}}
|
||||
data := &state.data
|
||||
server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
state.mu.Lock()
|
||||
defer state.mu.Unlock()
|
||||
data.requests++
|
||||
tag := data.tag
|
||||
if r.Header.Get("Authorization") != "token fixture-token" {
|
||||
t.Errorf("delivery authorization = %q", r.Header.Get("Authorization"))
|
||||
}
|
||||
apiRoot := "/api/v1/repos/owner/example/"
|
||||
escapedTag := url.PathEscape(tag)
|
||||
switch r.URL.EscapedPath() {
|
||||
case "/api/v1/repos/owner/example", "/api/v1/repositories/1":
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"id": 1, "name": "example", "full_name": "owner/example",
|
||||
"owner": map[string]string{"login": "owner"},
|
||||
})
|
||||
case apiRoot + "tags/" + escapedTag:
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"name": tag, "commit": map[string]string{"sha": data.commit}})
|
||||
case apiRoot + "releases/tags/" + escapedTag:
|
||||
if !data.page {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"id": 10, "html_url": serverURL(r) + "/releases/10", "tag_name": tag, "target_commitish": data.commit, "name": data.name, "body": data.body, "draft": false, "prerelease": false})
|
||||
case apiRoot + "releases":
|
||||
var payload struct {
|
||||
Tag string `json:"tag_name"`
|
||||
Commit string `json:"target_commitish"`
|
||||
Name string `json:"name"`
|
||||
Body string `json:"body"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
|
||||
t.Errorf("decode release create: %v", err)
|
||||
}
|
||||
if payload.Tag != tag || payload.Commit != data.commit {
|
||||
t.Errorf("release payload = %#v", payload)
|
||||
}
|
||||
data.page = true
|
||||
data.name = payload.Name
|
||||
data.body = payload.Body
|
||||
data.creates++
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"id": 10, "html_url": serverURL(r) + "/releases/10", "tag_name": tag, "target_commitish": data.commit, "name": payload.Name, "body": payload.Body, "draft": false, "prerelease": false})
|
||||
case apiRoot + "releases/10/assets":
|
||||
if r.Method == http.MethodGet {
|
||||
listing := make([]map[string]any, 0, len(data.assets))
|
||||
for name, content := range data.assets {
|
||||
listing = append(listing, map[string]any{"id": len(listing) + 1, "name": name, "size": len(content), "browser_download_url": serverURL(r) + "/files/" + name})
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(listing)
|
||||
return
|
||||
}
|
||||
if err := r.ParseMultipartForm(1 << 20); err != nil {
|
||||
t.Errorf("parse asset upload: %v", err)
|
||||
http.Error(w, "multipart", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
name := r.URL.Query().Get("name")
|
||||
file, _, err := r.FormFile("attachment")
|
||||
if err != nil {
|
||||
t.Errorf("read asset %q: %v", name, err)
|
||||
http.Error(w, "attachment", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
content, err := io.ReadAll(file)
|
||||
_ = file.Close()
|
||||
if err != nil {
|
||||
t.Errorf("read asset bytes: %v", err)
|
||||
}
|
||||
data.assets[name] = content
|
||||
data.uploads++
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"id": data.uploads, "name": name, "size": len(content)})
|
||||
default:
|
||||
if strings.HasPrefix(r.URL.Path, "/files/") {
|
||||
name := strings.TrimPrefix(r.URL.Path, "/files/")
|
||||
if content, ok := data.assets[name]; ok {
|
||||
_, _ = w.Write(content)
|
||||
return
|
||||
}
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
t.Errorf("unexpected delivery request %s %s", r.Method, r.URL.EscapedPath())
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
data.URL = "http://" + server.Listener.Addr().String()
|
||||
server.Start()
|
||||
t.Cleanup(server.Close)
|
||||
return state
|
||||
}
|
||||
|
||||
func serverURL(r *http.Request) string {
|
||||
return "http://" + r.Host
|
||||
}
|
||||
|
||||
func buildWorkflowCLI(t *testing.T, root string) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "releasekit")
|
||||
command := exec.Command("go", "build", "-o", path, "./cmd/releasekit")
|
||||
command.Dir = root
|
||||
command.Env = append(os.Environ(), "GOTOOLCHAIN=local", "GOPROXY=off", "GOSUMDB=off")
|
||||
if output, err := command.CombinedOutput(); err != nil {
|
||||
t.Fatalf("build workflow CLI: %v\n%s", err, output)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func writeWorkflowToolProxy(t *testing.T) string {
|
||||
t.Helper()
|
||||
const module = "go.maximumdirect.net/releasekit"
|
||||
const helper = "example.com/releasekit-helper"
|
||||
proxyDir := t.TempDir()
|
||||
moduleFile := "module " + module + "\n\ngo 1.25.0\n\nrequire " + helper + " v1.0.0\n"
|
||||
for _, version := range []string{"v0.2.197", "v0.2.198"} {
|
||||
main := fmt.Sprintf(`package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
helper "%s"
|
||||
)
|
||||
|
||||
func main() {
|
||||
fmt.Println("tool-version=%s helper=" + helper.Version)
|
||||
command := exec.Command(os.Getenv("RELEASEKIT_TEST_BINARY"), os.Args[1:]...)
|
||||
command.Env = os.Environ()
|
||||
command.Stdout = os.Stdout
|
||||
command.Stderr = os.Stderr
|
||||
if err := command.Run(); err != nil {
|
||||
if exit, ok := err.(*exec.ExitError); ok { os.Exit(exit.ExitCode()) }
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
`, helper, version)
|
||||
files := map[string]string{
|
||||
"cmd/releasekit/main.go": main,
|
||||
"buildinfo/version.go": "package buildinfo\nimport \"go.maximumdirect.net/releasekit/internal/runtimeinfo\"\nfunc Version() string { return runtimeinfo.Version() }\n",
|
||||
"internal/runtimeinfo/version.go": "package runtimeinfo\nvar injectedVersion string\nfunc Version() string { if injectedVersion != \"\" { return injectedVersion }; return \"dev\" }\n",
|
||||
}
|
||||
writeModuleProxyVersion(t, proxyDir, module, version, moduleFile, files)
|
||||
}
|
||||
writeModuleProxyVersion(t, proxyDir, helper, "v1.0.0", "module "+helper+"\n\ngo 1.25.0\n", map[string]string{"helper.go": "package helper\nconst Version = \"tagged dependency\"\n"})
|
||||
return proxyDir
|
||||
}
|
||||
|
||||
func newWorkflowRepository(t *testing.T, example string) string {
|
||||
t.Helper()
|
||||
repository := filepath.Join(t.TempDir(), "multi module checkout")
|
||||
if err := os.Mkdir(repository, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
copyExampleTree(t, example, repository)
|
||||
for _, selection := range []struct{ directory, module string }{
|
||||
{".", "example.com/multi-module-consumer"},
|
||||
{"integrations/ckconfig", "example.com/multi-module-consumer/integrations/ckconfig"},
|
||||
{"integrations/core/v2", "example.com/multi-module-consumer/integrations/core/v2"},
|
||||
} {
|
||||
writeRepositoryFile(t, repository, selection.directory+"/go.mod", workflowModuleFile(selection.module, "v0.2.197"))
|
||||
}
|
||||
cliGitRun(t, repository, "init", "--initial-branch=main")
|
||||
cliGitRun(t, repository, "config", "user.name", "ReleaseKit Test")
|
||||
cliGitRun(t, repository, "config", "user.email", "releasekit@example.test")
|
||||
cliGitRun(t, repository, "config", "commit.gpgsign", "false")
|
||||
return repository
|
||||
}
|
||||
|
||||
func workflowModuleFile(module, version string) string {
|
||||
return fmt.Sprintf("module %s\n\ngo 1.25.0\n\nrequire go.maximumdirect.net/releasekit %s\n", module, version)
|
||||
}
|
||||
|
||||
func workflowDeliverySettings(baseURL string) *cli.DeliverySettings {
|
||||
return &cli.DeliverySettings{Forge: "gitea", BaseURL: baseURL, Owner: "owner", Repository: "example", Credentials: &cli.DeliveryCredentials{CI: &cli.CICredential{TokenEnvironmentVariable: "RELEASEKIT_GITEA_TOKEN"}}}
|
||||
}
|
||||
|
||||
func writeMappedProfile(t *testing.T, repository, name string, settings cli.Settings) {
|
||||
t.Helper()
|
||||
contents, err := json.MarshalIndent(settings, "", " ")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writeRepositoryFile(t, repository, name, string(contents)+"\n")
|
||||
}
|
||||
|
||||
func tagAndPushWorkflowRepository(t *testing.T, repository, tag string) string {
|
||||
t.Helper()
|
||||
cliGitRun(t, repository, "add", "--all")
|
||||
cliGitRun(t, repository, "commit", "-m", "prepare mapped delivery")
|
||||
commit := cliGitOutput(t, repository, "rev-parse", "HEAD")
|
||||
cliGitRun(t, repository, "tag", "-a", tag, "-m", "mapped release")
|
||||
remote := filepath.Join(filepath.Dir(repository), "origin.git")
|
||||
cliGitRun(t, repository, "init", "--bare", remote)
|
||||
cliGitRun(t, repository, "remote", "add", "origin", remote)
|
||||
cliGitRun(t, repository, "push", "origin", "HEAD:refs/heads/main", "refs/tags/"+tag)
|
||||
return commit
|
||||
}
|
||||
|
||||
func multiModuleWorkflowEnvironment(t *testing.T, repository, commit, tag, binary, proxy string) map[string]string {
|
||||
t.Helper()
|
||||
goDir, goLog := installGoBootstrapShim(t)
|
||||
environment := templateEnvironment(repository, commit, goDir, goLog)
|
||||
environment["GOOS"], environment["GOARCH"] = foreignTarget()
|
||||
environment["CI_COMMIT_TAG"] = tag
|
||||
environment["RELEASEKIT_TEST_BINARY"] = binary
|
||||
useSyntheticModuleProxy(t, environment, "file://"+filepath.ToSlash(proxy))
|
||||
cache := environment["GOMODCACHE"]
|
||||
t.Cleanup(func() {
|
||||
_ = filepath.WalkDir(cache, func(path string, entry fs.DirEntry, err error) error {
|
||||
if err == nil && entry.IsDir() {
|
||||
_ = os.Chmod(path, 0o700)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
})
|
||||
return environment
|
||||
}
|
||||
|
||||
func prepareWorkflowModuleSum(t *testing.T, repository, moduleDir, proxy string) {
|
||||
t.Helper()
|
||||
cache := t.TempDir()
|
||||
t.Cleanup(func() {
|
||||
_ = filepath.WalkDir(cache, func(path string, entry fs.DirEntry, err error) error {
|
||||
if err == nil && entry.IsDir() {
|
||||
_ = os.Chmod(path, 0o700)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
})
|
||||
command := exec.Command("go", "mod", "download", "go.maximumdirect.net/releasekit@v0.2.197")
|
||||
command.Dir = filepath.Join(repository, filepath.FromSlash(moduleDir))
|
||||
command.Env = append(os.Environ(), "GOMODCACHE="+cache, "GOPROXY=file://"+filepath.ToSlash(proxy), "GOSUMDB=off", "GOWORK=off", "GOTOOLCHAIN=local", "GOFLAGS=-modcacherw")
|
||||
if output, err := command.CombinedOutput(); err != nil {
|
||||
t.Fatalf("prepare tagged module sums: %v\n%s", err, output)
|
||||
}
|
||||
}
|
||||
|
||||
func readWorkflowFile(t *testing.T, repository, name string) string {
|
||||
t.Helper()
|
||||
contents, err := os.ReadFile(filepath.Join(repository, filepath.FromSlash(name)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return string(contents)
|
||||
}
|
||||
616
cmd/releasekit/publication_handoff_test.go
Normal file
616
cmd/releasekit/publication_handoff_test.go
Normal file
@@ -0,0 +1,616 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/mod/modfile"
|
||||
|
||||
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
|
||||
"go.maximumdirect.net/releasekit/internal/gotool"
|
||||
"go.maximumdirect.net/releasekit/internal/publish"
|
||||
)
|
||||
|
||||
func TestSourceOnlyPublicationRecoveryAfterLauncherExit(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("fixture executes POSIX recovery commands")
|
||||
}
|
||||
repo, remote := newSimplePublishRepository(t, false)
|
||||
cliGitRun(t, repo, "rm", "go.mod")
|
||||
writeRepositoryFile(t, repo, "releasekit.json", `{"product":"Example Product","source":{},"version":{"format":"date"}}`)
|
||||
writeRepositoryFile(t, repo, "docs/releases/2026-12-01.md", "# Example Product 2026-12-01\n\nRelease.\n")
|
||||
cliGitRun(t, repo, "add", ".")
|
||||
cliGitRun(t, repo, "commit", "-m", "Configure source only publication")
|
||||
cliGitRun(t, repo, "push", "origin", "main")
|
||||
if err := os.WriteFile(filepath.Join(remote, "hooks", "pre-receive"), []byte("#!/bin/sh\nexit 1\n"), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
executable := filepath.Join(t.TempDir(), "releasekit")
|
||||
build := exec.Command(filepath.Join(runtime.GOROOT(), "bin", "go"), "build", "-o", executable, "./cmd/releasekit")
|
||||
build.Dir = repositoryRoot(t)
|
||||
if output, err := build.CombinedOutput(); err != nil {
|
||||
t.Fatalf("build CLI: %v: %s", err, output)
|
||||
}
|
||||
launcher := exec.Command(executable, "publish", "--repo", repo, "2026-12-01")
|
||||
output, err := launcher.CombinedOutput()
|
||||
var exitError *exec.ExitError
|
||||
if !errors.As(err, &exitError) || exitError.ExitCode() != 1 {
|
||||
t.Fatalf("publication: %v: %s", err, output)
|
||||
}
|
||||
command := outputLineValue(string(output), "recovery command: ")
|
||||
if command == "" || !strings.Contains(command, shellQuote(executable)) {
|
||||
t.Fatalf("missing installed tool handoff: %s", output)
|
||||
}
|
||||
recovery := exec.Command("sh", "-c", command)
|
||||
recovery.Dir = t.TempDir()
|
||||
recovered, err := recovery.CombinedOutput()
|
||||
if !errors.As(err, &exitError) || exitError.ExitCode() != 1 || !strings.Contains(string(recovered), "tag=2026-12-01 state=not_published") {
|
||||
t.Fatalf("source recovery: %v: %s", err, recovered)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVendoredAPIOnlyPublicationRecovery(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("fixture executes POSIX recovery commands")
|
||||
}
|
||||
repo, remote := newSimplePublishRepository(t, false)
|
||||
source := repositoryRoot(t)
|
||||
relative, err := filepath.Rel(repo, source)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writeRepositoryFile(t, repo, "go.mod", "module example.com/cli-candidate\n\ngo 1.27.0\n\nrequire go.maximumdirect.net/releasekit v0.0.0\n\nreplace go.maximumdirect.net/releasekit => "+strconv.Quote(relative)+"\n")
|
||||
writeRepositoryFile(t, repo, "uses_releasekit.go", "package candidate\nimport _ \"go.maximumdirect.net/releasekit\"\n")
|
||||
sums, err := os.ReadFile(filepath.Join(source, "go.sum"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writeRepositoryFile(t, repo, "go.sum", string(sums))
|
||||
goBinary := filepath.Join(runtime.GOROOT(), "bin", "go")
|
||||
for _, args := range [][]string{{"mod", "tidy"}, {"mod", "vendor"}} {
|
||||
command := exec.Command(goBinary, args...)
|
||||
command.Dir = repo
|
||||
if out, err := command.CombinedOutput(); err != nil {
|
||||
t.Fatalf("prepare vendored API: %v: %s", err, out)
|
||||
}
|
||||
}
|
||||
cliGitRun(t, repo, "add", ".")
|
||||
cliGitRun(t, repo, "commit", "-m", "Vendor API dependency")
|
||||
cliGitRun(t, repo, "push", "origin", "main")
|
||||
before := cliGitOutput(t, repo, "rev-parse", "HEAD^{tree}")
|
||||
if err := os.WriteFile(filepath.Join(remote, "hooks", "pre-receive"), []byte("#!/bin/sh\nexit 1\n"), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
launcherStore := t.TempDir()
|
||||
launcherArgs, err := gotool.RecoveryTool(t.Context(), repo, launcherStore)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
launcher := exec.Command(goBinary, append(launcherArgs.Args, "publish", "--repo", repo, "v1.2.3")...)
|
||||
launcher.Dir = launcherArgs.Directory
|
||||
publicationOutput, err := launcher.CombinedOutput()
|
||||
var exitError *exec.ExitError
|
||||
if !errors.As(err, &exitError) || exitError.ExitCode() != 1 {
|
||||
t.Fatalf("vendored publication: %v: %s", err, publicationOutput)
|
||||
}
|
||||
// The later handoff owns different launch metadata from the original driver.
|
||||
if err := os.RemoveAll(launcherStore); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
command := outputLineValue(string(publicationOutput), "recovery command: ")
|
||||
if command == "" {
|
||||
t.Fatalf("no handoff: %s", publicationOutput)
|
||||
}
|
||||
recovery := exec.Command("sh", "-c", command)
|
||||
recovery.Dir = t.TempDir()
|
||||
recovered, err := recovery.CombinedOutput()
|
||||
if !errors.As(err, &exitError) || exitError.ExitCode() != 1 || !strings.Contains(string(recovered), "module=example.com/cli-candidate tag=v1.2.3 state=not_published") {
|
||||
t.Fatalf("vendored recovery: %v: %s", err, recovered)
|
||||
}
|
||||
if status := cliGitOutput(t, repo, "status", "--porcelain"); status != "" {
|
||||
t.Fatalf("handoff changed consumer files: %s", status)
|
||||
}
|
||||
if after := cliGitOutput(t, repo, "write-tree"); after != before {
|
||||
t.Fatalf("handoff changed consumer index: %s != %s", after, before)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecoveryToolPreservesVersionedReplacement(t *testing.T) {
|
||||
proxy := writeReleaseKitModuleProxy(t)
|
||||
environment := make(map[string]string)
|
||||
useSyntheticModuleProxy(t, environment, "file://"+filepath.ToSlash(proxy))
|
||||
for key, value := range environment {
|
||||
t.Setenv(key, value)
|
||||
}
|
||||
module := t.TempDir()
|
||||
data := "module example.com/recovery-consumer\n\ngo 1.26.0\n\nrequire go.maximumdirect.net/releasekit v0.2.197\n\nreplace go.maximumdirect.net/releasekit v0.2.197 => go.maximumdirect.net/releasekit v0.2.198\n"
|
||||
if err := os.WriteFile(filepath.Join(module, "go.mod"), []byte(data), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
shimDir := t.TempDir()
|
||||
logPath := filepath.Join(t.TempDir(), "target")
|
||||
realGo := filepath.Join(runtime.GOROOT(), "bin", "go")
|
||||
shim := "#!/bin/sh\ncase \" $* \" in *\" -deps \"*) printf '%s/%s\\n' \"$GOOS\" \"$GOARCH\" > \"$RECOVERY_TARGET_LOG\" ;; esac\nexec \"$RECOVERY_REAL_GO\" \"$@\"\n"
|
||||
if err := os.WriteFile(filepath.Join(shimDir, "go"), []byte(shim), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("RECOVERY_TARGET_LOG", logPath)
|
||||
t.Setenv("RECOVERY_REAL_GO", realGo)
|
||||
t.Setenv("PATH", shimDir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||
foreignOS, foreignArch := foreignTarget()
|
||||
t.Setenv("GOOS", foreignOS)
|
||||
t.Setenv("GOARCH", foreignArch)
|
||||
args, err := gotool.RecoveryTool(t.Context(), module, t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if target, err := os.ReadFile(logPath); err != nil || strings.TrimSpace(string(target)) != runtime.GOOS+"/"+runtime.GOARCH {
|
||||
t.Fatalf("recovery preparation target = %q, %v", target, err)
|
||||
}
|
||||
command := exec.Command(realGo, args.Args...)
|
||||
command.Dir = args.Directory
|
||||
command.Env = setEnvironment(setEnvironment(os.Environ(), "GOOS", runtime.GOOS), "GOARCH", runtime.GOARCH)
|
||||
output, err := command.CombinedOutput()
|
||||
if err != nil || !strings.Contains(string(output), "tool-version=v0.2.198 helper=tool-only dependency") {
|
||||
t.Fatalf("versioned recovery selection: %v: %s", err, output)
|
||||
}
|
||||
after, err := os.ReadFile(filepath.Join(module, "go.mod"))
|
||||
if err != nil || string(after) != data {
|
||||
t.Fatalf("consumer metadata changed: %q, %v", after, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecoveryToolSupportsReleaseKitSourceModule(t *testing.T) {
|
||||
args, err := gotool.RecoveryTool(t.Context(), repositoryRoot(t), t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
command := exec.Command(filepath.Join(runtime.GOROOT(), "bin", "go"), append(args.Args, "version")...)
|
||||
command.Dir = args.Directory
|
||||
output, err := command.CombinedOutput()
|
||||
if err != nil || !strings.HasPrefix(string(output), "releasekit ") {
|
||||
t.Fatalf("source module recovery entry point: %v: %s", err, output)
|
||||
}
|
||||
}
|
||||
|
||||
func TestColdGoToolRecoverySurvivesLauncherExit(t *testing.T) {
|
||||
if runtime.GOOS != "linux" {
|
||||
t.Skip("fixture observes the cold executable through /proc")
|
||||
}
|
||||
for _, mode := range []struct{ registered, canceled bool }{{true, false}, {false, false}, {true, true}, {false, true}} {
|
||||
registered := mode.registered
|
||||
t.Run(fmt.Sprintf("registered=%t/canceled=%t", registered, mode.canceled), func(t *testing.T) {
|
||||
repo, remote := newSimplePublishRepository(t, false)
|
||||
source := repositoryRoot(t)
|
||||
// A distinct replacement identity gives this tool a fresh link action
|
||||
// while retaining the shared compilation cache for its dependencies.
|
||||
selectedSource := filepath.Join(t.TempDir(), "ReleaseKit source")
|
||||
if err := os.Symlink(source, selectedSource); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
const toolModule = "go.maximumdirect.net/releasekit"
|
||||
const toolVersion = "v0.0.0"
|
||||
module := "module example.com/cli-candidate\n\ngo 1.27.0\n\nrequire " + toolModule + " " + toolVersion + "\n"
|
||||
var wildcardSource string
|
||||
if registered {
|
||||
module += "\nreplace " + toolModule + " => " + strconv.Quote(selectedSource) + "\n"
|
||||
module += "\ntool " + toolModule + "/cmd/releasekit\n"
|
||||
} else {
|
||||
wildcardSource = t.TempDir()
|
||||
writeRepositoryFile(t, wildcardSource, "go.mod", "module "+toolModule+"\n\ngo 1.26.0\n")
|
||||
wildcard, err := filepath.Rel(repo, wildcardSource)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
specific, err := filepath.Rel(repo, selectedSource)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
module += "\nreplace (\n" + toolModule + " => " + strconv.Quote(wildcard) + "\n" + toolModule + " " + toolVersion + " => " + strconv.Quote(specific) + "\n)\n"
|
||||
}
|
||||
writeRepositoryFile(t, repo, "go.mod", module)
|
||||
sums, err := os.ReadFile(filepath.Join(source, "go.sum"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writeRepositoryFile(t, repo, "go.sum", string(sums))
|
||||
if !registered {
|
||||
for _, name := range []string{"release.sh", "select-module.sh"} {
|
||||
data, err := os.ReadFile(filepath.Join(source, "examples", "multi-module", name))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(repo, name), data, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
writeRepositoryFile(t, repo, "release-modules.tsv", "root\tv*\t.\treleasekit.json\n")
|
||||
}
|
||||
goBinary := filepath.Join(runtime.GOROOT(), "bin", "go")
|
||||
if registered {
|
||||
prepare := exec.Command(goBinary, "list", "-mod=mod", "-deps", "go.maximumdirect.net/releasekit/cmd/releasekit")
|
||||
prepare.Dir = repo
|
||||
if out, err := prepare.CombinedOutput(); err != nil {
|
||||
t.Fatalf("prepare tool: %v: %s", err, out)
|
||||
}
|
||||
}
|
||||
cliGitRun(t, repo, "add", ".")
|
||||
cliGitRun(t, repo, "commit", "-m", "Select release tool")
|
||||
cliGitRun(t, repo, "push", "origin", "main")
|
||||
if err := os.WriteFile(filepath.Join(remote, "hooks", "pre-receive"), []byte("#!/bin/sh\nexit 1\n"), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
realGit, err := exec.LookPath("git")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bin := t.TempDir()
|
||||
executed := filepath.Join(t.TempDir(), "executed-tool")
|
||||
wrapper := "#!/bin/sh\nparent=$(readlink \"/proc/$PPID/exe\")\ncase \"$parent\" in */exe/releasekit) printf '%s' \"$parent\" > " + shellQuote(executed) + ";; esac\n" + cancelPushScript + "exec " + shellQuote(realGit) + " \"$@\"\n"
|
||||
if err := os.WriteFile(filepath.Join(bin, "git"), []byte(wrapper), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||
var launch *exec.Cmd
|
||||
if registered {
|
||||
launch = exec.Command(goBinary, "tool", "releasekit", "publish", "--repo", repo, "v1.2.3")
|
||||
} else {
|
||||
launch = exec.Command(filepath.Join(repo, "release.sh"), "root", "v1.2.3")
|
||||
}
|
||||
launch.Dir = repo
|
||||
var out []byte
|
||||
if mode.canceled {
|
||||
out, err = canceledPublicationOutput(t, launch, repo, "")
|
||||
} else {
|
||||
out, err = launch.CombinedOutput()
|
||||
}
|
||||
var exitError *exec.ExitError
|
||||
if !errors.As(err, &exitError) || exitError.ExitCode() != 1 {
|
||||
t.Fatalf("publication: %v: %s", err, out)
|
||||
}
|
||||
text := string(out)
|
||||
launchedPath, err := os.ReadFile(executed)
|
||||
if err != nil {
|
||||
t.Fatalf("did not exercise a cold temporary executable: %v: %s", err, text)
|
||||
}
|
||||
if _, err := os.Stat(string(launchedPath)); !os.IsNotExist(err) {
|
||||
t.Fatalf("cold executable still exists: %s: %v", launchedPath, err)
|
||||
}
|
||||
entries, err := os.ReadDir(filepath.Dir(repo))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if strings.HasPrefix(entry.Name(), ".releasekit-bootstrap.") {
|
||||
t.Fatalf("launcher bootstrap survived: %s", entry.Name())
|
||||
}
|
||||
}
|
||||
command := outputLineValue(text, "recovery command: ")
|
||||
if !strings.Contains(command, "go ") || strings.Contains(command, "/exe/releasekit") {
|
||||
t.Fatalf("unstable handoff: %s", command)
|
||||
}
|
||||
if !registered {
|
||||
store := filepath.Join(repo, ".git", "releasekit", "publication-recovery")
|
||||
entries, err := os.ReadDir(store)
|
||||
if err != nil || len(entries) != 1 {
|
||||
t.Fatalf("API-only recovery modules = %v, %v", entries, err)
|
||||
}
|
||||
dir := filepath.Join(store, entries[0].Name())
|
||||
if !strings.Contains(command, shellQuote(dir)) {
|
||||
t.Fatalf("API-only handoff lacks durable metadata: %s", command)
|
||||
}
|
||||
path := filepath.Join(dir, "go.mod")
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
prepared, err := modfile.Parse(path, data, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
paths := map[string]string{}
|
||||
for _, replacement := range prepared.Replace {
|
||||
if replacement.Old.Path == toolModule {
|
||||
paths[replacement.Old.Version] = replacement.New.Path
|
||||
}
|
||||
}
|
||||
if len(paths) != 2 || paths[""] != wildcardSource || paths[toolVersion] != selectedSource {
|
||||
t.Fatalf("durable recovery lost replacement selection: %v", paths)
|
||||
}
|
||||
}
|
||||
// Execute from another directory after the original driver and the
|
||||
// API-only launcher's temporary files are gone.
|
||||
originalRecord := outputLineValue(text, "publication record saved: ")
|
||||
evidence, err := publish.LoadEvidence(originalRecord)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
evidence.Endpoint = filepath.Join(t.TempDir(), "unavailable.git")
|
||||
unknownRecord, err := publish.SaveEvidence(t.Context(), repo, t.TempDir(), evidence)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, scenario := range []struct {
|
||||
record string
|
||||
status int
|
||||
}{{"", 1}, {filepath.Join(t.TempDir(), "missing.json"), 2}, {unknownRecord, 3}, {"", 0}} {
|
||||
if scenario.status == 0 {
|
||||
if err := os.Remove(filepath.Join(remote, "hooks", "pre-receive")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cliGitRun(t, repo, "push", "origin", "refs/tags/v1.2.3")
|
||||
}
|
||||
selected := command
|
||||
if scenario.record != "" {
|
||||
selected = strings.Replace(selected, shellQuote(originalRecord), shellQuote(scenario.record), 1)
|
||||
}
|
||||
foreignOS, foreignArch := foreignTarget()
|
||||
goFunction := "go() { GOOS=" + shellQuote(foreignOS) + " GOARCH=" + shellQuote(foreignArch) + " command go \"$@\"; }\n"
|
||||
recovery := exec.Command("sh", "-c", goFunction+selected)
|
||||
recovery.Dir = t.TempDir()
|
||||
recovery.Env = setEnvironment(setEnvironment(os.Environ(), "GOOS", foreignOS), "GOARCH", foreignArch)
|
||||
recovered, err := recovery.CombinedOutput()
|
||||
if scenario.status == 0 && err != nil || scenario.status != 0 && (!errors.As(err, &exitError) || exitError.ExitCode() != scenario.status) {
|
||||
t.Fatalf("recovery status want %d: %v: %s", scenario.status, err, recovered)
|
||||
}
|
||||
if scenario.status == 1 && !strings.Contains(string(recovered), "state=not_published") {
|
||||
t.Fatalf("wrong observation: %s", recovered)
|
||||
}
|
||||
}
|
||||
if status := cliGitOutput(t, repo, "status", "--porcelain"); status != "" {
|
||||
t.Fatalf("handoff modified candidate: %s", status)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishRecordOverrideWarningDoesNotChangeSuccess(t *testing.T) {
|
||||
repository, _ := newSimplePublishRepository(t, true)
|
||||
var stdout, stderr bytes.Buffer
|
||||
status := run(t.Context(), []string{"publish", "--repo", repository, "--record-dir", "record-blocker", "v1.2.3"}, &stdout, &stderr)
|
||||
if status != 0 || !strings.Contains(stdout.String(), "published v1.2.3") {
|
||||
t.Fatalf("status = %d, stdout = %q, stderr = %q", status, stdout.String(), stderr.String())
|
||||
}
|
||||
if !strings.Contains(stderr.String(), "publication record warning:") || strings.Contains(stderr.String(), "publication record saved:") || strings.Contains(stderr.String(), "recovery command:") {
|
||||
t.Fatalf("recording warning or success handoff output = %q", stderr.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuiltPublishRecoveryCommandSelectsItsRecordAmongOtherAttempts(t *testing.T) {
|
||||
for _, mode := range []string{"rejected", "canceled", "preparation failure"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
|
||||
t.Setenv("GIT_CONFIG_GLOBAL", os.DevNull)
|
||||
t.Setenv("GIT_TERMINAL_PROMPT", "0")
|
||||
repository, remote := newSimplePublishRepository(t, false)
|
||||
store := filepath.Join(t.TempDir(), "attempt records with ' apostrophe")
|
||||
hook := filepath.Join(remote, "hooks", "pre-receive")
|
||||
if err := os.WriteFile(hook, []byte("#!/bin/sh\nexit 1\n"), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
goBinary := filepath.Join(runtime.GOROOT(), "bin", "go")
|
||||
executable := filepath.Join(t.TempDir(), "releasekit's CLI")
|
||||
build := exec.Command(goBinary, "build", "-o", executable, "./cmd/releasekit")
|
||||
build.Dir = repositoryRoot(t)
|
||||
if output, err := build.CombinedOutput(); err != nil {
|
||||
t.Fatalf("build CLI: %v\n%s", err, output)
|
||||
}
|
||||
|
||||
if mode == "canceled" {
|
||||
realGit, err := exec.LookPath("git")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bin := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(bin, "git"), []byte("#!/bin/sh\n"+cancelPushScript+"exec "+shellQuote(realGit)+" \"$@\"\n"), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||
}
|
||||
if mode == "preparation failure" {
|
||||
realGo, err := exec.LookPath("go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bin := t.TempDir()
|
||||
script := "#!/bin/sh\nif [ \"$1\" = list ] && [ \"$2\" = -e ]; then exit 73; fi\nexec " + shellQuote(realGo) + " \"$@\"\n"
|
||||
if err := os.WriteFile(filepath.Join(bin, "go"), []byte(script), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||
}
|
||||
command := exec.Command(executable, "publish", "--repo", repository, "--record-dir", store, "v1.2.3")
|
||||
command.Dir = repositoryRoot(t)
|
||||
var output []byte
|
||||
var err error
|
||||
if mode == "canceled" {
|
||||
output, err = canceledPublicationOutput(t, command, repository, store)
|
||||
} else {
|
||||
output, err = command.CombinedOutput()
|
||||
}
|
||||
var exitError *exec.ExitError
|
||||
if !errors.As(err, &exitError) || exitError.ExitCode() != 1 {
|
||||
t.Fatalf("publication exit = %v, output = %q; want status 1", err, output)
|
||||
}
|
||||
text := string(output)
|
||||
if mode == "preparation failure" && !strings.Contains(text, "recovery tool preparation warning:") {
|
||||
t.Fatalf("preparation warning missing: %s", text)
|
||||
}
|
||||
if !strings.Contains(text, "publication state=not_published phase=reconciliation") {
|
||||
t.Fatalf("publication failure classification changed: %q", text)
|
||||
}
|
||||
recordPath := outputLineValue(text, "publication record saved: ")
|
||||
if !filepath.IsAbs(recordPath) || !strings.Contains(recordPath, "attempt records with ' apostrophe") {
|
||||
t.Fatalf("saved record path = %q, output = %q", recordPath, text)
|
||||
}
|
||||
recoveryCommand := outputLineValue(text, "recovery command: ")
|
||||
if recoveryCommand == "" || !strings.Contains(recoveryCommand, shellQuote(executable)) || !strings.Contains(recoveryCommand, shellQuote(recordPath)) {
|
||||
t.Fatalf("copyable recovery command = %q, output = %q", recoveryCommand, text)
|
||||
}
|
||||
if !strings.Contains(text, "selected supported ReleaseKit CLI") {
|
||||
t.Fatalf("output omits guidance for an unavailable original executable: %q", text)
|
||||
}
|
||||
|
||||
for _, decoy := range []publish.Evidence{
|
||||
{RepositoryDir: repository, ModulePath: "example.com/other-module", Version: "v8.8.8", Tag: "v8.8.8", Endpoint: remote, Remote: "origin"},
|
||||
{RepositoryDir: repository, ModulePath: "example.com/retry", Version: "v1.2.4", Tag: "v1.2.4", Endpoint: remote, Remote: "origin"},
|
||||
} {
|
||||
if _, err := publish.SaveEvidence(t.Context(), repository, store, decoy); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
recovery := exec.Command("/bin/sh", "-c", recoveryCommand)
|
||||
recovery.Dir = t.TempDir()
|
||||
recoveryOutput, recoveryErr := recovery.CombinedOutput()
|
||||
if !errors.As(recoveryErr, &exitError) || exitError.ExitCode() != 1 {
|
||||
t.Fatalf("recovery command exit = %v, output = %q; want known absence status 1", recoveryErr, recoveryOutput)
|
||||
}
|
||||
recoveryText := string(recoveryOutput)
|
||||
if !strings.Contains(recoveryText, "module=example.com/cli-candidate tag=v1.2.3 state=not_published") || strings.Contains(recoveryText, "example.com/other-module") || strings.Contains(recoveryText, "example.com/retry") {
|
||||
t.Fatalf("printed command selected the wrong attempt: %q", recoveryText)
|
||||
}
|
||||
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestShellQuoteHandlesApostrophesAndSpaces(t *testing.T) {
|
||||
got := shellQuote("/tmp/ReleaseKit's recovery record.json")
|
||||
if got != "'/tmp/ReleaseKit'\"'\"'s recovery record.json'" {
|
||||
t.Fatalf("shellQuote() = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func newSimplePublishRepository(t *testing.T, recordBlocker bool) (string, string) {
|
||||
t.Helper()
|
||||
repository := newCLIRepository(t)
|
||||
settings, err := json.Marshal(cli.Settings{Product: "Example Product", Remote: "origin"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writeRepositoryFile(t, repository, "releasekit.json", string(settings))
|
||||
files := []string{"releasekit.json"}
|
||||
if recordBlocker {
|
||||
writeRepositoryFile(t, repository, "record-blocker", "tracked file\n")
|
||||
files = append(files, "record-blocker")
|
||||
}
|
||||
cliGitRun(t, repository, append([]string{"add"}, files...)...)
|
||||
cliGitRun(t, repository, "commit", "-m", "configure source release")
|
||||
remote := filepath.Join(t.TempDir(), "origin.git")
|
||||
cliGitRun(t, repository, "init", "--bare", "--initial-branch=main", remote)
|
||||
cliGitRun(t, repository, "remote", "add", "origin", remote)
|
||||
cliGitRun(t, repository, "push", "--set-upstream", "origin", "main")
|
||||
return repository, remote
|
||||
}
|
||||
|
||||
func outputLineValue(output, prefix string) string {
|
||||
for _, line := range strings.Split(output, "\n") {
|
||||
if strings.HasPrefix(line, prefix) {
|
||||
return strings.TrimPrefix(line, prefix)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func repositoryRoot(t *testing.T) string {
|
||||
t.Helper()
|
||||
directory, err := os.Getwd()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return filepath.Clean(filepath.Join(directory, "..", ".."))
|
||||
}
|
||||
|
||||
// The shim blocks exactly when Git would start the recorded tag push. The CLI
|
||||
// PID lets the test cancel the actual operation even behind a Go driver/launcher.
|
||||
const cancelPushScript = `if [ -n "$RELEASEKIT_CANCEL_PUSH_READY" ]; then
|
||||
for arg in "$@"; do
|
||||
if [ "$arg" = push ]; then
|
||||
printf '%s' "$PPID" > "$RELEASEKIT_CANCEL_PUSH_READY"
|
||||
exec sleep 600
|
||||
fi
|
||||
done
|
||||
fi
|
||||
`
|
||||
|
||||
func canceledPublicationOutput(t *testing.T, command *exec.Cmd, repo, store string) ([]byte, error) {
|
||||
t.Helper()
|
||||
ready := filepath.Join(t.TempDir(), "push-ready")
|
||||
command.Env = append(os.Environ(), "RELEASEKIT_CANCEL_PUSH_READY="+ready)
|
||||
var output bytes.Buffer
|
||||
command.Stdout = &output
|
||||
command.Stderr = &output
|
||||
if err := command.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer command.Process.Kill()
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- command.Wait() }()
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second)
|
||||
defer cancel()
|
||||
ticker := time.NewTicker(5 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
var operation *os.Process
|
||||
waiting:
|
||||
for {
|
||||
select {
|
||||
case err := <-done:
|
||||
t.Fatalf("publication finished before push interception: %v: %s", err, &output)
|
||||
case <-ctx.Done():
|
||||
_ = command.Process.Kill()
|
||||
<-done
|
||||
t.Fatal("publication never reached push interception")
|
||||
case <-ticker.C:
|
||||
data, err := os.ReadFile(ready)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
pid, err := strconv.Atoi(string(data))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
operation, err = os.FindProcess(pid)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer operation.Release()
|
||||
break waiting
|
||||
}
|
||||
}
|
||||
// Check the handoff identity before allowing cancellation to reach publication.
|
||||
listed, err := publish.ListAttempts(t.Context(), repo, store)
|
||||
if err != nil || len(listed.Attempts) != 1 || listed.Attempts[0].Evidence.TagObject == "" {
|
||||
_ = operation.Signal(os.Interrupt)
|
||||
<-done
|
||||
t.Fatalf("pre-push record is incomplete: %#v, %v", listed, err)
|
||||
}
|
||||
if err := operation.Signal(os.Interrupt); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case err := <-done:
|
||||
if !strings.Contains(output.String(), "context canceled") {
|
||||
t.Fatalf("publication lost its cancellation diagnostic: %s", &output)
|
||||
}
|
||||
return output.Bytes(), err
|
||||
case <-ctx.Done():
|
||||
_ = operation.Kill()
|
||||
_ = command.Process.Kill()
|
||||
<-done
|
||||
t.Fatal("canceled publication did not return")
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
351
cmd/releasekit/publication_recovery_workflow_test.go
Normal file
351
cmd/releasekit/publication_recovery_workflow_test.go
Normal file
@@ -0,0 +1,351 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"go.maximumdirect.net/releasekit"
|
||||
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
|
||||
)
|
||||
|
||||
func TestPublicationPushGateHelper(t *testing.T) {
|
||||
address := os.Getenv("RELEASEKIT_PUSH_GATE_ADDR")
|
||||
if address == "" {
|
||||
return
|
||||
}
|
||||
connection, err := net.DialTimeout("tcp", address, 10*time.Second)
|
||||
if err != nil {
|
||||
t.Fatalf("connect to pre-receive gate: %v", err)
|
||||
}
|
||||
defer connection.Close()
|
||||
if _, err := fmt.Fprintln(connection, "ready"); err != nil {
|
||||
t.Fatalf("announce pre-receive readiness: %v", err)
|
||||
}
|
||||
response, err := bufio.NewReader(connection).ReadString('\n')
|
||||
if err != nil || strings.TrimSpace(response) != "reject" {
|
||||
t.Fatalf("pre-receive gate response = %q, %v", response, err)
|
||||
}
|
||||
// The test process is the pre-receive hook's gate. Reject only after the
|
||||
// parent has observed the pre-push record and explicitly released it.
|
||||
t.Fatal("controlled rejection after pre-push record observation")
|
||||
}
|
||||
|
||||
func TestLostPublicationOutputCanBeRecoveredFromExplicitRecords(t *testing.T) {
|
||||
setIsolatedGitEnvironment(t)
|
||||
repository := newCLIRepository(t)
|
||||
store := filepath.Join(t.TempDir(), "publication records")
|
||||
checkLog := filepath.Join(t.TempDir(), "candidate checks.log")
|
||||
var hostedRequests atomic.Int64
|
||||
hostedServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
hostedRequests.Add(1)
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}))
|
||||
defer hostedServer.Close()
|
||||
|
||||
settings := cli.Settings{
|
||||
Product: "Example Product",
|
||||
Remote: "origin",
|
||||
Checks: []cli.CheckCommand{{
|
||||
Args: []string{"/bin/sh", "-c", "printf 'candidate\\n' >> \"$RELEASEKIT_CANDIDATE_LOG\""},
|
||||
Env: map[string]string{"RELEASEKIT_CANDIDATE_LOG": checkLog},
|
||||
}},
|
||||
Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: hostedServer.URL, Owner: "example", Repository: "candidate"},
|
||||
}
|
||||
writeSettings := func() {
|
||||
t.Helper()
|
||||
contents, err := json.Marshal(settings)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writeRepositoryFile(t, repository, "releasekit.json", string(contents))
|
||||
cliGitRun(t, repository, "add", "releasekit.json")
|
||||
cliGitRun(t, repository, "commit", "-m", "update publication profile")
|
||||
}
|
||||
writeSettings()
|
||||
remote := filepath.Join(t.TempDir(), "original.git")
|
||||
cliGitRun(t, repository, "init", "--bare", "--initial-branch=main", remote)
|
||||
cliGitRun(t, repository, "remote", "add", "origin", remote)
|
||||
cliGitRun(t, repository, "push", "--set-upstream", "origin", "main")
|
||||
|
||||
nestedDir := "integrations/recovery"
|
||||
writeRepositoryFile(t, repository, filepath.ToSlash(filepath.Join(nestedDir, "go.mod")), "module example.com/cli-candidate/recovery\n\ngo 1.25.0\n")
|
||||
writeRepositoryFile(t, repository, filepath.ToSlash(filepath.Join(nestedDir, "candidate_test.go")), "package recovery\nimport \"testing\"\nfunc TestFixture(t *testing.T) {}\n")
|
||||
writeRepositoryFile(t, repository, filepath.ToSlash(filepath.Join(nestedDir, "docs/releases/v1.2.3.md")), "# Example Product v1.2.3\n\nRecovery fixture.\n")
|
||||
cliGitRun(t, repository, "add", nestedDir)
|
||||
cliGitRun(t, repository, "commit", "-m", "add nested module")
|
||||
cliGitRun(t, repository, "push", "origin", "main")
|
||||
installPushGate(t, remote)
|
||||
|
||||
goBinary := filepath.Join(runtime.GOROOT(), "bin", "go")
|
||||
executable := filepath.Join(t.TempDir(), "releasekit recovery workflow")
|
||||
build := exec.Command(goBinary, "build", "-o", executable, "./cmd/releasekit")
|
||||
build.Dir = repositoryRoot(t)
|
||||
if output, err := build.CombinedOutput(); err != nil {
|
||||
t.Fatalf("build CLI: %v\n%s", err, output)
|
||||
}
|
||||
testBinary, err := os.Executable()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
rootTag := "v1.2.3"
|
||||
rootRecord := rejectPublicationAfterRecording(t, executable, testBinary, repository, store, rootTag, "")
|
||||
if rootRecord.Evidence.ModuleDir != repository || rootRecord.Evidence.Tag != rootTag {
|
||||
t.Fatalf("root attempt evidence = %#v", rootRecord.Evidence)
|
||||
}
|
||||
|
||||
settings.ModuleDir = nestedDir
|
||||
writeSettings()
|
||||
cliGitRun(t, repository, "push", "origin", "main")
|
||||
nestedTag := nestedDir + "/v1.2.3"
|
||||
nestedRecord := rejectPublicationAfterRecording(t, executable, testBinary, repository, store, nestedTag, nestedDir)
|
||||
if nestedRecord.Evidence.ModuleDir != filepath.Join(repository, nestedDir) || nestedRecord.Evidence.Tag != nestedTag {
|
||||
t.Fatalf("nested attempt evidence = %#v", nestedRecord.Evidence)
|
||||
}
|
||||
if rootRecord.RecordPath == nestedRecord.RecordPath {
|
||||
t.Fatalf("publication attempts reused record path %q", rootRecord.RecordPath)
|
||||
}
|
||||
|
||||
// Replace the rejected root tag on the original endpoint with a different
|
||||
// annotated object, then make the current checkout point somewhere else.
|
||||
hook := filepath.Join(remote, "hooks", "pre-receive")
|
||||
if err := os.Remove(hook); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cliGitRun(t, repository, "tag", "-f", "-a", rootTag, "-m", "remote replacement after failed attempt", "HEAD")
|
||||
cliGitRun(t, repository, "push", "origin", "refs/tags/"+rootTag)
|
||||
decoyRemote := filepath.Join(t.TempDir(), "replacement-origin.git")
|
||||
cliGitRun(t, repository, "init", "--bare", "--initial-branch=main", decoyRemote)
|
||||
cliGitRun(t, repository, "remote", "set-url", "origin", decoyRemote)
|
||||
cliGitRun(t, repository, "switch", "-c", "recovery-inspection")
|
||||
cliGitRun(t, repository, "commit", "--allow-empty", "-m", "move recovery checkout")
|
||||
cliGitRun(t, repository, "tag", "-d", rootTag, nestedTag)
|
||||
writeRepositoryFile(t, repository, "untracked recovery marker", "preserve this file\n")
|
||||
|
||||
before := snapshotRecoveryRepository(t, repository, remote, rootRecord.RecordPath, nestedRecord.RecordPath)
|
||||
listing := runCLIJSON(t, executable, t.TempDir(), "publication-attempts", "--repo", repository, "--record-dir", store, "--json")
|
||||
var listed struct {
|
||||
Attempts []struct {
|
||||
RecordPath string `json:"record_path"`
|
||||
Evidence struct {
|
||||
Tag string `json:"tag"`
|
||||
ModuleDir string `json:"module_dir"`
|
||||
} `json:"evidence"`
|
||||
} `json:"attempts"`
|
||||
}
|
||||
if err := json.Unmarshal(listing, &listed); err != nil {
|
||||
t.Fatalf("decode publication-attempts output: %v\n%s", err, listing)
|
||||
}
|
||||
selectedRoot := ""
|
||||
selectedNested := ""
|
||||
for _, attempt := range listed.Attempts {
|
||||
switch attempt.Evidence.Tag {
|
||||
case rootTag:
|
||||
selectedRoot = attempt.RecordPath
|
||||
case nestedTag:
|
||||
selectedNested = attempt.RecordPath
|
||||
}
|
||||
}
|
||||
if selectedRoot != rootRecord.RecordPath || selectedNested != nestedRecord.RecordPath {
|
||||
t.Fatalf("discovery selected root=%q nested=%q; want %q and %q; listing=%s", selectedRoot, selectedNested, rootRecord.RecordPath, nestedRecord.RecordPath, listing)
|
||||
}
|
||||
|
||||
rootResult := runCLIStatusJSON(t, executable, t.TempDir(), "reconcile", "--record", selectedRoot, "--json")
|
||||
if rootResult.status != 1 || rootResult.document["state"] != "conflict" {
|
||||
t.Fatalf("explicit root reconciliation status=%d document=%s; want conflict on the recorded original endpoint", rootResult.status, rootResult.output)
|
||||
}
|
||||
nestedResult := runCLIStatusJSON(t, executable, t.TempDir(), "reconcile", "--record", selectedNested, "--json")
|
||||
if nestedResult.status != 1 || nestedResult.document["state"] != "not_published" {
|
||||
t.Fatalf("explicit nested reconciliation status=%d document=%s; want not_published", nestedResult.status, nestedResult.output)
|
||||
}
|
||||
if got := hostedRequests.Load(); got != 0 {
|
||||
t.Fatalf("later recovery made %d hosted delivery requests", got)
|
||||
}
|
||||
after := snapshotRecoveryRepository(t, repository, remote, rootRecord.RecordPath, nestedRecord.RecordPath)
|
||||
if before != after {
|
||||
t.Fatalf("reconciliation changed local or saved state:\nbefore: %#v\nafter: %#v", before, after)
|
||||
}
|
||||
checkBytes, err := os.ReadFile(checkLog)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := strings.Count(string(checkBytes), "candidate\n"); got != 2 {
|
||||
t.Fatalf("candidate checks ran %d times; want once per publication and none during recovery: %q", got, checkBytes)
|
||||
}
|
||||
}
|
||||
|
||||
type listedAttempt struct {
|
||||
RecordPath string
|
||||
Evidence releasekit.PublicationEvidence
|
||||
}
|
||||
|
||||
func rejectPublicationAfterRecording(t *testing.T, executable, testBinary, repository, store, tag, expectedModule string) listedAttempt {
|
||||
t.Helper()
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer listener.Close()
|
||||
commandArgs := []string{"publish", "--repo", repository, "--record-dir", store}
|
||||
if expectedModule != "" {
|
||||
commandArgs = append(commandArgs, "--expected-module", expectedModule)
|
||||
}
|
||||
commandArgs = append(commandArgs, "v1.2.3")
|
||||
command := exec.Command(executable, commandArgs...)
|
||||
command.Dir = repositoryRoot(t)
|
||||
command.Env = append(os.Environ(), "RELEASEKIT_PUSH_GATE_ADDR="+listener.Addr().String(), "RELEASEKIT_PUSH_GATE_TEST_BINARY="+testBinary)
|
||||
command.Stdout = io.Discard
|
||||
command.Stderr = io.Discard
|
||||
if err := command.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() {
|
||||
if command.Process != nil {
|
||||
_ = command.Process.Kill()
|
||||
_ = command.Wait()
|
||||
}
|
||||
}()
|
||||
if tcpListener, ok := listener.(*net.TCPListener); ok {
|
||||
if err := tcpListener.SetDeadline(time.Now().Add(90 * time.Second)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
connection, err := listener.Accept()
|
||||
if err != nil {
|
||||
t.Fatalf("wait for pre-receive gate for %s: %v", tag, err)
|
||||
}
|
||||
defer connection.Close()
|
||||
if tcpConnection, ok := connection.(*net.TCPConn); ok {
|
||||
if err := tcpConnection.SetDeadline(time.Now().Add(30 * time.Second)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
line, err := bufio.NewReader(connection).ReadString('\n')
|
||||
if err != nil || strings.TrimSpace(line) != "ready" {
|
||||
t.Fatalf("pre-receive gate readiness for %s = %q, %v", tag, line, err)
|
||||
}
|
||||
listed, err := releasekit.ListPublicationAttempts(context.Background(), releasekit.PublicationAttemptsRequest{RepositoryDir: repository, RecordDir: store})
|
||||
if err != nil {
|
||||
t.Fatalf("list attempts while tag push is held: %v", err)
|
||||
}
|
||||
var selected *releasekit.PublicationAttempt
|
||||
for i := range listed.Attempts {
|
||||
if listed.Attempts[i].Evidence.Tag == tag {
|
||||
selected = &listed.Attempts[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
if selected == nil {
|
||||
t.Fatalf("pre-push record for %s was not visible before the hook continued: %#v", tag, listed.Attempts)
|
||||
}
|
||||
if selected.Evidence.CandidateCommit == "" || selected.Evidence.TagObject == "" || selected.Evidence.Endpoint == "" {
|
||||
t.Fatalf("pre-push evidence for %s is incomplete: %#v", tag, selected.Evidence)
|
||||
}
|
||||
if _, err := fmt.Fprintln(connection, "reject"); err != nil {
|
||||
t.Fatalf("release pre-receive gate for %s: %v", tag, err)
|
||||
}
|
||||
waitErr := command.Wait()
|
||||
command.Process = nil
|
||||
if waitErr == nil {
|
||||
t.Fatalf("publish %s succeeded despite the controlled rejection", tag)
|
||||
} else {
|
||||
var exitError *exec.ExitError
|
||||
if !errors.As(waitErr, &exitError) || exitError.ExitCode() != 1 {
|
||||
t.Fatalf("publish %s exit = %v; want publication failure status 1", tag, waitErr)
|
||||
}
|
||||
}
|
||||
return listedAttempt{RecordPath: selected.RecordPath, Evidence: selected.Evidence}
|
||||
}
|
||||
|
||||
func installPushGate(t *testing.T, remote string) {
|
||||
t.Helper()
|
||||
hook := filepath.Join(remote, "hooks", "pre-receive")
|
||||
script := "#!/bin/sh\nwhile read old new ref; do\n case \"$ref\" in\n refs/tags/*) \"$RELEASEKIT_PUSH_GATE_TEST_BINARY\" -test.run='^TestPublicationPushGateHelper$'; exit $? ;;\n esac\ndone\nexit 0\n"
|
||||
if err := os.WriteFile(hook, []byte(script), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func setIsolatedGitEnvironment(t *testing.T) {
|
||||
t.Helper()
|
||||
t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
|
||||
t.Setenv("GIT_CONFIG_GLOBAL", os.DevNull)
|
||||
t.Setenv("GIT_TERMINAL_PROMPT", "0")
|
||||
}
|
||||
|
||||
func runCLIJSON(t *testing.T, executable, directory string, args ...string) []byte {
|
||||
t.Helper()
|
||||
result := runCLIStatusJSON(t, executable, directory, args...)
|
||||
if result.status != 0 {
|
||||
t.Fatalf("CLI %v exited with status %d: %s", args, result.status, result.output)
|
||||
}
|
||||
return result.output
|
||||
}
|
||||
|
||||
type cliJSONResult struct {
|
||||
status int
|
||||
output []byte
|
||||
document map[string]any
|
||||
}
|
||||
|
||||
func runCLIStatusJSON(t *testing.T, executable, directory string, args ...string) cliJSONResult {
|
||||
t.Helper()
|
||||
command := exec.Command(executable, args...)
|
||||
command.Dir = directory
|
||||
output, err := command.CombinedOutput()
|
||||
status := 0
|
||||
if err != nil {
|
||||
var exitError *exec.ExitError
|
||||
if !errors.As(err, &exitError) {
|
||||
t.Fatalf("run CLI %v: %v\n%s", args, err, output)
|
||||
}
|
||||
status = exitError.ExitCode()
|
||||
}
|
||||
var document map[string]any
|
||||
if err := json.Unmarshal(output, &document); err != nil {
|
||||
t.Fatalf("decode CLI JSON for %v: %v\n%s", args, err, output)
|
||||
}
|
||||
return cliJSONResult{status: status, output: output, document: document}
|
||||
}
|
||||
|
||||
type recoverySnapshot struct {
|
||||
Branch string
|
||||
Head string
|
||||
Worktree string
|
||||
LocalRefs string
|
||||
RemoteRefs string
|
||||
Records string
|
||||
}
|
||||
|
||||
func snapshotRecoveryRepository(t *testing.T, repository, remote string, recordPaths ...string) recoverySnapshot {
|
||||
t.Helper()
|
||||
branch := cliGitOutput(t, repository, "branch", "--show-current")
|
||||
head := cliGitOutput(t, repository, "rev-parse", "HEAD")
|
||||
worktree := cliGitOutput(t, repository, "status", "--porcelain=v1", "--untracked-files=all")
|
||||
localRefs := cliGitOutput(t, repository, "show-ref")
|
||||
remoteRefs := cliGitOutput(t, remote, "show-ref")
|
||||
var records strings.Builder
|
||||
for _, path := range recordPaths {
|
||||
contents, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatalf("read saved record %s: %v", path, err)
|
||||
}
|
||||
fmt.Fprintf(&records, "%s\x00%s\n", path, contents)
|
||||
}
|
||||
return recoverySnapshot{Branch: branch, Head: head, Worktree: worktree, LocalRefs: localRefs, RemoteRefs: remoteRefs, Records: records.String()}
|
||||
}
|
||||
170
cmd/releasekit/readiness.go
Normal file
170
cmd/releasekit/readiness.go
Normal 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
|
||||
}
|
||||
330
cmd/releasekit/readiness_test.go
Normal file
330
cmd/releasekit/readiness_test.go
Normal file
@@ -0,0 +1,330 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
|
||||
)
|
||||
|
||||
func TestValidateReportsUnavailableOnlineObservation(t *testing.T) {
|
||||
repo, _ := newSimplePublishRepository(t, false)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
t.Errorf("unexpected remote write %s", r.Method)
|
||||
}
|
||||
http.Error(w, "unavailable", http.StatusServiceUnavailable)
|
||||
}))
|
||||
defer server.Close()
|
||||
profile := fmt.Sprintf(`{"product":"Config","source":{},"delivery":{"forge":"gitea","base_url":%q,"owner":"owner","repository":"example","credentials":{"ci":{}}}}`, server.URL)
|
||||
writeRepositoryFile(t, repo, "releasekit.json", profile)
|
||||
t.Setenv("RELEASEKIT_DELIVERY_TOKEN", "fixture-token")
|
||||
var output bytes.Buffer
|
||||
status := run(context.Background(), []string{"validate", "--repo", repo, "--context", "ci", "--operation", "delivery", "--json"}, &output, &bytes.Buffer{})
|
||||
if status != 1 || !strings.Contains(output.String(), `"reason":"remote"`) || strings.Contains(output.String(), "fixture-token") {
|
||||
t.Fatalf("status=%d output=%s", status, &output)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateAggregatesDestinationAndCredentialFailures(t *testing.T) {
|
||||
repo, _ := newSimplePublishRepository(t, false)
|
||||
writeRepositoryFile(t, repo, "releasekit.json", `{"product":"Config","source":{},"delivery":{"forge":"gitea","base_url":"ssh://invalid","owner":"owner","repository":"example","credentials":{"local":{"token_file":"missing"}}}}`)
|
||||
var output bytes.Buffer
|
||||
status := run(context.Background(), []string{"validate", "--repo", repo, "--operation", "delivery", "--json"}, &output, &bytes.Buffer{})
|
||||
if status != 2 || !strings.Contains(output.String(), `"id":"delivery-inputs","operation":"delivery","status":"failed"`) || !strings.Contains(output.String(), `"id":"delivery-credential","operation":"delivery","status":"failed"`) || !strings.Contains(output.String(), `"id":"delivery-access","operation":"delivery","status":"skipped"`) {
|
||||
t.Fatalf("status=%d output=%s", status, &output)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidatePrebuiltInputsWithoutWorkingReleaseNote(t *testing.T) {
|
||||
repo := newCLIRepository(t)
|
||||
build := cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}}
|
||||
writeDeliveryProfile(t, repo, cli.Settings{Product: "Example Product", Build: &build, Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: "https://gitea.example", Owner: "owner", Repository: "example"}})
|
||||
assets, binary := writeDeliveryReceipt(t, repo, build)
|
||||
if err := os.Remove(filepath.Join(repo, "docs", "releases", "v1.2.3.md")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var output bytes.Buffer
|
||||
args := []string{"validate", "--repo", repo, "--operation", "delivery", "--offline", "--assets", assets, "--json"}
|
||||
if status := run(context.Background(), args, &output, &bytes.Buffer{}); status != 0 {
|
||||
t.Fatalf("status=%d report=%s", status, &output)
|
||||
}
|
||||
if err := os.WriteFile(binary, []byte("tampered artifact"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
output.Reset()
|
||||
if status := run(context.Background(), args, &output, &bytes.Buffer{}); status != 2 || !strings.Contains(output.String(), `"id":"prebuilt"`) {
|
||||
t.Fatalf("tampered status=%d report=%s", status, &output)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateOnlineUsesReadOnlyDeliveryPreflight(t *testing.T) {
|
||||
repo, _ := newSimplePublishRepository(t, false)
|
||||
state := &deliveryServerState{}
|
||||
server := newDeliveryServer(t, state)
|
||||
defer server.Close()
|
||||
profile := fmt.Sprintf(`{"product":"Config","source":{},"delivery":{"forge":"gitea","base_url":%q,"owner":"owner","repository":"example","credentials":{"ci":{"token_environment_variable":"READINESS_TEST_TOKEN"}}}}`, server.URL)
|
||||
writeRepositoryFile(t, repo, "releasekit.json", profile)
|
||||
t.Setenv("READINESS_TEST_TOKEN", "fixture-token")
|
||||
var output bytes.Buffer
|
||||
status := run(context.Background(), []string{"validate", "--repo", repo, "--context", "ci", "--operation", "delivery", "--json"}, &output, &bytes.Buffer{})
|
||||
if status != 0 || state.snapshot().apiRequests != 2 || state.snapshot().releaseCreates != 0 || state.snapshot().assetUploads != 0 || strings.Contains(output.String(), "fixture-token") {
|
||||
t.Fatalf("status=%d requests=%d creates=%d output=%s", status, state.snapshot().apiRequests, state.snapshot().releaseCreates, &output)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateBuildChecksInputsWithoutBuilding(t *testing.T) {
|
||||
repo := newCLIRepository(t)
|
||||
writeRepositoryFile(t, repo, "main.go", "package main\nfunc main() {}\n")
|
||||
writeRepositoryFile(t, repo, "releasekit.json", `{"product":"Example Product","build":{"main_package":".","binary_name":"helper","targets":["linux/amd64"]},"checks":[{"args":["false"]}]}`)
|
||||
shim := t.TempDir()
|
||||
log := filepath.Join(shim, "calls")
|
||||
script := "#!/bin/sh\nprintf '%s\\n' \"$*\" >> \"$READINESS_GO_LOG\"\nif [ \"$1\" = version ]; then echo 'go version go1.27.4 linux/amd64'; exit 0; fi\nexit 99\n"
|
||||
if err := os.WriteFile(filepath.Join(shim, "go"), []byte(script), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("READINESS_GO_LOG", log)
|
||||
t.Setenv("PATH", shim+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||
var output bytes.Buffer
|
||||
status := run(context.Background(), []string{"validate", "--repo", repo, "--operation", "build", "--offline", "--json"}, &output, &bytes.Buffer{})
|
||||
calls, err := os.ReadFile(log)
|
||||
if err != nil || status != 0 || string(calls) != "version\n" || !strings.Contains(output.String(), `"id":"go-dependencies","operation":"go","status":"unchecked"`) {
|
||||
t.Fatalf("status=%d calls=%q error=%v output=%s", status, calls, err, &output)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(repo, "dist")); !os.IsNotExist(err) {
|
||||
t.Fatalf("validation created build outputs: %v", err)
|
||||
}
|
||||
writeRepositoryFile(t, repo, "go.mod", "module example.com/cli-candidate\n\ngo 1.28.0\n")
|
||||
output.Reset()
|
||||
status = run(context.Background(), []string{"validate", "--repo", repo, "--operation", "build", "--offline", "--json"}, &output, &bytes.Buffer{})
|
||||
if status != 2 || !strings.Contains(output.String(), "older than declared Go 1.28.0") {
|
||||
t.Fatalf("toolchain status=%d report=%s", status, &output)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateOfflineInspectsWorkingSourceWithoutReleaseNote(t *testing.T) {
|
||||
repo, remote := newSimplePublishRepository(t, false)
|
||||
writeRepositoryFile(t, repo, "releasekit.json", `{"product":"Config","source":{},"readiness":{"required_files":["required.txt"]}}`)
|
||||
writeRepositoryFile(t, repo, "required.txt", "local input\n")
|
||||
before := cliGitOutput(t, remote, "show-ref", "--heads")
|
||||
var output bytes.Buffer
|
||||
status := run(context.Background(), []string{"validate", "--repo", repo, "--offline", "--json"}, &output, &bytes.Buffer{})
|
||||
var report readinessDocument
|
||||
if err := json.Unmarshal(output.Bytes(), &report); err != nil {
|
||||
t.Fatalf("decode: %v: %s", err, output.String())
|
||||
}
|
||||
if status != 0 || report.SchemaVersion != 1 || report.Command != "validate" || report.InputSource != "working" || !report.Offline || len(report.Operations) != 1 || report.Operations[0] != "publication" {
|
||||
t.Fatalf("status=%d report=%+v", status, report)
|
||||
}
|
||||
found := false
|
||||
for _, check := range report.Checks {
|
||||
if check.ID == "git-main" && check.Status == "unchecked" && check.Reason == "offline" {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("missing offline evidence: %+v", report.Checks)
|
||||
}
|
||||
if got := cliGitOutput(t, remote, "show-ref", "--heads"); got != before {
|
||||
t.Fatalf("validation changed remote refs: %s != %s", got, before)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidatePublicationReadsMainWithoutRequiringCurrentCommit(t *testing.T) {
|
||||
repo, remote := newSimplePublishRepository(t, false)
|
||||
before := cliGitOutput(t, remote, "rev-parse", "refs/heads/main")
|
||||
writeRepositoryFile(t, repo, "new-file", "unpublished\n")
|
||||
cliGitRun(t, repo, "add", "new-file")
|
||||
cliGitRun(t, repo, "commit", "-m", "unpublished work")
|
||||
writeRepositoryFile(t, repo, "releasekit.json", `{"product":"Config","source":{}}`)
|
||||
var output bytes.Buffer
|
||||
status := run(context.Background(), []string{"validate", "--repo", repo, "--operation", "publication", "--json"}, &output, &bytes.Buffer{})
|
||||
if status != 0 || !strings.Contains(output.String(), `"id":"git-main","operation":"publication","status":"passed"`) {
|
||||
t.Fatalf("status=%d output=%s", status, &output)
|
||||
}
|
||||
if got := cliGitOutput(t, remote, "rev-parse", "refs/heads/main"); got != before {
|
||||
t.Fatalf("validation changed remote main to %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateOfflineChecksGitIdentity(t *testing.T) {
|
||||
repo, _ := newSimplePublishRepository(t, false)
|
||||
writeRepositoryFile(t, repo, "releasekit.json", `{"product":"Config","source":{}}`)
|
||||
cliGitRun(t, repo, "config", "--unset", "user.name")
|
||||
cliGitRun(t, repo, "config", "--unset", "user.email")
|
||||
t.Setenv("GIT_CONFIG_GLOBAL", os.DevNull)
|
||||
t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
|
||||
t.Setenv("GIT_COMMITTER_NAME", "")
|
||||
t.Setenv("GIT_COMMITTER_EMAIL", "")
|
||||
t.Setenv("EMAIL", "")
|
||||
var output bytes.Buffer
|
||||
status := run(context.Background(), []string{"validate", "--repo", repo, "--offline", "--json"}, &output, &bytes.Buffer{})
|
||||
if status != 2 || !strings.Contains(output.String(), `"id":"git-identity","operation":"publication","status":"failed"`) {
|
||||
t.Fatalf("status=%d output=%s", status, &output)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateAggregatesInputsAndKeepsCredentialContextsSeparate(t *testing.T) {
|
||||
repo, _ := newSimplePublishRepository(t, false)
|
||||
profile := `{"product":"Config","source":{},"readiness":{"required_files":["absent"]},"delivery":{"forge":"gitea","base_url":"https://gitea.example","owner":"owner","repository":"project","credentials":{"local":{"token_file":"absent-token"},"ci":{"token_environment_variable":"READINESS_TEST_TOKEN"}}}}`
|
||||
writeRepositoryFile(t, repo, "releasekit.json", profile)
|
||||
t.Setenv("READINESS_TEST_TOKEN", "secret-value")
|
||||
var output bytes.Buffer
|
||||
status := run(context.Background(), []string{"validate", "--repo", repo, "--context", "ci", "--operation", "delivery", "--offline", "--json"}, &output, &bytes.Buffer{})
|
||||
var report readinessDocument
|
||||
if err := json.Unmarshal(output.Bytes(), &report); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if status != 2 || strings.Contains(output.String(), "secret-value") {
|
||||
t.Fatalf("status=%d report=%s", status, &output)
|
||||
}
|
||||
required, destination := false, false
|
||||
for _, check := range report.Checks {
|
||||
if check.ID == "required-file" && check.Status == "failed" {
|
||||
required = true
|
||||
}
|
||||
if check.ID == "delivery-inputs" && check.Status == "passed" {
|
||||
destination = true
|
||||
}
|
||||
}
|
||||
if !required || !destination {
|
||||
t.Fatalf("checks = %+v", report.Checks)
|
||||
}
|
||||
writeRepositoryFile(t, repo, "absent", "present\n")
|
||||
output.Reset()
|
||||
status = run(context.Background(), []string{"validate", "--repo", repo, "--context", "local", "--operation", "delivery", "--offline", "--json"}, &output, &bytes.Buffer{})
|
||||
if status != 2 || strings.Contains(output.String(), "secret-value") || !strings.Contains(output.String(), "absent-token") {
|
||||
t.Fatalf("local status=%d report=%s", status, &output)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateReportsMalformedProfileAsJSON(t *testing.T) {
|
||||
repo := newCLIRepository(t)
|
||||
if err := os.WriteFile(filepath.Join(repo, "releasekit.json"), []byte("{"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var output bytes.Buffer
|
||||
status := run(context.Background(), []string{"validate", "--repo", repo, "--json"}, &output, &bytes.Buffer{})
|
||||
var report readinessDocument
|
||||
if err := json.Unmarshal(output.Bytes(), &report); err != nil || status != 2 || len(report.Checks) != 1 || report.Checks[0].ID != "profile" {
|
||||
t.Fatalf("status=%d report=%s err=%v", status, &output, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateSkipsAssetsWhenSourceIsUnavailable(t *testing.T) {
|
||||
repo := newCLIRepository(t)
|
||||
writeRepositoryFile(t, repo, "releasekit.json", `{"product":"Example","source":{"dir":"missing"},"delivery":{"forge":"gitea","base_url":"https://gitea.example","owner":"owner","repository":"example","credentials":{"ci":{}}}}`)
|
||||
t.Setenv("RELEASEKIT_DELIVERY_TOKEN", "fixture-token")
|
||||
var output bytes.Buffer
|
||||
status := run(context.Background(), []string{"validate", "--repo", repo, "--context", "ci", "--operation", "delivery", "--offline", "--assets", "dist", "--json"}, &output, &bytes.Buffer{})
|
||||
if status != 2 || !strings.Contains(output.String(), `"id":"prebuilt","operation":"delivery","status":"skipped"`) {
|
||||
t.Fatalf("status=%d output=%s", status, &output)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateRejectsInconsistentSourceSelection(t *testing.T) {
|
||||
repo := newCLIRepository(t)
|
||||
for _, profile := range []string{
|
||||
`{"product":"Example","go":{},"publication":{"mode":"go-module"},"version":{"format":"date"}}`,
|
||||
`{"product":"Example","source":{"tag_prefix":"bad..tag"}}`,
|
||||
} {
|
||||
writeRepositoryFile(t, repo, "releasekit.json", profile)
|
||||
var output bytes.Buffer
|
||||
status := run(context.Background(), []string{"validate", "--repo", repo, "--operation", "go", "--offline", "--json"}, &output, &bytes.Buffer{})
|
||||
if status != 2 || !strings.Contains(output.String(), `"id":"source","operation":"configuration","status":"failed"`) {
|
||||
t.Fatalf("status=%d output=%s profile=%s", status, &output, profile)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateRehearsalObservesWoodpeckerWithSeparateLocalCredential(t *testing.T) {
|
||||
repo, _ := newSimplePublishRepository(t, false)
|
||||
state := &deliveryServerState{}
|
||||
forgeServer := newDeliveryServer(t, state)
|
||||
defer forgeServer.Close()
|
||||
calls := 0
|
||||
ciServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls++
|
||||
if r.Method != http.MethodGet || r.URL.Path != "/api/repos/42" || r.Header.Get("Authorization") != "Bearer woodpecker-private-value" {
|
||||
t.Errorf("unexpected Woodpecker request %s %s", r.Method, r.URL.Path)
|
||||
http.Error(w, "invalid", 400)
|
||||
return
|
||||
}
|
||||
fmt.Fprint(w, `{"id":42}`)
|
||||
}))
|
||||
defer ciServer.Close()
|
||||
writeRepositoryFile(t, repo, "forge-token", "fixture-token\n")
|
||||
writeRepositoryFile(t, repo, "ci-token", "woodpecker-private-value\n")
|
||||
profile := fmt.Sprintf(`{"product":"Config","source":{},"delivery":{"forge":"gitea","base_url":%q,"owner":"owner","repository":"example","credentials":{"local":{"token_file":"forge-token"},"ci":{}}},"rehearsal":{"woodpecker":{"base_url":%q,"repository_id":42,"workflow":"release","step":"deliver","token_file":"ci-token"}}}`, forgeServer.URL, ciServer.URL)
|
||||
writeRepositoryFile(t, repo, "releasekit.json", profile)
|
||||
var output bytes.Buffer
|
||||
status := run(context.Background(), []string{"validate", "--repo", repo, "--operation", "rehearsal", "--json"}, &output, &bytes.Buffer{})
|
||||
if status != 0 || calls != 1 || !strings.Contains(output.String(), `"id":"woodpecker-access","operation":"rehearsal","status":"passed"`) || strings.Contains(output.String(), "woodpecker-private-value") || strings.Contains(output.String(), "fixture-token") {
|
||||
t.Fatalf("status=%d calls=%d report=%s", status, calls, output.String())
|
||||
}
|
||||
output.Reset()
|
||||
calls = 0
|
||||
status = run(context.Background(), []string{"validate", "--repo", repo, "--operation", "rehearsal", "--offline", "--json"}, &output, &bytes.Buffer{})
|
||||
if status != 0 || calls != 0 || !strings.Contains(output.String(), `"id":"woodpecker-access","operation":"rehearsal","status":"unchecked","reason":"offline"`) {
|
||||
t.Fatalf("offline status=%d calls=%d report=%s", status, calls, output.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateChecksSelectedExecutionConfiguration(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name, operation, selector string
|
||||
goChecks map[string]any
|
||||
missingCI, online bool
|
||||
want int
|
||||
}{
|
||||
{name: "source race", goChecks: map[string]any{"race": true}, want: 2},
|
||||
{name: "source vet", goChecks: map[string]any{"full_vet": true}, want: 2},
|
||||
{name: "source compilation", goChecks: map[string]any{"compile_targets": []string{"linux/amd64"}}, want: 2},
|
||||
{name: "narrow local delivery", operation: "delivery", goChecks: map[string]any{"race": true}},
|
||||
{name: "missing CI offline", operation: "rehearsal", missingCI: true, want: 2},
|
||||
{name: "missing CI online", operation: "rehearsal", missingCI: true, online: true, want: 2},
|
||||
{name: "selector slash", operation: "rehearsal", selector: "invalid/selector", want: 2},
|
||||
{name: "selector ref syntax", operation: "rehearsal", selector: "invalid..selector", want: 2},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
repo, _ := newSimplePublishRepository(t, false)
|
||||
forge := newDeliveryServer(t, &deliveryServerState{})
|
||||
defer forge.Close()
|
||||
ci := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, `{"id":42}`) }))
|
||||
defer ci.Close()
|
||||
writeRepositoryFile(t, repo, "forge-token", "fixture-token\n")
|
||||
writeRepositoryFile(t, repo, "ci-token", "wood-token\n")
|
||||
credentials := map[string]any{"local": map[string]any{"token_file": "forge-token"}}
|
||||
if !test.missingCI {
|
||||
credentials["ci"] = map[string]any{}
|
||||
}
|
||||
profile := map[string]any{"product": "Config", "source": map[string]any{}, "validation": map[string]any{"go": test.goChecks},
|
||||
"delivery": map[string]any{"forge": "gitea", "base_url": forge.URL, "owner": "owner", "repository": "example", "credentials": credentials},
|
||||
"rehearsal": map[string]any{"selector": test.selector, "woodpecker": map[string]any{"base_url": ci.URL, "repository_id": 42, "workflow": "release", "step": "deliver", "token_file": "ci-token"}}}
|
||||
data, err := json.Marshal(profile)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writeRepositoryFile(t, repo, "releasekit.json", string(data))
|
||||
args := []string{"validate", "--repo", repo, "--json"}
|
||||
if test.operation != "" {
|
||||
args = append(args, "--operation", test.operation)
|
||||
}
|
||||
if !test.online {
|
||||
args = append(args, "--offline")
|
||||
}
|
||||
var output bytes.Buffer
|
||||
if status := run(t.Context(), args, &output, &bytes.Buffer{}); status != test.want {
|
||||
t.Fatalf("status=%d want=%d report=%s", status, test.want, &output)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
275
cmd/releasekit/recovery.go
Normal file
275
cmd/releasekit/recovery.go
Normal file
@@ -0,0 +1,275 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"go.maximumdirect.net/releasekit"
|
||||
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
|
||||
"go.maximumdirect.net/releasekit/internal/git"
|
||||
)
|
||||
|
||||
type recoveryDiagnostic struct {
|
||||
Kind string `json:"kind"`
|
||||
Message string `json:"message"`
|
||||
RecordPath string `json:"record_path,omitempty"`
|
||||
MissingFields []string `json:"missing_fields,omitempty"`
|
||||
}
|
||||
|
||||
type safeEvidence struct {
|
||||
RepositoryDir string `json:"repository_dir,omitempty"`
|
||||
SourceDir string `json:"source_dir,omitempty"`
|
||||
SourceSubdir string `json:"source_subdir,omitempty"`
|
||||
GoEnabled bool `json:"go_enabled,omitempty"`
|
||||
Publication string `json:"publication_mode,omitempty"`
|
||||
VersionFormat string `json:"version_format,omitempty"`
|
||||
VersionPrefix string `json:"version_prefix,omitempty"`
|
||||
IdentityKind string `json:"identity_kind,omitempty"`
|
||||
NotePath string `json:"note_path,omitempty"`
|
||||
ModuleDir string `json:"module_dir,omitempty"`
|
||||
ModulePath string `json:"module_path,omitempty"`
|
||||
Version string `json:"version,omitempty"`
|
||||
Tag string `json:"tag,omitempty"`
|
||||
CandidateCommit string `json:"candidate_commit,omitempty"`
|
||||
TagObject string `json:"tag_object,omitempty"`
|
||||
Endpoint string `json:"endpoint,omitempty"`
|
||||
Remote string `json:"remote,omitempty"`
|
||||
RecordedAt string `json:"recorded_at,omitempty"`
|
||||
}
|
||||
|
||||
type attemptDocument struct {
|
||||
RecordPath string `json:"record_path"`
|
||||
Evidence safeEvidence `json:"evidence"`
|
||||
}
|
||||
|
||||
type reconciliationDocument struct {
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
Command string `json:"command"`
|
||||
RecordPath string `json:"record_path"`
|
||||
Evidence *safeEvidence `json:"evidence,omitempty"`
|
||||
State string `json:"state,omitempty"`
|
||||
ObservedTagObject string `json:"observed_tag_object,omitempty"`
|
||||
ObservedCommit string `json:"observed_commit,omitempty"`
|
||||
Diagnostic *recoveryDiagnostic `json:"diagnostic,omitempty"`
|
||||
}
|
||||
|
||||
type attemptsDocument struct {
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
Command string `json:"command"`
|
||||
RecordDir string `json:"record_dir"`
|
||||
Attempts []attemptDocument `json:"attempts"`
|
||||
Diagnostics []*recoveryDiagnostic `json:"diagnostics"`
|
||||
Diagnostic *recoveryDiagnostic `json:"diagnostic,omitempty"`
|
||||
}
|
||||
|
||||
func safe(e releasekit.PublicationEvidence) safeEvidence {
|
||||
return safeEvidence{
|
||||
RepositoryDir: git.DisplayDiagnostic(e.RepositoryDir),
|
||||
SourceDir: git.DisplayDiagnostic(e.SourceDir),
|
||||
SourceSubdir: git.DisplayDiagnostic(e.SourceSubdir),
|
||||
GoEnabled: e.GoEnabled,
|
||||
Publication: git.DisplayDiagnostic(e.Publication),
|
||||
VersionFormat: git.DisplayDiagnostic(e.VersionFormat),
|
||||
VersionPrefix: git.DisplayDiagnostic(e.VersionPrefix),
|
||||
IdentityKind: git.DisplayDiagnostic(e.IdentityKind),
|
||||
NotePath: git.DisplayDiagnostic(e.NotePath),
|
||||
ModuleDir: git.DisplayDiagnostic(e.ModuleDir),
|
||||
ModulePath: git.DisplayDiagnostic(e.ModulePath),
|
||||
Version: git.DisplayDiagnostic(e.Version),
|
||||
Tag: git.DisplayDiagnostic(e.Tag),
|
||||
CandidateCommit: git.DisplayDiagnostic(e.CandidateCommit),
|
||||
TagObject: git.DisplayDiagnostic(e.TagObject),
|
||||
Endpoint: git.DisplayDiagnostic(e.Endpoint),
|
||||
Remote: git.DisplayDiagnostic(e.Remote),
|
||||
RecordedAt: git.DisplayDiagnostic(e.RecordedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func diagnostic(err error) *recoveryDiagnostic {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
var typed *releasekit.PublicationRecoveryError
|
||||
if errors.As(err, &typed) {
|
||||
missing := make([]string, len(typed.MissingFields))
|
||||
for i, field := range typed.MissingFields {
|
||||
missing[i] = git.DisplayDiagnostic(field)
|
||||
}
|
||||
return &recoveryDiagnostic{Kind: git.DisplayDiagnostic(typed.Kind), Message: git.DisplayError(err).Error(), RecordPath: git.DisplayDiagnostic(typed.RecordPath), MissingFields: missing}
|
||||
}
|
||||
return &recoveryDiagnostic{Kind: "invocation", Message: git.DisplayError(err).Error()}
|
||||
}
|
||||
|
||||
func runRecovery(ctx context.Context, invocation cli.Invocation, stdout, stderr io.Writer) int {
|
||||
if invocation.Command == cli.ReconcileAction {
|
||||
return runReconcile(ctx, invocation, stdout, stderr)
|
||||
}
|
||||
listed, err := releasekit.ListPublicationAttempts(ctx, releasekit.PublicationAttemptsRequest{RepositoryDir: invocation.Repository, RecordDir: invocation.RecordDir})
|
||||
return reportAttempts(listed, err, invocation.JSON, stdout, stderr)
|
||||
}
|
||||
|
||||
func reportAttempts(listed releasekit.PublicationAttemptsResult, err error, jsonOutput bool, stdout, stderr io.Writer) int {
|
||||
if jsonOutput {
|
||||
attempts := make([]attemptDocument, 0, len(listed.Attempts))
|
||||
for _, item := range listed.Attempts {
|
||||
attempts = append(attempts, attemptDocument{RecordPath: git.DisplayDiagnostic(item.RecordPath), Evidence: safe(item.Evidence)})
|
||||
}
|
||||
diagnostics := make([]*recoveryDiagnostic, 0, len(listed.Diagnostics))
|
||||
for _, item := range listed.Diagnostics {
|
||||
diagnostics = append(diagnostics, diagnostic(item))
|
||||
}
|
||||
if writeErr := writeJSON(stdout, attemptsDocument{
|
||||
SchemaVersion: 1,
|
||||
Command: "publication-attempts",
|
||||
RecordDir: git.DisplayDiagnostic(listed.RecordDir),
|
||||
Attempts: attempts,
|
||||
Diagnostics: diagnostics,
|
||||
Diagnostic: diagnostic(err),
|
||||
}); writeErr != nil {
|
||||
fmt.Fprintf(stderr, "write recovery output: %v\n", git.DisplayError(writeErr))
|
||||
return 1
|
||||
}
|
||||
} else {
|
||||
fmt.Fprintf(stdout, "publication records in %s\n", git.DisplayDiagnostic(listed.RecordDir))
|
||||
for _, item := range listed.Attempts {
|
||||
fmt.Fprintf(stdout, "%s module=%s tag=%s commit=%s recorded-at=%s\n", git.DisplayDiagnostic(item.RecordPath), git.DisplayDiagnostic(item.Evidence.ModulePath), git.DisplayDiagnostic(item.Evidence.Tag), git.DisplayDiagnostic(item.Evidence.CandidateCommit), git.DisplayDiagnostic(item.Evidence.RecordedAt))
|
||||
}
|
||||
if err != nil || len(listed.Diagnostics) > 0 {
|
||||
fmt.Fprintln(stderr, "discovery is incomplete")
|
||||
}
|
||||
for _, item := range listed.Diagnostics {
|
||||
fmt.Fprintf(stderr, "record %s: %s\n", git.DisplayDiagnostic(item.RecordPath), humanDiagnostic(item))
|
||||
}
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "discovery failed: %v\n", git.DisplayError(err))
|
||||
}
|
||||
}
|
||||
if err != nil || len(listed.Diagnostics) > 0 {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func runReconcile(ctx context.Context, invocation cli.Invocation, stdout, stderr io.Writer) int {
|
||||
evidence, loadErr := releasekit.LoadPublicationEvidence(invocation.RecordPath)
|
||||
var result releasekit.PublicationReconciliationResult
|
||||
err := loadErr
|
||||
if err == nil {
|
||||
result, err = releasekit.ReconcilePublication(ctx, evidence)
|
||||
}
|
||||
status := reconciliationStatus(result.State, err)
|
||||
if invocation.JSON {
|
||||
dto := reconciliationDocument{SchemaVersion: 1, Command: "reconcile", RecordPath: git.DisplayDiagnostic(invocation.RecordPath)}
|
||||
if loadErr == nil {
|
||||
safeEvidence := safe(evidence)
|
||||
dto.Evidence = &safeEvidence
|
||||
dto.State = string(result.State)
|
||||
dto.ObservedTagObject = result.ObservedTagObject
|
||||
dto.ObservedCommit = result.ObservedCommit
|
||||
}
|
||||
dto.Diagnostic = diagnostic(err)
|
||||
if writeErr := writeJSON(stdout, dto); writeErr != nil {
|
||||
fmt.Fprintf(stderr, "write recovery output: %v\n", git.DisplayError(writeErr))
|
||||
return 1
|
||||
}
|
||||
} else if err == nil {
|
||||
fmt.Fprintf(stdout, "reconciled %s module=%s tag=%s state=%s\n", git.DisplayDiagnostic(invocation.RecordPath), git.DisplayDiagnostic(evidence.ModulePath), git.DisplayDiagnostic(evidence.Tag), result.State)
|
||||
if result.State == releasekit.PublicationConflict {
|
||||
fmt.Fprintf(stdout, "expected tag-object=%s commit=%s; observed tag-object=%s commit=%s\n", git.DisplayDiagnostic(evidence.TagObject), git.DisplayDiagnostic(evidence.CandidateCommit), result.ObservedTagObject, result.ObservedCommit)
|
||||
} else if result.ObservedTagObject != "" || result.ObservedCommit != "" {
|
||||
fmt.Fprintf(stdout, "observed tag-object=%s commit=%s\n", result.ObservedTagObject, result.ObservedCommit)
|
||||
}
|
||||
if guidance := reconciliationGuidance(result.State); guidance != "" {
|
||||
fmt.Fprintf(stdout, "%s\n", guidance)
|
||||
}
|
||||
}
|
||||
if err != nil && !invocation.JSON {
|
||||
if loadErr == nil {
|
||||
fmt.Fprintf(stdout, "reconciled %s module=%s tag=%s state=%s\n", git.DisplayDiagnostic(invocation.RecordPath), git.DisplayDiagnostic(evidence.ModulePath), git.DisplayDiagnostic(evidence.Tag), result.State)
|
||||
if result.ObservedTagObject != "" || result.ObservedCommit != "" {
|
||||
fmt.Fprintf(stdout, "observed tag-object=%s commit=%s\n", result.ObservedTagObject, result.ObservedCommit)
|
||||
}
|
||||
}
|
||||
fmt.Fprintf(stderr, "reconcile %s: %s\n", git.DisplayDiagnostic(invocation.RecordPath), humanDiagnostic(err))
|
||||
if guidance := recoveryGuidance(err); guidance != "" {
|
||||
fmt.Fprintf(stderr, "%s\n", guidance)
|
||||
}
|
||||
}
|
||||
return status
|
||||
}
|
||||
|
||||
func reconciliationStatus(state releasekit.PublicationState, err error) int {
|
||||
if err == nil {
|
||||
switch state {
|
||||
case releasekit.PublicationPublished:
|
||||
return 0
|
||||
case releasekit.PublicationNotPublished, releasekit.PublicationConflict:
|
||||
return 1
|
||||
case releasekit.PublicationUnknown:
|
||||
return 3
|
||||
default:
|
||||
return 2
|
||||
}
|
||||
}
|
||||
var typed *releasekit.PublicationRecoveryError
|
||||
if errors.As(err, &typed) {
|
||||
switch typed.Kind {
|
||||
case "record_read", "record_format":
|
||||
return 2
|
||||
default:
|
||||
return 3
|
||||
}
|
||||
}
|
||||
return 2
|
||||
}
|
||||
|
||||
func recoveryGuidance(err error) string {
|
||||
var typed *releasekit.PublicationRecoveryError
|
||||
if !errors.As(err, &typed) {
|
||||
return ""
|
||||
}
|
||||
switch typed.Kind {
|
||||
case "missing_evidence":
|
||||
return "Select a record with the missing identity fields, or provide complete typed evidence through the Go API."
|
||||
case "invalid_evidence":
|
||||
return "Use a record with a valid full tag and Git object ID."
|
||||
case "endpoint_changed":
|
||||
return "Review Git URL rewrite settings and restore the captured endpoint mapping before retrying."
|
||||
case "transport_configuration":
|
||||
return "Review Git configuration and the supported transport settings, then retry observation."
|
||||
case "canceled":
|
||||
return "Retry observation with a context that allows it to complete."
|
||||
case "remote_observation", "inconsistent_observation":
|
||||
return "Review the Git diagnostic and the remote tag refs before taking any corrective action."
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func reconciliationGuidance(state releasekit.PublicationState) string {
|
||||
switch state {
|
||||
case releasekit.PublicationNotPublished:
|
||||
return "This reports current absence only; review publication history and version policy before retrying."
|
||||
case releasekit.PublicationConflict:
|
||||
return "Do not replace a conflicting remote tag; verify the observed IDs and follow the repository's immutable-tag procedure."
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func humanDiagnostic(err error) string {
|
||||
var typed *releasekit.PublicationRecoveryError
|
||||
if errors.As(err, &typed) && len(typed.MissingFields) > 0 {
|
||||
return git.DisplayDiagnostic(fmt.Sprintf("%s (missing fields: %s): %s", typed.Kind, strings.Join(typed.MissingFields, ", "), err.Error()))
|
||||
}
|
||||
return git.DisplayError(err).Error()
|
||||
}
|
||||
|
||||
func writeJSON(writer io.Writer, value any) error {
|
||||
encoder := json.NewEncoder(writer)
|
||||
return encoder.Encode(value)
|
||||
}
|
||||
487
cmd/releasekit/recovery_test.go
Normal file
487
cmd/releasekit/recovery_test.go
Normal file
@@ -0,0 +1,487 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
releasekit "go.maximumdirect.net/releasekit"
|
||||
"go.maximumdirect.net/releasekit/internal/publish"
|
||||
)
|
||||
|
||||
func TestRecoveryEndpointSetupFailureDiagnostics(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("fixture injects Git failures through a POSIX launcher")
|
||||
}
|
||||
for _, test := range []struct {
|
||||
name, remote, kind, guidance string
|
||||
exitCode int
|
||||
}{
|
||||
{"unnamed configuration", "", "transport_configuration", "Git configuration", 128},
|
||||
{"named configuration", "origin", "transport_configuration", "Git configuration", 128},
|
||||
{"rewrite", "", "endpoint_changed", "URL rewrite", 0},
|
||||
{"tooling", "", "remote_observation", "Git diagnostic", 71},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
repo := newCLIRepository(t)
|
||||
evidence := publish.Evidence{RepositoryDir: repo, Endpoint: repo, Tag: "v1.2.3", Remote: test.remote}
|
||||
path, err := publish.SaveEvidence(t.Context(), repo, t.TempDir(), evidence)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if test.kind == "transport_configuration" {
|
||||
file, err := os.OpenFile(filepath.Join(repo, ".git", "config"), os.O_APPEND|os.O_WRONLY, 0600)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := file.WriteString("\n[broken\n"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := file.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
} else if test.kind == "endpoint_changed" {
|
||||
cliGitRun(t, repo, "config", "url."+t.TempDir()+".insteadOf", repo)
|
||||
}
|
||||
realGit, err := exec.LookPath("git")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
marker := filepath.Join(t.TempDir(), "queried")
|
||||
bin := t.TempDir()
|
||||
failValidation := ""
|
||||
if test.name == "tooling" {
|
||||
failValidation = "[ \"$arg\" = check-ref-format ] && exit 71\n"
|
||||
}
|
||||
script := "#!/bin/sh\nquery=0\nget_url=0\nfor arg in \"$@\"; do\n" + failValidation + "[ \"$arg\" = ls-remote ] && query=1\n[ \"$arg\" = --get-url ] && get_url=1\ndone\nif [ \"$query\" = 1 ] && [ \"$get_url\" = 0 ]; then : > " + shellQuote(marker) + "; exit 72; fi\nexec " + shellQuote(realGit) + " \"$@\"\n"
|
||||
if err := os.WriteFile(filepath.Join(bin, "git"), []byte(script), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||
loaded, err := releasekit.LoadPublicationEvidence(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result, err := releasekit.ReconcilePublication(t.Context(), loaded)
|
||||
var typed *releasekit.PublicationRecoveryError
|
||||
if !errors.As(err, &typed) || typed.Kind != test.kind || result.State != releasekit.PublicationUnknown {
|
||||
t.Fatalf("setup classification = %#v, %v", result, err)
|
||||
}
|
||||
if test.exitCode != 0 {
|
||||
var exitErr *exec.ExitError
|
||||
if !errors.As(err, &exitErr) || exitErr.ExitCode() != test.exitCode {
|
||||
t.Fatalf("lost Git cause: %v", err)
|
||||
}
|
||||
}
|
||||
for _, structured := range []bool{false, true} {
|
||||
args := []string{"reconcile", "--record", path}
|
||||
if structured {
|
||||
args = append(args, "--json")
|
||||
}
|
||||
var stdout, stderr bytes.Buffer
|
||||
if status := run(t.Context(), args, &stdout, &stderr); status != 3 {
|
||||
t.Fatalf("setup status=%d: %s%s", status, &stdout, &stderr)
|
||||
}
|
||||
if structured {
|
||||
var document reconciliationDocument
|
||||
if err := json.Unmarshal(stdout.Bytes(), &document); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if document.State != "unknown" || document.Diagnostic == nil || document.Diagnostic.Kind != test.kind {
|
||||
t.Fatalf("setup JSON: %s", &stdout)
|
||||
}
|
||||
} else if !strings.Contains(stderr.String(), test.kind) || !strings.Contains(stderr.String(), test.guidance) {
|
||||
t.Fatalf("setup guidance: %s", &stderr)
|
||||
}
|
||||
}
|
||||
if _, err := os.Stat(marker); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("setup failure reached remote query: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type failingRecoveryWriter struct{ err error }
|
||||
|
||||
func (writer failingRecoveryWriter) Write([]byte) (int, error) { return 0, writer.err }
|
||||
|
||||
func TestRecoveryCommandsReportJSONWriteFailure(t *testing.T) {
|
||||
repo := newCLIRepository(t)
|
||||
cliGitRun(t, repo, "tag", "-a", "v1.2.3", "-m", "Release")
|
||||
store := t.TempDir()
|
||||
path, err := publish.SaveEvidence(t.Context(), repo, store, publish.Evidence{
|
||||
RepositoryDir: repo, Endpoint: repo, Tag: "v1.2.3",
|
||||
CandidateCommit: cliGitOutput(t, repo, "rev-parse", "HEAD"),
|
||||
TagObject: cliGitOutput(t, repo, "rev-parse", "v1.2.3"),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
failure := errors.New("output unavailable: https://user:audit-secret@example.invalid/output")
|
||||
for _, args := range [][]string{{"reconcile", "--record", path, "--json"}, {"publication-attempts", "--record-dir", store, "--json"}} {
|
||||
var normal, stderr bytes.Buffer
|
||||
if status := run(t.Context(), args, &normal, &stderr); status != 0 {
|
||||
t.Fatalf("normal output status=%d: %s", status, &stderr)
|
||||
}
|
||||
stderr.Reset()
|
||||
if status := run(t.Context(), args, failingRecoveryWriter{failure}, &stderr); status != 1 {
|
||||
t.Fatalf("failed output status=%d: %s", status, &stderr)
|
||||
}
|
||||
if !strings.Contains(stderr.String(), "output unavailable") || strings.Contains(stderr.String(), "audit-secret") {
|
||||
t.Fatalf("output diagnostic: %s", &stderr)
|
||||
}
|
||||
if args[0] == "reconcile" && !strings.Contains(normal.String(), `"state":"published"`) {
|
||||
t.Fatalf("observation changed: %s", &normal)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscoveryReportsPartialAttemptsAndEnumerationFailure(t *testing.T) {
|
||||
listed := releasekit.PublicationAttemptsResult{
|
||||
RecordDir: "records",
|
||||
Attempts: []releasekit.PublicationAttempt{{RecordPath: "good.json", Evidence: releasekit.PublicationEvidence{Tag: "v1.2.3"}}},
|
||||
Diagnostics: []*releasekit.PublicationRecoveryError{{Kind: "record_format", RecordPath: "broken.json"}},
|
||||
}
|
||||
failure := &releasekit.PublicationRecoveryError{Kind: "storage_enumeration"}
|
||||
for _, jsonOutput := range []bool{false, true} {
|
||||
var stdout, stderr bytes.Buffer
|
||||
if status := reportAttempts(listed, failure, jsonOutput, &stdout, &stderr); status != 1 {
|
||||
t.Fatalf("partial discovery status=%d", status)
|
||||
}
|
||||
if jsonOutput {
|
||||
var document attemptsDocument
|
||||
if err := json.Unmarshal(stdout.Bytes(), &document); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(document.Attempts) != 1 || document.Attempts[0].RecordPath != "good.json" || len(document.Diagnostics) != 1 || document.Diagnostics[0].RecordPath != "broken.json" || document.Diagnostic == nil || document.Diagnostic.Kind != "storage_enumeration" {
|
||||
t.Fatalf("partial JSON lost data: %s", &stdout)
|
||||
}
|
||||
} else if !strings.Contains(stdout.String(), "good.json") || !strings.Contains(stderr.String(), "broken.json") || !strings.Contains(stderr.String(), "storage_enumeration") {
|
||||
t.Fatalf("partial human output lost data: %s%s", &stdout, &stderr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecoveryDisplaysRedactCredentialPathsAndMetadata(t *testing.T) {
|
||||
secret := "audit-secret"
|
||||
raw := "https://audit-user:" + secret + "@example.invalid/attempt.json"
|
||||
for _, jsonOutput := range []bool{false, true} {
|
||||
args := []string{"reconcile", "--record", raw}
|
||||
if jsonOutput {
|
||||
args = append(args, "--json")
|
||||
}
|
||||
var out, diagnostics bytes.Buffer
|
||||
if status := run(t.Context(), args, &out, &diagnostics); status != 2 {
|
||||
t.Fatalf("load status=%d", status)
|
||||
}
|
||||
if strings.Contains(out.String()+diagnostics.String(), secret) {
|
||||
t.Fatalf("credential leaked: %s%s", &out, &diagnostics)
|
||||
}
|
||||
}
|
||||
repo := newCLIRepository(t)
|
||||
store := t.TempDir()
|
||||
evidence := publish.Evidence{RepositoryDir: raw, ModuleDir: raw, ModulePath: raw, Version: raw, Tag: raw, CandidateCommit: raw, TagObject: raw, Remote: raw, RecordedAt: raw}
|
||||
path, err := publish.SaveEvidence(t.Context(), repo, store, evidence)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, command := range [][]string{{"reconcile", "--record", path}, {"publication-attempts", "--record-dir", store}} {
|
||||
for _, jsonOutput := range []bool{false, true} {
|
||||
args := append([]string{}, command...)
|
||||
if jsonOutput {
|
||||
args = append(args, "--json")
|
||||
}
|
||||
var out, diagnostics bytes.Buffer
|
||||
run(t.Context(), args, &out, &diagnostics)
|
||||
if strings.Contains(out.String()+diagnostics.String(), secret) {
|
||||
t.Fatalf("metadata leaked: %s%s", &out, &diagnostics)
|
||||
}
|
||||
}
|
||||
}
|
||||
loaded, err := publish.LoadEvidence(path)
|
||||
if err != nil || loaded != evidence {
|
||||
t.Fatalf("private metadata changed: %#v, %v", loaded, err)
|
||||
}
|
||||
var out bytes.Buffer
|
||||
reportPublicationRecord(t.Context(), releasekit.PublicationResult{RecordPath: raw, Phase: releasekit.PublicationPush}, fmt.Errorf("push failed"), &out)
|
||||
if strings.Contains(out.String(), secret) {
|
||||
t.Fatalf("handoff leaked credentials: %s", &out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReconcileCommandClassifiesRecordsFromAnotherWorkingDirectory(t *testing.T) {
|
||||
repository := newCLIRepository(t)
|
||||
remote := filepath.Join(t.TempDir(), "bare remote.git")
|
||||
cliGitRun(t, repository, "init", "--bare", "--initial-branch=main", remote)
|
||||
cliGitRun(t, repository, "remote", "add", "origin", remote)
|
||||
cliGitRun(t, repository, "tag", "-a", "v1.2.3", "-m", "first tag object")
|
||||
cliGitRun(t, repository, "push", "origin", "refs/tags/v1.2.3")
|
||||
commit := cliGitOutput(t, repository, "rev-parse", "HEAD")
|
||||
tagObject := cliGitOutput(t, repository, "rev-parse", "refs/tags/v1.2.3")
|
||||
|
||||
store := filepath.Join(t.TempDir(), "records with ' punctuation")
|
||||
evidence := publish.Evidence{
|
||||
RepositoryDir: repository,
|
||||
ModuleDir: repository,
|
||||
ModulePath: "example.com/cli-candidate",
|
||||
Version: "v1.2.3",
|
||||
Tag: "v1.2.3",
|
||||
CandidateCommit: commit,
|
||||
TagObject: tagObject,
|
||||
Endpoint: remote,
|
||||
Remote: "origin",
|
||||
RecordedAt: "2026-11-02T00:00:00Z",
|
||||
}
|
||||
record, err := publish.SaveEvidence(t.Context(), repository, store, evidence)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cliGitRun(t, repository, "switch", "-c", "changed-head")
|
||||
cliGitRun(t, repository, "commit", "--allow-empty", "-m", "change current HEAD")
|
||||
cliGitRun(t, repository, "tag", "-d", "v1.2.3")
|
||||
if err := os.WriteFile(filepath.Join(repository, "uncommitted recovery check.txt"), []byte("dirty"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
otherDirectory := t.TempDir()
|
||||
relativeRecord, err := filepath.Rel(otherDirectory, record)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
previousDirectory, err := os.Getwd()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Chdir(otherDirectory); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := os.Chdir(previousDirectory); err != nil {
|
||||
t.Errorf("restore working directory: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
var stdout, stderr bytes.Buffer
|
||||
status := run(context.Background(), []string{"reconcile", "--record", relativeRecord, "--json"}, &stdout, &stderr)
|
||||
if status != 0 || stderr.Len() != 0 {
|
||||
t.Fatalf("published status = %d, stdout = %q, stderr = %q", status, stdout.String(), stderr.String())
|
||||
}
|
||||
var published map[string]any
|
||||
if err := json.Unmarshal(stdout.Bytes(), &published); err != nil {
|
||||
t.Fatalf("decode published JSON: %v; output = %q", err, stdout.String())
|
||||
}
|
||||
if published["state"] != string("published") || published["record_path"] != relativeRecord {
|
||||
t.Fatalf("published JSON = %#v", published)
|
||||
}
|
||||
if _, ok := published["diagnostic"]; ok {
|
||||
t.Fatalf("successful reconciliation includes a diagnostic: %#v", published)
|
||||
}
|
||||
evidenceJSON, ok := published["evidence"].(map[string]any)
|
||||
if !ok || evidenceJSON["candidate_commit"] != commit || evidenceJSON["tag_object"] != tagObject {
|
||||
t.Fatalf("safe evidence = %#v", published["evidence"])
|
||||
}
|
||||
if evidenceJSON["module_path"] != evidence.ModulePath || evidenceJSON["candidateCommit"] != nil {
|
||||
t.Fatalf("evidence does not use the versioned snake-case shape: %#v", evidenceJSON)
|
||||
}
|
||||
|
||||
cliGitRun(t, repository, "push", "origin", ":refs/tags/v1.2.3")
|
||||
cliGitRun(t, repository, "tag", "-f", "-a", "v1.2.3", "-m", "replacement tag object")
|
||||
cliGitRun(t, repository, "push", "origin", "refs/tags/v1.2.3")
|
||||
var conflictOut, conflictErr bytes.Buffer
|
||||
status = run(context.Background(), []string{"reconcile", "--record", record, "--json"}, &conflictOut, &conflictErr)
|
||||
if status != 1 || conflictErr.Len() != 0 {
|
||||
t.Fatalf("conflict status = %d, stdout = %q, stderr = %q", status, conflictOut.String(), conflictErr.String())
|
||||
}
|
||||
var conflict map[string]any
|
||||
if err := json.Unmarshal(conflictOut.Bytes(), &conflict); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if conflict["state"] != string("conflict") || conflict["observed_tag_object"] == tagObject {
|
||||
t.Fatalf("conflict JSON = %#v", conflict)
|
||||
}
|
||||
|
||||
var humanOut, humanErr bytes.Buffer
|
||||
status = run(context.Background(), []string{"reconcile", "--record", record}, &humanOut, &humanErr)
|
||||
if status != 1 || !strings.Contains(humanOut.String(), "expected tag-object="+tagObject) || !strings.Contains(humanOut.String(), "observed tag-object=") || !strings.Contains(humanOut.String(), "Do not replace a conflicting remote tag") {
|
||||
t.Fatalf("human conflict status = %d, stdout = %q, stderr = %q", status, humanOut.String(), humanErr.String())
|
||||
}
|
||||
|
||||
partialEvidence := evidence
|
||||
partialEvidence.TagObject = cliGitOutput(t, repository, "rev-parse", "refs/tags/v1.2.3")
|
||||
partialEvidence.CandidateCommit = ""
|
||||
partialRecord, err := publish.SaveEvidence(t.Context(), repository, store, partialEvidence)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var unknownOut, unknownErr bytes.Buffer
|
||||
status = run(context.Background(), []string{"reconcile", "--record", partialRecord, "--json"}, &unknownOut, &unknownErr)
|
||||
if status != 3 || unknownErr.Len() != 0 {
|
||||
t.Fatalf("unknown status = %d, stdout = %q, stderr = %q", status, unknownOut.String(), unknownErr.String())
|
||||
}
|
||||
var unknown map[string]any
|
||||
if err := json.Unmarshal(unknownOut.Bytes(), &unknown); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
unknownDiagnostic, ok := unknown["diagnostic"].(map[string]any)
|
||||
if unknown["state"] != "unknown" || !ok || unknownDiagnostic["kind"] != "missing_evidence" {
|
||||
t.Fatalf("unknown JSON = %#v", unknown)
|
||||
}
|
||||
var unknownHumanOut, unknownHumanErr bytes.Buffer
|
||||
status = run(context.Background(), []string{"reconcile", "--record", partialRecord}, &unknownHumanOut, &unknownHumanErr)
|
||||
if status != 3 || !strings.Contains(unknownHumanOut.String(), "state=unknown") || !strings.Contains(unknownHumanErr.String(), "candidate_commit") {
|
||||
t.Fatalf("human unknown status = %d, stdout = %q, stderr = %q", status, unknownHumanOut.String(), unknownHumanErr.String())
|
||||
}
|
||||
|
||||
cliGitRun(t, repository, "push", "origin", ":refs/tags/v1.2.3")
|
||||
var absentOut, absentErr bytes.Buffer
|
||||
status = run(context.Background(), []string{"reconcile", "--record", record, "--json"}, &absentOut, &absentErr)
|
||||
if status != 1 || absentErr.Len() != 0 {
|
||||
t.Fatalf("absent status = %d, stdout = %q, stderr = %q", status, absentOut.String(), absentErr.String())
|
||||
}
|
||||
var absent map[string]any
|
||||
if err := json.Unmarshal(absentOut.Bytes(), &absent); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if absent["state"] != "not_published" {
|
||||
t.Fatalf("absence JSON = %#v", absent)
|
||||
}
|
||||
if _, ok := absent["diagnostic"]; ok {
|
||||
t.Fatalf("known absence includes an unresolved diagnostic: %#v", absent)
|
||||
}
|
||||
var absentHumanOut, absentHumanErr bytes.Buffer
|
||||
status = run(context.Background(), []string{"reconcile", "--record", record}, &absentHumanOut, &absentHumanErr)
|
||||
if status != 1 || !strings.Contains(absentHumanOut.String(), "state=not_published") || !strings.Contains(absentHumanOut.String(), "current absence only") {
|
||||
t.Fatalf("human absence status = %d, stdout = %q, stderr = %q", status, absentHumanOut.String(), absentHumanErr.String())
|
||||
}
|
||||
|
||||
brokenRecord := filepath.Join(store, "broken record's.json")
|
||||
if err := os.WriteFile(brokenRecord, []byte("{"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var brokenOut, brokenErr bytes.Buffer
|
||||
status = run(context.Background(), []string{"reconcile", "--record", brokenRecord, "--json"}, &brokenOut, &brokenErr)
|
||||
if status != 2 || brokenErr.Len() != 0 {
|
||||
t.Fatalf("record-format status = %d, stdout = %q, stderr = %q", status, brokenOut.String(), brokenErr.String())
|
||||
}
|
||||
var broken map[string]any
|
||||
if err := json.Unmarshal(brokenOut.Bytes(), &broken); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
brokenDiagnostic, ok := broken["diagnostic"].(map[string]any)
|
||||
if !ok || brokenDiagnostic["kind"] != "record_format" || broken["record_path"] != brokenRecord {
|
||||
t.Fatalf("record-format JSON = %#v", broken)
|
||||
}
|
||||
for _, field := range []string{"evidence", "state", "observed_tag_object", "observed_commit"} {
|
||||
if _, ok := broken[field]; ok {
|
||||
t.Errorf("record-format JSON includes %q: %#v", field, broken)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublicationAttemptsCommandRedactsCredentialsAndReportsPartialDiscovery(t *testing.T) {
|
||||
repository := newCLIRepository(t)
|
||||
store := filepath.Join(t.TempDir(), "external records")
|
||||
evidence := publish.Evidence{
|
||||
RepositoryDir: repository,
|
||||
ModulePath: "example.com/cli-candidate",
|
||||
Version: "v1.2.3",
|
||||
Tag: "v1.2.3",
|
||||
Endpoint: "https://cli-user:cli-secret@example.test/repository.git",
|
||||
Remote: "origin",
|
||||
RecordedAt: "2026-11-02T00:00:00Z",
|
||||
}
|
||||
if _, err := publish.SaveEvidence(t.Context(), repository, store, evidence); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
brokenPath := filepath.Join(store, "damaged.json")
|
||||
if err := os.WriteFile(brokenPath, []byte(`{"format_version":99,"evidence":{}}`), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var stdout, stderr bytes.Buffer
|
||||
status := run(context.Background(), []string{"publication-attempts", "--record-dir", store, "--json"}, &stdout, &stderr)
|
||||
if status != 1 || stderr.Len() != 0 {
|
||||
t.Fatalf("partial discovery status = %d, stdout = %q, stderr = %q", status, stdout.String(), stderr.String())
|
||||
}
|
||||
output := stdout.String()
|
||||
if strings.Contains(output, "cli-user") || strings.Contains(output, "cli-secret") || !strings.Contains(output, "https://redacted@example.test/repository.git") {
|
||||
t.Fatalf("structured discovery exposed or failed to redact endpoint credentials: %q", output)
|
||||
}
|
||||
var listed map[string]any
|
||||
if err := json.Unmarshal(stdout.Bytes(), &listed); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
attempts, ok := listed["attempts"].([]any)
|
||||
if !ok || len(attempts) != 1 {
|
||||
t.Fatalf("attempts = %#v", listed["attempts"])
|
||||
}
|
||||
diagnostics, ok := listed["diagnostics"].([]any)
|
||||
if !ok || len(diagnostics) != 1 {
|
||||
t.Fatalf("diagnostics = %#v", listed["diagnostics"])
|
||||
}
|
||||
if listed["schema_version"] != float64(1) || listed["command"] != "publication-attempts" || listed["diagnostic"] != nil {
|
||||
t.Fatalf("listing document = %#v", listed)
|
||||
}
|
||||
entry := attempts[0].(map[string]any)
|
||||
if entry["record_path"] == "" {
|
||||
t.Fatalf("attempt is missing record_path: %#v", entry)
|
||||
}
|
||||
entryEvidence := entry["evidence"].(map[string]any)
|
||||
if entryEvidence["module_path"] != evidence.ModulePath || entryEvidence["recorded_at"] != evidence.RecordedAt {
|
||||
t.Fatalf("attempt evidence = %#v", entryEvidence)
|
||||
}
|
||||
diagnostic := diagnostics[0].(map[string]any)
|
||||
if diagnostic["kind"] != "record_format" || diagnostic["record_path"] != brokenPath {
|
||||
t.Fatalf("record diagnostic = %#v", diagnostic)
|
||||
}
|
||||
|
||||
emptyStore := filepath.Join(t.TempDir(), "empty store")
|
||||
if err := os.Mkdir(emptyStore, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var emptyOut, emptyErr bytes.Buffer
|
||||
status = run(context.Background(), []string{"publication-attempts", "--record-dir", emptyStore, "--json"}, &emptyOut, &emptyErr)
|
||||
if status != 0 || emptyErr.Len() != 0 {
|
||||
t.Fatalf("empty discovery status = %d, stdout = %q, stderr = %q", status, emptyOut.String(), emptyErr.String())
|
||||
}
|
||||
var empty map[string]any
|
||||
if err := json.Unmarshal(emptyOut.Bytes(), &empty); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(empty["attempts"].([]any)) != 0 || len(empty["diagnostics"].([]any)) != 0 || empty["diagnostic"] != nil {
|
||||
t.Fatalf("empty listing document = %#v", empty)
|
||||
}
|
||||
|
||||
var failedOut, failedErr bytes.Buffer
|
||||
status = run(context.Background(), []string{"publication-attempts", "--record-dir", filepath.Join(emptyStore, "missing"), "--json"}, &failedOut, &failedErr)
|
||||
if status != 1 || failedErr.Len() != 0 {
|
||||
t.Fatalf("enumeration failure status = %d, stdout = %q, stderr = %q", status, failedOut.String(), failedErr.String())
|
||||
}
|
||||
var failed map[string]any
|
||||
if err := json.Unmarshal(failedOut.Bytes(), &failed); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
failedDiagnostic, ok := failed["diagnostic"].(map[string]any)
|
||||
if !ok || failedDiagnostic["kind"] != "storage_enumeration" {
|
||||
t.Fatalf("enumeration failure JSON = %#v", failed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecoveryArgumentErrorsUseExistingUsagePath(t *testing.T) {
|
||||
var stdout, stderr bytes.Buffer
|
||||
status := run(context.Background(), []string{"reconcile", "--json"}, &stdout, &stderr)
|
||||
if status != 2 || stdout.Len() != 0 || !strings.Contains(stderr.String(), "reconcile requires --record FILE") {
|
||||
t.Fatalf("argument failure status = %d, stdout = %q, stderr = %q", status, stdout.String(), stderr.String())
|
||||
}
|
||||
if strings.Contains(stdout.String(), "schema_version") || strings.Contains(stderr.String(), fmt.Sprint("\"command\"")) {
|
||||
t.Fatalf("argument failure unexpectedly used structured output: stdout=%q stderr=%q", stdout.String(), stderr.String())
|
||||
}
|
||||
}
|
||||
250
cmd/releasekit/rehearsal.go
Normal file
250
cmd/releasekit/rehearsal.go
Normal 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
|
||||
}
|
||||
181
cmd/releasekit/rehearsal_test.go
Normal file
181
cmd/releasekit/rehearsal_test.go
Normal 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)
|
||||
}
|
||||
}
|
||||
@@ -79,10 +79,11 @@ func TestReleaseCandidate(t *testing.T) {
|
||||
"product": "ReleaseKit",
|
||||
"checks": []map[string]any{{"args": []string{"sh", "-c", "if [ -n \"$RELEASEKIT_TEST_ARM_GIT_SHIM\" ]; then : > \"$RELEASEKIT_TEST_ARM_GIT_SHIM\"; fi"}}},
|
||||
"delivery": map[string]any{
|
||||
"base_url": "https://gitea.maximumdirect.net",
|
||||
"owner": "eric",
|
||||
"repository": "ReleaseKit",
|
||||
"token_env": "RELEASEKIT_GITEA_TOKEN",
|
||||
"forge": "gitea",
|
||||
"base_url": "https://forge.maximumdirect.net",
|
||||
"owner": "base-layer",
|
||||
"repository": "releasekit",
|
||||
"credentials": map[string]any{"ci": map[string]string{"token_environment_variable": "RELEASEKIT_GITEA_TOKEN"}},
|
||||
},
|
||||
}
|
||||
content, _ := json.Marshal(profile)
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit/internal/cli"
|
||||
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
|
||||
)
|
||||
|
||||
func TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout(t *testing.T) {
|
||||
@@ -24,7 +24,7 @@ func TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout(t *testing.T) {
|
||||
if profile.Build != nil && len(profile.Build.Targets) != 0 {
|
||||
t.Fatalf("ReleaseKit profile declares binary targets: %#v", profile.Build.Targets)
|
||||
}
|
||||
if profile.Delivery == nil || profile.Delivery.BaseURL != "https://gitea.maximumdirect.net" || profile.Delivery.Owner != "eric" || profile.Delivery.Repository != "ReleaseKit" || profile.Delivery.TokenEnv != "RELEASEKIT_GITEA_TOKEN" {
|
||||
if profile.Delivery == nil || profile.Delivery.BaseURL != "https://forge.maximumdirect.net" || profile.Delivery.Owner != "base-layer" || profile.Delivery.Repository != "releasekit" || profile.Delivery.Credentials == nil || profile.Delivery.Credentials.CI == nil || profile.Delivery.Credentials.CI.TokenEnvironmentVariable != "RELEASEKIT_GITEA_TOKEN" {
|
||||
t.Fatalf("ReleaseKit delivery profile = %#v", profile.Delivery)
|
||||
}
|
||||
repository := filepath.Join(t.TempDir(), "tagged ReleaseKit")
|
||||
@@ -34,12 +34,22 @@ func TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout(t *testing.T) {
|
||||
}
|
||||
cliGitRun(t, repository, "config", "user.name", "ReleaseKit Test")
|
||||
cliGitRun(t, repository, "config", "user.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"
|
||||
note := "# ReleaseKit v1.2.3\n\nSource-only delivery fixture.\n\n" +
|
||||
"[COPYRIGHT](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v1.2.3/COPYRIGHT) |\n" +
|
||||
"[LICENSE](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v1.2.3/LICENSE) |\n" +
|
||||
"[ATTRIBUTION](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v1.2.3/docs/oss/attribution.md)\n"
|
||||
"[COPYRIGHT](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v1.2.3/COPYRIGHT) |\n" +
|
||||
"[LICENSE](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v1.2.3/LICENSE) |\n" +
|
||||
"[ATTRIBUTION](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v1.2.3/docs/oss/attribution.md)\n"
|
||||
notePath := filepath.Join(repository, "docs", "releases", version+".md")
|
||||
if err := os.MkdirAll(filepath.Dir(notePath), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -47,17 +57,17 @@ func TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout(t *testing.T) {
|
||||
if err := os.WriteFile(notePath, []byte(note), 0o600); err != nil {
|
||||
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")
|
||||
|
||||
state := &deliveryServerState{product: "ReleaseKit"}
|
||||
state := &deliveryServerState{data: deliveryServerData{product: "ReleaseKit"}}
|
||||
server := newDeliveryServer(t, state)
|
||||
defer server.Close()
|
||||
writeDeliveryProfile(t, repository, cli.Settings{
|
||||
Product: "ReleaseKit",
|
||||
Delivery: &cli.DeliverySettings{BaseURL: server.URL, Owner: "owner", Repository: "example"},
|
||||
Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example"},
|
||||
})
|
||||
state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD")
|
||||
state.update(func(state *deliveryServerData) { state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") })
|
||||
cliGitRun(t, repository, "tag", "-a", version, "-m", "ReleaseKit v1.2.3")
|
||||
|
||||
remote := filepath.Join(t.TempDir(), "origin.git")
|
||||
@@ -78,7 +88,7 @@ func TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout(t *testing.T) {
|
||||
}
|
||||
env := map[string]string{
|
||||
"CI_WORKSPACE": repository,
|
||||
"CI_COMMIT_SHA": state.commit,
|
||||
"CI_COMMIT_SHA": cliGitOutput(t, repository, "rev-parse", "refs/tags/"+version),
|
||||
"CI_COMMIT_TAG": version,
|
||||
"RELEASEKIT_GITEA_TOKEN": "fixture-token",
|
||||
"GOTOOLCHAIN": "local",
|
||||
@@ -87,14 +97,14 @@ func TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout(t *testing.T) {
|
||||
}
|
||||
command := strings.ReplaceAll(block, "$${", "${")
|
||||
|
||||
state.remoteCommit = strings.Repeat("f", 40)
|
||||
state.update(func(state *deliveryServerData) { state.remoteCommit = strings.Repeat("f", 40) })
|
||||
if output, err := executeWoodpeckerBlock(command, repository, env); err == nil {
|
||||
t.Fatalf("delivery with a mismatched hosted tag succeeded: %s", output)
|
||||
}
|
||||
if state.releaseCreates != 0 || cliGitOutput(t, repository, "rev-parse", "refs/tags/"+version+"^{commit}") != state.commit {
|
||||
if state.snapshot().releaseCreates != 0 || cliGitOutput(t, repository, "rev-parse", "refs/tags/"+version+"^{commit}") != state.snapshot().commit {
|
||||
t.Fatal("delivery failure changed hosted release state or source tag")
|
||||
}
|
||||
state.remoteCommit = ""
|
||||
state.update(func(state *deliveryServerData) { state.remoteCommit = "" })
|
||||
|
||||
for attempt := 0; attempt < 2; attempt++ {
|
||||
output := runWoodpeckerBlock(t, command, repository, env)
|
||||
@@ -102,14 +112,14 @@ func TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout(t *testing.T) {
|
||||
t.Fatalf("delivery attempt %d output = %q", attempt+1, output)
|
||||
}
|
||||
}
|
||||
if state.releaseCreates != 1 || state.assetUploads != 0 || state.assetListReads != 0 {
|
||||
t.Fatalf("page-only workflow calls = creates:%d uploads:%d asset reads:%d", state.releaseCreates, state.assetUploads, state.assetListReads)
|
||||
if state.snapshot().releaseCreates != 1 || state.snapshot().assetUploads != 0 || state.snapshot().assetListReads != 0 {
|
||||
t.Fatalf("page-only workflow calls = creates:%d uploads:%d asset reads:%d", state.snapshot().releaseCreates, state.snapshot().assetUploads, state.snapshot().assetListReads)
|
||||
}
|
||||
if state.noteBody != note {
|
||||
t.Fatalf("hosted note body = %q, want complete note %q", state.noteBody, note)
|
||||
if state.snapshot().noteBody != note {
|
||||
t.Fatalf("hosted note body = %q, want complete note %q", state.snapshot().noteBody, note)
|
||||
}
|
||||
if got := cliGitOutput(t, repository, "rev-parse", "refs/tags/"+version+"^{commit}"); got != state.commit {
|
||||
t.Fatalf("source tag moved after delivery: %s, want %s", got, state.commit)
|
||||
if got := cliGitOutput(t, repository, "rev-parse", "refs/tags/"+version+"^{commit}"); got != state.snapshot().commit {
|
||||
t.Fatalf("source tag moved after delivery: %s, want %s", got, state.snapshot().commit)
|
||||
}
|
||||
if status := cliGitOutput(t, repository, "status", "--porcelain"); status != "" {
|
||||
t.Fatalf("tagged checkout became dirty after delivery: %s", status)
|
||||
|
||||
36
cmd/releasekit/repository_test.go
Normal file
36
cmd/releasekit/repository_test.go
Normal file
@@ -0,0 +1,36 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNativeCheckFromChildUsesRootProfileAndSuite(t *testing.T) {
|
||||
binary := buildWorkflowCLI(t, cliRepositoryRoot(t))
|
||||
repository := newCLIRepository(t)
|
||||
writeRepositoryFile(t, repository, "candidate_test.go", "package candidate\nimport \"testing\"\nfunc TestFixture(t *testing.T) { t.Fatal(\"root suite failure\") }\n")
|
||||
writeRepositoryFile(t, repository, "releasekit.json", `{"product":"Example Product"}`)
|
||||
writeRepositoryFile(t, repository, "apps/widget/go.mod", "module example.com/widget\n\ngo 1.26.0\n")
|
||||
writeRepositoryFile(t, repository, "apps/widget/widget_test.go", "package widget\nimport \"testing\"\nfunc TestWidget(t *testing.T) {}\n")
|
||||
cliGitRun(t, repository, "add", ".")
|
||||
cliGitRun(t, repository, "commit", "-m", "Add failing root and passing child")
|
||||
command := exec.Command(binary, "check", "v1.2.3")
|
||||
command.Dir = filepath.Join(repository, "apps", "widget")
|
||||
output, err := command.CombinedOutput()
|
||||
if exit, ok := err.(*exec.ExitError); !ok || exit.ExitCode() != 1 || !strings.Contains(string(output), "root suite failure") || !strings.Contains(string(output), "module=example.com/cli-candidate") {
|
||||
t.Fatalf("child invocation error = %v, output = %s", err, output)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNativeBuildClassifiesInvalidVersionAfterProfileSelection(t *testing.T) {
|
||||
binary := buildWorkflowCLI(t, cliRepositoryRoot(t))
|
||||
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()
|
||||
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)
|
||||
}
|
||||
}
|
||||
338
cmd/releasekit/source_only_bootstrap_test.go
Normal file
338
cmd/releasekit/source_only_bootstrap_test.go
Normal 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)
|
||||
}
|
||||
}
|
||||
174
cmd/releasekit/source_test.go
Normal file
174
cmd/releasekit/source_test.go
Normal 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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
118
cmd/releasekit/token_file_test.go
Normal file
118
cmd/releasekit/token_file_test.go
Normal file
@@ -0,0 +1,118 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
|
||||
)
|
||||
|
||||
func TestDeliveryCredentialSelection(t *testing.T) {
|
||||
repository := t.TempDir()
|
||||
path := filepath.Join(repository, "token")
|
||||
if err := os.WriteFile(path, []byte(" file-secret \n"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("RELEASEKIT_TEST_TOKEN", " ambient-secret ")
|
||||
credentials := &cli.DeliveryCredentials{Local: &cli.LocalCredential{TokenFile: "token"}, CI: &cli.CICredential{TokenEnvironmentVariable: "RELEASEKIT_TEST_TOKEN"}}
|
||||
for _, test := range []struct {
|
||||
context cli.CredentialContext
|
||||
want string
|
||||
}{{cli.LocalCredentials, "file-secret"}, {cli.CICredentials, "ambient-secret"}} {
|
||||
token, source, err := cli.ResolveDeliveryCredential(repository, credentials, test.context)
|
||||
if err != nil || token != test.want || source.Context != test.context {
|
||||
t.Fatalf("context=%s token matches=%t source=%+v error=%v", test.context, token == test.want, source, err)
|
||||
}
|
||||
}
|
||||
credentials.Local.TokenFile = "missing"
|
||||
if _, _, err := cli.ResolveDeliveryCredential(repository, credentials, cli.LocalCredentials); err == nil || strings.Contains(err.Error(), "ambient-secret") {
|
||||
t.Fatalf("missing local file error = %v", err)
|
||||
}
|
||||
if token, _, err := cli.ResolveDeliveryCredential(repository, credentials, cli.CICredentials); err != nil || token != "ambient-secret" {
|
||||
t.Fatalf("CI credential with missing local file: token matches=%t error=%v", token == "ambient-secret", err)
|
||||
}
|
||||
credentials.Local.TokenFile = path
|
||||
if err := os.WriteFile(path, []byte(" \t\n"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := cli.ResolveDeliveryCredential(repository, credentials, cli.LocalCredentials); err == nil {
|
||||
t.Fatal("accepted blank file")
|
||||
}
|
||||
t.Setenv("RELEASEKIT_DELIVERY_TOKEN", "default-secret")
|
||||
token, _, err := cli.ResolveDeliveryCredential(repository, &cli.DeliveryCredentials{CI: &cli.CICredential{}}, cli.CICredentials)
|
||||
if err != nil || token != "default-secret" {
|
||||
t.Fatalf("default CI credential matches=%t error=%v", token == "default-secret", err)
|
||||
}
|
||||
if _, _, err := cli.ResolveDeliveryCredential(repository, &cli.DeliveryCredentials{}, cli.CICredentials); err == nil {
|
||||
t.Fatal("accepted missing CI declaration")
|
||||
}
|
||||
t.Setenv("RELEASEKIT_TEST_TOKEN", " ")
|
||||
if _, _, err := cli.ResolveDeliveryCredential(repository, credentials, cli.CICredentials); err == nil {
|
||||
t.Fatal("accepted blank CI token")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckReadsForbiddenFilesSelectionFromProfile(t *testing.T) {
|
||||
repository := newCLIRepository(t)
|
||||
writeDeliveryProfile(t, repository, cli.Settings{
|
||||
Product: "Example Product",
|
||||
Validation: &cli.ValidationSettings{ForbiddenFiles: []string{"token-file"}},
|
||||
Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: "https://gitea.example", Owner: "owner", Repository: "example", Credentials: &cli.DeliveryCredentials{Local: &cli.LocalCredential{TokenFile: "missing-token-file"}}},
|
||||
})
|
||||
writeRepositoryFile(t, repository, "token-file", "fixture-secret\n")
|
||||
cliGitRun(t, repository, "add", "token-file")
|
||||
cliGitRun(t, repository, "commit", "-m", "capture a selected token path")
|
||||
var stdout, stderr bytes.Buffer
|
||||
status := run(context.Background(), []string{"check", "--repo", repository, "v1.2.3"}, &stdout, &stderr)
|
||||
if status != 1 || !strings.Contains(stderr.String(), "forbidden-files") || !strings.Contains(stderr.String(), "token-file") {
|
||||
t.Fatalf("check status=%d output=%s diagnostics=%s", status, &stdout, &stderr)
|
||||
}
|
||||
if strings.Contains(stdout.String()+stderr.String(), "fixture-secret") {
|
||||
t.Fatal("check exposed the token")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeliverAndCIDeliverSelectContextCredentials(t *testing.T) {
|
||||
for _, command := range []string{"deliver", "ci-deliver"} {
|
||||
t.Run(command, func(t *testing.T) {
|
||||
repository := newCLIRepository(t)
|
||||
state := &deliveryServerState{}
|
||||
server := newDeliveryServer(t, state)
|
||||
defer server.Close()
|
||||
writeDeliveryProfile(t, repository, cli.Settings{
|
||||
Product: "Example Product",
|
||||
Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example", Credentials: &cli.DeliveryCredentials{Local: &cli.LocalCredential{TokenFile: ".releasekit/token"}, CI: &cli.CICredential{TokenEnvironmentVariable: "RELEASEKIT_GITEA_TOKEN"}}},
|
||||
})
|
||||
writeRepositoryFile(t, repository, ".gitignore", ".releasekit/\n")
|
||||
cliGitRun(t, repository, "add", ".gitignore")
|
||||
cliGitRun(t, repository, "commit", "-m", "ignore local delivery credentials")
|
||||
commit := pushTaggedCLIRepository(t, repository)
|
||||
state.update(func(data *deliveryServerData) { data.commit = commit })
|
||||
if command == "deliver" {
|
||||
writeRepositoryFile(t, repository, ".releasekit/token", "fixture-token\n")
|
||||
} else if err := os.MkdirAll(filepath.Join(repository, ".releasekit"), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("RELEASEKIT_GITEA_TOKEN", "fixture-token")
|
||||
var stdout, stderr bytes.Buffer
|
||||
args := []string{command, "--repo", filepath.Join(repository, ".releasekit")}
|
||||
if command == "ci-deliver" {
|
||||
args = append(args, "--commit", commit)
|
||||
}
|
||||
args = append(args, "v1.2.3")
|
||||
if status := run(context.Background(), args, &stdout, &stderr); status != 0 {
|
||||
t.Fatalf("delivery status=%d output=%s diagnostics=%s", status, &stdout, &stderr)
|
||||
}
|
||||
if state.snapshot().releaseCreates != 1 {
|
||||
t.Fatal("token-file delivery did not create the release page")
|
||||
}
|
||||
if strings.Contains(stdout.String()+stderr.String(), "fixture-token") {
|
||||
t.Fatal("delivery exposed the token")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,7 @@ import (
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit/internal/cli"
|
||||
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
|
||||
)
|
||||
|
||||
func TestWoodpeckerTagDeliveryTemplate(t *testing.T) {
|
||||
@@ -39,20 +39,21 @@ func TestWoodpeckerTagDeliveryTemplate(t *testing.T) {
|
||||
defer server.Close()
|
||||
writeDeliveryProfile(t, repository, cli.Settings{
|
||||
Product: "Example Product",
|
||||
Delivery: &cli.DeliverySettings{BaseURL: server.URL, Owner: "owner", Repository: "example"},
|
||||
Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example"},
|
||||
})
|
||||
commit := pushTaggedCLIRepository(t, repository)
|
||||
state.commit = commit
|
||||
state.update(func(state *deliveryServerData) { state.commit = commit })
|
||||
|
||||
goDir, goLog := installGoBootstrapShim(t)
|
||||
env := templateEnvironment(repository, commit, goDir, goLog)
|
||||
env["GOOS"], env["GOARCH"] = foreignTarget()
|
||||
moduleBefore := readWoodpeckerFixtureFile(t, filepath.Join(repository, "go.mod"))
|
||||
output := runWoodpeckerBlock(t, command, repository, env)
|
||||
if !strings.Contains(output, "state complete") {
|
||||
t.Fatalf("delivery output=%q", output)
|
||||
}
|
||||
if state.releaseCreates != 1 || state.assetUploads != 0 {
|
||||
t.Fatalf("source-only calls = creates:%d uploads:%d", state.releaseCreates, state.assetUploads)
|
||||
if state.snapshot().releaseCreates != 1 || state.snapshot().assetUploads != 0 {
|
||||
t.Fatalf("source-only calls = creates:%d uploads:%d", state.snapshot().releaseCreates, state.snapshot().assetUploads)
|
||||
}
|
||||
assertModuleBootstrap(t, repository, goLog, moduleBefore)
|
||||
})
|
||||
@@ -70,13 +71,14 @@ func TestWoodpeckerTagDeliveryTemplate(t *testing.T) {
|
||||
BinaryName: "helper",
|
||||
Targets: []string{fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH)},
|
||||
},
|
||||
Delivery: &cli.DeliverySettings{BaseURL: server.URL, Owner: "owner", Repository: "example"},
|
||||
Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example"},
|
||||
})
|
||||
commit := pushTaggedCLIRepository(t, repository)
|
||||
state.commit = commit
|
||||
state.update(func(state *deliveryServerData) { state.commit = commit })
|
||||
|
||||
goDir, goLog := installGoBootstrapShim(t)
|
||||
env := templateEnvironment(repository, commit, goDir, goLog)
|
||||
env["GOOS"], env["GOARCH"] = foreignTarget()
|
||||
moduleBefore := readWoodpeckerFixtureFile(t, filepath.Join(repository, "go.mod"))
|
||||
sumBefore := readWoodpeckerFixtureFile(t, filepath.Join(repository, "go.sum"))
|
||||
for attempt := 0; attempt < 2; attempt++ {
|
||||
@@ -88,14 +90,14 @@ func TestWoodpeckerTagDeliveryTemplate(t *testing.T) {
|
||||
t.Fatalf("second delivery did not reuse matching assets: %q", output)
|
||||
}
|
||||
}
|
||||
if state.releaseCreates != 1 || state.assetUploads != 2 {
|
||||
t.Fatalf("binary calls = creates:%d uploads:%d", state.releaseCreates, state.assetUploads)
|
||||
if state.snapshot().releaseCreates != 1 || state.snapshot().assetUploads != 2 {
|
||||
t.Fatalf("binary calls = creates:%d uploads:%d", state.snapshot().releaseCreates, state.snapshot().assetUploads)
|
||||
}
|
||||
if _, ok := state.assets["helper-v1.2.3-"+runtime.GOOS+"-"+runtime.GOARCH]; !ok {
|
||||
t.Fatalf("binary asset was not delivered: %#v", state.assets)
|
||||
if _, ok := state.snapshot().assets["helper-v1.2.3-"+runtime.GOOS+"-"+runtime.GOARCH]; !ok {
|
||||
t.Fatalf("binary asset was not delivered: %#v", state.snapshot().assets)
|
||||
}
|
||||
if _, ok := state.assets["SHA256SUMS"]; !ok {
|
||||
t.Fatalf("checksum manifest was not delivered: %#v", state.assets)
|
||||
if _, ok := state.snapshot().assets["SHA256SUMS"]; !ok {
|
||||
t.Fatalf("checksum manifest was not delivered: %#v", state.snapshot().assets)
|
||||
}
|
||||
assertModuleBootstrap(t, repository, goLog, moduleBefore, sumBefore)
|
||||
})
|
||||
@@ -104,10 +106,15 @@ func TestWoodpeckerTagDeliveryTemplate(t *testing.T) {
|
||||
repository := newCLIRepository(t)
|
||||
selectReleaseKitModule(t, repository, root, false)
|
||||
commit := pushTaggedCLIRepository(t, repository)
|
||||
cliGitRun(t, repository, "commit", "--allow-empty", "-m", "unrelated event commit")
|
||||
unrelated := cliGitOutput(t, repository, "rev-parse", "HEAD")
|
||||
goDir, goLog := installControlledGoBootstrapShim(t)
|
||||
env := templateEnvironment(repository, strings.Repeat("f", len(commit)), goDir, goLog)
|
||||
env := templateEnvironment(repository, unrelated, goDir, goLog)
|
||||
env["GOOS"], env["GOARCH"] = foreignTarget()
|
||||
if output, err := executeWoodpeckerBlock(command, repository, env); err == nil {
|
||||
t.Fatalf("wrong tag succeeded: %s", output)
|
||||
} else if !strings.Contains(output, commit) || !strings.Contains(output, unrelated) {
|
||||
t.Fatalf("tag mismatch omitted commit identities: %s", output)
|
||||
}
|
||||
assertNoCommands(t, goLog)
|
||||
})
|
||||
@@ -119,6 +126,7 @@ func TestWoodpeckerTagDeliveryTemplate(t *testing.T) {
|
||||
writeRepositoryFile(t, repository, "go.mod", "module example.com/different-tool-selection\n\ngo 1.25.0\n")
|
||||
goDir, goLog := installControlledGoBootstrapShim(t)
|
||||
env := templateEnvironment(repository, commit, goDir, goLog)
|
||||
env["GOOS"], env["GOARCH"] = foreignTarget()
|
||||
if output, err := executeWoodpeckerBlock(command, repository, env); err == nil {
|
||||
t.Fatalf("dirty module succeeded: %s", output)
|
||||
}
|
||||
@@ -126,29 +134,78 @@ func TestWoodpeckerTagDeliveryTemplate(t *testing.T) {
|
||||
})
|
||||
|
||||
t.Run("selected executable receives event arguments and its status", func(t *testing.T) {
|
||||
repository := newCLIRepository(t)
|
||||
selectReleaseKitModule(t, repository, root, false)
|
||||
commit := pushTaggedCLIRepository(t, repository)
|
||||
goDir, goLog := installControlledGoBootstrapShim(t)
|
||||
toolArgs := filepath.Join(t.TempDir(), "tool-arguments")
|
||||
env := templateEnvironment(repository, strings.ToUpper(commit), goDir, goLog)
|
||||
env["RELEASEKIT_TOOL_ARGS_LOG"] = toolArgs
|
||||
env["RELEASEKIT_TOOL_EXIT"] = "37"
|
||||
output, err := executeWoodpeckerBlock(command, repository, env)
|
||||
var exitError *exec.ExitError
|
||||
if !errors.As(err, &exitError) || exitError.ExitCode() != 37 {
|
||||
t.Fatalf("template error = %v, want propagated exit 37; output=%q", err, output)
|
||||
for _, event := range []struct {
|
||||
name, tag string
|
||||
tagObject bool
|
||||
}{
|
||||
{"lightweight commit", "v1.2.3", false},
|
||||
{"annotated commit", "v1.2.4", false},
|
||||
{"annotated tag object", "v1.2.4", true},
|
||||
} {
|
||||
t.Run(event.name, func(t *testing.T) {
|
||||
repository := newCLIRepository(t)
|
||||
selectReleaseKitModule(t, repository, root, false)
|
||||
commit := pushTaggedCLIRepository(t, repository)
|
||||
if event.tag == "v1.2.4" {
|
||||
cliGitRun(t, repository, "tag", "-a", event.tag, "-m", "annotated release")
|
||||
cliGitRun(t, repository, "push", "origin", "refs/tags/"+event.tag)
|
||||
}
|
||||
eventID := commit
|
||||
if event.tagObject {
|
||||
eventID = cliGitOutput(t, repository, "rev-parse", "refs/tags/"+event.tag)
|
||||
}
|
||||
goDir, goLog := installControlledGoBootstrapShim(t)
|
||||
toolArgs := filepath.Join(t.TempDir(), "tool-arguments")
|
||||
env := templateEnvironment(repository, strings.ToUpper(eventID), goDir, goLog)
|
||||
env["GOOS"], env["GOARCH"] = foreignTarget()
|
||||
env["CI_COMMIT_TAG"] = event.tag
|
||||
env["RELEASEKIT_TOOL_ARGS_LOG"] = toolArgs
|
||||
env["RELEASEKIT_TOOL_EXIT"] = "37"
|
||||
output, err := executeWoodpeckerBlock(command, repository, env)
|
||||
var exitError *exec.ExitError
|
||||
if !errors.As(err, &exitError) || exitError.ExitCode() != 37 {
|
||||
t.Fatalf("template error = %v, want propagated exit 37; output=%q", err, output)
|
||||
}
|
||||
args := readWoodpeckerFixtureFile(t, toolArgs)
|
||||
for _, expected := range []string{"<ci-deliver>", "<--repo>", "<" + repository + ">", "<--prepared>", "<" + event.tag + ">"} {
|
||||
if !strings.Contains(args, expected) {
|
||||
t.Errorf("selected executable arguments %q omit %q", args, expected)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(strings.ToLower(args), "<--commit>\n<"+commit+">") {
|
||||
t.Errorf("selected executable did not receive source commit %s: %q", commit, args)
|
||||
}
|
||||
assertGoSelection(t, repository, goLog)
|
||||
})
|
||||
}
|
||||
args := readWoodpeckerFixtureFile(t, toolArgs)
|
||||
for _, expected := range []string{"<ci-deliver>", "<--repo>", "<" + repository + ">", "<--commit>", "<" + strings.ToUpper(commit) + ">", "<v1.2.3>"} {
|
||||
if !strings.Contains(args, expected) {
|
||||
t.Errorf("selected executable arguments %q omit %q", args, expected)
|
||||
}
|
||||
}
|
||||
assertGoSelection(t, repository, goLog)
|
||||
})
|
||||
}
|
||||
|
||||
func 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) {
|
||||
// Synthetic downloads must leave the caller's module cache untouched.
|
||||
callerCache := t.TempDir()
|
||||
@@ -178,7 +235,7 @@ func TestWoodpeckerTagDeliveryUsesTaggedModuleVersion(t *testing.T) {
|
||||
t.Run("older tag retry uses its committed module selection", func(t *testing.T) {
|
||||
goDir, goLog := installGoBootstrapShim(t)
|
||||
repository := newCLIRepository(t)
|
||||
const module = "gitea.maximumdirect.net/eric/ReleaseKit"
|
||||
const module = "go.maximumdirect.net/releasekit"
|
||||
writeRepositoryFile(t, repository, "go.mod", "module example.com/cli-candidate\n\ngo 1.25.0\n\nrequire "+module+" v0.2.197\n")
|
||||
cliGitRun(t, repository, "add", "go.mod")
|
||||
cliGitRun(t, repository, "commit", "-m", "select the earlier ReleaseKit version")
|
||||
@@ -198,6 +255,7 @@ func TestWoodpeckerTagDeliveryUsesTaggedModuleVersion(t *testing.T) {
|
||||
moduleBefore := readWoodpeckerFixtureFile(t, filepath.Join(repository, "go.mod"))
|
||||
commit := oldCommit
|
||||
env := templateEnvironment(repository, commit, goDir, goLog)
|
||||
env["GOOS"], env["GOARCH"] = foreignTarget()
|
||||
useSyntheticModuleProxy(t, env, "file://"+filepath.ToSlash(proxy))
|
||||
sumLog := filepath.Join(t.TempDir(), "tool-only-sums")
|
||||
env["RELEASEKIT_SUM_LOG"] = sumLog
|
||||
@@ -209,10 +267,31 @@ func TestWoodpeckerTagDeliveryUsesTaggedModuleVersion(t *testing.T) {
|
||||
assertToolOnlyChecksums(t, sumLog)
|
||||
})
|
||||
|
||||
t.Run("vendored tool dependency", func(t *testing.T) {
|
||||
goDir, goLog := installGoBootstrapShim(t)
|
||||
repository := newCLIRepository(t)
|
||||
const module = "go.maximumdirect.net/releasekit"
|
||||
writeRepositoryFile(t, repository, "go.mod", "module example.com/cli-candidate\n\ngo 1.25.0\n\nrequire "+module+" v0.2.197\n\ntool "+module+"/cmd/releasekit\n")
|
||||
env := templateEnvironment(repository, "", goDir, goLog)
|
||||
env["GOOS"], env["GOARCH"] = foreignTarget()
|
||||
useSyntheticModuleProxy(t, env, "file://"+filepath.ToSlash(proxy))
|
||||
runWoodpeckerBlock(t, "go mod tidy\ngo mod vendor", repository, env)
|
||||
cliGitRun(t, repository, "add", "go.mod", "go.sum", "vendor")
|
||||
cliGitRun(t, repository, "commit", "-m", "vendor the selected release tool")
|
||||
env["CI_COMMIT_SHA"] = pushTaggedCLIRepository(t, repository)
|
||||
moduleBefore := readWoodpeckerFixtureFile(t, filepath.Join(repository, "go.mod"))
|
||||
sumBefore := readWoodpeckerFixtureFile(t, filepath.Join(repository, "go.sum"))
|
||||
output := runWoodpeckerBlock(t, command, repository, env)
|
||||
if !strings.Contains(output, "tool-version=v0.2.197 helper=tool-only dependency") {
|
||||
t.Fatalf("vendored tool was not selected: %q", output)
|
||||
}
|
||||
assertModuleBootstrap(t, repository, goLog, moduleBefore, sumBefore)
|
||||
})
|
||||
|
||||
t.Run("versioned replacement selects its declared source", func(t *testing.T) {
|
||||
goDir, goLog := installGoBootstrapShim(t)
|
||||
repository := newCLIRepository(t)
|
||||
const module = "gitea.maximumdirect.net/eric/ReleaseKit"
|
||||
const module = "go.maximumdirect.net/releasekit"
|
||||
goMod := "module example.com/cli-candidate\n\ngo 1.25.0\n\nrequire " + module + " v0.2.197\n\nreplace " + module + " v0.2.197 => " + module + " v0.2.198\n"
|
||||
writeRepositoryFile(t, repository, "go.mod", goMod)
|
||||
cliGitRun(t, repository, "add", "go.mod")
|
||||
@@ -220,6 +299,7 @@ func TestWoodpeckerTagDeliveryUsesTaggedModuleVersion(t *testing.T) {
|
||||
commit := pushTaggedCLIRepository(t, repository)
|
||||
moduleBefore := readWoodpeckerFixtureFile(t, filepath.Join(repository, "go.mod"))
|
||||
env := templateEnvironment(repository, commit, goDir, goLog)
|
||||
env["GOOS"], env["GOARCH"] = foreignTarget()
|
||||
useSyntheticModuleProxy(t, env, "file://"+filepath.ToSlash(proxy))
|
||||
sumLog := filepath.Join(t.TempDir(), "tool-only-sums")
|
||||
env["RELEASEKIT_SUM_LOG"] = sumLog
|
||||
@@ -266,6 +346,7 @@ func TestWoodpeckerSourceDeliveryTemplateSelfBootstraps(t *testing.T) {
|
||||
commit := pushTaggedCLIRepository(t, repository)
|
||||
goDir, goLog := installGoBootstrapShim(t)
|
||||
env := templateEnvironment(repository, commit, goDir, goLog)
|
||||
env["GOOS"], env["GOARCH"] = foreignTarget()
|
||||
useSyntheticModuleProxy(t, env, proxy.URL)
|
||||
proxyRequests.Store(0)
|
||||
env["CI_COMMIT_SHA"] = strings.Repeat("0", len(commit))
|
||||
@@ -284,10 +365,13 @@ func TestWoodpeckerSourceDeliveryTemplateSelfBootstraps(t *testing.T) {
|
||||
if proxyRequests.Load() == 0 {
|
||||
t.Fatal("self-bootstrap did not prepare its dependency from the local proxy")
|
||||
}
|
||||
if !strings.Contains(output, `"ci-deliver"`) || !strings.Contains(output, `"`+repository+`"`) || !strings.Contains(output, `"v1.2.3"`) {
|
||||
if !strings.Contains(output, `"ci-deliver"`) || !strings.Contains(output, `"`+repository+`"`) || !strings.Contains(output, `"--prepared"`) || !strings.Contains(output, `"v1.2.3"`) {
|
||||
t.Fatalf("self-bootstrapped command arguments = %q", output)
|
||||
}
|
||||
log := readWoodpeckerFixtureFile(t, goLog)
|
||||
if !strings.Contains(log, "build-target="+runtime.GOOS+"/"+runtime.GOARCH) {
|
||||
t.Fatalf("source build did not use host target: %s", log)
|
||||
}
|
||||
if !strings.Contains(log, "GOWORK=off GOTOOLCHAIN=local") || !strings.Contains(log, "build -mod=readonly -o ") || !strings.Contains(log, "./cmd/releasekit") {
|
||||
t.Fatalf("self-bootstrap Go command = %q", log)
|
||||
}
|
||||
@@ -371,9 +455,11 @@ func installGoBootstrapShim(t *testing.T) (string, string) {
|
||||
goLog := filepath.Join(shimDir, "go-commands")
|
||||
shim := `#!/bin/sh
|
||||
printf 'cwd=%s GOWORK=%s GOTOOLCHAIN=%s %s\n' "$PWD" "$GOWORK" "$GOTOOLCHAIN" "$*" >> "$RELEASEKIT_GO_LOG"
|
||||
case " $* " in *" -deps "*) printf 'target=%s/%s\n' "$GOOS" "$GOARCH" >> "$RELEASEKIT_GO_LOG" ;; esac
|
||||
if [ "$1" = build ]; then printf 'build-target=%s/%s\n' "$GOOS" "$GOARCH" >> "$RELEASEKIT_GO_LOG"; fi
|
||||
"$RELEASEKIT_REAL_GO" "$@"
|
||||
status=$?
|
||||
if [ "$status" -eq 0 ] && [ "$1" = "build" ] && [ -n "${RELEASEKIT_SUM_LOG:-}" ]; then
|
||||
if [ "$status" -eq 0 ] && [ "$1" = "tool" ] && [ -n "${RELEASEKIT_SUM_LOG:-}" ]; then
|
||||
modfile=
|
||||
for argument in "$@"; do
|
||||
case "$argument" in -modfile=*) modfile=${argument#-modfile=} ;; esac
|
||||
@@ -395,6 +481,8 @@ func installControlledGoBootstrapShim(t *testing.T) (string, string) {
|
||||
shim := `#!/bin/sh
|
||||
set -eu
|
||||
printf 'cwd=%s GOWORK=%s GOTOOLCHAIN=%s %s\n' "$PWD" "$GOWORK" "$GOTOOLCHAIN" "$*" >> "$RELEASEKIT_GO_LOG"
|
||||
if [ "$1" = env ]; then exec "$RELEASEKIT_REAL_GO" "$@"; fi
|
||||
case " $* " in *" -deps "*) printf 'target=%s/%s\n' "$GOOS" "$GOARCH" >> "$RELEASEKIT_GO_LOG" ;; esac
|
||||
modfile=
|
||||
for argument in "$@"; do
|
||||
case "$argument" in -modfile=*) modfile=${argument#-modfile=} ;; esac
|
||||
@@ -406,20 +494,12 @@ case "$1" in
|
||||
list)
|
||||
printf '%s v0.2.0\n' "$RELEASEKIT_MODULE"
|
||||
;;
|
||||
build)
|
||||
output=
|
||||
previous=
|
||||
for argument in "$@"; do
|
||||
if [ "$previous" = "-o" ]; then output=$argument; break; fi
|
||||
previous=$argument
|
||||
done
|
||||
[ -n "$output" ] || { echo 'go build omitted output path' >&2; exit 90; }
|
||||
cat > "$output" <<'TOOL'
|
||||
#!/bin/sh
|
||||
printf '<%s>\n' "$@" > "$RELEASEKIT_TOOL_ARGS_LOG"
|
||||
exit "${RELEASEKIT_TOOL_EXIT:-0}"
|
||||
TOOL
|
||||
chmod +x "$output"
|
||||
mod)
|
||||
;;
|
||||
tool)
|
||||
shift 3
|
||||
printf '<%s>\n' "$@" > "$RELEASEKIT_TOOL_ARGS_LOG"
|
||||
exit "${RELEASEKIT_TOOL_EXIT:-0}"
|
||||
;;
|
||||
*)
|
||||
echo "unexpected Go command: $1" >&2
|
||||
@@ -453,7 +533,7 @@ func templateEnvironment(repository, commit, shimDir, goLog string) map[string]s
|
||||
"CI_COMMIT_SHA": commit,
|
||||
"CI_COMMIT_TAG": "v1.2.3",
|
||||
"RELEASEKIT_GITEA_TOKEN": "fixture-token",
|
||||
"RELEASEKIT_MODULE": "gitea.maximumdirect.net/eric/ReleaseKit",
|
||||
"RELEASEKIT_MODULE": "go.maximumdirect.net/releasekit",
|
||||
"RELEASEKIT_REAL_GO": realGo,
|
||||
"RELEASEKIT_GO_LOG": goLog,
|
||||
"GOTOOLCHAIN": "local",
|
||||
@@ -486,8 +566,8 @@ func executeWoodpeckerBlock(block, repository string, environment map[string]str
|
||||
|
||||
func selectReleaseKitModule(t *testing.T, repository, releaseKitSource string, includeSum bool) {
|
||||
t.Helper()
|
||||
const module = "gitea.maximumdirect.net/eric/ReleaseKit"
|
||||
goMod := fmt.Sprintf("module example.com/tagged-app\n\ngo 1.26.0\n\nrequire %s v0.2.0\n\nreplace %s => %s\n", module, module, strconv.Quote(releaseKitSource))
|
||||
const module = "go.maximumdirect.net/releasekit"
|
||||
goMod := fmt.Sprintf("module example.com/tagged-app\n\ngo 1.27.0\n\nrequire %s v0.2.0\n\nreplace %s => %s\n", module, module, strconv.Quote(releaseKitSource))
|
||||
writeRepositoryFile(t, repository, "go.mod", goMod)
|
||||
cliGitRun(t, repository, "add", "go.mod")
|
||||
if includeSum {
|
||||
@@ -499,13 +579,13 @@ func selectReleaseKitModule(t *testing.T, repository, releaseKitSource string, i
|
||||
|
||||
func writeReleaseKitModuleProxy(t *testing.T) string {
|
||||
t.Helper()
|
||||
const module = "gitea.maximumdirect.net/eric/ReleaseKit"
|
||||
const module = "go.maximumdirect.net/releasekit"
|
||||
const toolDependency = "example.com/releasekit-helper"
|
||||
proxyDir := t.TempDir()
|
||||
toolModule := "module " + module + "\n\ngo 1.25.0\n\nrequire " + toolDependency + " v1.0.0\n"
|
||||
for _, version := range []string{"v0.2.197", "v0.2.198"} {
|
||||
files := map[string]string{
|
||||
"cmd/releasekit/main.go": "package main\n\nimport (\"fmt\"; \"os\"; tooldep \"example.com/releasekit-helper\")\n\nfunc main() {\n\tfmt.Println(\"tool-version=" + version + " helper=\" + tooldep.Version)\n\tfmt.Printf(\"tool-args=%q\\n\", os.Args[1:])\n}\n",
|
||||
"cmd/releasekit/main.go": "package main\n\nimport (\"fmt\"; \"os\"; \"strconv\"; tooldep \"example.com/releasekit-helper\")\n\nfunc main() {\n\tfmt.Println(\"tool-version=" + version + " helper=\" + tooldep.Version)\n\tfmt.Printf(\"tool-args=%q\\n\", os.Args[1:])\n\tstatus, _ := strconv.Atoi(os.Getenv(\"RELEASEKIT_TOOL_EXIT\"))\n\tos.Exit(status)\n}\n",
|
||||
}
|
||||
writeModuleProxyVersion(t, proxyDir, module, version, toolModule, files)
|
||||
}
|
||||
@@ -605,17 +685,20 @@ func assertModuleBootstrap(t *testing.T, repository, goLog, moduleBefore string,
|
||||
func assertGoSelection(t *testing.T, repository, goLog string) {
|
||||
t.Helper()
|
||||
log := readWoodpeckerFixtureFile(t, goLog)
|
||||
if !strings.Contains(log, "target="+runtime.GOOS+"/"+runtime.GOARCH) {
|
||||
t.Fatalf("dependency inspection did not use host target: %s", log)
|
||||
}
|
||||
list := "list -mod=mod -modfile="
|
||||
build := "build -mod=mod -modfile="
|
||||
module := "gitea.maximumdirect.net/eric/ReleaseKit"
|
||||
tool := "tool -modfile="
|
||||
module := "go.maximumdirect.net/releasekit"
|
||||
if !strings.Contains(log, "GOWORK=off GOTOOLCHAIN=local") || !strings.Contains(log, list) || !strings.Contains(log, "-m "+module) {
|
||||
t.Fatalf("Go module selection command is missing required settings: %q", log)
|
||||
}
|
||||
if !strings.Contains(log, build) || !strings.Contains(log, module+"/cmd/releasekit") || strings.Contains(log, "@v0.2.0") {
|
||||
t.Fatalf("Go build did not use the selected module without a version suffix: %q", log)
|
||||
if !strings.Contains(log, tool) || !strings.Contains(log, " "+module+"/cmd/releasekit ci-deliver ") || strings.Contains(log, "@v0.2.0") {
|
||||
t.Fatalf("Go tool did not run the module-selected ReleaseKit: %q", log)
|
||||
}
|
||||
if strings.Index(log, list) > strings.Index(log, build) {
|
||||
t.Fatalf("Go build ran before module selection: %q", log)
|
||||
if strings.Index(log, list) > strings.Index(log, tool) {
|
||||
t.Fatalf("Go tool ran before module selection: %q", log)
|
||||
}
|
||||
var modfile string
|
||||
for _, field := range strings.Fields(log) {
|
||||
|
||||
203
delivery.go
203
delivery.go
@@ -2,11 +2,15 @@ package releasekit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
internalbuild "gitea.maximumdirect.net/eric/ReleaseKit/internal/build"
|
||||
internaldelivery "gitea.maximumdirect.net/eric/ReleaseKit/internal/delivery"
|
||||
"gitea.maximumdirect.net/eric/ReleaseKit/internal/gitea"
|
||||
internalbuild "go.maximumdirect.net/releasekit/internal/build"
|
||||
internaldelivery "go.maximumdirect.net/releasekit/internal/delivery"
|
||||
"go.maximumdirect.net/releasekit/internal/forge"
|
||||
"go.maximumdirect.net/releasekit/internal/gitea"
|
||||
)
|
||||
|
||||
// DeliveryState describes the result of one delivery invocation.
|
||||
@@ -25,30 +29,87 @@ const (
|
||||
DeliveryUnknown DeliveryState = "unknown"
|
||||
)
|
||||
|
||||
// GiteaDestination supplies the hosted repository and explicit access token.
|
||||
type GiteaDestination struct {
|
||||
// Forge selects the hosted delivery backend. A delivery request must select a
|
||||
// supported value explicitly; the destination URL does not select a backend.
|
||||
type Forge string
|
||||
|
||||
const (
|
||||
// ForgeGitea selects Gitea for hosted delivery.
|
||||
ForgeGitea Forge = "gitea"
|
||||
)
|
||||
|
||||
// DeliveryDestination supplies an explicitly selected hosted destination.
|
||||
type DeliveryDestination struct {
|
||||
// Forge selects the adapter that interprets the destination fields.
|
||||
Forge Forge
|
||||
BaseURL string
|
||||
Owner string
|
||||
Repository string
|
||||
Token string
|
||||
}
|
||||
|
||||
// DeliveryPreflightFailureKind classifies a failure while checking destination
|
||||
// settings, credentials, and repository access.
|
||||
type DeliveryPreflightFailureKind string
|
||||
|
||||
const (
|
||||
// DeliveryPreflightInvalidDestination means the destination settings fail local validation.
|
||||
DeliveryPreflightInvalidDestination DeliveryPreflightFailureKind = "invalid_destination"
|
||||
// DeliveryPreflightMissingCredential means no nonblank credential was supplied.
|
||||
DeliveryPreflightMissingCredential DeliveryPreflightFailureKind = "missing_credential"
|
||||
// DeliveryPreflightInvalidCredential means the selected service rejected the credential.
|
||||
DeliveryPreflightInvalidCredential DeliveryPreflightFailureKind = "invalid_credential"
|
||||
// DeliveryPreflightInsufficientPermissions means a required delivery permission is known to be absent.
|
||||
DeliveryPreflightInsufficientPermissions DeliveryPreflightFailureKind = "insufficient_permissions"
|
||||
// DeliveryPreflightInaccessibleDestination means the credential cannot access the selected repository.
|
||||
DeliveryPreflightInaccessibleDestination DeliveryPreflightFailureKind = "inaccessible_destination"
|
||||
// DeliveryPreflightUnavailable means the service response could not verify access.
|
||||
DeliveryPreflightUnavailable DeliveryPreflightFailureKind = "unavailable"
|
||||
)
|
||||
|
||||
// DeliveryPreflightError reports a classified failure to verify a destination.
|
||||
type DeliveryPreflightError struct {
|
||||
Kind DeliveryPreflightFailureKind
|
||||
Err error
|
||||
}
|
||||
|
||||
func (err *DeliveryPreflightError) Error() string {
|
||||
if err.Err == nil {
|
||||
return fmt.Sprintf("delivery preflight %s", err.Kind)
|
||||
}
|
||||
return fmt.Sprintf("delivery preflight %s: %v", err.Kind, err.Err)
|
||||
}
|
||||
|
||||
func (err *DeliveryPreflightError) Unwrap() error { return err.Err }
|
||||
|
||||
// DeliveryAsset identifies a hosted asset by filename and SHA-256 digest.
|
||||
type DeliveryAsset struct {
|
||||
Filename string
|
||||
SHA256 string
|
||||
}
|
||||
|
||||
// DeliveryRequest identifies a local tagged checkout and its explicit Gitea
|
||||
// DeliveryRequest identifies a local tagged checkout and its explicit
|
||||
// destination. Build selects a managed build; Prebuilt supplies caller-owned
|
||||
// build output instead. They cannot both be set. Either may be nil for
|
||||
// page-only delivery when both are nil. Build with no targets, or an empty
|
||||
// Prebuilt result, also performs page-only delivery.
|
||||
// build output instead. They cannot both be set. The ordinary page-only request
|
||||
// leaves both nil. A Build with no targets or a matching Prebuilt result with
|
||||
// no targets or artifacts also performs page-only delivery. Any supplied
|
||||
// Prebuilt must match the repository, module directory and path, tag, commit,
|
||||
// and version; a zero BuildResult does not supply that identity. Source and
|
||||
// artifact requirements for binaries apply when binary work is selected.
|
||||
type DeliveryRequest struct {
|
||||
RepositoryDir string
|
||||
Product string
|
||||
Version string
|
||||
Destination GiteaDestination
|
||||
RepositoryDir string // directory within the tagged source Git checkout.
|
||||
// ModuleDir selects a repository-relative module directory; empty selects
|
||||
// the repository root.
|
||||
ModuleDir string
|
||||
// Source selects explicit source and publication capabilities. Nil retains
|
||||
// the ModuleDir Go-module shorthand.
|
||||
Source *SourceSpec
|
||||
Product string
|
||||
Version string
|
||||
// ExpectedTag optionally requires the full CI event tag to match the
|
||||
// selected module's derived tag before building or making hosted requests.
|
||||
ExpectedTag string
|
||||
Destination DeliveryDestination
|
||||
// Build selects binaries to build in temporary storage outside the checkout.
|
||||
Build *BuildSpec
|
||||
// Prebuilt supplies an existing build whose files remain caller-owned.
|
||||
@@ -58,11 +119,22 @@ type DeliveryRequest struct {
|
||||
}
|
||||
|
||||
// DeliveryResult reports hosted content and the state reached by this
|
||||
// invocation. A partial result may accompany an error. The asset slices are
|
||||
// invocation. A result may accompany an error, including Complete when hosted
|
||||
// delivery succeeded but local managed-build cleanup failed. The asset slices are
|
||||
// current observations: an asset appears in at most one slice, and early
|
||||
// failures may leave some declared assets unreported.
|
||||
type DeliveryResult struct {
|
||||
Version string
|
||||
RepositoryDir string
|
||||
SourceDir string
|
||||
SourceSubdir string
|
||||
GoEnabled bool
|
||||
Publication PublicationMode
|
||||
VersionFormat VersionFormat
|
||||
VersionPrefix string
|
||||
ModuleDir string
|
||||
ModulePath string
|
||||
Tag string // complete derived Git tag.
|
||||
Version string // selected production or diagnostic identifier.
|
||||
CandidateCommit string
|
||||
ReleaseURL string
|
||||
State DeliveryState
|
||||
@@ -78,16 +150,22 @@ type DeliveryResult struct {
|
||||
Uncertain []DeliveryAsset
|
||||
}
|
||||
|
||||
// Deliver verifies the selected local tag and hosted source, then creates or
|
||||
// finds its release page and adds any missing declared build assets. Build
|
||||
// requests are compiled into temporary storage that Deliver removes on return.
|
||||
// Prebuilt artifacts remain caller-owned and are not removed. Both paths
|
||||
// validate source identity and artifact contents before hosted writes.
|
||||
// Deliver requires an explicit supported destination forge. It checks the local
|
||||
// request and source, then performs read-only credential preflight before a
|
||||
// managed build or full artifact verification. It verifies the selected local
|
||||
// tag and hosted source, then creates or finds its release page and adds any
|
||||
// missing declared build assets. Prebuilt artifacts remain caller-owned. Local
|
||||
// artifact contents are verified after preflight and before hosted writes.
|
||||
// Module selection and declaration links resolve from the captured commit.
|
||||
// Page-only delivery can use a sparse checkout with available committed objects;
|
||||
// managed builds require their selected source files in the working tree.
|
||||
// Preflight failures return a [DeliveryPreflightError] and leave State at
|
||||
// [DeliveryNotAttempted].
|
||||
func Deliver(ctx context.Context, request DeliveryRequest) (DeliveryResult, error) {
|
||||
result := DeliveryResult{Version: request.Version, State: DeliveryNotAttempted}
|
||||
destination := gitea.Destination{
|
||||
BaseURL: request.Destination.BaseURL, Owner: request.Destination.Owner,
|
||||
Repository: request.Destination.Repository, Token: request.Destination.Token,
|
||||
backend, err := deliveryBackend(request.Destination)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
var prebuilt *internalbuild.Result
|
||||
if request.Prebuilt != nil {
|
||||
@@ -95,13 +173,31 @@ func Deliver(ctx context.Context, request DeliveryRequest) (DeliveryResult, erro
|
||||
}
|
||||
internalResult, err := internaldelivery.Deliver(ctx, internaldelivery.Request{
|
||||
RepositoryDir: request.RepositoryDir,
|
||||
ModuleDir: request.ModuleDir,
|
||||
Source: internalSourceSpec(request.Source),
|
||||
Product: request.Product,
|
||||
Version: request.Version,
|
||||
Destination: destination,
|
||||
ExpectedTag: request.ExpectedTag,
|
||||
Backend: backend,
|
||||
Build: internalBuildSpec(request.Build),
|
||||
Prebuilt: prebuilt,
|
||||
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.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.ModulePath = internalResult.ModulePath
|
||||
result.Tag = internalResult.Tag
|
||||
result.CandidateCommit = internalResult.CandidateCommit
|
||||
result.ReleaseURL = internalResult.ReleaseURL
|
||||
result.State = DeliveryState(internalResult.State)
|
||||
@@ -110,10 +206,65 @@ func Deliver(ctx context.Context, request DeliveryRequest) (DeliveryResult, erro
|
||||
result.Pending = deliveryAssets(internalResult.Pending)
|
||||
result.Conflicting = deliveryAssets(internalResult.Conflicting)
|
||||
result.Uncertain = deliveryAssets(internalResult.Uncertain)
|
||||
return result, err
|
||||
return result
|
||||
}
|
||||
|
||||
func deliveryAssets(assets []gitea.AssetIdentity) []DeliveryAsset {
|
||||
// PreflightDelivery checks destination credentials and repository access using
|
||||
// read-only backend operations. It does not require a checkout or published tag.
|
||||
// The result verifies only the access and permission evidence exposed by the
|
||||
// selected backend; it does not guarantee that a later write will succeed.
|
||||
// Failures are returned as [DeliveryPreflightError] values when classified by
|
||||
// the backend, and retain their underlying cause for errors.Is and errors.As.
|
||||
func PreflightDelivery(ctx context.Context, destination DeliveryDestination) error {
|
||||
backend, err := deliveryBackend(destination)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return publicPreflightError(backend.Preflight(ctx))
|
||||
}
|
||||
|
||||
func deliveryBackend(destination DeliveryDestination) (forge.Backend, error) {
|
||||
selection := Forge(strings.TrimSpace(string(destination.Forge)))
|
||||
switch selection {
|
||||
case ForgeGitea:
|
||||
return gitea.NewBackend(gitea.Destination{
|
||||
BaseURL: destination.BaseURL, Owner: destination.Owner,
|
||||
Repository: destination.Repository, Token: destination.Token,
|
||||
}, nil), nil
|
||||
case "":
|
||||
return nil, errors.New("delivery forge must be selected explicitly")
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported delivery forge %q", destination.Forge)
|
||||
}
|
||||
}
|
||||
|
||||
func publicPreflightError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
var failure *forge.PreflightFailure
|
||||
if !errors.As(err, &failure) {
|
||||
return err
|
||||
}
|
||||
kind := DeliveryPreflightUnavailable
|
||||
switch failure.Kind {
|
||||
case forge.PreflightInvalidDestination:
|
||||
kind = DeliveryPreflightInvalidDestination
|
||||
case forge.PreflightMissingCredential:
|
||||
kind = DeliveryPreflightMissingCredential
|
||||
case forge.PreflightInvalidCredential:
|
||||
kind = DeliveryPreflightInvalidCredential
|
||||
case forge.PreflightInsufficientPermissions:
|
||||
kind = DeliveryPreflightInsufficientPermissions
|
||||
case forge.PreflightInaccessibleDestination:
|
||||
kind = DeliveryPreflightInaccessibleDestination
|
||||
case forge.PreflightUnavailable:
|
||||
kind = DeliveryPreflightUnavailable
|
||||
}
|
||||
return &DeliveryPreflightError{Kind: kind, Err: failure.Err}
|
||||
}
|
||||
|
||||
func deliveryAssets(assets []internaldelivery.AssetIdentity) []DeliveryAsset {
|
||||
result := make([]DeliveryAsset, 0, len(assets))
|
||||
for _, asset := range assets {
|
||||
result = append(result, DeliveryAsset{Filename: asset.Filename, SHA256: asset.SHA256})
|
||||
|
||||
63
delivery_causes_test.go
Normal file
63
delivery_causes_test.go
Normal file
@@ -0,0 +1,63 @@
|
||||
package releasekit_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
releasekit "go.maximumdirect.net/releasekit"
|
||||
)
|
||||
|
||||
func TestDeliveryPreservesAssetInspectionCauses(t *testing.T) {
|
||||
repository := newTaggedDeliveryConsumer(t)
|
||||
prebuilt, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||
RepositoryDir: repository, Version: "v1.2.3", OutputDir: t.TempDir(),
|
||||
Spec: releasekit.BuildSpec{MainPackage: "./cmd/app", BinaryName: "fixture", Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
filename := prebuilt.Artifacts[0].Filename
|
||||
for _, cause := range []error{context.Canceled, io.ErrUnexpectedEOF} {
|
||||
t.Run(cause.Error(), func(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
state := &facadeDeliveryServer{data: facadeDeliveryData{
|
||||
t: t, commit: prebuilt.CandidateCommit, tag: prebuilt.Tag, version: prebuilt.Version,
|
||||
noteBody: "# Fixture v1.2.3\n\nDelivery fixture.\n",
|
||||
pages: map[string]bool{prebuilt.Tag: true}, assets: map[string][]byte{filename: []byte("data")},
|
||||
}}
|
||||
server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.HasPrefix(r.URL.Path, "/files/") {
|
||||
if cause == context.Canceled {
|
||||
cancel()
|
||||
<-r.Context().Done()
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Length", "100")
|
||||
_, _ = w.Write([]byte("truncated"))
|
||||
return
|
||||
}
|
||||
state.serveHTTP(w, r)
|
||||
}))
|
||||
state.data.url = "http://" + server.Listener.Addr().String()
|
||||
server.Start()
|
||||
defer server.Close()
|
||||
result, err := releasekit.Deliver(ctx, releasekit.DeliveryRequest{
|
||||
RepositoryDir: repository, Product: "Fixture", Version: "v1.2.3",
|
||||
Destination: facadeDeliveryDestination(server.URL), Prebuilt: &prebuilt,
|
||||
})
|
||||
if !errors.Is(err, cause) || !strings.Contains(err.Error(), filename) {
|
||||
t.Fatalf("Deliver() error = %v, want cause %v and asset context", err, cause)
|
||||
}
|
||||
if result.State != releasekit.DeliveryNotAttempted || len(result.Uncertain) != 1 || result.Uncertain[0].Filename != filename || state.snapshot().writes != 0 {
|
||||
t.Fatalf("result = %#v, want read-only uncertain asset without write", result)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
53
delivery_destination_test.go
Normal file
53
delivery_destination_test.go
Normal file
@@ -0,0 +1,53 @@
|
||||
package releasekit_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
releasekit "go.maximumdirect.net/releasekit"
|
||||
)
|
||||
|
||||
func TestInvalidDestinationFailsStandaloneAndAutomaticPreflight(t *testing.T) {
|
||||
repository := newTaggedDeliveryConsumer(t)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
t.Errorf("invalid destination made a hosted request: %s", r.URL.Path)
|
||||
http.Error(w, "unexpected request", http.StatusInternalServerError)
|
||||
}))
|
||||
defer server.Close()
|
||||
for _, test := range []struct {
|
||||
name, setting string
|
||||
change func(*releasekit.DeliveryDestination)
|
||||
}{
|
||||
{"URL", "base URL", func(d *releasekit.DeliveryDestination) { d.BaseURL = "ssh://forge.example" }},
|
||||
{"owner", "owner", func(d *releasekit.DeliveryDestination) { d.Owner = "owner/child" }},
|
||||
{"repository", "repository", func(d *releasekit.DeliveryDestination) { d.Repository = "repo/child" }},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
destination := facadeDeliveryDestination(server.URL)
|
||||
test.change(&destination)
|
||||
assertFailure := func(err error) {
|
||||
t.Helper()
|
||||
var preflight *releasekit.DeliveryPreflightError
|
||||
if !errors.As(err, &preflight) || preflight.Kind != releasekit.DeliveryPreflightInvalidDestination || preflight.Err == nil {
|
||||
t.Fatalf("error = %#v, want invalid destination with cause", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), test.setting) {
|
||||
t.Fatalf("error = %v, want invalid setting %q", err, test.setting)
|
||||
}
|
||||
}
|
||||
assertFailure(releasekit.PreflightDelivery(context.Background(), destination))
|
||||
result, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
|
||||
RepositoryDir: repository, Product: "Fixture", Version: "v1.2.3", Destination: destination,
|
||||
Build: &releasekit.BuildSpec{MainPackage: "./missing", BinaryName: "fixture", Targets: []releasekit.Target{{OS: "linux", Arch: "amd64"}}},
|
||||
})
|
||||
assertFailure(err)
|
||||
if result.State != releasekit.DeliveryNotAttempted {
|
||||
t.Fatalf("delivery state = %s, want not attempted", result.State)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
554
delivery_test.go
554
delivery_test.go
@@ -8,15 +8,186 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
releasekit "gitea.maximumdirect.net/eric/ReleaseKit"
|
||||
releasekit "go.maximumdirect.net/releasekit"
|
||||
)
|
||||
|
||||
func TestDeliveryForgeSelectionIsExplicit(t *testing.T) {
|
||||
var requests int
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requests++
|
||||
http.Error(w, "unexpected request", http.StatusInternalServerError)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
for _, forge := range []releasekit.Forge{"", " \t", "unknown"} {
|
||||
t.Run(string(forge), func(t *testing.T) {
|
||||
destination := releasekit.DeliveryDestination{
|
||||
Forge: forge, BaseURL: server.URL, Owner: "owner", Repository: "example", Token: "fixture-token",
|
||||
}
|
||||
if err := releasekit.PreflightDelivery(context.Background(), destination); err == nil || !strings.Contains(err.Error(), "forge") {
|
||||
t.Fatalf("PreflightDelivery() error = %v, want explicit forge selection error", err)
|
||||
}
|
||||
result, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
|
||||
Version: "v1.2.3", Destination: destination,
|
||||
})
|
||||
if err == nil || !strings.Contains(err.Error(), "forge") || result.State != releasekit.DeliveryNotAttempted || result.Version != "v1.2.3" {
|
||||
t.Fatalf("Deliver() = %#v, %v; want selection error before delivery", result, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
if requests != 0 {
|
||||
t.Fatalf("hosted requests = %d, want 0 for invalid forge selection", requests)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreflightDeliveryChecksAuthenticatedRepositoryWithoutCheckout(t *testing.T) {
|
||||
var requests, writes int
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
writes++
|
||||
t.Errorf("preflight method = %q, want GET", r.Method)
|
||||
http.Error(w, "unexpected write", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
if got, want := r.Header.Get("Authorization"), "token fixture-token"; got != want {
|
||||
t.Errorf("authorization = %q, want %q", got, want)
|
||||
}
|
||||
requests++
|
||||
switch r.URL.Path {
|
||||
case "/api/v1/repos/owner/example":
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"id": 31, "name": "example", "full_name": "owner/example", "owner": map[string]string{"login": "owner"}})
|
||||
case "/api/v1/repositories/31":
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"id": 31, "name": "example", "full_name": "owner/example", "owner": map[string]string{"login": "owner"}})
|
||||
default:
|
||||
t.Errorf("preflight path = %q", r.URL.Path)
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
if err := releasekit.PreflightDelivery(context.Background(), facadeDeliveryDestination(server.URL)); err != nil {
|
||||
t.Fatalf("PreflightDelivery() error = %v", err)
|
||||
}
|
||||
if requests != 2 || writes != 0 {
|
||||
t.Fatalf("preflight requests=%d writes=%d, want two reads and no writes", requests, writes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreflightDeliveryPreservesPublicFailureKindsAndCauses(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
token string
|
||||
status int
|
||||
wantKind releasekit.DeliveryPreflightFailureKind
|
||||
wantReads int
|
||||
canceled bool
|
||||
}{
|
||||
{name: "missing credential", wantKind: releasekit.DeliveryPreflightMissingCredential},
|
||||
{name: "invalid credential", token: "fixture-token", status: http.StatusUnauthorized, wantKind: releasekit.DeliveryPreflightInvalidCredential, wantReads: 1},
|
||||
{name: "inaccessible destination", token: "fixture-token", status: http.StatusForbidden, wantKind: releasekit.DeliveryPreflightInaccessibleDestination, wantReads: 1},
|
||||
{name: "unavailable service", token: "fixture-token", status: http.StatusServiceUnavailable, wantKind: releasekit.DeliveryPreflightUnavailable, wantReads: 1},
|
||||
{name: "canceled request", token: "fixture-token", wantKind: releasekit.DeliveryPreflightUnavailable, canceled: true},
|
||||
}
|
||||
for _, test := range cases {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
reads := 0
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
reads++
|
||||
if test.status != 0 {
|
||||
http.Error(w, "controlled failure", test.status)
|
||||
return
|
||||
}
|
||||
t.Errorf("unexpected request to %q", r.URL.Path)
|
||||
http.Error(w, "unexpected request", http.StatusInternalServerError)
|
||||
}))
|
||||
defer server.Close()
|
||||
destination := facadeDeliveryDestination(server.URL)
|
||||
destination.Token = test.token
|
||||
ctx := context.Background()
|
||||
if test.canceled {
|
||||
canceled, cancel := context.WithCancel(ctx)
|
||||
cancel()
|
||||
ctx = canceled
|
||||
}
|
||||
err := releasekit.PreflightDelivery(ctx, destination)
|
||||
var preflight *releasekit.DeliveryPreflightError
|
||||
if !errors.As(err, &preflight) || preflight.Kind != test.wantKind || preflight.Err == nil {
|
||||
t.Fatalf("PreflightDelivery() error = %#v, want kind %q with cause", err, test.wantKind)
|
||||
}
|
||||
if test.canceled && !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("PreflightDelivery() error = %v, want cancellation identity", err)
|
||||
}
|
||||
if reads != test.wantReads {
|
||||
t.Fatalf("preflight reads = %d, want %d", reads, test.wantReads)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomaticPreflightFailurePrecedesPrebuiltArtifactHashing(t *testing.T) {
|
||||
repository := newTaggedDeliveryConsumer(t)
|
||||
prebuilt, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||
RepositoryDir: repository,
|
||||
Version: "v1.2.3",
|
||||
Spec: releasekit.BuildSpec{
|
||||
MainPackage: "./cmd/app",
|
||||
BinaryName: "fixture",
|
||||
Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}},
|
||||
},
|
||||
OutputDir: t.TempDir(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Build() error = %v", err)
|
||||
}
|
||||
contents, err := os.ReadFile(prebuilt.Artifacts[0].Path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
contents[0] ^= 0xff
|
||||
if err := os.WriteFile(prebuilt.Artifacts[0].Path, contents, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var reads, writes int
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
writes++
|
||||
http.Error(w, "unexpected write", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
reads++
|
||||
if r.URL.Path == "/api/v1/repos/owner/example" {
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"id": 31, "name": "example", "full_name": "owner/example", "owner": map[string]string{"login": "owner"}})
|
||||
return
|
||||
}
|
||||
http.Error(w, "verification unavailable", http.StatusServiceUnavailable)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
result, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
|
||||
RepositoryDir: repository,
|
||||
Product: "Fixture",
|
||||
Version: "v1.2.3",
|
||||
Destination: facadeDeliveryDestination(server.URL),
|
||||
Prebuilt: &prebuilt,
|
||||
})
|
||||
var preflight *releasekit.DeliveryPreflightError
|
||||
if !errors.As(err, &preflight) || preflight.Kind != releasekit.DeliveryPreflightUnavailable || result.State != releasekit.DeliveryNotAttempted {
|
||||
t.Fatalf("Deliver() = %#v, %v; want unavailable preflight before tamper verification", result, err)
|
||||
}
|
||||
if reads != 2 || writes != 0 {
|
||||
t.Fatalf("preflight reads=%d writes=%d, want two reads and no writes", reads, writes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeliverManagedBuildUploadsArtifactsAndCleansTemporaryOutput(t *testing.T) {
|
||||
repository := newTaggedDeliveryConsumer(t)
|
||||
temporaryRoot := t.TempDir()
|
||||
@@ -40,11 +211,12 @@ func TestDeliverManagedBuildUploadsArtifactsAndCleansTemporaryOutput(t *testing.
|
||||
if err != nil {
|
||||
t.Fatalf("Deliver() error = %v; result = %#v", err, result)
|
||||
}
|
||||
if result.State != releasekit.DeliveryComplete || result.CandidateCommit != remote.commit {
|
||||
observed := remote.snapshot()
|
||||
if result.State != releasekit.DeliveryComplete || result.CandidateCommit != observed.commit {
|
||||
t.Fatalf("delivery result = %#v", result)
|
||||
}
|
||||
if len(result.Uploaded) != 2 || len(remote.assets) != 2 {
|
||||
t.Fatalf("uploaded = %#v; hosted assets = %v", result.Uploaded, mapKeys(remote.assets))
|
||||
if len(result.Uploaded) != 2 || len(observed.assets) != 2 {
|
||||
t.Fatalf("uploaded = %#v; hosted assets = %v", result.Uploaded, mapKeys(observed.assets))
|
||||
}
|
||||
if !strings.Contains(progress.String(), "checking fixture version output") {
|
||||
t.Fatalf("build progress = %q", progress.String())
|
||||
@@ -78,7 +250,8 @@ func TestDeliverBinaryConsumerWithBuildinfoAndSelectedTargets(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("Deliver() error = %v; result = %#v", err, result)
|
||||
}
|
||||
if result.State != releasekit.DeliveryComplete || result.CandidateCommit != remote.commit {
|
||||
observed := remote.snapshot()
|
||||
if result.State != releasekit.DeliveryComplete || result.CandidateCommit != observed.commit {
|
||||
t.Fatalf("delivery result = %#v", result)
|
||||
}
|
||||
wantAssets := []string{
|
||||
@@ -86,12 +259,12 @@ func TestDeliverBinaryConsumerWithBuildinfoAndSelectedTargets(t *testing.T) {
|
||||
"fixture-v1.2.3-linux-arm64",
|
||||
"SHA256SUMS",
|
||||
}
|
||||
if len(result.Uploaded) != len(wantAssets) || len(remote.assets) != len(wantAssets) {
|
||||
t.Fatalf("uploaded = %#v; hosted assets = %v", result.Uploaded, mapKeys(remote.assets))
|
||||
if len(result.Uploaded) != len(wantAssets) || len(observed.assets) != len(wantAssets) {
|
||||
t.Fatalf("uploaded = %#v; hosted assets = %v", result.Uploaded, mapKeys(observed.assets))
|
||||
}
|
||||
for _, name := range wantAssets {
|
||||
if _, ok := remote.assets[name]; !ok {
|
||||
t.Errorf("hosted assets omit %q: %v", name, mapKeys(remote.assets))
|
||||
if _, ok := observed.assets[name]; !ok {
|
||||
t.Errorf("hosted assets omit %q: %v", name, mapKeys(observed.assets))
|
||||
}
|
||||
}
|
||||
if !strings.Contains(progress.String(), "checking fixture version output") {
|
||||
@@ -134,6 +307,34 @@ func TestDeliverPrebuiltArtifactsRemainCallerOwned(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeliverRejectsOversizedExistingPrebuiltAsset(t *testing.T) {
|
||||
repository := newTaggedDeliveryConsumer(t)
|
||||
prebuilt, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||
RepositoryDir: repository, Version: "v1.2.3", OutputDir: t.TempDir(),
|
||||
Spec: releasekit.BuildSpec{MainPackage: "./cmd/app", BinaryName: "fixture", Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
content, err := os.ReadFile(prebuilt.Artifacts[0].Path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server, remote := newFacadeDeliveryServer(t, repository)
|
||||
defer server.Close()
|
||||
remote.update(func(data *facadeDeliveryData) {
|
||||
data.pages["v1.2.3"] = true
|
||||
data.assets[prebuilt.Artifacts[0].Filename] = append(content, 'x')
|
||||
})
|
||||
result, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
|
||||
RepositoryDir: repository, Product: "Fixture", Version: "v1.2.3",
|
||||
Destination: facadeDeliveryDestination(server.URL), Prebuilt: &prebuilt,
|
||||
})
|
||||
if err == nil || result.State != releasekit.DeliveryConflict || len(result.Conflicting) != 1 || result.Conflicting[0].Filename != prebuilt.Artifacts[0].Filename || remote.snapshot().writes != 0 {
|
||||
t.Fatalf("delivery = %#v, error = %v, writes = %d", result, err, remote.snapshot().writes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeliverRejectsSameSizePrebuiltTamperingBeforeHostedWrites(t *testing.T) {
|
||||
repository := newTaggedDeliveryConsumer(t)
|
||||
prebuilt, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||
@@ -173,8 +374,8 @@ func TestDeliverRejectsSameSizePrebuiltTamperingBeforeHostedWrites(t *testing.T)
|
||||
if err == nil || !strings.Contains(err.Error(), "verify build assets") || result.State != releasekit.DeliveryNotAttempted {
|
||||
t.Fatalf("Deliver() = %#v, %v; want local asset verification failure", result, err)
|
||||
}
|
||||
if remote.requests != 0 {
|
||||
t.Fatalf("hosted requests = %d, want none before local verification", remote.requests)
|
||||
if remote.snapshot().writes != 0 {
|
||||
t.Fatalf("hosted writes = %d, want none before local verification", remote.snapshot().writes)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -190,6 +391,14 @@ func TestDeliverPageOnlySkipsBuildAndHostedAssets(t *testing.T) {
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
repository := newTaggedDeliveryConsumer(t)
|
||||
prebuilt := test.prebuilt
|
||||
if prebuilt != nil {
|
||||
built, err := releasekit.Build(context.Background(), releasekit.BuildRequest{RepositoryDir: repository, Version: "v1.2.3"})
|
||||
if err != nil {
|
||||
t.Fatalf("Build() for page-only prebuilt identity = %#v, %v", built, err)
|
||||
}
|
||||
prebuilt = &built
|
||||
}
|
||||
temporaryRoot := t.TempDir()
|
||||
t.Setenv("TMPDIR", temporaryRoot)
|
||||
server, remote := newFacadeDeliveryServer(t, repository)
|
||||
@@ -202,14 +411,14 @@ func TestDeliverPageOnlySkipsBuildAndHostedAssets(t *testing.T) {
|
||||
Version: "v1.2.3",
|
||||
Destination: facadeDeliveryDestination(server.URL),
|
||||
Build: test.build,
|
||||
Prebuilt: test.prebuilt,
|
||||
Prebuilt: prebuilt,
|
||||
Output: &progress,
|
||||
})
|
||||
if err != nil || result.State != releasekit.DeliveryComplete {
|
||||
t.Fatalf("Deliver() = %#v, %v", result, err)
|
||||
}
|
||||
if len(remote.assets) != 0 || len(result.Uploaded) != 0 || len(result.Pending) != 0 {
|
||||
t.Fatalf("page-only delivery included assets: result=%#v assets=%v", result, mapKeys(remote.assets))
|
||||
if len(remote.snapshot().assets) != 0 || len(result.Uploaded) != 0 || len(result.Pending) != 0 {
|
||||
t.Fatalf("page-only delivery included assets: result=%#v assets=%v", result, mapKeys(remote.snapshot().assets))
|
||||
}
|
||||
if progress.Len() != 0 {
|
||||
t.Fatalf("page-only delivery emitted build progress: %q", progress.String())
|
||||
@@ -221,6 +430,131 @@ func TestDeliverPageOnlySkipsBuildAndHostedAssets(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeliverUsesOriginalNoteWithBlobReplacement(t *testing.T) {
|
||||
repository := newTaggedDeliveryConsumer(t)
|
||||
original := buildGit(t, repository, "rev-parse", "HEAD:docs/releases/v1.2.3.md")
|
||||
replacementPath := filepath.Join(t.TempDir(), "note.md")
|
||||
if err := os.WriteFile(replacementPath, []byte("# Fixture v1.2.3\n\nReplacement note.\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
replacement := buildGit(t, repository, "hash-object", "-w", replacementPath)
|
||||
buildGit(t, repository, "replace", original, replacement)
|
||||
server, remote := newFacadeDeliveryServer(t, repository)
|
||||
defer server.Close()
|
||||
result, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
|
||||
RepositoryDir: repository, Product: "Fixture", Version: "v1.2.3",
|
||||
Destination: facadeDeliveryDestination(server.URL),
|
||||
})
|
||||
if err != nil || result.State != releasekit.DeliveryComplete {
|
||||
t.Fatalf("delivery = %#v, error = %v", result, err)
|
||||
}
|
||||
if got := remote.snapshot().createdBody; got != "# Fixture v1.2.3\n\nDelivery fixture.\n" {
|
||||
t.Fatalf("delivered note = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeliverUsesCommittedModuleIdentityForSeparatePages(t *testing.T) {
|
||||
repository := newTwoModuleDeliveryConsumer(t)
|
||||
server, remote := newFacadeDeliveryServer(t, repository)
|
||||
defer server.Close()
|
||||
|
||||
wrongTag, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
|
||||
RepositoryDir: repository,
|
||||
Product: "Fixture",
|
||||
Version: "v1.2.3",
|
||||
ExpectedTag: "integrations/wrong/v1.2.3",
|
||||
Destination: facadeDeliveryDestination(server.URL),
|
||||
})
|
||||
if err == nil || wrongTag.Tag != "v1.2.3" || remote.snapshot().requests != 0 {
|
||||
t.Fatalf("delivery with inconsistent expected tag = %#v, %v; hosted requests %d", wrongTag, err, remote.snapshot().requests)
|
||||
}
|
||||
|
||||
rootResult, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
|
||||
RepositoryDir: repository,
|
||||
Product: "Fixture",
|
||||
Version: "v1.2.3",
|
||||
ExpectedTag: "v1.2.3",
|
||||
Destination: facadeDeliveryDestination(server.URL),
|
||||
})
|
||||
if err != nil || rootResult.State != releasekit.DeliveryComplete || rootResult.Tag != "v1.2.3" {
|
||||
t.Fatalf("root delivery = %#v, %v", rootResult, err)
|
||||
}
|
||||
|
||||
nestedTag := "integrations/ckconfig/v1.2.3"
|
||||
remote.update(func(remote *facadeDeliveryData) {
|
||||
remote.tag = nestedTag
|
||||
remote.noteBody = "# Fixture v1.2.3\n\nNested delivery fixture.\n"
|
||||
})
|
||||
nestedResult, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
|
||||
RepositoryDir: repository,
|
||||
ModuleDir: "integrations/ckconfig",
|
||||
Product: "Fixture",
|
||||
Version: "v1.2.3",
|
||||
ExpectedTag: nestedTag,
|
||||
Destination: facadeDeliveryDestination(server.URL),
|
||||
})
|
||||
if err != nil || nestedResult.State != releasekit.DeliveryComplete || nestedResult.Tag != nestedTag || nestedResult.ModulePath != "example.com/ckconfig" {
|
||||
t.Fatalf("nested delivery = %#v, %v", nestedResult, err)
|
||||
}
|
||||
if len(remote.snapshot().pages) != 2 || !remote.snapshot().pages["v1.2.3"] || !remote.snapshot().pages[nestedTag] {
|
||||
t.Fatalf("created hosted pages = %#v", remote.snapshot().pages)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeliverRejectsPrebuiltArtifactsForAnotherModuleBeforeHostedRequests(t *testing.T) {
|
||||
repository := newTwoModuleDeliveryConsumer(t)
|
||||
prebuilt, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||
RepositoryDir: repository,
|
||||
Version: "v1.2.3",
|
||||
Spec: releasekit.BuildSpec{
|
||||
MainPackage: "./cmd/app",
|
||||
BinaryName: "fixture",
|
||||
Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}},
|
||||
},
|
||||
OutputDir: filepath.Join(t.TempDir(), "root-artifacts"),
|
||||
})
|
||||
if err != nil || !prebuilt.SourceVerified {
|
||||
t.Fatalf("root Build() = %#v, %v", prebuilt, err)
|
||||
}
|
||||
server, remote := newFacadeDeliveryServer(t, repository)
|
||||
defer server.Close()
|
||||
remote.update(func(remote *facadeDeliveryData) { remote.tag = "integrations/ckconfig/v1.2.3" })
|
||||
result, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
|
||||
RepositoryDir: repository,
|
||||
ModuleDir: "integrations/ckconfig",
|
||||
Product: "Fixture",
|
||||
Version: "v1.2.3",
|
||||
ExpectedTag: remote.snapshot().tag,
|
||||
Destination: facadeDeliveryDestination(server.URL),
|
||||
Prebuilt: &prebuilt,
|
||||
})
|
||||
if err == nil || !strings.Contains(err.Error(), "selected tagged module") || result.Tag != remote.snapshot().tag {
|
||||
t.Fatalf("nested delivery with root artifacts = %#v, %v", result, err)
|
||||
}
|
||||
if remote.snapshot().requests != 0 {
|
||||
t.Fatalf("hosted requests before prebuilt identity rejection = %d", remote.snapshot().requests)
|
||||
}
|
||||
}
|
||||
|
||||
func newTwoModuleDeliveryConsumer(t *testing.T) string {
|
||||
t.Helper()
|
||||
repository := newTaggedDeliveryConsumer(t)
|
||||
writeNestedBuildConsumer(t, repository, "integrations/ckconfig", "example.com/ckconfig", `package main
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"go.maximumdirect.net/releasekit/buildinfo"
|
||||
)
|
||||
func main() { if len(os.Args) == 2 && os.Args[1] == "version" { fmt.Println("fixture", buildinfo.Version()) } }
|
||||
`)
|
||||
writeBuildFixture(t, repository, "integrations/ckconfig/docs/releases/v1.2.3.md", "# Fixture v1.2.3\n\nNested delivery fixture.\n")
|
||||
buildGit(t, repository, "add", "--all")
|
||||
buildGit(t, repository, "commit", "-m", "add nested release module")
|
||||
buildGit(t, repository, "tag", "-f", "v1.2.3")
|
||||
buildGit(t, repository, "tag", "integrations/ckconfig/v1.2.3")
|
||||
return repository
|
||||
}
|
||||
|
||||
func TestDeliverRejectsDirtyTaggedSourceBeforeBuildOrHostedWrites(t *testing.T) {
|
||||
repository := newTaggedDeliveryConsumer(t)
|
||||
writeBuildFixture(t, repository, "local-change.txt", "dirty source")
|
||||
@@ -242,19 +576,20 @@ func TestDeliverRejectsDirtyTaggedSourceBeforeBuildOrHostedWrites(t *testing.T)
|
||||
},
|
||||
Output: &progress,
|
||||
})
|
||||
if err == nil || result.State != releasekit.DeliveryNotAttempted || result.CandidateCommit != remote.commit {
|
||||
if err == nil || result.State != releasekit.DeliveryNotAttempted || result.CandidateCommit != remote.snapshot().commit {
|
||||
t.Fatalf("Deliver() = %#v, %v; want preflight failure for known commit", result, err)
|
||||
}
|
||||
if progress.Len() != 0 {
|
||||
t.Fatalf("build started before source eligibility passed: %q", progress.String())
|
||||
}
|
||||
if remote.requests != 0 {
|
||||
t.Fatalf("hosted requests = %d, want none", remote.requests)
|
||||
if remote.snapshot().requests != 0 {
|
||||
t.Fatalf("hosted requests = %d, want none", remote.snapshot().requests)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeliverRejectsCheckoutAwayFromTagBeforeBuildOrHostedWrites(t *testing.T) {
|
||||
repository := newTaggedDeliveryConsumer(t)
|
||||
tagCommit := buildGit(t, repository, "rev-parse", "HEAD")
|
||||
writeBuildFixture(t, repository, "later-change.txt", "new commit")
|
||||
buildGit(t, repository, "add", "--all")
|
||||
buildGit(t, repository, "commit", "-m", "advance checkout after release tag")
|
||||
@@ -276,14 +611,14 @@ func TestDeliverRejectsCheckoutAwayFromTagBeforeBuildOrHostedWrites(t *testing.T
|
||||
},
|
||||
Output: &progress,
|
||||
})
|
||||
if err == nil || result.State != releasekit.DeliveryNotAttempted || result.CandidateCommit == remote.commit {
|
||||
if err == nil || result.State != releasekit.DeliveryNotAttempted || result.CandidateCommit == tagCommit {
|
||||
t.Fatalf("Deliver() = %#v, %v; want tag/HEAD mismatch", result, err)
|
||||
}
|
||||
if progress.Len() != 0 {
|
||||
t.Fatalf("build started before tag/HEAD agreement: %q", progress.String())
|
||||
}
|
||||
if remote.requests != 0 {
|
||||
t.Fatalf("hosted requests = %d, want none", remote.requests)
|
||||
if remote.snapshot().requests != 0 {
|
||||
t.Fatalf("hosted requests = %d, want none", remote.snapshot().requests)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -307,14 +642,14 @@ func TestDeliverRejectsInvalidCommittedNoteBeforeBuildOrHostedWrites(t *testing.
|
||||
},
|
||||
Output: &progress,
|
||||
})
|
||||
if err == nil || result.State != releasekit.DeliveryNotAttempted || result.CandidateCommit != remote.commit {
|
||||
if err == nil || result.State != releasekit.DeliveryNotAttempted || result.CandidateCommit != remote.snapshot().commit {
|
||||
t.Fatalf("Deliver() = %#v, %v; want committed-note preflight failure", result, err)
|
||||
}
|
||||
if progress.Len() != 0 {
|
||||
t.Fatalf("build started before committed-note validation: %q", progress.String())
|
||||
}
|
||||
if remote.requests != 0 {
|
||||
t.Fatalf("hosted requests = %d, want none", remote.requests)
|
||||
if remote.snapshot().requests != 0 {
|
||||
t.Fatalf("hosted requests = %d, want none", remote.snapshot().requests)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -348,8 +683,8 @@ func TestDeliverManagedBuildRejectsCheckoutMutationBeforeHostedWrites(t *testing
|
||||
if err == nil || !strings.Contains(err.Error(), "build source") || result.State != releasekit.DeliveryNotAttempted {
|
||||
t.Fatalf("Deliver() = %#v, %v; want build-source eligibility failure", result, err)
|
||||
}
|
||||
if remote.requests != 0 {
|
||||
t.Fatalf("hosted requests = %d, want none", remote.requests)
|
||||
if remote.snapshot().writes != 0 {
|
||||
t.Fatalf("hosted writes = %d, want none after preflight", remote.snapshot().writes)
|
||||
}
|
||||
if entries, err := os.ReadDir(temporaryRoot); err != nil || len(entries) != 0 {
|
||||
t.Fatalf("ineligible managed build output remains: entries=%v error=%v", entries, err)
|
||||
@@ -374,11 +709,11 @@ func TestDeliverManagedBuildFailureCleansTemporaryOutputBeforeHostedWrites(t *te
|
||||
Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}},
|
||||
},
|
||||
})
|
||||
if err == nil || result.State != releasekit.DeliveryNotAttempted || result.CandidateCommit != remote.commit {
|
||||
if err == nil || result.State != releasekit.DeliveryNotAttempted || result.CandidateCommit != remote.snapshot().commit {
|
||||
t.Fatalf("Deliver() = %#v, %v; want managed build failure before hosted writes", result, err)
|
||||
}
|
||||
if remote.requests != 0 {
|
||||
t.Fatalf("hosted requests = %d, want none", remote.requests)
|
||||
if remote.snapshot().writes != 0 {
|
||||
t.Fatalf("hosted writes = %d, want none after preflight", remote.snapshot().writes)
|
||||
}
|
||||
if entries, err := os.ReadDir(temporaryRoot); err != nil || len(entries) != 0 {
|
||||
t.Fatalf("failed managed build output remains: entries=%v error=%v", entries, err)
|
||||
@@ -410,8 +745,8 @@ func TestDeliverManagedBuildCancellationCleansTemporaryOutput(t *testing.T) {
|
||||
if !errors.Is(err, context.Canceled) || result.State != releasekit.DeliveryNotAttempted {
|
||||
t.Fatalf("Deliver() = %#v, %v; want cancellation before hosted writes", result, err)
|
||||
}
|
||||
if remote.requests != 0 {
|
||||
t.Fatalf("hosted requests = %d, want none", remote.requests)
|
||||
if remote.snapshot().writes != 0 {
|
||||
t.Fatalf("hosted writes = %d, want none after preflight", remote.snapshot().writes)
|
||||
}
|
||||
if entries, err := os.ReadDir(temporaryRoot); err != nil || len(entries) != 0 {
|
||||
t.Fatalf("canceled managed build output remains: entries=%v error=%v", entries, err)
|
||||
@@ -434,8 +769,8 @@ func TestDeliverRejectsBothBuildSourcesBeforeHostedWrites(t *testing.T) {
|
||||
if err == nil || result.State != releasekit.DeliveryNotAttempted || !strings.Contains(err.Error(), "both") {
|
||||
t.Fatalf("Deliver() = %#v, %v; want invalid build-source combination", result, err)
|
||||
}
|
||||
if remote.requests != 0 {
|
||||
t.Fatalf("hosted requests = %d, want none", remote.requests)
|
||||
if remote.snapshot().requests != 0 {
|
||||
t.Fatalf("hosted requests = %d, want none", remote.snapshot().requests)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -449,7 +784,7 @@ func newTaggedDeliveryConsumerWithNote(t *testing.T, note string) string {
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo"
|
||||
"go.maximumdirect.net/releasekit/buildinfo"
|
||||
)
|
||||
func main() { if len(os.Args) == 2 && os.Args[1] == "version" { fmt.Println("fixture", buildinfo.Version()) } }
|
||||
`)
|
||||
@@ -460,8 +795,8 @@ func main() { if len(os.Args) == 2 && os.Args[1] == "version" { fmt.Println("fix
|
||||
return repository
|
||||
}
|
||||
|
||||
func facadeDeliveryDestination(baseURL string) releasekit.GiteaDestination {
|
||||
return releasekit.GiteaDestination{BaseURL: baseURL, Owner: "owner", Repository: "example", Token: "fixture-token"}
|
||||
func facadeDeliveryDestination(baseURL string) releasekit.DeliveryDestination {
|
||||
return releasekit.DeliveryDestination{Forge: releasekit.ForgeGitea, BaseURL: baseURL, Owner: "owner", Repository: "example", Token: "fixture-token"}
|
||||
}
|
||||
|
||||
type deliveryCancelWriter struct{ cancel context.CancelFunc }
|
||||
@@ -471,35 +806,109 @@ func (writer deliveryCancelWriter) Write(content []byte) (int, error) {
|
||||
return len(content), nil
|
||||
}
|
||||
|
||||
func TestDeliverExistingPageWithoutReleaseID(t *testing.T) {
|
||||
repository := newTaggedDeliveryConsumer(t)
|
||||
prebuilt, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||
RepositoryDir: repository, Version: "v1.2.3", OutputDir: t.TempDir(),
|
||||
Spec: releasekit.BuildSpec{MainPackage: "./cmd/app", BinaryName: "fixture", Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server, remote := newFacadeDeliveryServer(t, repository)
|
||||
defer server.Close()
|
||||
remote.update(func(data *facadeDeliveryData) { data.pages[data.tag] = true; data.omitReleaseID = true })
|
||||
request := releasekit.DeliveryRequest{RepositoryDir: repository, Product: "Fixture", Version: "v1.2.3", Destination: facadeDeliveryDestination(server.URL)}
|
||||
page, err := releasekit.Deliver(context.Background(), request)
|
||||
if err != nil || page.State != releasekit.DeliveryComplete {
|
||||
t.Fatalf("page result = %#v, error = %v", page, err)
|
||||
}
|
||||
request.Prebuilt = &prebuilt
|
||||
result, err := releasekit.Deliver(context.Background(), request)
|
||||
if err == nil || result.State != releasekit.DeliveryNotAttempted || !strings.Contains(err.Error(), "release ID") {
|
||||
t.Fatalf("asset result = %#v, error = %v", result, err)
|
||||
}
|
||||
if snapshot := remote.snapshot(); snapshot.writes != 0 {
|
||||
t.Fatalf("unexpected hosted writes: %#v", snapshot)
|
||||
}
|
||||
}
|
||||
|
||||
type facadeDeliveryServer struct {
|
||||
t *testing.T
|
||||
commit string
|
||||
page bool
|
||||
requests int
|
||||
assets map[string][]byte
|
||||
url string
|
||||
mu sync.Mutex
|
||||
data facadeDeliveryData
|
||||
}
|
||||
|
||||
func (state *facadeDeliveryServer) update(change func(*facadeDeliveryData)) {
|
||||
state.mu.Lock()
|
||||
defer state.mu.Unlock()
|
||||
change(&state.data)
|
||||
}
|
||||
|
||||
func (state *facadeDeliveryServer) snapshot() facadeDeliveryData {
|
||||
state.mu.Lock()
|
||||
defer state.mu.Unlock()
|
||||
result := state.data
|
||||
|
||||
result.assets = make(map[string][]byte, len(state.data.assets))
|
||||
for key, value := range state.data.assets {
|
||||
result.assets[key] = append([]byte(nil), value...)
|
||||
}
|
||||
|
||||
result.pages = make(map[string]bool, len(state.data.pages))
|
||||
for key, value := range state.data.pages {
|
||||
result.pages[key] = value
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
type facadeDeliveryData struct {
|
||||
t *testing.T
|
||||
commit string
|
||||
tag string
|
||||
version string
|
||||
noteBody string
|
||||
createdBody string
|
||||
pages map[string]bool
|
||||
requests int
|
||||
writes int
|
||||
omitReleaseID bool
|
||||
assets map[string][]byte
|
||||
url string
|
||||
}
|
||||
|
||||
func newFacadeDeliveryServer(t *testing.T, repository string) (*httptest.Server, *facadeDeliveryServer) {
|
||||
t.Helper()
|
||||
state := &facadeDeliveryServer{t: t, commit: buildGit(t, repository, "rev-parse", "HEAD"), assets: make(map[string][]byte)}
|
||||
server := httptest.NewServer(http.HandlerFunc(state.serveHTTP))
|
||||
state.url = server.URL
|
||||
state := &facadeDeliveryServer{data: facadeDeliveryData{t: t, commit: buildGit(t, repository, "rev-parse", "HEAD"), tag: "v1.2.3", version: "v1.2.3", noteBody: "# Fixture v1.2.3\n\nDelivery fixture.\n", pages: make(map[string]bool), assets: make(map[string][]byte)}}
|
||||
server := httptest.NewUnstartedServer(http.HandlerFunc(state.serveHTTP))
|
||||
state.data.url = "http://" + server.Listener.Addr().String()
|
||||
server.Start()
|
||||
return server, state
|
||||
}
|
||||
|
||||
func (state *facadeDeliveryServer) serveHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
state.mu.Lock()
|
||||
defer state.mu.Unlock()
|
||||
data := &state.data
|
||||
if strings.HasPrefix(r.URL.Path, "/api/") {
|
||||
state.requests++
|
||||
data.requests++
|
||||
if r.Method != http.MethodGet {
|
||||
data.writes++
|
||||
}
|
||||
if r.Header.Get("Authorization") != "token fixture-token" {
|
||||
state.t.Errorf("authorization = %q", r.Header.Get("Authorization"))
|
||||
data.t.Errorf("authorization = %q", r.Header.Get("Authorization"))
|
||||
}
|
||||
}
|
||||
switch r.URL.Path {
|
||||
case "/api/v1/repos/owner/example/tags/v1.2.3":
|
||||
_, _ = fmt.Fprintf(w, `{"name":"v1.2.3","commit":{"sha":%q}}`, state.commit)
|
||||
case "/api/v1/repos/owner/example/releases/tags/v1.2.3":
|
||||
if !state.page {
|
||||
switch r.URL.EscapedPath() {
|
||||
case "/api/v1/repos/owner/example", "/api/v1/repositories/1":
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"id": 1, "name": "example", "full_name": "owner/example",
|
||||
"owner": map[string]string{"login": "owner"},
|
||||
})
|
||||
case "/api/v1/repos/owner/example/tags/" + url.PathEscape(data.tag):
|
||||
_, _ = fmt.Fprintf(w, `{"name":%q,"commit":{"sha":%q}}`, data.tag, data.commit)
|
||||
case "/api/v1/repos/owner/example/releases/tags/" + url.PathEscape(data.tag):
|
||||
if !data.pages[data.tag] {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
@@ -512,20 +921,21 @@ func (state *facadeDeliveryServer) serveHTTP(w http.ResponseWriter, r *http.Requ
|
||||
Body string `json:"body"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
|
||||
state.t.Errorf("decode release payload: %v", err)
|
||||
data.t.Errorf("decode release payload: %v", err)
|
||||
http.Error(w, "invalid payload", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if payload.Tag != "v1.2.3" || payload.Target != state.commit || payload.Name != "Fixture v1.2.3" {
|
||||
state.t.Errorf("release payload = %#v", payload)
|
||||
if payload.Tag != data.tag || payload.Target != data.commit || payload.Name != "Fixture "+data.version {
|
||||
data.t.Errorf("release payload = %#v", payload)
|
||||
}
|
||||
state.page = true
|
||||
data.createdBody = payload.Body
|
||||
data.pages[data.tag] = true
|
||||
state.writeRelease(w)
|
||||
case "/api/v1/repos/owner/example/releases/10/assets":
|
||||
if r.Method == http.MethodGet {
|
||||
list := make([]map[string]any, 0, len(state.assets))
|
||||
for name, content := range state.assets {
|
||||
list = append(list, map[string]any{"id": len(list) + 1, "name": name, "size": len(content), "browser_download_url": state.url + "/files/" + name})
|
||||
list := make([]map[string]any, 0, len(data.assets))
|
||||
for name, content := range data.assets {
|
||||
list = append(list, map[string]any{"id": len(list) + 1, "name": name, "size": len(content), "browser_download_url": data.url + "/files/" + name})
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(list)
|
||||
return
|
||||
@@ -533,22 +943,22 @@ func (state *facadeDeliveryServer) serveHTTP(w http.ResponseWriter, r *http.Requ
|
||||
name := r.URL.Query().Get("name")
|
||||
file, _, err := r.FormFile("attachment")
|
||||
if err != nil {
|
||||
state.t.Errorf("read upload %q: %v", name, err)
|
||||
data.t.Errorf("read upload %q: %v", name, err)
|
||||
http.Error(w, "invalid multipart upload", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
content, err := io.ReadAll(file)
|
||||
_ = file.Close()
|
||||
if err != nil {
|
||||
state.t.Errorf("read upload %q: %v", name, err)
|
||||
data.t.Errorf("read upload %q: %v", name, err)
|
||||
}
|
||||
state.assets[name] = content
|
||||
data.assets[name] = content
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"id": len(state.assets), "name": name, "size": len(content)})
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"id": len(data.assets), "name": name, "size": len(content)})
|
||||
default:
|
||||
if strings.HasPrefix(r.URL.Path, "/files/") {
|
||||
name := strings.TrimPrefix(r.URL.Path, "/files/")
|
||||
content, ok := state.assets[name]
|
||||
content, ok := data.assets[name]
|
||||
if !ok {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
@@ -556,18 +966,24 @@ func (state *facadeDeliveryServer) serveHTTP(w http.ResponseWriter, r *http.Requ
|
||||
_, _ = w.Write(content)
|
||||
return
|
||||
}
|
||||
state.t.Errorf("unexpected delivery request %s %s", r.Method, r.URL)
|
||||
data.t.Errorf("unexpected delivery request %s %s", r.Method, r.URL)
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func (state *facadeDeliveryServer) writeRelease(w http.ResponseWriter) {
|
||||
// The request handler holds state.mu.
|
||||
data := &state.data
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"id": 10, "html_url": state.url + "/releases/10", "tag_name": "v1.2.3",
|
||||
"target_commitish": state.commit, "name": "Fixture v1.2.3",
|
||||
"body": "# Fixture v1.2.3\n\nDelivery fixture.\n", "draft": false, "prerelease": false,
|
||||
})
|
||||
release := map[string]any{
|
||||
"html_url": data.url + "/releases/10", "tag_name": data.tag,
|
||||
"target_commitish": data.commit, "name": "Fixture " + data.version,
|
||||
"body": data.noteBody, "draft": false, "prerelease": false,
|
||||
}
|
||||
if !data.omitReleaseID {
|
||||
release["id"] = 10
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(release)
|
||||
}
|
||||
|
||||
func mapKeys(values map[string][]byte) []string {
|
||||
|
||||
113
docs/adr/0005-module-release-scope.md
Normal file
113
docs/adr/0005-module-release-scope.md
Normal file
@@ -0,0 +1,113 @@
|
||||
# ADR 0005: Select a Go module as the unit of release
|
||||
|
||||
## Status
|
||||
|
||||
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
|
||||
|
||||
2026-10-09
|
||||
|
||||
## Context
|
||||
|
||||
A Go repository can contain independently versioned modules. CommandKit plans
|
||||
to release its core and optional integrations from one repository. Each module
|
||||
needs its own validation, release note, semantic version, and Git tag.
|
||||
|
||||
ReleaseKit currently couples the semantic version to the Git tag and uses the
|
||||
repository directory for Go validation and release-note discovery. Supporting
|
||||
independent modules through consumer-owned publication code would duplicate
|
||||
ReleaseKit's responsibilities.
|
||||
|
||||
[ADR 0002](0002-routine-releases.md) prioritizes routine releases with little
|
||||
application-owned code or recurring decision-making.
|
||||
[ADR 0003](0003-declarative-validation.md) establishes shared declarative
|
||||
validation. Module selection should give those checks a coherent release scope.
|
||||
|
||||
## Decision
|
||||
|
||||
Each check or publication invocation selects one Go module within a Git
|
||||
repository. Omitted module selection means the repository-root module. The
|
||||
public Go API and CLI/profile interface express the same selection. Consumers
|
||||
can use small per-module profiles through a shared launcher.
|
||||
|
||||
ReleaseKit distinguishes the repository directory, selected module directory,
|
||||
semantic version, and complete Git tag. It derives the tag using Go's module
|
||||
tag conventions and the selected module's committed declaration. Derivation
|
||||
accounts for major-version directories. For example, a module in
|
||||
`integrations/ckconfig` at `v0.2.0` uses the tag
|
||||
`integrations/ckconfig/v0.2.0`. A module declared with a `/v2` suffix and stored
|
||||
in `integrations/ckconfig/v2` uses `integrations/ckconfig/v2.0.0` for `v2.0.0`.
|
||||
|
||||
The semantic version identifies the module release. The complete tag identifies
|
||||
its source in the shared repository and governs uniqueness, tag creation,
|
||||
publication, source links, and recovery. Candidate evidence, publication
|
||||
results, and CLI output identify the selected module and both version and tag,
|
||||
alongside the existing commit and publication evidence. Failure outcomes retain
|
||||
the resolved identity for recovery.
|
||||
|
||||
Release notes belong at `<module-directory>/docs/releases/<version>.md` and
|
||||
identify the product and semantic version in their title. ReleaseKit reads the
|
||||
selected note from the captured candidate. Root-module releases retain the
|
||||
existing note layout and unprefixed tags. Modules can publish equal semantic
|
||||
versions through their distinct notes and tags.
|
||||
|
||||
Mandatory and optional release validation share the selected module's scope.
|
||||
Go tests, selected vet, and package compilation execute in that module with
|
||||
the existing offline environment. File checks inspect the module's committed
|
||||
contents and relevant release materials. Independently released nested modules
|
||||
are excluded from their parent's validation scope. Selecting the root module
|
||||
follows the same rule.
|
||||
|
||||
A check may inspect referenced material outside the selected module when needed
|
||||
to validate an in-scope item. Resolving a Markdown link to shared repository
|
||||
documentation does not add that destination's documents to the validation input
|
||||
set. The checkout remains the boundary for checks of outside-checkout links.
|
||||
Shared release materials follow established conventions and documented
|
||||
consumer requirements.
|
||||
|
||||
Product-specific checks receive the selected module context and repository
|
||||
context for deliberate composition checks. ReleaseKit applies module selection
|
||||
consistently across its shared checks, avoiding separate scope settings for
|
||||
each check.
|
||||
|
||||
Publication guards cover the shared repository: cleanliness, branch, candidate
|
||||
commit, authoritative endpoint, and the complete selected tag. The standard
|
||||
suite runs once for the selected candidate and module. Successful source-tag
|
||||
publication remains the completion point, with existing failure and uncertain
|
||||
publication outcomes preserved. Consumers prepare released sibling dependencies
|
||||
and choose their publication order.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
- Consumer-owned module publication gives each application responsibility for
|
||||
tag conventions, validation, and recovery, duplicating shared mechanics.
|
||||
- Module-local Go execution with repository-wide optional validation lets
|
||||
unrelated modules block a selected release and gives checks inconsistent
|
||||
scopes.
|
||||
- Independent scope settings for each check require consumers to coordinate
|
||||
multiple declarations of the same release boundary.
|
||||
- Coordinated multi-module publication adds release-set and dependency-ordering
|
||||
responsibilities beyond the demonstrated need for individual releases.
|
||||
|
||||
## Consequences
|
||||
|
||||
Consumers describe the module and product being released while ReleaseKit owns
|
||||
the common procedure. Existing single-module repositories retain their default
|
||||
behavior. Root modules containing independently released nested modules gain
|
||||
module-scoped validation; release notes and migration guidance must explain
|
||||
that change.
|
||||
|
||||
The shared candidate and publication paths must carry module scope and separate
|
||||
version and tag identity throughout validation, diagnostics, and recovery.
|
||||
Verification must cover root defaults, nested-module failures, equal versions
|
||||
across modules, major-version directories, validation boundaries, and exact-tag
|
||||
publication outcomes.
|
||||
|
||||
GoDoc and consumer documentation will own exact API and scope contracts.
|
||||
Configuration and CLI documentation will own profile fields, commands, and
|
||||
output. Implementation planning will define interactions with artifact builds
|
||||
and hosted delivery. ReleaseKit's maintainer release policy continues to govern
|
||||
ReleaseKit's own releases; consumers document their adopted module conventions.
|
||||
92
docs/adr/0006-neutral-forge-delivery-and-preflight.md
Normal file
92
docs/adr/0006-neutral-forge-delivery-and-preflight.md
Normal file
@@ -0,0 +1,92 @@
|
||||
# ADR 0006: Separate delivery policy from forge protocols
|
||||
|
||||
## Status
|
||||
|
||||
Accepted.
|
||||
|
||||
## Date
|
||||
|
||||
2026-11-01
|
||||
|
||||
## Context
|
||||
|
||||
ReleaseKit's delivery workflow handles release-page matching and creation
|
||||
recovery, remote asset comparison, upload ordering, retries, and partial or
|
||||
uncertain outcomes. Those policies are useful independently of the Gitea HTTP
|
||||
protocol, but the earlier client-owned flow coupled them to Gitea types and
|
||||
operations.
|
||||
|
||||
Delivery also benefits from checking credentials and repository access before
|
||||
managed builds, dependency preparation, or complete artifact hashing. Gitea
|
||||
exposes authenticated repository reads, but its `permissions.push` metadata and
|
||||
basic token evidence do not establish permission to write release pages or
|
||||
assets. A read-only check must represent that evidence limit without claiming
|
||||
that later writes are guaranteed.
|
||||
|
||||
The root `releasekit` facade owns public types, while implementation packages
|
||||
remain internal. The CLI owns credential loading and process exit status.
|
||||
Source publication has separate Git authentication and completion semantics.
|
||||
|
||||
## Decision
|
||||
|
||||
The root facade owns `Forge`, `DeliveryDestination`, explicit backend selection,
|
||||
and public preflight errors. `internal/forge` defines the internal backend
|
||||
contract and neutral release, asset, failure, and write-evidence values.
|
||||
`internal/delivery` owns shared delivery coordination and policy.
|
||||
`internal/gitea` owns Gitea destination rules, authenticated preflight requests,
|
||||
protocol operations, codecs, handles, streaming, and conversion to neutral
|
||||
failures. `internal/artifact` owns local asset declarations and verification.
|
||||
Shared delivery, forge, and artifact packages have no production dependency
|
||||
path to the Gitea adapter.
|
||||
|
||||
Delivery selection is explicit. The supported value is `gitea`; neither a URL
|
||||
nor an omitted selection chooses a backend. There is no compatibility alias for
|
||||
the removed public Gitea destination type.
|
||||
|
||||
The facade exposes `PreflightDelivery` and runs the same read-only backend
|
||||
preflight automatically during `Deliver`. Gitea preflight authenticates through
|
||||
repository-scoped reads and classifies missing or rejected credentials,
|
||||
inaccessible destinations, and unavailable verification. It does not issue a
|
||||
test release or upload, require extra user/admin token scopes, or treat
|
||||
unexposed write permission evidence as a failure. Success confirms only the
|
||||
authentication, repository access, and permission evidence available through
|
||||
that check; ordinary writes remain authoritative. Preflight failures preserve
|
||||
their causes and leave delivery `not_attempted`.
|
||||
|
||||
The CLI requires `delivery.forge` only for `deliver` and `ci-deliver`. Binary
|
||||
CI delivery performs a standalone preflight after checkout/profile/token
|
||||
preparation and before application dependency downloads, then `Deliver`
|
||||
rechecks. Page-only CI relies on automatic delivery preflight. `check`,
|
||||
`build`, and source `publish` do not require delivery configuration or hosted
|
||||
credentials. Local artifact verification follows preflight but completes before
|
||||
hosted writes.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
- Keep delivery policy in the Gitea client. This retains protocol coupling and
|
||||
makes shared recovery behavior harder to exercise without the adapter.
|
||||
- Select Gitea from the URL or preserve the old Gitea-specific facade type.
|
||||
This hides backend selection and keeps the public contract tied to one
|
||||
adapter.
|
||||
- Probe permissions with a test release or asset, or require additional user
|
||||
scopes. Those operations can create remote state or demand evidence unrelated
|
||||
to release delivery; the repository read does not expose the required
|
||||
release-write proof.
|
||||
- Skip preflight and let the first write discover credential problems. That
|
||||
delays a known failure until after costly local work and provides no
|
||||
standalone check for callers preparing their own delivery.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Shared policy can be tested with controlled backends, while local HTTP tests
|
||||
focus on Gitea protocol behavior and assembled integration flows.
|
||||
- Consumers must replace the removed Gitea-specific destination type, set
|
||||
`ForgeGitea` in API calls, and add `"forge": "gitea"` to delivery profiles.
|
||||
- Delivery may make additional authenticated read requests before local
|
||||
artifact hashing. It still verifies full local content before any hosted
|
||||
write.
|
||||
- Credential, access, and availability failures have distinct public error
|
||||
kinds and CLI classifications. Successful preflight does not certify future
|
||||
release or asset writes.
|
||||
- Source publication retains native Git authentication and is not gated by
|
||||
hosted delivery preflight.
|
||||
102
docs/adr/0007-general-source-release-identity.md
Normal file
102
docs/adr/0007-general-source-release-identity.md
Normal 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.
|
||||
114
docs/adr/0008-woodpecker-rehearsal-lifecycle.md
Normal file
114
docs/adr/0008-woodpecker-rehearsal-lifecycle.md
Normal 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.
|
||||
277
docs/cli.md
277
docs/cli.md
@@ -1,9 +1,11 @@
|
||||
# Command line
|
||||
|
||||
ReleaseKit currently provides six commands. The exit statuses below belong
|
||||
The exit statuses below belong
|
||||
to the native executable. `go run` examples are convenient for source execution,
|
||||
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.
|
||||
For the `go run` examples, [select the Go host target](consumers/adoption.md#select-the-go-host-target)
|
||||
before running from a shell set to cross-compile.
|
||||
|
||||
Print the executable version:
|
||||
|
||||
@@ -20,28 +22,42 @@ Check a local candidate:
|
||||
go run ./cmd/releasekit check [--repo DIR] [--config FILE] VERSION
|
||||
```
|
||||
|
||||
`VERSION` must use stable `vMAJOR.MINOR.PATCH` syntax. Options must precede the
|
||||
version. The repository defaults to the current directory, and the profile
|
||||
defaults to `<repository>/releasekit.json`. A successful command prints the
|
||||
captured local commit and version. It checks the committed release note and
|
||||
local Git state, runs the standard offline Go test suite (with `-race` when
|
||||
`VERSION` must match the profile's selected identifier format. Options must precede the
|
||||
version. The repository argument defaults to the current directory. ReleaseKit
|
||||
resolves its containing Git checkout root before selecting the module or profile;
|
||||
the profile defaults to `<repository-root>/releasekit.json`. A successful command prints the
|
||||
captured module, version, full tag, and commit. It checks the committed release note and
|
||||
local Git state, runs the standard offline Go test suite when Go is selected (with `-race` when
|
||||
`validation.go.race` is true), and runs a separate `go vet -mod=readonly ./...`
|
||||
pass after successful tests when `validation.go.full_vet` is true. It then runs
|
||||
selected package compilation and committed Go formatting, followed by
|
||||
configured additional checks in profile order. It does not inspect remote
|
||||
availability or publish a tag.
|
||||
|
||||
For legacy profiles, `module_dir` selects a repository-relative physical
|
||||
module directory; omission selects the root module. Explicit profiles select
|
||||
source and Go capabilities as described in the [configuration reference](config.md).
|
||||
Additional check commands run with
|
||||
the selected source as their working directory and receive
|
||||
`RELEASEKIT_VERSION`, `RELEASEKIT_CANDIDATE`, `RELEASEKIT_REPOSITORY_DIR`,
|
||||
`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
|
||||
the ReleaseKit process environment. Module values are empty for source-only
|
||||
selections.
|
||||
|
||||
When `validation.go.compile_targets` is selected, `check` compiles all packages
|
||||
for each configured `GOOS/GOARCH` pair after tests and full vet, using static
|
||||
mode with cgo disabled. This check produces no artifacts and does not execute
|
||||
target binaries. Compilation failures use the `package-compile` identity and
|
||||
show the selected target. When `validation.go_format` is true, `check` examines
|
||||
regular committed Go files with the Go formatter after tests, vet, and package
|
||||
compilation. It includes vendor and nested-module source, ignores the worktree
|
||||
compilation. It uses the selected module and shared-file inputs, including
|
||||
vendored source, and ignores the worktree
|
||||
and symlink blobs, and reports unformatted paths as `go-format` without
|
||||
modifying files. When `validation.module_distribution.workspace_files` is true,
|
||||
`check` reports committed `go.work` and `go.work.sum` blobs, including nested
|
||||
and symlink entries, as `workspace-files`. This inspection is independent of
|
||||
`check` reports committed `go.work` and `go.work.sum` blobs in those inputs,
|
||||
including symlink entries, as `workspace-files`. Automatic file inputs stop at
|
||||
independent nested modules. This inspection is independent of
|
||||
`GOWORK` and ignores uncommitted files. Any artifact build selected by the
|
||||
separate `build` setting runs after shared validation and configured checks.
|
||||
When `validation.markdown` is a non-null object, `check` checks committed local
|
||||
@@ -63,23 +79,24 @@ Unsupported argument sequences print usage to standard error.
|
||||
Publish a source tag:
|
||||
|
||||
```sh
|
||||
go run ./cmd/releasekit publish [--repo DIR] [--config FILE] VERSION
|
||||
go run ./cmd/releasekit publish [--repo DIR] [--config FILE] [--expected-module DIR] [--expected-source DIR] [--record-dir DIR] VERSION
|
||||
```
|
||||
|
||||
`publish` reads the same product, remote, validation, and additional-check
|
||||
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,
|
||||
test-time vet is disabled and `go vet -mod=readonly ./...` runs after successful
|
||||
tests. Selected package compilation and committed Go formatting follow. The
|
||||
selected file checks then run in order: workspace files, local replacements,
|
||||
file size, and Markdown. Configured checks run afterward in profile order. It
|
||||
then creates an annotated local tag
|
||||
and pushes only its exact tag object. It prints the confirmed version,
|
||||
candidate commit, and tag object
|
||||
and pushes only its exact full tag object. It prints the confirmed identifier,
|
||||
full tag, candidate commit, and tag object
|
||||
on success. Validation
|
||||
progress and failed publication state, including the captured publication
|
||||
endpoint for recovery, are written to standard error. A signal
|
||||
endpoint for recovery, are written to standard error. HTTP(S) endpoint
|
||||
userinfo is masked in diagnostics. A signal
|
||||
cancels the active operation; if it arrives during a push, the library's
|
||||
bounded reconciliation determines whether the exact tag was accepted.
|
||||
Shared validation failures use the same check and finding presentation as
|
||||
@@ -95,9 +112,11 @@ go.work.sum paths as `workspace-files`. Formatting failures are reported as
|
||||
`go-format` with affected paths and preserve parser or source-inspection causes.
|
||||
|
||||
When `validation.module_distribution.local_replacements` is true, the command
|
||||
parses committed `go.mod` declarations, including nested and vendor modules,
|
||||
after workspace-file inspection. Filesystem replacements use the
|
||||
`local-replacements` identity and include the declaration path, source line,
|
||||
parses committed `go.mod` declarations in the selected module after
|
||||
workspace-file inspection. Vendored contents remain in scope, while
|
||||
automatic inputs stop at independently released nested modules. Explicit shared
|
||||
files join the file-check inputs without expanding Go scope. Filesystem replacements use
|
||||
the `local-replacements` identity and include the declaration path, source line,
|
||||
and target; versioned replacements are permitted. Committed module symlinks are
|
||||
resolved within the candidate, regardless of `GOWORK`.
|
||||
When `validation.file_size` is a non-null object, the command checks each
|
||||
@@ -112,19 +131,90 @@ It reports outside-checkout links to standard error unless boundary enforcement
|
||||
is selected; submodule contents remain out of scope. Markdown failures stop
|
||||
publication before product checks or tag creation.
|
||||
|
||||
`--expected-module DIR` and `--expected-source DIR` optionally check a
|
||||
launcher's selected physical directory against the profile's source selection
|
||||
before candidate work. Paths are normalized relative to the repository; the
|
||||
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
|
||||
nonempty value must exactly match the effective push URL resolved by Git;
|
||||
mismatches fail during preflight before Go validation or tag creation. Git URL
|
||||
rewrites are resolved first, and the push URL is used when fetch and push URLs
|
||||
differ. `check` ignores this field.
|
||||
|
||||
The command automatically saves available publication evidence in the repository's
|
||||
private attempt store. Use `--record-dir DIR` to select another directory; a
|
||||
relative override is resolved from the source repository root. Standard error
|
||||
reports the absolute saved record path or a recording warning separately from
|
||||
the publication result. Recording failure does not change publication status.
|
||||
When publication fails and a record was saved, the CLI also prints a copyable
|
||||
`reconcile --record` command for that exact record. The command selects the
|
||||
consumer module's registered Go tool when available. API-only consumers receive
|
||||
a Go-tool invocation with durable private module files; see
|
||||
[recovery storage](consumers/publish.md#retain-and-reconcile-publication-evidence).
|
||||
Consumers without a module-selected ReleaseKit dependency use the running
|
||||
executable's absolute path. A module-preparation failure reports a warning and
|
||||
uses a persistent native executable when available. Recognized temporary Go-build
|
||||
executables provide no native fallback after their driver exits. Command
|
||||
preparation has its own bounded context after a failed publication, so publication
|
||||
cancellation permits preparing the later invocation. Each entry point preserves
|
||||
the recovery exit status. Run a generated Go-tool handoff in a POSIX shell.
|
||||
When it runs, it sets `GOOS` and `GOARCH` to the selected Go toolchain's
|
||||
`GOHOSTOS` and `GOHOSTARCH`.
|
||||
If the selected entry point becomes unavailable, use another supported ReleaseKit
|
||||
CLI with the saved record.
|
||||
|
||||
The command returns status 0 for confirmed publication, 1 for a known
|
||||
publication failure or conflict, 2 for usage, profile, or invalid-version
|
||||
errors, and 3 when the push outcome remains unknown. Unknown status must be
|
||||
resolved against the authoritative remote before retrying. The
|
||||
resolved with the explicit-record recovery operation below before retrying. The
|
||||
[maintainer procedure](release.md) selects the repository profile and gives
|
||||
the source-release workflow.
|
||||
|
||||
## Recover a saved publication attempt or discover local attempts
|
||||
|
||||
```sh
|
||||
releasekit reconcile --record FILE [--json]
|
||||
releasekit publication-attempts [--repo DIR] [--record-dir DIR] [--json]
|
||||
```
|
||||
|
||||
`reconcile` requires one explicitly selected record and reads a relative `FILE`
|
||||
from the invoking directory. It observes the endpoint and tag stored in that
|
||||
record; it does not load a profile, inspect the current candidate or local tag,
|
||||
run checks, or change repository state. `publication-attempts` lists records in
|
||||
the selected store without querying remotes or choosing an attempt. An omitted
|
||||
`--repo` means the current directory. Its relative `--record-dir` is resolved
|
||||
from the selected repository root; an absolute directory can be listed outside
|
||||
a checkout. The selected directory must already exist. Discovery reports usable
|
||||
records and per-record diagnostics together when some records cannot be read.
|
||||
|
||||
By default, both operations print human-readable output. `--json` writes one
|
||||
structured document to standard output after valid arguments, including for
|
||||
reconciliation and discovery failures. Recovery does not run candidate checks
|
||||
or make hosted delivery requests. It reads the record's captured endpoint, while
|
||||
using current supported transport settings for its recorded remote name.
|
||||
|
||||
| Recovery command result | Status |
|
||||
| --- | --- |
|
||||
| Reconciliation observes the intended publication | 0 |
|
||||
| Reconciliation observes absence or conflict | 1 |
|
||||
| Reconciliation cannot read or decode the selected record, or has an invocation error | 2 |
|
||||
| Reconciliation remains unknown, including missing evidence or cancellation | 3 |
|
||||
| Discovery completes without record diagnostics, including an existing empty store | 0 |
|
||||
| Discovery is incomplete or fails, including cancellation | 1 |
|
||||
| Discovery argument or usage error | 2 |
|
||||
| Either command cannot write its JSON output | 1 |
|
||||
|
||||
A JSON write failure reports a local output diagnostic on standard error. This
|
||||
status describes reporting failure and leaves the observed publication state
|
||||
unchanged.
|
||||
|
||||
The CLI JSON schema and safe evidence fields are documented in the
|
||||
[publication record format](integrations/publication-records.md). Recovery
|
||||
guidance for storage, older evidence, and retry decisions is in the
|
||||
[maintainer procedure](release.md#resolve-publication-failures).
|
||||
|
||||
Build selected application targets:
|
||||
|
||||
```sh
|
||||
@@ -135,28 +225,45 @@ go run ./cmd/releasekit build [--repo DIR] [--config FILE] [--output DIR] VERSIO
|
||||
targets with the requested version injected, checks the native `version`
|
||||
invocation, and writes binaries plus the private `.releasekit-build.json`
|
||||
receipt into `dist` by default. `--output` selects a different directory;
|
||||
relative paths are resolved from the repository. Selected artifact filenames
|
||||
are regenerated while unrelated files are preserved. A complete nonempty build
|
||||
relative paths are resolved from the selected module directory. Selected
|
||||
artifact filenames are regenerated while unrelated files are preserved. A complete nonempty build
|
||||
writes a receipt only after compilation and smoke checking succeed. On partial
|
||||
failure, standard error lists completed outputs and prior receipts in that
|
||||
output directory are invalidated; no new receipt is written. An
|
||||
empty target list returns the source commit without building or writing a
|
||||
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
|
||||
2 for usage, profile, or invalid-version errors. It builds the current source
|
||||
tree and does not perform candidate validation or remote publication. `check`
|
||||
and `publish` run the same configured build after their one candidate
|
||||
validation, using temporary output outside the worktree.
|
||||
|
||||
Deliver a tagged source release to Gitea:
|
||||
Inspect working release configuration without creating a release:
|
||||
|
||||
```sh
|
||||
releasekit validate [--repo DIR] [--config FILE] [--context local|ci] [--operation NAME ...] [--offline] [--assets DIR] [--json]
|
||||
```
|
||||
|
||||
Validation defaults to local credentials and read-only remote access. Operation
|
||||
flags narrow the selected capabilities; `--offline` omits remote observations.
|
||||
See the [readiness guide](consumers/readiness.md) for scope, evidence, and exit
|
||||
statuses.
|
||||
|
||||
Deliver a tagged source release:
|
||||
|
||||
```sh
|
||||
go run ./cmd/releasekit deliver [--repo DIR] [--config FILE] [--assets DIR] VERSION
|
||||
```
|
||||
|
||||
`deliver` requires a `delivery` profile object and its configured token
|
||||
environment variable, which defaults to `RELEASEKIT_GITEA_TOKEN`. It verifies
|
||||
`deliver` requires a `delivery` profile object with an explicit
|
||||
`"forge": "gitea"` selection and a token loaded from its configured local
|
||||
credential file. The destination URL does not select a forge. Selection
|
||||
errors are reported before token access or delivery work. Credential selection
|
||||
and errors are defined in the [configuration reference](config.md). It verifies
|
||||
the local tag, clean tagged checkout, hosted tag, and committed release note,
|
||||
then creates or finds the release page and reports delivery state separately
|
||||
from source publication. Historical lightweight tags and detached checkouts
|
||||
@@ -169,20 +276,34 @@ the tagged source into temporary storage, removes it when the operation ends,
|
||||
and uploads its binaries and complete `SHA256SUMS`. When `--assets DIR` is
|
||||
supplied, that directory must contain the private `.releasekit-build.json`
|
||||
receipt and matching unchanged artifacts; this keeps the caller's original
|
||||
bytes available for retries. Profiles without targets use page-only delivery
|
||||
bytes available for retries. Relative `--assets` paths use the selected module
|
||||
directory, matching `build --output`; absolute paths retain their supplied base.
|
||||
Profiles without targets use page-only delivery
|
||||
and need no receipt, binary build, or manifest. `deliver` never runs candidate
|
||||
checks or publishes a tag.
|
||||
|
||||
After cheap local checks, delivery performs authenticated, read-only repository
|
||||
preflight before a managed build or full artifact size and digest verification.
|
||||
An unavailable preflight leaves delivery `not_attempted`; after preflight
|
||||
succeeds, local artifact verification still finishes before any hosted write.
|
||||
|
||||
Use one `deliver` invocation for the normal workflow. To build without delivery
|
||||
credentials, or to retain build output across retries, run `build --output DIR`
|
||||
first and then run `deliver --assets DIR` with the token available. The ordinary
|
||||
`deliver` command does not download application dependencies or change the
|
||||
checkout.
|
||||
|
||||
The command returns 0 for complete delivery, 1 for a known failure, conflict,
|
||||
or partial delivery, 2 for usage, profile, or missing-credential errors, and 3
|
||||
when a remote write remains uncertain. The result lists matching, uploaded,
|
||||
pending, conflicting, and uncertain assets as disjoint current observations;
|
||||
The command returns 0 for complete delivery without a local error, 1 for an
|
||||
unavailable preflight, a known delivery failure, conflict, partial delivery, or
|
||||
local cleanup failure after hosted completion, and 2 for usage,
|
||||
profile, forge-selection, local credential-loading, or classified preflight
|
||||
configuration/access errors. A remote write whose outcome remains uncertain
|
||||
returns 3, including when cancellation prevents reconciliation. Cancellation
|
||||
without an unresolved write returns 1, including during preflight or
|
||||
preparation. Later authorization failures follow
|
||||
the delivery outcome: known failure returns 1; an unresolved write returns 3.
|
||||
The result lists matching, uploaded, pending, conflicting, and uncertain assets
|
||||
as disjoint current observations;
|
||||
early failures may leave some declared assets unreported. On failure, the CLI
|
||||
prints state-based recovery guidance. Fix local or preflight failures before
|
||||
retrying; fix the reported cause before retrying partial delivery; resolve an
|
||||
@@ -197,36 +318,90 @@ known missing assets are added. See the
|
||||
Prepare a tagged CI checkout and deliver it:
|
||||
|
||||
```sh
|
||||
releasekit ci-deliver [--repo DIR] [--config FILE] [--remote NAME] --commit OID VERSION
|
||||
releasekit ci-deliver [--repo DIR] [--config FILE] [--remote NAME] [--prepared] [--expected-module DIR] [--expected-source DIR] --commit OID TAG
|
||||
```
|
||||
|
||||
`ci-deliver` fetches `VERSION` from the selected Git remote (default `origin`),
|
||||
requires the tag's peeled commit to match the required full `--commit` object
|
||||
ID, and checks out that commit detached. It then loads the profile from the
|
||||
prepared checkout, validates delivery settings and the configured token, and
|
||||
downloads application dependencies only when the profile selects build targets.
|
||||
Binary profiles are built and delivered through the same facade path as
|
||||
`deliver`; source-only profiles skip dependency downloads and binary builds.
|
||||
`TAG` is the complete Git tag name, including any source path prefix. Its last
|
||||
component is validated against the profile's selected version format after
|
||||
checkout. By default, `ci-deliver` fetches the exact `TAG` from
|
||||
the selected Git remote (default `origin`), requires its peeled commit to match
|
||||
the required full `--commit` object ID, checks out that commit detached, then
|
||||
verifies the tag, HEAD, and clean worktree. With `--prepared`, it performs those
|
||||
checks read-only against the existing checkout and does not fetch or check out.
|
||||
Preparation diagnostics mask userinfo in HTTP(S) remote URLs.
|
||||
In either mode, it loads the profile from the verified source. The optional
|
||||
`--expected-module` and `--expected-source` checks verify the launcher's
|
||||
selected directory against the profile. The command compares the selected
|
||||
source's derived release tag with the full event tag before forge access or
|
||||
dependency preparation, then validates explicit forge selection and resolves
|
||||
the configured CI environment token. For binary profiles, it performs a read-only repository
|
||||
preflight before downloading application
|
||||
dependencies; delivery performs a fresh check after dependency preparation.
|
||||
Source-only profiles rely on delivery's automatic preflight and skip dependency
|
||||
downloads and binary builds.
|
||||
`--config` follows the existing profile path rules: relative paths are resolved
|
||||
from `--repo`, and absolute paths are used as-is. This command explicitly
|
||||
prepares and changes the selected checkout. Ordinary `deliver` continues to
|
||||
operate on already prepared source without fetching, checking out, or
|
||||
downloading dependencies.
|
||||
from `--repo`, and absolute paths are used as-is. The default mode prepares and
|
||||
changes the selected checkout; `--prepared` reuses a verified checkout.
|
||||
Ordinary `deliver` continues to operate on already prepared source without
|
||||
fetching, checking out, or downloading dependencies.
|
||||
|
||||
In Woodpecker, pass `CI_WORKSPACE`, `CI_COMMIT_SHA`, and `CI_COMMIT_TAG` as the
|
||||
repository, expected commit, and version arguments. The CLI does not read
|
||||
In Woodpecker, pass `CI_WORKSPACE`, the source commit resolved from
|
||||
`CI_COMMIT_SHA`, and `CI_COMMIT_TAG` as the repository, expected commit, and full
|
||||
tag arguments. The event ID may identify an annotated tag object; see the
|
||||
[delivery guide](consumers/delivery.md#woodpecker-tag-workflows) for resolution
|
||||
and workflow preparation. The CLI does not read
|
||||
provider-specific environment variable names. Checkout and dependency
|
||||
preparation failures return status 1; usage, profile, credential, and invalid
|
||||
version errors return status 2. Final delivery uses the same statuses as
|
||||
`deliver`: 0 for complete, 1 for known failure, conflict, or partial delivery,
|
||||
and 3 for uncertain remote state.
|
||||
preparation failures, unavailable preflight, and cancellation during those
|
||||
steps return status 1. Usage, profile, forge-selection, local credential-loading,
|
||||
classified preflight configuration/access, and invalid-version errors return
|
||||
status 2. Final delivery uses the same statuses as `deliver`: 0 for complete,
|
||||
1 for known failure, conflict, or partial delivery, and 3 for uncertain remote
|
||||
state, including when cancellation prevents reconciliation.
|
||||
|
||||
The maintained module-based tag workflow verifies and checks out the event tag
|
||||
before resolving the consumer module. It builds the ReleaseKit version already
|
||||
selected by that tagged `go.mod`, using temporary alternate module files outside
|
||||
the source checkout. This tool bootstrap is separate from `ci-deliver`'s
|
||||
application dependency preparation for binary profiles. ReleaseKit's own
|
||||
source workflow self-bootstraps `./cmd/releasekit`; consumers without a declared
|
||||
before resolving the consumer module. It invokes the ReleaseKit tool by its full
|
||||
package path for the version already selected by that tagged `go.mod`, using
|
||||
temporary alternate module files outside the source checkout. This tool bootstrap
|
||||
is separate from `ci-deliver`'s application dependency preparation for binary
|
||||
profiles. ReleaseKit's own source workflow self-bootstraps `./cmd/releasekit`;
|
||||
consumers without a declared
|
||||
ReleaseKit module dependency can use the separately installed-tool command.
|
||||
See the [delivery guide](consumers/delivery.md#woodpecker-tag-workflows) for
|
||||
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.
|
||||
|
||||
184
docs/config.md
184
docs/config.md
@@ -1,20 +1,58 @@
|
||||
# Configuration
|
||||
|
||||
ReleaseKit reads a JSON profile from `<repository>/releasekit.json` by default.
|
||||
The repository directory defaults to the current directory. A relative profile
|
||||
path is resolved from that repository directory; an absolute path is used as-is.
|
||||
ReleaseKit reads a JSON profile from `<repository-root>/releasekit.json` by default.
|
||||
The repository argument defaults to the current directory; the CLI resolves its
|
||||
containing Git checkout root. A relative profile path is resolved from that root;
|
||||
an absolute path is used as-is.
|
||||
|
||||
The current profile fields are:
|
||||
|
||||
| Field | Required | Behavior |
|
||||
| --- | --- | --- |
|
||||
| `product` | Yes | Product name used by release operations. |
|
||||
| `module_dir` | No | Repository-relative physical 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`. |
|
||||
| `expected_push_url` | No | Exact effective push URL required by `publish`; ignored by local `check`. |
|
||||
| `checks` | No | Ordered additional child commands, each with an argument vector and optional environment map. |
|
||||
| `validation` | No | Optional shared checks selected by ReleaseKit. |
|
||||
| `build` | No | Optional main package, binary name, and selected `GOOS/GOARCH` target strings. |
|
||||
| `delivery` | No | Optional Gitea `base_url`, `owner`, `repository`, and `token_env` settings for tagged-source delivery. |
|
||||
| `delivery` | No | Optional selected forge and destination fields for tagged-source delivery. |
|
||||
| `readiness` | No | Optional explicit files to check during readiness. |
|
||||
| `rehearsal` | No | Diagnostic selector and Woodpecker observation settings, required for a rehearsal. |
|
||||
|
||||
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
|
||||
physical directory and declared path are distinct: a declared `/v2` module can
|
||||
live either at `integrations/core` or `integrations/core/v2`, while both use the
|
||||
same full release tag. Root-only profiles can omit `module_dir` and do not need
|
||||
a module map.
|
||||
|
||||
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
|
||||
executable. Arguments are passed directly to the child process; ReleaseKit does
|
||||
@@ -28,6 +66,19 @@ target requires the package and binary name; each target is written as one
|
||||
`GOOS/GOARCH` pair. An omitted or empty target list means no binary work.
|
||||
|
||||
The optional `validation` object selects shared checks implemented by ReleaseKit.
|
||||
`validation.shared_files` is a committed file list resolved from the repository
|
||||
root. Omission or `null` uses `COPYRIGHT`, `LICENSE`, and
|
||||
`docs/oss/attribution.md` when present for enabled file checks; `[]` selects no
|
||||
shared files. An explicit list replaces those defaults. Each explicit file must
|
||||
exist in the candidate, even when no file checks are enabled. Paths are literal,
|
||||
repository-relative files with no glob semantics and may select a file outside
|
||||
the chosen module. ReleaseKit deduplicates them with module inputs by path. This
|
||||
field does not enable any checks or expand Go test, vet, or package-compilation
|
||||
scope. For Go selections, automatic file inputs stop at independent
|
||||
nested-module boundaries; source-only selections treat nested `go.mod` files
|
||||
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
|
||||
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
|
||||
@@ -39,8 +90,11 @@ This source compatibility check does not name or produce binaries, run a target
|
||||
executable, or create an artifact manifest. Omitted or empty `compile_targets`
|
||||
selects no package-compilation pass. When `full_vet` is omitted or false, the
|
||||
test command keeps its existing vet behavior. These settings are independent.
|
||||
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
|
||||
used to build ReleaseKit. It includes vendor and nested-module source, ignores
|
||||
used to build ReleaseKit. It uses the selected file inputs, including vendor and
|
||||
explicit shared files, and ignores
|
||||
symlink blobs and the worktree, and reports every selected path whose bytes
|
||||
change under formatting. It never writes formatted bytes back. Omitted or false
|
||||
disables the check. It runs after tests, selected full vet, and selected package
|
||||
@@ -69,12 +123,14 @@ Anchors keep Unicode letters and numbers, underscores, and hyphens; spaces
|
||||
become hyphens, and repeated headings receive numeric suffixes.
|
||||
|
||||
When `validation.module_distribution.workspace_files` is true, it reports
|
||||
committed blob entries whose basename is `go.work` or `go.work.sum`, including
|
||||
nested paths and symlinks. It checks candidate distribution contents regardless
|
||||
committed `go.work` and `go.work.sum` files in the selected module inputs,
|
||||
including nested paths and symlinks. It checks the captured candidate regardless
|
||||
of `GOWORK`; it does not select or change the workspace used by Go commands,
|
||||
and it does not alter existing vendor behavior. Omitted or false disables it.
|
||||
When `validation.module_distribution.local_replacements` is true, it parses all
|
||||
committed `go.mod` declarations, including vendor and nested modules, and reports
|
||||
and vendored contents remain in scope. Omitted or false disables it. When
|
||||
`validation.module_distribution.local_replacements` is true, it parses the
|
||||
selected module's committed `go.mod` declarations. Vendored contents remain in
|
||||
scope; an explicit shared-file selection can include an individual declaration
|
||||
from another module. It reports
|
||||
`replace` directives whose replacement has no version. These filesystem
|
||||
replacements include relative and absolute paths; versioned module replacements
|
||||
are permitted. Committed `go.mod` symlinks are resolved within the candidate,
|
||||
@@ -109,8 +165,8 @@ check; `{}` enables it with a default of 1,000,000 bytes. A missing or null
|
||||
`limit_bytes` selects that default, zero is a valid limit, and negative limits
|
||||
are invalid.
|
||||
|
||||
`validation.file_size.exclusions` contains literal repository-relative file or
|
||||
directory paths. Directory exclusions include committed descendants, using path
|
||||
`validation.file_size.exclusions` contains literal paths relative to the
|
||||
selected module. Directory exclusions include committed descendants, using path
|
||||
boundaries (`assets` does not exclude `assets-old`). Ordinary relative path
|
||||
normalization applies; metacharacters are literal and unmatched paths have no
|
||||
effect. The check measures regular and symlink blobs, including small binaries;
|
||||
@@ -118,12 +174,70 @@ symlink size is the committed link text. Gitlinks have no measured size. Only
|
||||
the captured candidate is checked, one offending file is reported at a time,
|
||||
and historical or aggregate repository size is not measured.
|
||||
|
||||
The `delivery` object contains `base_url`, `owner`, `repository`, and optional
|
||||
`token_env`. Its values are required when running `deliver`, but credentials are
|
||||
not required for `check`, `publish`, or `build`. `token_env` names the
|
||||
environment variable containing the Gitea token; it defaults to
|
||||
`RELEASEKIT_GITEA_TOKEN`. The CLI reads this variable only for `deliver` and
|
||||
passes its value explicitly to the library operation.
|
||||
`validation.forbidden_files` is an optional list of literal repository-relative
|
||||
file paths that must be absent from the captured commit. It runs after the Go
|
||||
checks and before other file checks, using the `forbidden-files` identity and
|
||||
reporting selected committed paths. Omission, `null`, or `[]` disables it.
|
||||
Paths use slash separators and ordinary relative normalization and must stay
|
||||
within the repository. They are checked against the whole captured repository,
|
||||
independently of the selected module and `shared_files`. The check reads path
|
||||
metadata only; it does not read token contents, follow symlink targets, require
|
||||
local files to exist, or inspect Git history. Existing clean-index/worktree
|
||||
requirements still apply to candidate operations. An ignore rule alone does
|
||||
not remove a previously committed file from the candidate.
|
||||
|
||||
`readiness.required_files` optionally lists literal repository-root-relative or
|
||||
absolute files whose readability `validate` checks. These are explicit local
|
||||
inputs, not inferred SSH authentication requirements; see the
|
||||
[readiness guide](consumers/readiness.md).
|
||||
|
||||
A `rehearsal` object can select a dispatch `selector` (default `root`) and a
|
||||
`woodpecker` object with `base_url`, numeric `repository_id`, exact `workflow`
|
||||
and `step` names, and a local `token_file`. These settings are required only
|
||||
for rehearsal operations. Relative token paths resolve from the checkout root;
|
||||
the file is read separately from the forge credential and its token is never
|
||||
stored in the attempt record. See the
|
||||
[rehearsal record format](integrations/rehearsal-records.md) for captured
|
||||
identity and recovery evidence.
|
||||
|
||||
The `delivery` object contains `forge`, `base_url`, `owner`, `repository`, and
|
||||
context-specific `credentials`. A delivery request must set `forge` to
|
||||
`"gitea"`; a missing or unsupported selection is an error for delivery. These
|
||||
requirements do not apply to `check`, `publish`, or `build`.
|
||||
|
||||
`delivery.credentials.local.token_file` selects the local delivery token file.
|
||||
Relative paths resolve from the Git repository root; absolute paths are used as
|
||||
supplied. `delivery.credentials.ci.token_environment_variable` selects the job
|
||||
environment variable, defaulting to `RELEASEKIT_DELIVERY_TOKEN` when the `ci`
|
||||
object is present without a name. `deliver` requires local credentials and
|
||||
`ci-deliver` requires CI credentials. Neither context falls back to the other.
|
||||
Missing, unreadable, or blank selected credentials fail with status 2. Token
|
||||
contents are trimmed. The obsolete `delivery.token_file` and `delivery.token_env`
|
||||
fields must be moved to their corresponding context-specific locations.
|
||||
|
||||
Ignore the local token file in Git. Optionally select the same path in
|
||||
`validation.forbidden_files` to reject candidates that include it; an ignore
|
||||
rule does not remove an already tracked file.
|
||||
|
||||
After resolving the token, delivery performs an authenticated, read-only
|
||||
repository access check. Invalid destination settings, missing or rejected
|
||||
credentials, known insufficient permissions, and inaccessible destinations are
|
||||
configuration/credential failures. An unavailable service or canceled check is
|
||||
an operational failure.
|
||||
See the [CLI contract](cli.md) for exact exit statuses. Successful preflight
|
||||
confirms authentication and repository access and accounts for any exposed
|
||||
delivery-permission deficiency. It does not guarantee later release or asset
|
||||
writes. Local artifact size and digest checks follow preflight and still finish
|
||||
before hosted writes.
|
||||
|
||||
`validate` loads only credentials for selected operations. `test` and recovery
|
||||
commands load their selected local credentials; `check`, `publish`, and `build`
|
||||
do not read a delivery token. The CLI passes the
|
||||
resolved value explicitly to the library operation. `ci-deliver` checks the
|
||||
destination before downloading application dependencies for a binary build;
|
||||
the later delivery performs a fresh check. Page-only CI relies on delivery's
|
||||
automatic check. Selecting a token file and selecting the optional
|
||||
forbidden-file validator are independent settings.
|
||||
|
||||
`expected_push_url`, when nonempty, is compared exactly with Git's resolved
|
||||
effective push URL during `publish`, before candidate validation. It applies
|
||||
@@ -132,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
|
||||
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
|
||||
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
|
||||
run native `go vet -mod=readonly ./...` after successful tests. They then run
|
||||
`go build -mod=readonly -o <os.DevNull> ./...` in static mode for each
|
||||
`validation.go.compile_targets` entry, in profile order. Compile failures use
|
||||
the `package-compile` identity and include the selected target. When selected,
|
||||
`validation.go_format` checks regular committed Go source with go/format after
|
||||
package compilation; unformatted paths use the `go-format` identity. When
|
||||
the `package-compile` identity and include the selected target.
|
||||
|
||||
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
|
||||
also reports committed go.work and go.work.sum blobs after Go formatting, using
|
||||
the workspace-files identity. Uncommitted workspace files are not inspected.
|
||||
@@ -173,14 +288,23 @@ retained for retries or when build and delivery credentials need separate
|
||||
invocations. Ordinary `deliver` does not download application dependencies or
|
||||
change the checkout.
|
||||
|
||||
`ci-deliver` uses the same profile after preparing the selected tag in the
|
||||
checkout. It checks out the tag only after its peeled commit matches the
|
||||
provider-supplied commit ID, then loads the profile and validates delivery
|
||||
settings and credentials. It runs `go mod download` only when the profile has
|
||||
selected build targets; source-only delivery does not need application
|
||||
dependencies. This preparation may access the network and may update
|
||||
`go.sum`. The command takes CI values as arguments, so profile settings remain
|
||||
independent of Woodpecker environment variable names. See the
|
||||
`ci-deliver` takes a full Git `TAG`. A production tag ends in the identifier
|
||||
accepted by the profile's selected version format, and the complete value is
|
||||
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
|
||||
the tag, HEAD, and clean worktree. With `--prepared`, it performs the same
|
||||
checks against an existing checkout without fetching or checking out. It then
|
||||
loads the profile from that source and validates delivery settings and
|
||||
credentials. An optional `--expected-module` checks a launcher's module
|
||||
selection against the profile. It runs `go mod download` only when the profile
|
||||
has selected build targets; source-only delivery does not need application
|
||||
dependencies. Default preparation may access the network and may update
|
||||
`go.sum`. For binary tagged delivery, prepare and commit that module's sums
|
||||
before tagging so dependency preparation leaves the tagged checkout clean. The
|
||||
command takes CI values as arguments, so profile settings remain independent of
|
||||
Woodpecker environment variable names. See the
|
||||
[CLI contract](cli.md) for the invocation and exit statuses.
|
||||
|
||||
This application dependency preparation is separate from bootstrapping the
|
||||
|
||||
@@ -1,34 +1,83 @@
|
||||
# Adopt ReleaseKit
|
||||
|
||||
Use a versioned Go tool dependency when ReleaseKit provides the repository's
|
||||
release commands. This records the CLI in `go.mod` and keeps it available to
|
||||
maintainers without adding imports to application or library code.
|
||||
Use a versioned Go tool dependency when a Go module provides the repository's
|
||||
release commands. Source-only repositories can instead use the installed-tool
|
||||
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
|
||||
|
||||
From the consumer module's root, select the ReleaseKit version to adopt:
|
||||
|
||||
```sh
|
||||
go get -tool gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit@v0.2.0
|
||||
: "${RELEASEKIT_TOOL_VERSION:?Set the released ReleaseKit version to adopt}"
|
||||
go get -tool "go.maximumdirect.net/releasekit/cmd/releasekit@${RELEASEKIT_TOOL_VERSION}"
|
||||
go mod tidy
|
||||
go tool releasekit version
|
||||
```
|
||||
|
||||
Replace `v0.2.0` with the intended release. Go records the executable package in
|
||||
Select a release that implements the API, profile, and workflow you are adopting.
|
||||
The [v0.11.0 release note](../releases/v0.11.0.md) covers
|
||||
the new source selections, credential contexts, and rehearsal workflow.
|
||||
The vanity module path starts with v0.5.0. Versions through v0.4.2 declare the
|
||||
original module path and use their corresponding historical instructions.
|
||||
The module-release interface requires a release containing that feature;
|
||||
pre-feature versions through v0.3.0 use their corresponding historical interface.
|
||||
Go records the executable package in
|
||||
a `tool` directive and the module version in a `require` directive. The tool
|
||||
declaration retains the dependency through `go mod tidy`. Commit the resulting
|
||||
`go.mod` and `go.sum` changes. To upgrade, repeat the command with the chosen
|
||||
version and review the module changes.
|
||||
|
||||
Go tool dependencies require Go 1.24 or later, together with a toolchain that
|
||||
satisfies the selected ReleaseKit version and its dependencies. Tools share the
|
||||
consumer's module graph: their requirements participate in dependency version
|
||||
selection and can raise the consumer module's Go minimum. See the
|
||||
The Go tool dependency feature requires Go 1.24 or later. The current ReleaseKit
|
||||
module declares a Go 1.27.0 minimum, so use Go 1.27.0 or later for the current
|
||||
source. Tool dependencies share the consumer's module graph: their requirements
|
||||
participate in dependency version selection and can raise the consumer module's
|
||||
Go minimum. See the
|
||||
[Go tool dependency reference](https://go.dev/ref/mod#go-mod-file-tool).
|
||||
|
||||
Run `go tool releasekit` from within the consumer module to use its selected
|
||||
version. Follow the [CLI contract](../cli.md) for commands and exit statuses,
|
||||
and the [configuration reference](../config.md) for the release profile.
|
||||
### Select the Go host target
|
||||
|
||||
Invoke the ReleaseKit tool by its full package path from within the consumer
|
||||
module to use its selected version. Go builds and caches the executable and
|
||||
preserves its exit status. The full path distinguishes tools with the same
|
||||
short name. A launcher can forward commands directly:
|
||||
|
||||
```sh
|
||||
#!/bin/sh
|
||||
releasekit_host_os=$(go env GOHOSTOS) || exit $?
|
||||
releasekit_host_arch=$(go env GOHOSTARCH) || exit $?
|
||||
export GOOS="$releasekit_host_os" GOARCH="$releasekit_host_arch"
|
||||
exec go tool go.maximumdirect.net/releasekit/cmd/releasekit "$@"
|
||||
```
|
||||
|
||||
Save this launcher as `releasekit` and run `sh ./releasekit version` from the
|
||||
selected module to verify registration. It preserves the consumer's workspace
|
||||
and toolchain settings while selecting the host for the executable.
|
||||
For a launcher callable from other directories, first change to its consumer
|
||||
module directory. Follow the [CLI contract](../cli.md) for commands and exit
|
||||
statuses.
|
||||
|
||||
Configured product checks inherit the launcher's host `GOOS` and `GOARCH`.
|
||||
If a check needs an application target, set it in that check's `env` map or
|
||||
command. The [configuration reference](../config.md) describes
|
||||
check environments and the separate target selection for built-in builds.
|
||||
|
||||
For consumers using vendoring, register the CLI before running `go mod vendor`
|
||||
so the vendor tree includes its dependencies. `go tool` follows Go's normal
|
||||
vendor selection.
|
||||
|
||||
## Go API consumers
|
||||
|
||||
@@ -37,17 +86,64 @@ Consumers importing the root `releasekit` API or
|
||||
required imports and select the module version:
|
||||
|
||||
```sh
|
||||
go get gitea.maximumdirect.net/eric/ReleaseKit@v0.2.0
|
||||
: "${RELEASEKIT_TOOL_VERSION:?Set the released ReleaseKit version to adopt}"
|
||||
go get "go.maximumdirect.net/releasekit@${RELEASEKIT_TOOL_VERSION}"
|
||||
go mod tidy
|
||||
```
|
||||
|
||||
API consumers can also register the CLI with `go get -tool` as above. Both uses
|
||||
share the module-selected ReleaseKit version.
|
||||
|
||||
## Migrating from the original module path
|
||||
|
||||
Starting with v0.5.0, ReleaseKit's module is `go.maximumdirect.net/releasekit`.
|
||||
Earlier releases declare `gitea.maximumdirect.net/eric/ReleaseKit`. The migration
|
||||
is a direct cutover with the existing facade roles and command behavior.
|
||||
|
||||
For API consumers, update imports of the root facade and `buildinfo` to
|
||||
`go.maximumdirect.net/releasekit` and
|
||||
`go.maximumdirect.net/releasekit/buildinfo`, including generated code and tests.
|
||||
Select v0.5.0 or a later compatible release using the package-dependency command
|
||||
above. Packages imported through the old and new paths have distinct Go
|
||||
identities; coordinate updates in packages that exchange ReleaseKit facade
|
||||
types. Builders and applications using `buildinfo` should adopt the new path
|
||||
together so version injection addresses the runtime implementation they use.
|
||||
|
||||
For CLI tool consumers, remove the old tool declaration before registering the
|
||||
new CLI package with the tool-dependency command above:
|
||||
|
||||
```sh
|
||||
go mod edit -droptool=gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit
|
||||
```
|
||||
|
||||
Update copied release launchers and Woodpecker workflows so their
|
||||
`releasekit_module` value is `go.maximumdirect.net/releasekit`. Use the maintained
|
||||
examples matching the selected tool version. Run `go mod tidy` after updating
|
||||
imports and tool declarations, review any old-path dependencies retained
|
||||
transitively, and commit the resulting module files with the workflow changes.
|
||||
|
||||
Existing consumer tags retain their recorded module files, tool selection, and
|
||||
matching workflows for retries. Apply these migration steps to new consumer
|
||||
revisions. Source repository and hosted release URLs use
|
||||
`https://forge.maximumdirect.net/base-layer/releasekit`; the vanity path is the
|
||||
Go module identity.
|
||||
|
||||
## CI adoption
|
||||
|
||||
The maintained [consumer tag-delivery workflow](delivery.md#woodpecker-tag-workflows)
|
||||
supports both tool and ordinary package dependencies. It builds ReleaseKit from
|
||||
the tagged consumer's module selection, so the committed module files also
|
||||
govern CI delivery and retries. Registering the CLI as a tool is sufficient for
|
||||
supports both tool and ordinary package dependencies. It runs the ReleaseKit
|
||||
tool by its full package path with temporary metadata derived from the tagged
|
||||
module, so the committed module files also govern CI delivery and retries.
|
||||
Registering the CLI as a tool is sufficient for
|
||||
consumers that use ReleaseKit only for maintainer commands.
|
||||
|
||||
Update copied launchers and workflow templates separately when upgrading the
|
||||
module dependency. ReleaseKit tests the generic bootstrap; consumer wiring tests
|
||||
can focus on selectors and profile mapping. Profiles continue to select
|
||||
application build targets.
|
||||
Upgrade the module-selected tool and workflow together. For a tag created before
|
||||
that upgrade, retry with the workflow matching the tool recorded at that tag.
|
||||
Keep its immutable module files and tag intact. See the
|
||||
[delivery guide](delivery.md#woodpecker-tag-workflows) for tagged-source bootstrap
|
||||
and the [example's source verification](../../examples/multi-module/README.md#local-source-verification)
|
||||
for testing an unreleased checkout in a disposable consumer repository.
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
releasekit "gitea.maximumdirect.net/eric/ReleaseKit"
|
||||
releasekit "go.maximumdirect.net/releasekit"
|
||||
)
|
||||
|
||||
func build(ctx context.Context) error {
|
||||
@@ -36,19 +36,30 @@ func build(ctx context.Context) error {
|
||||
}
|
||||
```
|
||||
|
||||
`Build` records the repository's current `HEAD`, injects the selected stable
|
||||
version into `buildinfo.Version`, and returns the compiler identity, normalized
|
||||
targets, artifact paths, filenames, and SHA-256 digests. Names follow
|
||||
`Build` resolves the selected source and module's working-tree declaration
|
||||
once, records the repository's current `HEAD`, injects the selected identifier
|
||||
into `buildinfo.Version`, and returns repository/source and module identity, the
|
||||
derived tag, compiler identity, normalized targets, artifact paths, filenames,
|
||||
and SHA-256 digests. It does not require a release note, unused tag, clean
|
||||
`main`, or publication. Names follow
|
||||
`<binary>-<version>-<goos>-<goarch>`; Windows targets add `.exe`. A repeated
|
||||
target pair is built once, at its first position. Local builds may use modified
|
||||
source. `SourceVerified` is true only after a complete build observes clean
|
||||
source and the same HEAD before and after compilation; binary delivery requires
|
||||
that fact. This observation is not a source snapshot or attestation guarantee.
|
||||
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.
|
||||
|
||||
The default output directory is `<repository>/dist`; a relative `OutputDir` is
|
||||
resolved from the repository. Selected artifact filenames are regenerated. Other files in the output
|
||||
directory are left in place. A failed later build or native version check returns the binaries already
|
||||
generated in `BuildResult.Artifacts`.
|
||||
Go commands run from `ModuleDir`, so `MainPackage` is interpreted within that
|
||||
module. The default output directory is `<module>/dist`; a relative `OutputDir`
|
||||
is resolved from the module, while an absolute path is used as supplied.
|
||||
Selected artifact filenames are regenerated. Other files in the output
|
||||
directory are left in place. A failed later build or native version check
|
||||
returns completed, hashed binaries in `BuildResult.Artifacts`. If hashing a
|
||||
newly built file fails, the error identifies its path and earlier completed
|
||||
artifacts remain in the result.
|
||||
|
||||
Builds use the available compatible Go toolchain selected locally; ReleaseKit
|
||||
does not download a different toolchain automatically. It disables workspace
|
||||
@@ -72,10 +83,14 @@ The [`build` command](../cli.md) reads the same build specification from the
|
||||
profile and writes a private receipt alongside its artifacts. `check` and
|
||||
`publish` run selected builds after the standard suite and any additional
|
||||
checks using temporary output outside the worktree. Candidate checks do not
|
||||
write a receipt or leave build files in the repository.
|
||||
write a receipt or leave build files in the repository. Disposable native
|
||||
version-check output also remains outside the whole repository when `TMPDIR`
|
||||
points inside the source tree.
|
||||
|
||||
For delivery from a tagged checkout, `deliver` builds selected tagged-source
|
||||
targets into temporary storage by default. Use `--assets DIR` to deliver a
|
||||
separate build output; ReleaseKit requires its receipt and verifies the source,
|
||||
build settings, and artifact hashes before the first Gitea write. See the
|
||||
separate build output; ReleaseKit requires the current module-bound receipt and
|
||||
checks its source identity and normalized build settings. It verifies artifact
|
||||
bytes and sizes during delivery before the first Gitea write. Older receipts
|
||||
must be regenerated with the updated `build` command. See the
|
||||
[delivery consumer guide](delivery.md) for page-only delivery and retry states.
|
||||
|
||||
@@ -21,14 +21,40 @@ if err != nil {
|
||||
fmt.Println(result.Version, result.Commit)
|
||||
```
|
||||
|
||||
The repository must have a clean index and worktree on `main`, and the selected
|
||||
version must be stable `vMAJOR.MINOR.PATCH`. The committed
|
||||
`docs/releases/<version>.md` note must have a first Markdown H1 containing the
|
||||
product name and exact version as complete title elements. No local tag with
|
||||
that version may already exist.
|
||||
Set `ReleaseRequest.ModuleDir` to select a nested module using a
|
||||
repository-relative physical directory; omission or `.` selects the root
|
||||
module. ReleaseKit reads that module's committed `go.mod` and returns its
|
||||
physical `ModuleDir`, declared `ModulePath`, semantic `Version`, and complete
|
||||
`Tag` in the candidate and result. A physical `/v2` directory is removed from
|
||||
the tag prefix only when the declared module path also ends in `/v2`. For
|
||||
example, both `integrations/core/v2` and `integrations/core` can declare
|
||||
`example.com/project/integrations/core/v2` and use the tag
|
||||
`integrations/core/v2.1.0`. The release note lives under the physical module at
|
||||
`<module>/docs/releases/<version>.md`.
|
||||
|
||||
ReleaseKit runs one `go test -mod=readonly -count=1 ./...` suite with the
|
||||
available compatible local Go toolchain. Set `Validation.Go.Race` to run that
|
||||
The repository must have a clean index and worktree on `main`, and the selected
|
||||
version must 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
|
||||
product name and exact version as complete title elements. No local tag with
|
||||
the derived complete tag may already exist. Different modules may use the same
|
||||
semantic version with distinct notes and tags.
|
||||
|
||||
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.
|
||||
Set `Validation.Go.Race` to run that
|
||||
suite with `-race`; set `Validation.Go.FullVet` to run
|
||||
`go vet -mod=readonly ./...` after successful tests, with test-time vet disabled
|
||||
for the suite. Set `Validation.Go.CompileTargets` to compile packages for each
|
||||
@@ -37,28 +63,32 @@ complete target pair after tests and vet. Package compilation uses
|
||||
failures use the `package-compile` identity and include the target. The zero
|
||||
values retain the ordinary native test behavior and select no compilation.
|
||||
Set `Validation.GoFormat` to check committed regular Go files using the Go
|
||||
formatter built into ReleaseKit. It includes vendor and nested-module source,
|
||||
formatter built into ReleaseKit. It uses the selected file inputs, including
|
||||
vendor and explicit shared files, and
|
||||
ignores symlink blobs and worktree changes, and reports unformatted paths as
|
||||
`go-format` without rewriting files. Its zero value disables the check; it runs
|
||||
after tests, selected vet, and package compilation, before `AdditionalChecks`.
|
||||
|
||||
Set `Validation.ModuleDistribution.WorkspaceFiles` to reject committed
|
||||
`go.work` and `go.work.sum` blobs, including nested and symlink entries. It
|
||||
examines the captured candidate even when `GOWORK=off`, ignores uncommitted
|
||||
files, and does not change Go test workspace selection or vendor behavior. The
|
||||
zero value disables the check; failures use `workspace-files`.
|
||||
`go.work` and `go.work.sum` files in the selected module inputs, including
|
||||
symlink entries. It examines the captured candidate even when
|
||||
`GOWORK=off`, ignores uncommitted files, and does not change Go test workspace
|
||||
selection; vendored contents remain in scope. The zero value disables the check;
|
||||
failures use `workspace-files`.
|
||||
Set `Validation.ModuleDistribution.LocalReplacements` independently to parse
|
||||
committed `go.mod` declarations throughout the candidate, including nested and
|
||||
vendor modules. It reports filesystem `replace` directives with their source
|
||||
path, line, and target as `local-replacements`; versioned replacements are
|
||||
the selected module's committed `go.mod` declarations. Vendored contents remain
|
||||
in scope; automatic inputs stop at independently released nested modules. An
|
||||
explicit shared-file selection can include another module's declaration. It reports
|
||||
filesystem `replace` directives with their source path, line, and target as
|
||||
`local-replacements`; versioned replacements are
|
||||
permitted. Committed module symlinks are resolved within the candidate. Parse
|
||||
and inspection errors retain their causes, and the rule applies even when
|
||||
`GOWORK=off`. Its zero value disables the check.
|
||||
Set `Validation.FileSize` to check each committed blob against a byte limit.
|
||||
Nil disables the check; an empty object enables the default of 1,000,000
|
||||
decimal bytes. `LimitBytes` is strict greater-than, accepts zero, and rejects
|
||||
negative values. `Exclusions` contains literal repository-relative files or
|
||||
directories; excluded directories include descendants. Symlink blobs are
|
||||
negative values. `Exclusions` contains literal files or directories relative to
|
||||
the selected module; excluded directories include descendants. Symlink blobs are
|
||||
measured by link-text bytes, and gitlinks are omitted. The check applies to the
|
||||
captured candidate and reports one oversized file with its measurement as
|
||||
`file-size`; it does not measure historical or aggregate size.
|
||||
@@ -76,7 +106,32 @@ standard suite, selected vet/format/distribution checks, or Markdown navigation
|
||||
checks in `AdditionalChecks` or profile `checks`. Keep release-note rules and
|
||||
consumer-specific assertions—such as tests of maintained examples—in those
|
||||
product-owned checks.
|
||||
ReleaseKit calls `AdditionalChecks` once after shared validation when supplied.
|
||||
The `Candidate` supplies `RepositoryDir` and `SourceDir`, plus optional module
|
||||
fields, the selected `Version`, and full `Tag`; use its source directory for
|
||||
source-local product checks. ReleaseKit calls `AdditionalChecks` once after
|
||||
shared validation when supplied.
|
||||
|
||||
For local token files, set `Validation.ForbiddenFiles` to the repository-relative
|
||||
paths that should stay out of the committed candidate, such as
|
||||
`[]string{".releasekit/gitea-token"}`. Failures use `forbidden-files` and carry the
|
||||
selected committed paths in `ValidationError.Findings`. This selection is
|
||||
independent of module and shared-file inputs; see [GoDoc](../../check.go) for
|
||||
the API contract and the [configuration reference](../config.md) for CLI use.
|
||||
|
||||
`ValidationSpec.SharedFiles` adds committed, repository-relative files to
|
||||
ReleaseKit's optional file checks without enabling any checks. A nil slice
|
||||
selects the optional defaults `COPYRIGHT`, `LICENSE`, and
|
||||
`docs/oss/attribution.md`, when present; a non-nil empty slice selects none.
|
||||
Explicit files replace those defaults, must exist even when file checks are
|
||||
disabled, and may be in another module. Combined inputs are deduplicated by
|
||||
repository-relative path.
|
||||
|
||||
Automatic file inputs stop at independent nested-module boundaries, including
|
||||
fixture modules. Vendored files remain included. Shared selection affects file
|
||||
inputs only; Go validation retains the selected module's scope. Reference reads
|
||||
can inspect destinations elsewhere in the captured repository without adding
|
||||
those destinations to the input set.
|
||||
|
||||
It does not download a different toolchain automatically. If race prerequisites
|
||||
are unavailable, the `go-test` check fails rather than being skipped; a selected
|
||||
full-vet failure is reported as `go-vet`. The suite uses the Go host target,
|
||||
@@ -97,10 +152,11 @@ commands from `releasekit.json`.
|
||||
## Publishing the source tag
|
||||
|
||||
`releasekit.Publish` uses the same request and validation order: the standard
|
||||
suite runs first, followed by `AdditionalChecks` when supplied. It then performs
|
||||
authoritative remote checks, annotated-tag creation, and an exact tag push. The
|
||||
suite runs first, followed by `AdditionalChecks` when supplied. It surrounds
|
||||
validation with authoritative remote guards before annotated-tag creation and
|
||||
an exact tag push. The
|
||||
selected remote must publish `main` at the captured commit and must not already
|
||||
contain the selected version tag. A successful result includes the endpoint and
|
||||
contain the selected complete tag. A successful result includes the endpoint and
|
||||
tag object ID. Publication states distinguish an unattempted push, a tag that
|
||||
was created locally but not pushed, a successful push, a guard conflict, and an
|
||||
unresolved push error. See the [publication guide](publish.md) for the complete
|
||||
|
||||
@@ -1,12 +1,25 @@
|
||||
# Deliver a tagged source release
|
||||
|
||||
Use `releasekit.Deliver` or the `deliver` command after a source tag exists.
|
||||
Select the delivery backend explicitly in the profile or
|
||||
`DeliveryDestination`; the destination URL does not infer a backend.
|
||||
Delivery status is separate from source publication: a delivery problem does
|
||||
not move or remove the tag, and a retry can use the same immutable version.
|
||||
The operation accepts historical lightweight and annotated tags, including a
|
||||
detached checkout, when the checked-out `HEAD` identifies the selected tag
|
||||
commit. It does not require the old remote `main` to match.
|
||||
|
||||
Delivery resolves the selected source and release note from the captured commit;
|
||||
it reads a module declaration only when Go is enabled. `Version` follows the
|
||||
selected identifier format, and the full tag follows the selected publication
|
||||
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
|
||||
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
|
||||
|
||||
Use `PrepareTaggedCheckout` when a disposable CI checkout must be verified
|
||||
@@ -20,7 +33,7 @@ or hosted content.
|
||||
```go
|
||||
err := releasekit.PrepareTaggedCheckout(ctx, releasekit.TaggedCheckoutRequest{
|
||||
RepositoryDir: repositoryDir,
|
||||
Version: version,
|
||||
Tag: "integrations/example/v1.2.3",
|
||||
ExpectedCommit: ciCommit,
|
||||
})
|
||||
if err != nil {
|
||||
@@ -28,16 +41,31 @@ if err != nil {
|
||||
}
|
||||
```
|
||||
|
||||
For binary profiles, call `PrepareBuildDependencies(ctx, repositoryDir)` after
|
||||
checkout preparation and before delivery. It runs `go mod download` with
|
||||
workspace discovery disabled and the available compatible local Go toolchain.
|
||||
The operation may use the network and updates the Go module cache while
|
||||
preserving the caller's proxy, private-module, credential, and cache settings.
|
||||
If checksums are missing, Go may update `go.sum`; see the
|
||||
For binary profiles, call `PrepareBuildDependencies` with a
|
||||
`DependencyPreparationRequest` selecting the repository and module after
|
||||
checkout preparation and before delivery. It runs `go mod download` in that
|
||||
module with workspace discovery disabled and the available compatible local Go
|
||||
toolchain. Inside a Git checkout, `RepositoryDir` can name a subdirectory;
|
||||
`ModuleDir` is interpreted relative to the containing checkout root, and an
|
||||
empty selection chooses that root. Previously, a supplied checkout subdirectory
|
||||
acted as the selection base. Outside a checkout, the supplied directory remains
|
||||
the base for `ModuleDir`.
|
||||
Preparation overrides an alternate module file selected by `GOFLAGS`, while
|
||||
retaining other effective Go settings. The operation may use the network and
|
||||
updates the Go module cache while preserving the caller's proxy, private-module,
|
||||
credential, and cache settings.
|
||||
If checksums are missing, Go may update `go.sum`. For binary CI delivery, prepare
|
||||
and commit the selected module's `go.sum` before tagging: delivery verifies the
|
||||
tagged source remains clean after dependency preparation. See the
|
||||
[Go Modules Reference](https://go.dev/ref/mod#go-mod-download). Cancellation
|
||||
and command errors are returned. Page-only profiles do not need dependency
|
||||
preparation.
|
||||
|
||||
Set `TaggedCheckoutRequest.VerifyOnly` when a bootstrap step already fetched and
|
||||
detached the event tag. This mode checks the exact tag, expected commit, `HEAD`,
|
||||
and clean worktree without fetching or changing the checkout. Both modes require
|
||||
the full `Tag` and expected commit.
|
||||
|
||||
## Command line
|
||||
|
||||
Add a Gitea destination to the profile:
|
||||
@@ -46,10 +74,14 @@ Add a Gitea destination to the profile:
|
||||
{
|
||||
"product": "Example",
|
||||
"delivery": {
|
||||
"forge": "gitea",
|
||||
"base_url": "https://gitea.example",
|
||||
"owner": "example",
|
||||
"repository": "example",
|
||||
"token_env": "RELEASEKIT_GITEA_TOKEN"
|
||||
"credentials": {
|
||||
"local": {"token_file": ".releasekit/gitea-token"},
|
||||
"ci": {"token_environment_variable": "RELEASEKIT_GITEA_TOKEN"}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -58,32 +90,68 @@ Fetch and check out the immutable tag, then deliver it:
|
||||
|
||||
```sh
|
||||
git checkout --detach v1.2.3
|
||||
RELEASEKIT_GITEA_TOKEN="$GITEA_TOKEN" releasekit deliver v1.2.3
|
||||
releasekit deliver v1.2.3
|
||||
```
|
||||
|
||||
The CLI reads the named token variable only for `deliver`; its default name is
|
||||
`RELEASEKIT_GITEA_TOKEN`. It verifies the local checkout and hosted tag before
|
||||
The CLI resolves the local token file for `deliver` and the CI environment
|
||||
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
|
||||
hosted body. A retry accepts an identical page and matching attachments, adds
|
||||
only missing assets, and reports conflicts without replacing content.
|
||||
|
||||
For local delivery, save a Gitea personal access token in a git-ignored file such
|
||||
as `.releasekit/gitea-token` and configure:
|
||||
|
||||
```json
|
||||
{
|
||||
"product": "Example",
|
||||
"validation": {
|
||||
"forbidden_files": [".releasekit/gitea-token"]
|
||||
},
|
||||
"delivery": {
|
||||
"forge": "gitea",
|
||||
"base_url": "https://gitea.example",
|
||||
"owner": "example",
|
||||
"repository": "example",
|
||||
"credentials": {"local": {"token_file": ".releasekit/gitea-token"}}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Add `.releasekit/` to the consumer's ignore rules and use owner-only file
|
||||
permissions for the saved token. Then run `releasekit deliver v1.2.3` from the
|
||||
tagged checkout. CI supplies the variable selected in its own credential declaration. See the
|
||||
[configuration reference](../config.md) for context selection, path resolution, and the
|
||||
optional candidate check. The validator checks the selected committed paths;
|
||||
it does not scan for secrets in other files or past commits.
|
||||
For nested modules, the note comes from that module's committed
|
||||
`docs/releases/<version>.md`, and the hosted page is keyed by its complete tag.
|
||||
|
||||
With no build targets, delivery is page-only: no builder, version smoke check,
|
||||
receipt, binary asset, or checksum manifest is involved. With selected targets,
|
||||
receipt, binary asset, or checksum manifest is involved. Committed module
|
||||
directories and declaration links can be resolved from a sparse checkout;
|
||||
page-only delivery needs the committed objects and note. Managed builds require
|
||||
the selected source files to be materialized. With selected targets,
|
||||
one `deliver` invocation builds the tagged source through the facade into
|
||||
temporary storage and delivers the result. To retain artifacts for a retry or
|
||||
separate credentials between build and delivery, use two invocations:
|
||||
|
||||
```sh
|
||||
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`
|
||||
directory must contain the private `.releasekit-build.json` receipt created by
|
||||
`build`. ReleaseKit checks the receipt's repository, commit, version, resolved
|
||||
build settings, and file hashes before making a remote request; caller-owned
|
||||
files remain available for retries. Ordinary `deliver` does not download
|
||||
application dependencies or change the checkout.
|
||||
`build`. ReleaseKit checks its schema, repository, commit, source selection,
|
||||
identity kind, version, module directory and path, full tag, normalized build
|
||||
settings, and artifact declarations. Old receipts must be regenerated with the
|
||||
updated `build` command. Delivery verifies the artifact bytes and sizes after read-only
|
||||
preflight and before any hosted write; caller-owned files remain available for
|
||||
retries. See the [receipt format](../integrations/build-receipts.md) for its
|
||||
identity and compatibility rules.
|
||||
Ordinary `deliver` does not download application dependencies or change the
|
||||
checkout.
|
||||
|
||||
The result reports `complete`, `partial`, `conflict`, `unknown`, or
|
||||
`not_attempted`, along with matching, uploaded, pending, conflicting, and
|
||||
@@ -94,6 +162,10 @@ an upload was confirmed during this invocation; `Pending` means known missing
|
||||
work; `Conflicting` means different hosted content was found; `Uncertain` means
|
||||
the remote state could not be resolved.
|
||||
|
||||
An error can accompany `complete` when hosted delivery succeeded but removal
|
||||
of managed build files failed. Address the reported local cleanup failure;
|
||||
the completed hosted delivery does not need to be repeated.
|
||||
|
||||
Fix local or preflight failures before retrying. For partial delivery, fix the
|
||||
reported cause and retry the same version. Resolve an unknown remote outcome
|
||||
before retrying. Investigate conflicts and use a new version if the source or
|
||||
@@ -101,29 +173,84 @@ published content needs correction. If rebuilding could change bytes already
|
||||
on the server, retain the original build output and retry with `--assets DIR`.
|
||||
The command does not run candidate checks or publish tags.
|
||||
|
||||
## Credential preflight
|
||||
|
||||
Both `Deliver` and the CLI perform a read-only destination preflight after
|
||||
cheap local request and source checks. It happens before managed builds and
|
||||
full artifact size and digest verification. If it succeeds, delivery verifies
|
||||
the local artifact contents before making any hosted write. A failed preflight
|
||||
leaves delivery `not_attempted`, including when the service is unavailable.
|
||||
|
||||
Call `PreflightDelivery` directly when another caller-controlled operation
|
||||
should follow credential verification. The check needs no checkout or published
|
||||
tag and performs no test release or upload. For Gitea it verifies authenticated
|
||||
repository access; exposed metadata can identify known deficiencies, but
|
||||
successful preflight does not guarantee later release or asset writes. A
|
||||
`DeliveryPreflightError` identifies invalid destination settings, missing or
|
||||
rejected credentials, known insufficient permissions, an inaccessible
|
||||
destination, or unavailable verification. Its `Unwrap` method preserves the
|
||||
cause for `errors.Is` and
|
||||
`errors.As`. A 403 means access was denied, not necessarily that a token
|
||||
expired; a 404 can mean a missing repository or hidden access.
|
||||
|
||||
```go
|
||||
err := releasekit.PreflightDelivery(ctx, releasekit.DeliveryDestination{
|
||||
Forge: releasekit.ForgeGitea,
|
||||
BaseURL: "https://gitea.example",
|
||||
Owner: "example",
|
||||
Repository: "example",
|
||||
Token: token,
|
||||
})
|
||||
if err != nil {
|
||||
var preflight *releasekit.DeliveryPreflightError
|
||||
if errors.As(err, &preflight) {
|
||||
log.Printf("delivery preflight %s: %v", preflight.Kind, preflight.Err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
```
|
||||
|
||||
The CLI performs the same check automatically. For binary `ci-deliver`, it
|
||||
checks access before application dependency downloads, then `Deliver` checks
|
||||
again after preparation. Page-only CI needs no separate preflight call.
|
||||
`check`, `build`, and source `publish` remain independent of hosted delivery
|
||||
credentials. Calling preflight before source publication is optional and does
|
||||
not add a publication gate.
|
||||
|
||||
## Go API
|
||||
|
||||
Pass the Gitea credential explicitly. Set `Build` to a `BuildSpec` to compile
|
||||
selected targets as part of delivery. The facade verifies the local tag, clean
|
||||
checkout, and committed release note before compiling. Managed output is stored
|
||||
outside the checkout and removed when delivery returns. `Output` receives build
|
||||
progress. With no build, or with an empty target set, delivery is page-only.
|
||||
Pass the Gitea credential explicitly and select `ForgeGitea`. Set `Build` to a
|
||||
`BuildSpec` to compile selected targets as part of delivery. The facade verifies
|
||||
the local tag, clean checkout, and committed release note before compiling.
|
||||
Managed output is stored outside the checkout and removed when delivery
|
||||
returns. `Output` receives build progress. With no build, or with an empty
|
||||
target set, delivery is page-only.
|
||||
|
||||
To deliver binaries built separately, set `Prebuilt` to the `BuildResult`.
|
||||
ReleaseKit checks that it identifies the selected repository, tagged commit, and
|
||||
version, that its source was verified clean and unchanged during compilation,
|
||||
and that the current files still match their recorded digests. The files remain
|
||||
caller-owned, so callers can retain the original bytes for retries and are
|
||||
responsible for cleanup. With neither artifact source, an empty managed target
|
||||
set, or an empty prebuilt result, delivery is page-only. Do not set both `Build`
|
||||
and `Prebuilt` in one request.
|
||||
ReleaseKit checks its repository, module directory, declared module path, full
|
||||
tag, semantic version, tagged commit, normalized settings, and artifact evidence
|
||||
against the selected committed module. Binary results must record verified
|
||||
source. After cheap local and source checks, delivery performs read-only
|
||||
credential preflight, verifies the local artifacts in full, and then makes
|
||||
hosted writes. The current files are checked against their recorded digests
|
||||
before those writes. Preflight confirms only the access evidence available from
|
||||
the service, as described above. The files remain caller-owned, so callers can
|
||||
retain the original bytes for retries and are responsible for cleanup. With
|
||||
neither artifact source, an empty managed target set, or a matching empty
|
||||
prebuilt result, delivery is page-only. A prebuilt result with no targets or artifacts
|
||||
must still identify the matching repository, module directory and path, tag,
|
||||
commit, and version; a zero `BuildResult` does not. Do not set both `Build` and
|
||||
`Prebuilt` in one request.
|
||||
|
||||
```go
|
||||
result, err := releasekit.Deliver(ctx, releasekit.DeliveryRequest{
|
||||
RepositoryDir: "/work/example",
|
||||
ModuleDir: "integrations/example",
|
||||
Product: "Example",
|
||||
Version: "v1.2.3",
|
||||
Destination: releasekit.GiteaDestination{
|
||||
ExpectedTag: "integrations/example/v1.2.3", // optional CI event check
|
||||
Destination: releasekit.DeliveryDestination{
|
||||
Forge: releasekit.ForgeGitea,
|
||||
BaseURL: "https://gitea.example",
|
||||
Owner: "example",
|
||||
Repository: "example",
|
||||
@@ -157,31 +284,55 @@ a different toolchain. The tag's `go.mod` must select ReleaseKit as a module
|
||||
dependency. For CLI-only consumers, use the versioned Go tool dependency
|
||||
described in the [adoption guide](adoption.md). Ordinary package dependencies
|
||||
also work with this template.
|
||||
|
||||
Select a tool release implementing this workflow's interface before adopting it;
|
||||
the [adoption guide](adoption.md#ci-adoption) owns coordinated tool/workflow
|
||||
upgrades. Retries of older tags use the workflow matching their recorded tool.
|
||||
|
||||
Configure the Woodpecker repository secret `releasekit_gitea_token`; the
|
||||
template maps it to `RELEASEKIT_GITEA_TOKEN` for delivery. The repository needs
|
||||
a `delivery` profile. Page-only and binary behavior both use this template; the
|
||||
profile's build target list selects whether application binaries are built and
|
||||
delivered.
|
||||
|
||||
Before running Go, the template fetches the explicit event tag, compares its
|
||||
peeled commit with the provider's full commit ID without regard to hex case,
|
||||
checks out that commit detached, and confirms the source tree is clean. It then
|
||||
copies the tagged `go.mod` and any `go.sum` to a temporary directory outside
|
||||
the checkout. `go list -m` confirms that the module selects ReleaseKit; Go uses
|
||||
an alternate `-modfile` to prepare dependencies and build the selected
|
||||
`cmd/releasekit` package without changing the tagged module files. The template
|
||||
invokes that executable with `CI_WORKSPACE`, `CI_COMMIT_SHA`, and
|
||||
`CI_COMMIT_TAG`. A cleanup trap removes the temporary metadata and executable.
|
||||
Before running Go, the template fetches the explicit event tag and independently
|
||||
resolves both the tag and `CI_COMMIT_SHA` to source commits. The event ID may
|
||||
identify an annotated tag object or a commit. The template requires the resolved
|
||||
commits to match, checks out that commit detached, and confirms the source tree
|
||||
is clean. It then copies the tagged `go.mod` and any `go.sum` to a temporary
|
||||
directory outside the checkout. `go list -m` confirms that the module selects
|
||||
ReleaseKit. The template selects the host Go target before preparing and running
|
||||
the CLI. The template adds its CLI tool declaration to that temporary copy
|
||||
and prepares tool dependencies with `go list -deps`. It then uses
|
||||
`go tool -modfile=... go.maximumdirect.net/releasekit/cmd/releasekit` to build,
|
||||
cache, and run the selected tool with `CI_WORKSPACE`, the resolved event commit,
|
||||
and `CI_COMMIT_TAG`. The tagged module files stay unchanged, including for
|
||||
consumers with an ordinary package
|
||||
dependency. A cleanup trap removes the temporary metadata; Go manages the
|
||||
cached executable. The command preserves the tool's exit status.
|
||||
|
||||
Tool bootstrap and application artifact preparation are separate. The bootstrap
|
||||
resolves and builds ReleaseKit from the tagged consumer's module configuration.
|
||||
Afterward, `ci-deliver` loads the profile and downloads application dependencies
|
||||
only when build targets are selected; it builds and delivers those targets with
|
||||
the note page. Source-only profiles skip application dependency downloads and
|
||||
binary work. Dependency preparation for binaries may use the network and may
|
||||
update an uncommitted checksum file in the checkout. A retry still uses the
|
||||
same immutable tag and that tag's module settings, even after the default branch
|
||||
selects a newer ReleaseKit version.
|
||||
After the workflow verifies and checks out the event tag, the resulting CLI uses
|
||||
`ci-deliver --prepared` to repeat the tag, commit, HEAD, and cleanliness checks
|
||||
without another fetch or checkout. It loads the tagged profile and downloads
|
||||
application dependencies only when build targets are selected; it builds and
|
||||
delivers those targets with the note page. Source-only profiles skip application
|
||||
dependency downloads and binary work. Dependency preparation for binaries may
|
||||
use the network. Prepare and commit the selected module's `go.sum` before
|
||||
tagging; an uncommitted change makes the later delivery source check fail. A
|
||||
retry still uses the same immutable tag and that tag's module settings, even
|
||||
after the default branch selects a newer ReleaseKit version.
|
||||
|
||||
The root-only [`tag-delivery.yml`](../../examples/woodpecker/tag-delivery.yml)
|
||||
keeps the small default profile and root-module bootstrap. For consumers that
|
||||
release several modules from one repository, copy the contents of the maintained
|
||||
[multi-module example](../../examples/multi-module/) to the consumer repository
|
||||
root and use its [`woodpecker.yml`](../../examples/multi-module/woodpecker.yml),
|
||||
[`release-modules.tsv`](../../examples/multi-module/release-modules.tsv), and
|
||||
shared selector. The event tag chooses one row from the tagged checkout; the
|
||||
profile and physical module must agree, and ReleaseKit verifies the derived tag.
|
||||
The example covers source-only integration pages and a binary core module.
|
||||
|
||||
If the application does not declare ReleaseKit as a module dependency, install
|
||||
the executable separately and invoke the same `ci-deliver` command. For
|
||||
@@ -195,12 +346,25 @@ and application artifact compilation retain their separate environments.
|
||||
|
||||
The normal Go module and build caches are sufficient. Cache mounts may be added
|
||||
as deployment configuration when they help the runner; they are not needed by
|
||||
the template. A separately installed executable can be installed with
|
||||
`go install gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit@PIN`, then run
|
||||
with the same arguments:
|
||||
the template. For a standalone installation, replace `PIN` with the desired
|
||||
version and [select the Go host target](adoption.md#select-the-go-host-target)
|
||||
for `go install`:
|
||||
|
||||
```sh
|
||||
releasekit ci-deliver --repo "$CI_WORKSPACE" --commit "$CI_COMMIT_SHA" "$CI_COMMIT_TAG"
|
||||
(
|
||||
releasekit_host_os=$(go env GOHOSTOS) || exit $?
|
||||
releasekit_host_arch=$(go env GOHOSTARCH) || exit $?
|
||||
export GOOS="$releasekit_host_os" GOARCH="$releasekit_host_arch"
|
||||
go install go.maximumdirect.net/releasekit/cmd/releasekit@PIN
|
||||
)
|
||||
```
|
||||
|
||||
With the event object available in the CI checkout, resolve it to its source
|
||||
commit before invoking the installed executable:
|
||||
|
||||
```sh
|
||||
expected_commit=$(git -C "$CI_WORKSPACE" rev-parse --verify "${CI_COMMIT_SHA}^{commit}")
|
||||
releasekit ci-deliver --repo "$CI_WORKSPACE" --commit "$expected_commit" "$CI_COMMIT_TAG"
|
||||
```
|
||||
|
||||
The module-based workflow follows the ReleaseKit version selected by the tagged
|
||||
@@ -209,6 +373,12 @@ consumer module configuration when adopting a newer ReleaseKit version and
|
||||
verify it with a tag fixture. The command and profile behavior are documented
|
||||
in the [CLI contract](../cli.md) and [configuration reference](../config.md).
|
||||
|
||||
Update copied workflow YAML when adopting corrected examples. A dependency
|
||||
upgrade alone leaves that copy unchanged. An older tagged workflow that passes
|
||||
a raw annotated tag object ID still fails on retry. Recover delivery from the
|
||||
original tagged source with the resolved event commit through the command above,
|
||||
preserving the published tag and existing content.
|
||||
|
||||
Woodpecker runs delivery after the tag event, independently from the source
|
||||
publication result. Read its workflow status as delivery status: a delivery
|
||||
failure does not undo source publication. A failed, partial, or uncertain run
|
||||
@@ -230,7 +400,9 @@ describes these checks.
|
||||
|
||||
To isolate a public ReleaseKit download from application settings and the
|
||||
existing module cache, run the following with a compatible local Go toolchain.
|
||||
Replace `v0.2.0` with the affected version. This diagnostic accesses the public
|
||||
Replace `v0.5.0` with the affected vanity-path version. For an earlier release,
|
||||
use its original `gitea.maximumdirect.net/eric/ReleaseKit` module path instead.
|
||||
This diagnostic accesses the public
|
||||
Go proxy and checksum database and retains its temporary directory for inspection.
|
||||
|
||||
```sh
|
||||
@@ -242,7 +414,7 @@ Go proxy and checksum database and retains its temporary directory for inspectio
|
||||
GOPRIVATE= GONOPROXY= GONOSUMDB= \
|
||||
GOPROXY=https://proxy.golang.org GOSUMDB=sum.golang.org \
|
||||
GOMODCACHE="$checksum_dir/modules" \
|
||||
go mod download -json gitea.maximumdirect.net/eric/ReleaseKit@v0.2.0
|
||||
go mod download -json go.maximumdirect.net/releasekit@v0.5.0
|
||||
)
|
||||
```
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ annotated source tag:
|
||||
```go
|
||||
result, err := releasekit.Publish(ctx, releasekit.ReleaseRequest{
|
||||
RepositoryDir: "/work/project",
|
||||
ModuleDir: "integrations/example",
|
||||
Product: "Example",
|
||||
Version: "v1.2.3",
|
||||
ExpectedPushURL: "ssh://git.example/owner/example.git",
|
||||
@@ -13,15 +14,35 @@ result, err := releasekit.Publish(ctx, releasekit.ReleaseRequest{
|
||||
Go: releasekit.GoValidationSpec{Race: true, FullVet: true},
|
||||
},
|
||||
AdditionalChecks: func(ctx context.Context, candidate releasekit.Candidate) error {
|
||||
return runProjectChecks(ctx, candidate.RepositoryDir)
|
||||
return runProjectChecks(ctx, candidate.ModuleDir)
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println(result.Version, result.CandidateCommit, result.TagObject)
|
||||
fmt.Println(result.ModulePath, result.Version, result.Tag, result.CandidateCommit, result.TagObject)
|
||||
```
|
||||
|
||||
`ModuleDir` is a repository-relative physical module directory; omit it or use
|
||||
`.` for a root-module release. ReleaseKit reads the selected module's committed
|
||||
declaration and derives the complete Git tag from its declared module path and
|
||||
physical location. `Version` remains the stable semantic version. The note is
|
||||
`<module>/docs/releases/<version>.md`; an on-disk `/v2` directory is part of
|
||||
the note path but is removed from the tag prefix only when the module path ends
|
||||
in `/v2`. `PublicationResult` returns the absolute `ModuleDir`, declared
|
||||
`ModulePath`, complete `Tag`, and existing commit and tag-object evidence.
|
||||
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
|
||||
for enabled file checks. Its nil and empty-slice behavior is described in the
|
||||
[candidate check guide](check.md#local-candidate-check).
|
||||
|
||||
Publication captures a clean candidate on `main`, validates its committed
|
||||
release note, and checks the selected remote before running candidate checks.
|
||||
Set `ExpectedPushURL` to require the effective push destination to match an
|
||||
@@ -30,7 +51,7 @@ when fetch and push URLs differ. A mismatch fails preflight before Go validation
|
||||
callbacks, or tag creation; detect it with
|
||||
`errors.Is(err, releasekit.ErrUnexpectedPushURL)`. `Check` ignores this
|
||||
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
|
||||
`-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
|
||||
@@ -49,22 +70,25 @@ does not execute target binaries. A failure is reported as `package-compile`
|
||||
with the selected target and prevents tag creation.
|
||||
|
||||
Set `Validation.GoFormat` to check committed regular Go source using the Go
|
||||
formatter built into ReleaseKit. It includes vendor and nested modules, ignores
|
||||
formatter built into ReleaseKit. It uses the selected file inputs, including
|
||||
vendor and explicit shared files, and ignores
|
||||
worktree changes and symlink blobs, and reports unformatted paths as
|
||||
`go-format` without changing files. The default is disabled. The check follows
|
||||
tests, selected vet, and package compilation, and a failure stops publication
|
||||
before product checks or tag creation.
|
||||
|
||||
Set `Validation.ModuleDistribution.WorkspaceFiles` to reject committed
|
||||
`go.work` and `go.work.sum` blobs, including nested paths and symlink entries.
|
||||
`go.work` and `go.work.sum` blobs in the selected inputs, including symlink entries.
|
||||
The rule reads the captured candidate regardless of `GOWORK`; uncommitted files
|
||||
are ignored, and Go workspace selection and vendor behavior are unchanged. Its
|
||||
zero value disables the check. Findings use `workspace-files` and stop
|
||||
publication before product checks or tag creation.
|
||||
Set `Validation.ModuleDistribution.LocalReplacements` independently to parse
|
||||
committed `go.mod` declarations across the candidate, including nested and
|
||||
vendor modules. Filesystem `replace` directives are reported with their source
|
||||
path, line, and target as `local-replacements`; versioned replacements are
|
||||
selected module's committed `go.mod` declarations. Vendored contents remain in
|
||||
scope; automatic inputs stop at independently released nested modules. Explicit
|
||||
shared files can include another module's declaration. Filesystem
|
||||
`replace` directives are reported with their source path, line, and target as
|
||||
`local-replacements`; versioned replacements are
|
||||
permitted. Committed module symlinks are resolved within the candidate, and
|
||||
parse or inspection errors retain their causes. This check is independent of
|
||||
`GOWORK`; its zero value disables it, and a failure stops publication before
|
||||
@@ -72,9 +96,9 @@ product checks or tag creation.
|
||||
Set `Validation.FileSize` to check each committed blob against a byte limit.
|
||||
Nil disables the check; an empty object enables the default of 1,000,000
|
||||
decimal bytes. `LimitBytes` uses strict greater-than, accepts zero, and rejects
|
||||
negative values. `Exclusions` contains literal repository-relative files or
|
||||
directories, including committed descendants of excluded directories. Symlink
|
||||
blob size is its link text; gitlinks are omitted. This check measures only the
|
||||
negative values. `Exclusions` contains literal files or directories relative to
|
||||
the selected module, including committed descendants of excluded directories.
|
||||
Symlink blob size is its link text; gitlinks are omitted. This check measures only the
|
||||
captured candidate and reports one oversized file with its measurement as
|
||||
`file-size`; it stops publication before product checks or tag creation.
|
||||
|
||||
@@ -97,9 +121,81 @@ candidate and remote guards, creates an annotated tag for the captured commit,
|
||||
and pushes only that tag object.
|
||||
|
||||
A successful result means Git confirmed the push or an exact authoritative tag
|
||||
query confirmed it after a push error. The local tag is retained after a failed
|
||||
push. `PublicationState` distinguishes a known failure, conflict, confirmed
|
||||
publication, and unresolved outcome. Resolve an unknown result against the
|
||||
captured endpoint before retrying; see the [maintainer procedure](../release.md)
|
||||
for the recovery steps. The [CLI contract](../cli.md) documents command output
|
||||
and exit statuses.
|
||||
query confirmed it after a push error. A failed inspection after local tag
|
||||
creation can leave the tag ref even when its object ID is unavailable; when
|
||||
the ID was established it remains in `TagObject`. The local tag is retained
|
||||
after a failed push. `PublicationState` distinguishes a known failure, conflict,
|
||||
confirmed publication, and unresolved outcome. Resolve an unknown result
|
||||
against the captured endpoint before retrying; see the [maintainer procedure](../release.md)
|
||||
for the recovery steps. The result's endpoint is the exact URL and can contain
|
||||
credentials; handle it accordingly. The [CLI contract](../cli.md) documents
|
||||
command output and exit statuses.
|
||||
|
||||
## Retain and reconcile publication evidence
|
||||
|
||||
`Publish` automatically attempts to save one private record for each invocation.
|
||||
The default store is under the repository's Git common directory, so linked
|
||||
worktrees share it. `ReleaseRequest.PublicationRecordDir` can override the
|
||||
directory; relative overrides resolve from the source repository root. The CLI
|
||||
equivalent is `publish --record-dir DIR`. ReleaseKit creates its owned storage
|
||||
directories privately and creates record files with owner-only permissions;
|
||||
existing directory permissions are left as they are. The caller owns storage
|
||||
retention and removal.
|
||||
|
||||
The CLI prepares a recovery entry point when a failed publication has a saved
|
||||
record. Registered-tool consumers use their selected module's Go tool directly.
|
||||
Command preparation uses a separate bounded context after publication failure,
|
||||
including cancellation. A module-preparation warning can accompany a persistent
|
||||
native executable fallback; the saved record and publication result retain their
|
||||
original meaning.
|
||||
For API-only consumers, ReleaseKit retains private bootstrap module and checksum files
|
||||
under `<Git common directory>/releasekit/publication-recovery/`, with private
|
||||
directory and file permissions. These files add the CLI tool declaration and
|
||||
prepare its module graph without changing consumer source. The bootstrap has
|
||||
its own module root, so tool resolution is independent of consumer vendoring;
|
||||
local replacements retain their original source locations. These files survive
|
||||
a launcher's temporary module-file cleanup. Registered-tool commands run from
|
||||
the selected module; API-only commands run from the private bootstrap root.
|
||||
Retain the source checkout and private recovery files while the entry point is
|
||||
needed. Remove the private recovery directories when
|
||||
their recovery value expires. Another supported CLI can read the saved record
|
||||
independently of these launch files.
|
||||
|
||||
The saved endpoint is retained exactly for later observation and may include
|
||||
credentials. Treat records, `PublicationEvidence`, and `PublicationResult` as
|
||||
sensitive. Store overrides in a location with suitable access controls, avoid
|
||||
printing raw endpoint values, and remove records when their recovery value has
|
||||
expired. Diagnostic errors and CLI output apply credential redaction; the
|
||||
private record and typed evidence preserve the raw endpoint.
|
||||
|
||||
Recording failure is reported in `PublicationResult.RecordError`, separately
|
||||
from `Publish`'s return error and publication state. A successful push remains
|
||||
successful if storage fails, but the saved handoff is unavailable. Callers can
|
||||
still pass `result.Evidence` directly to `ReconcilePublication` when it contains
|
||||
the required identity. For example:
|
||||
|
||||
```go
|
||||
func observe(ctx context.Context, result releasekit.PublicationResult) (releasekit.PublicationReconciliationResult, error) {
|
||||
return releasekit.ReconcilePublication(ctx, result.Evidence)
|
||||
}
|
||||
```
|
||||
|
||||
The evidence is populated as publication identity becomes available, including
|
||||
partial evidence on some earlier failures. An abrupt process termination before
|
||||
the save point can leave no record; removed storage also removes the handoff.
|
||||
Records from older attempts may lack the tag object, endpoint, or other identity
|
||||
needed for a conclusive observation.
|
||||
|
||||
Use `LoadPublicationEvidence(path)` to read one explicit record,
|
||||
`ListPublicationAttempts(ctx, request)` to discover readable records and
|
||||
per-record diagnostics in a local directory, or `ReconcilePublication(ctx,
|
||||
evidence)` to observe a selected endpoint. Listing does not query remotes, and
|
||||
neither listing nor reconciliation changes saved records. Recovery does not
|
||||
infer the attempt from current HEAD, local tags, module files, or profiles.
|
||||
`ReconcilePublication` returns a nil error for a completed `published`,
|
||||
`not_published`, or `conflict` observation; unresolved `unknown` results include
|
||||
a typed error that retains the underlying cause. See the
|
||||
[GoDoc](../../recovery.go) for the exported fields and error kinds, the
|
||||
[CLI guide](../cli.md) for command statuses, and the
|
||||
[record format guide](../integrations/publication-records.md) for supported
|
||||
stored and structured formats.
|
||||
|
||||
53
docs/consumers/readiness.md
Normal file
53
docs/consumers/readiness.md
Normal 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.
|
||||
76
docs/consumers/rehearsal.md
Normal file
76
docs/consumers/rehearsal.md
Normal 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.
|
||||
@@ -4,7 +4,7 @@ Applications can read their embedded version through the public `buildinfo`
|
||||
package:
|
||||
|
||||
```go
|
||||
import "gitea.maximumdirect.net/eric/ReleaseKit/buildinfo"
|
||||
import "go.maximumdirect.net/releasekit/buildinfo"
|
||||
|
||||
version := buildinfo.Version()
|
||||
```
|
||||
|
||||
22
docs/integrations/build-receipts.md
Normal file
22
docs/integrations/build-receipts.md
Normal 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.
|
||||
@@ -1,9 +1,10 @@
|
||||
# Gitea release pages
|
||||
|
||||
ReleaseKit's public `Deliver` operation and `deliver` command verify tagged
|
||||
source, find or create its stable release page, inspect existing assets, and
|
||||
upload missing assets through the internal Gitea client. Page-only and
|
||||
binary-producing profiles use the same delivery path. The
|
||||
ReleaseKit's public `Deliver` operation and `deliver` command select Gitea
|
||||
explicitly, verify tagged source, find or create the selected module's release
|
||||
page, inspect existing assets, and upload missing assets. Shared delivery code
|
||||
owns content comparison and recovery; the Gitea adapter owns the HTTP protocol.
|
||||
Page-only and binary-producing profiles use the same delivery path. The
|
||||
[consumer delivery guide](../consumers/delivery.md) covers caller workflows;
|
||||
this guide describes the Gitea protocol and its failure behavior.
|
||||
|
||||
@@ -13,34 +14,75 @@ the `Authorization: token …` request header and is not included in errors or
|
||||
results. The base URL must use HTTP or HTTPS and cannot contain URL credentials,
|
||||
a query, or a fragment.
|
||||
|
||||
For version `vMAJOR.MINOR.PATCH`, the client first reads
|
||||
Before a build or full local artifact verification, Gitea preflight makes two
|
||||
authenticated, read-only repository requests: `GET /api/v1/repos/{owner}/{repo}`
|
||||
resolves the repository, then `GET /api/v1/repositories/{id}` confirms access
|
||||
through the authenticated repository route. The response identity must match
|
||||
the configured owner and repository. This check also works without a checkout
|
||||
or a published tag and makes no release or asset writes.
|
||||
|
||||
A 401 response identifies a rejected credential. A 403 identifies denied
|
||||
access but does not establish that the credential is invalid. A 404 can mean a
|
||||
missing repository or access hidden by the service. Network failures, service
|
||||
errors, and malformed responses that prevent verification are reported as
|
||||
unavailable. Repository `permissions.push` describes Git code-push access; it
|
||||
does not establish permission to create release pages or upload assets. Gitea
|
||||
does not expose enough evidence through this probe to verify those write scopes,
|
||||
so they remain unverified and later writes remain authoritative. Preflight does
|
||||
not request unrelated user scopes or create a test release or asset.
|
||||
|
||||
The selected module derives a complete tag from its semantic version, declared
|
||||
module path, and physical repository-relative directory. For example, version
|
||||
`v1.2.3` in `integrations/ckconfig` uses
|
||||
`integrations/ckconfig/v1.2.3`; a root module uses `v1.2.3`. A `/v2` module
|
||||
stored at `integrations/core/v2` uses `integrations/core/v2.1.0`; the same
|
||||
declared module stored at `integrations/core` derives the same tag. ReleaseKit
|
||||
removes a final physical `/v2` directory from the tag prefix only when the
|
||||
module declaration has that `/v2` suffix. A module-local note stays at
|
||||
`<module>/docs/releases/<version>.md`, including a physical `/v2` directory.
|
||||
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`,
|
||||
`LICENSE`, and `docs/oss/attribution.md` when present. Consumers own their license
|
||||
layout and release-note links. Use the complete derived tag as the immutable
|
||||
source ref and the actual repository-relative file paths in those links.
|
||||
Shared-file selection controls validation inputs; delivery preserves the
|
||||
committed note and its footer links. After successful preflight, the Gitea
|
||||
adapter reads
|
||||
`/api/v1/repos/{owner}/{repo}/tags/{tag}` and requires the hosted tag's commit
|
||||
SHA to equal the captured source commit. It then reads
|
||||
`/api/v1/repos/{owner}/{repo}/releases/tags/{tag}`. A matching existing page
|
||||
must have that tag, the complete committed release note as its body, and stable
|
||||
is accepted by shared delivery policy only when it has that tag, the complete
|
||||
committed release note as its body, and stable
|
||||
non-draft state. Its existing title is retained. ReleaseKit does not edit a
|
||||
conflicting page.
|
||||
conflicting page. Slash-containing tags are escaped as one URL path segment.
|
||||
Page-only delivery does not require a release ID in this lookup response. Asset
|
||||
operations require a positive release ID; a missing or nonpositive ID is
|
||||
reported as a malformed service observation before an asset request is made.
|
||||
|
||||
If the page is absent, the client posts to `/api/v1/repos/{owner}/{repo}/releases`
|
||||
with the selected tag and commit, the release note's H1 as title, the complete
|
||||
note as body, and draft and prerelease disabled. A create conflict, interrupted
|
||||
response, or malformed create response (including inconsistent decoded fields)
|
||||
triggers one lookup. An exact page found
|
||||
there confirms the existing content; a differing page is a conflict. If that
|
||||
lookup cannot determine the result after a possibly successful write, the
|
||||
client returns an unknown outcome. Other HTTP failures retain their structured
|
||||
failure kind and status code. A recovered create retains its write history;
|
||||
a later asset-inspection failure reports partial page progress.
|
||||
If the page is absent, the adapter posts to
|
||||
`/api/v1/repos/{owner}/{repo}/releases` with the selected full tag and commit,
|
||||
the release note's H1 as title, the complete note as body, and draft and
|
||||
prerelease disabled. A create conflict, interrupted response, or malformed
|
||||
create response (including inconsistent decoded fields) triggers one lookup by
|
||||
the shared workflow. An exact page found there confirms the existing content;
|
||||
a differing page is a conflict. If that lookup cannot determine the result
|
||||
after a possibly successful write, delivery returns an unknown outcome. Other
|
||||
HTTP failures retain their structured failure kind and status code. A recovered
|
||||
create retains its write history; a later asset-inspection failure reports
|
||||
partial page progress.
|
||||
|
||||
For a binary-producing release, the client can build a deterministic
|
||||
For a binary-producing release, shared delivery builds a deterministic
|
||||
`SHA256SUMS` file from the declared artifact names and SHA-256 digests. Entries
|
||||
are sorted by filename and use the standard two-space separator. A source-only
|
||||
release produces no manifest.
|
||||
|
||||
Asset inspection lists the release attachments, streams each declared existing
|
||||
file, and compares its SHA-256 digest. It reports each asset as matching,
|
||||
missing, conflicting, or unverifiable. Same-name attachments with different
|
||||
bytes are conflicts even when their reported size matches. An existing
|
||||
The adapter lists release attachments and opens their download streams. Shared
|
||||
delivery compares each declared existing file by SHA-256 digest and reports it
|
||||
as matching, missing, conflicting, or unverifiable. Same-name attachments with
|
||||
different bytes are conflicts even when their reported size matches. An existing
|
||||
`SHA256SUMS` must exactly match the complete expected manifest; a subset or
|
||||
different manifest is a conflict. An unreadable attachment is unverifiable,
|
||||
not missing. A failed read-only inspection reports `not_attempted`; if this
|
||||
@@ -49,12 +91,15 @@ Unknown-write outcomes are reserved for unresolved writes. Unrelated attachments
|
||||
|
||||
Attachment downloads and redirects carry the Gitea authorization token only
|
||||
when their scheme, host, and port match the configured service. Cross-origin
|
||||
content is downloaded without that token and verified by its digest.
|
||||
content is downloaded without that token and verified by its digest. Downloads
|
||||
follow at most ten redirects; an additional redirect is unverifiable.
|
||||
Comparison reads no more than the declared local size plus one byte; shorter
|
||||
or longer content conflicts, regardless of the server's reported size.
|
||||
|
||||
The upload operation accepts only an inspection result without conflicts or
|
||||
Shared delivery uploads only after inspection finds no conflicts or
|
||||
unverifiable assets. It uploads missing binaries in filename order and then the
|
||||
missing `SHA256SUMS`, using multipart field `attachment` and the filename query
|
||||
parameter `name`. Matching attachments are retained; unrelated and existing
|
||||
missing `SHA256SUMS`, using the adapter's multipart field `attachment` and
|
||||
filename query parameter `name`. Matching attachments are retained; unrelated and existing
|
||||
attachments are never overwritten or deleted. Results use disjoint current
|
||||
observations: matching, uploaded, pending, conflicting, and uncertain. An asset
|
||||
moved from known missing work to another category is removed from `pending`;
|
||||
|
||||
132
docs/integrations/publication-records.md
Normal file
132
docs/integrations/publication-records.md
Normal file
@@ -0,0 +1,132 @@
|
||||
# Publication records and recovery output
|
||||
|
||||
This guide describes the supported private publication-record envelope and the
|
||||
versioned JSON documents emitted by the recovery CLI. The
|
||||
[publication consumer guide](../consumers/publish.md) owns storage placement,
|
||||
permissions, retention, and sensitive-data handling. The
|
||||
[CLI reference](../cli.md) owns command behavior, path selection, and exit
|
||||
statuses; the exported Go contract is documented in [GoDoc](../../recovery.go).
|
||||
|
||||
## Private attempt record
|
||||
|
||||
Each saved attempt is one complete JSON document with this versioned envelope:
|
||||
|
||||
```json
|
||||
{
|
||||
"format_version": 3,
|
||||
"evidence": {
|
||||
"repository_dir": "/work/project",
|
||||
"source_dir": "/work/project",
|
||||
"source_subdir": ".",
|
||||
"go_enabled": true,
|
||||
"publication_mode": "go-module",
|
||||
"version_format": "semver",
|
||||
"version_prefix": "v",
|
||||
"identity_kind": "production",
|
||||
"note_path": "docs/releases/v1.2.3.md",
|
||||
"module_dir": "/work/project",
|
||||
"module_path": "example.com/project",
|
||||
"version": "v1.2.3",
|
||||
"tag": "v1.2.3",
|
||||
"candidate_commit": "<full Git object ID>",
|
||||
"tag_object": "<full Git object ID>",
|
||||
"endpoint": "ssh://git.example/owner/project.git",
|
||||
"remote": "origin",
|
||||
"recorded_at": "2026-11-02T12:00:00Z"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The format version is an integer. Evidence fields may be absent when publication
|
||||
stopped before they were captured; loading preserves that partial evidence and
|
||||
does not fill fields from the current checkout. Additional fields in a
|
||||
supported version are ignored. A missing or unsupported version, malformed or
|
||||
multiple JSON documents, or fields with invalid structural types are reported
|
||||
as record-format errors. The codec reads versions 1, 2, and 3; no migration from
|
||||
an unsupported version is performed.
|
||||
|
||||
New records use version 3, including source and selection evidence. Legacy
|
||||
versions 1 and 2 retain only the evidence they captured. Version 2 and version 3
|
||||
may include an `evidence_bytes` object for non-UTF-8 string values. Each entry
|
||||
in `evidence_bytes` uses an evidence field
|
||||
name and a standard base64 string containing its exact bytes. That entry
|
||||
supplies the field's value when loading; the writer omits its lossy string form
|
||||
from `evidence`. Invalid known-field types or base64 encodings produce a
|
||||
record-format error with the available decoding cause. Unknown field names are
|
||||
ignored. This representation applies
|
||||
to string evidence fields and preserves the same identity as typed Go evidence.
|
||||
Older CLIs report an unsupported version for records they cannot read.
|
||||
|
||||
The `endpoint` value is stored exactly as captured and may contain credentials.
|
||||
Private records are sensitive. Do not copy them into public logs or source
|
||||
control. For their location, permissions, and lifecycle, see the
|
||||
[publication consumer guide](../consumers/publish.md#retain-and-reconcile-publication-evidence).
|
||||
|
||||
## Recovery CLI JSON
|
||||
|
||||
After valid command arguments, `--json` emits one JSON document to standard
|
||||
output for both successful and failed recovery operations. Each document has
|
||||
`schema_version: 1` and a `command` name. These are CLI presentation documents,
|
||||
not private attempt records or a Go serialization of public structs.
|
||||
|
||||
`reconcile` includes `record_path`, safe `evidence`, and `state` when a record
|
||||
was read. Available `observed_tag_object` and `observed_commit` fields are
|
||||
included when present. A `diagnostic` is included for unresolved observation
|
||||
or record loading failure. Loading failure omits evidence, state, and observed
|
||||
IDs. Safe evidence may include source, capability, publication, and version
|
||||
selection fields when those were captured.
|
||||
|
||||
`publication-attempts` includes `record_dir`, an `attempts` array with each
|
||||
`record_path` and safe `evidence`, and a `diagnostics` array. A top-level
|
||||
`diagnostic` describes enumeration or cancellation failure. Both arrays are
|
||||
present when empty so consumers can decode the same shape for empty stores.
|
||||
|
||||
For example, an unresolved reconciliation can have this shape:
|
||||
|
||||
```json
|
||||
{
|
||||
"schema_version": 1,
|
||||
"command": "reconcile",
|
||||
"record_path": "/private/attempt-abc.json",
|
||||
"evidence": {
|
||||
"repository_dir": "/work/project",
|
||||
"module_path": "example.com/project",
|
||||
"version": "v1.2.3",
|
||||
"tag": "v1.2.3",
|
||||
"candidate_commit": "<full Git object ID>",
|
||||
"tag_object": "<full Git object ID>",
|
||||
"endpoint": "ssh://git.example/owner/project.git",
|
||||
"remote": "origin"
|
||||
},
|
||||
"state": "unknown",
|
||||
"diagnostic": {
|
||||
"kind": "remote_observation",
|
||||
"message": "<credential-safe diagnostic>"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
A discovery document always contains both arrays, including for an empty store:
|
||||
|
||||
```json
|
||||
{
|
||||
"schema_version": 1,
|
||||
"command": "publication-attempts",
|
||||
"record_dir": "/private/publication-attempts",
|
||||
"attempts": [],
|
||||
"diagnostics": []
|
||||
}
|
||||
```
|
||||
|
||||
CLI evidence uses the private record's snake-case field names. Endpoint strings
|
||||
in CLI output are credential-redacted; the private record and typed
|
||||
`PublicationEvidence` retain the exact endpoint. A diagnostic contains `kind`
|
||||
and safe `message`, with `record_path` and `missing_fields` when applicable.
|
||||
Raw Go errors and private record contents are not emitted as JSON fields.
|
||||
|
||||
Consumers should select attempts by their returned record paths and evidence.
|
||||
The listing order is deterministic by path, not a recommendation to choose the
|
||||
first or newest attempt. Unknown fields may be added in later CLI schema
|
||||
versions; reject unsupported `schema_version` values rather than interpreting
|
||||
them as version 1. See the [CLI reference](../cli.md#recover-a-saved-publication-attempt-or-discover-local-attempts)
|
||||
for invocation and status behavior.
|
||||
89
docs/integrations/rehearsal-records.md
Normal file
89
docs/integrations/rehearsal-records.md
Normal 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.
|
||||
@@ -1,25 +1,49 @@
|
||||
# Go command environments
|
||||
|
||||
`internal/gotool` resolves effective Go settings once for a validation or build
|
||||
operation and applies the shared environment to its Go commands. It uses
|
||||
`internal/gotool` resolves effective Go settings when an operation first needs
|
||||
a Go command and applies the shared environment to its commands. Candidate
|
||||
validation and its build callback share an operation-local owner while the
|
||||
inherited environment and persistent Go settings file remain unchanged.
|
||||
Standalone and delivery builds create their own owners. The package uses
|
||||
`internal/process` for cancellation, the working directory, output, and wrapped
|
||||
errors.
|
||||
|
||||
For CLI publication recovery, the package selects a registered module tool or
|
||||
prepares a durable private module root for an API-only consumer. Go's module
|
||||
graph query includes transitive dependencies; preparation retains module
|
||||
requirements, versioned replacements, and checksums. Local replacements resolve
|
||||
against their original module directory before relocation. Each relocation
|
||||
updates the directive's destination and retains its path and version selector.
|
||||
The original main module remains a local replacement, including when releasing
|
||||
ReleaseKit itself.
|
||||
The private root provides tool resolution independently of consumer vendoring.
|
||||
API-only preparation discovers the host target for dependency inspection. The
|
||||
returned invocation carries its directory and tool arguments; the CLI's later
|
||||
shell command selects the host again when it runs.
|
||||
The CLI formats the later invocation using a separate bounded context after
|
||||
publication failure. It falls back to a persistent native executable when module
|
||||
selection is unavailable or preparation fails, and excludes recognized temporary
|
||||
Go-work executables from that fallback. The
|
||||
[publication consumer guide](../consumers/publish.md#retain-and-reconcile-publication-evidence)
|
||||
owns recovery-file placement and retention.
|
||||
|
||||
## Command output ownership
|
||||
|
||||
`Tool.Run` executes a status-only command. It forwards combined stdout and
|
||||
stderr to the optional writer while the child runs, then releases its capture
|
||||
on success. Failures include the captured diagnostic text and preserve the
|
||||
underlying process or forwarding error.
|
||||
stderr to the optional writer while the child runs, retaining only the last
|
||||
1,048,576 bytes for failure diagnostics. A truncation notice identifies omitted
|
||||
earlier bytes. Successful calls release their capture; failures preserve the
|
||||
underlying process or forwarding error. Dependency preparation uses the same
|
||||
bounded diagnostic capture.
|
||||
|
||||
`Tool.Output` returns combined stdout and stderr for commands whose output is
|
||||
needed by the caller, such as compiler identification. After the child stops,
|
||||
the capture's backing bytes transfer to the caller without a second copy. A
|
||||
failed output command returns both those bytes and an error containing the
|
||||
diagnostic text. The capture remains in memory for the duration of the child;
|
||||
the component benchmark compares one 8 MiB write with the same output in
|
||||
32 KiB writes, forwarding to `io.Discard`. Smaller writes incur buffer-growth
|
||||
allocations. The [output benchmark](../../internal/gotool/performance_test.go)
|
||||
the component benchmark compares full and bounded capture for modest output,
|
||||
one 8 MiB write, and 8 MiB in 32 KiB writes, forwarding to `io.Discard`.
|
||||
The [output benchmark](../../internal/gotool/performance_test.go)
|
||||
measures total allocated bytes per operation, excluding subprocess overhead and
|
||||
diagnostic strings. These totals count all allocations, including superseded
|
||||
buffers. The returned slice retains the final buffer holding the complete output.
|
||||
@@ -30,14 +54,17 @@ coexist. Disk-backed diagnostics could reduce large failure peaks, but add file
|
||||
lifecycle and cleanup work and remain a follow-up option.
|
||||
|
||||
Dependency preparation uses a separate command environment so proxy, private
|
||||
module, checksum, and cache settings remain available. Its completed capture
|
||||
uses the same ownership transfer when formatting a failure.
|
||||
module, checksum, cache, and other effective settings remain available. Its
|
||||
`go mod download -modfile=` command overrides an alternate module file selected
|
||||
through `GOFLAGS`, preserving ordinary module discovery. Its bounded capture
|
||||
is formatted into the error on failure.
|
||||
|
||||
## Configuration discovery
|
||||
|
||||
The owner asks the installed `go` command for `GOHOSTOS` and `GOHOSTARCH`, then
|
||||
queries effective operational settings with that host selected. Both queries
|
||||
use `GOTOOLCHAIN=local` and controlled `GOFLAGS`. Discovery sets
|
||||
The owner asks the installed `go` command for `GOHOSTOS`, `GOHOSTARCH`, and the
|
||||
`GOENV` settings-file path, then queries effective operational settings with
|
||||
that host selected. Both queries use `GOTOOLCHAIN=local` and controlled
|
||||
`GOFLAGS`. Discovery sets
|
||||
`GOEXPERIMENT=none` and clears architecture feature variables so an invalid or
|
||||
nonbaseline tuning value cannot prevent settings from being read. The
|
||||
experiment override is discovery-only.
|
||||
@@ -48,6 +75,13 @@ and native cgo/C-tool configuration into its settings. This captures values
|
||||
supplied by either the process environment or the persistent Go environment
|
||||
file.
|
||||
|
||||
The operation-local owner snapshots the inherited environment and selected
|
||||
settings file. It reuses the resolved tool across validation and its following
|
||||
build callback while those inputs match. Subsequent Go acquisition rediscovers
|
||||
settings when a consumer callback changes either input. An unavailable snapshot
|
||||
disables reuse while discovery follows the Go tool's accepted configuration.
|
||||
Ownership is operation-local.
|
||||
|
||||
Configuration discovery parses JSON from stdout. Stderr is captured separately
|
||||
and included in command-failure diagnostics, so a successful query can emit
|
||||
warnings while supplying valid configuration.
|
||||
@@ -69,9 +103,10 @@ baseline values. Effective `GOCACHE`, `GOCACHEPROG`, `GOMODCACHE`, `GOPATH`,
|
||||
`GOROOT`, and `GOTMPDIR` values are retained. Other process variables remain
|
||||
available to child commands.
|
||||
|
||||
Candidate validation uses native mode for the offline `go test` suite and
|
||||
selected full `go vet` pass. Package-compilation checks use static mode for each
|
||||
selected target and direct Go's output to the operating system null device, so
|
||||
they leave no binary artifact. Artifact builds also use static mode for
|
||||
selected-target compilation, then build the native version-check executable;
|
||||
that executable runs as a normal child process.
|
||||
Candidate validation runs the offline `go test` suite and selected full
|
||||
`go vet` pass from the selected module directory using native mode.
|
||||
Package-compilation checks use static mode for each selected target and direct
|
||||
Go's output to the operating system null device, so they leave no binary
|
||||
artifact. Artifact builds also compile selected targets in static mode, then
|
||||
build the native version-check executable, which runs as a normal child
|
||||
process.
|
||||
|
||||
@@ -3,53 +3,66 @@
|
||||
Public Go contracts are defined in declarations and GoDoc. ReleaseKit supports
|
||||
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
|
||||
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.
|
||||
- `buildinfo` is the small runtime facade. `Version` reports the injected
|
||||
application version, the main-module version when available, or `dev`.
|
||||
- `cmd/releasekit` is the executable interface. Its `version`, `check`,
|
||||
`publish`, `build`, `deliver`, and `ci-deliver` commands adapt profiles and
|
||||
command output to the supported library operations.
|
||||
- `cmd/releasekit` is the executable interface. Its `version`, `validate`, `check`,
|
||||
`publish`, `reconcile`, `publication-attempts`, `build`, `deliver`,
|
||||
`ci-deliver`, `test`, `test-resume`, and `test-cleanup` commands adapt
|
||||
profiles and command output to the supported library operations.
|
||||
|
||||
See the [CLI contract](../cli.md), [configuration reference](../config.md),
|
||||
[candidate check guide](../consumers/check.md),
|
||||
[source publication guide](../consumers/publish.md),
|
||||
[publication record format](../integrations/publication-records.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.
|
||||
Go declarations and GoDoc remain the owners of exact exported contracts.
|
||||
|
||||
## Module and dependencies
|
||||
|
||||
The module is `gitea.maximumdirect.net/eric/ReleaseKit`, with Go language
|
||||
version `1.25.0`. `go.mod` requires `golang.org/x/mod` and Goldmark for internal
|
||||
The module is `go.maximumdirect.net/releasekit`, with Go language
|
||||
version `1.27.0`. `go.mod` requires `golang.org/x/mod` and Goldmark for internal
|
||||
validation; public facades do not expose either dependency. `go list ./...`
|
||||
reports these implemented packages:
|
||||
|
||||
| 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. |
|
||||
| `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. |
|
||||
| `internal/apicheck` | Compiled-export and import-boundary checks run during development. |
|
||||
| `internal/artifact` | Shared build-target normalization, artifact declarations, filename rules, and checksum-manifest naming. |
|
||||
| `internal/build` | Candidate-build coordination, selected Go target compilation, version injection, native smoke check, and artifact digests. |
|
||||
| `internal/candidate` | Stable-version, note, repository-state, candidate capture, and post-validation checks. |
|
||||
| `internal/delivery` | Tagged-source and release-note checks, managed builds in disposable storage outside the checkout, structural artifact declaration, manifest assembly, one local digest-and-size preflight before hosted requests, and delivery coordination. |
|
||||
| `internal/git` | Git command boundary, committed-tree reads, lazy local-only batched blob reads, push-destination resolution, exact ref inspection, tagged checkout preparation, and tag operations, including captured-endpoint verification during recovery. |
|
||||
| `internal/gitea` | Gitea API transport, hosted release pages, asset inspection, manifests, and uploads. |
|
||||
| `internal/gotool` | Effective Go configuration discovery, shared native-validation and static-build environments, and network-capable dependency preparation; see [Go command environments](gotool.md). |
|
||||
| `internal/build` | Resolved-identity builds, normalized settings, selected-module compilation, version injection, external native smoke output, and artifact digests. |
|
||||
| `internal/candidate` | Release identifier and note validation, repository-state checks, candidate capture, and post-validation checks. |
|
||||
| `internal/delivery` | Read-only backend preflight, captured-commit source and optional module identity and note selection, literal-tag checkout checks, prebuilt identity binding, managed builds in disposable storage outside the checkout, artifact declaration, manifest assembly, shared page and asset policy, streamed comparisons, write recovery, and delivery outcomes. |
|
||||
| `internal/forge` | Backend contract, neutral observations and failures, opaque handles, preflight classifications, and write evidence shared by delivery policy and adapters. |
|
||||
| `internal/git` | Git command boundary, committed-tree reads and shared reference traversal, checkout-root and commit capture, lazy local-only batched blob reads, push-destination resolution, exact ref inspection, tagged checkout preparation, and tag operations, including captured-endpoint verification during recovery. |
|
||||
| `internal/gitea` | Gitea destination rules, authenticated repository preflight, HTTP operations and codecs, opaque handle interpretation, response validation, redirects, multipart streaming, and protocol-to-neutral failure conversion. |
|
||||
| `internal/gotool` | Operation-local Go configuration discovery and reuse, shared native-validation and static-build environments, and network-capable dependency preparation; see [Go command environments](gotool.md). |
|
||||
| `internal/tempdir` | Disposable system temporary storage outside source worktrees. |
|
||||
| `internal/process` | Cancellable child-process execution, 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/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/publish` | Publication guards, one validation run, annotated tag creation, push, and recovery state. |
|
||||
| `internal/publish` | Publication guards, one validation run, annotated tag creation, push, pre-push evidence recording, saved-attempt discovery, later observation, and recovery state. |
|
||||
| `internal/runtimeinfo` | Injected version selection and cached fallback metadata lookup for the runtime facade. |
|
||||
| `internal/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
|
||||
root facade forwards to internal implementation packages. The CLI adapter is
|
||||
@@ -61,15 +74,41 @@ also recorded in [ADR 0001](../adr/0001-public-facade.md) and the
|
||||
|
||||
Candidate checking captures and validates one clean committed source revision
|
||||
in `internal/candidate`. Its validation bridge calls `internal/validation` for
|
||||
the default offline Go suite, then runs product-specific checks once. The
|
||||
candidate package owns post-validation builds and local-state rechecks;
|
||||
publication owns endpoint guards, tag creation, push, and recovery around that
|
||||
same candidate validation path. `internal/validation.CandidateTree` reads
|
||||
the selected module's default offline Go suite, then runs product-specific
|
||||
checks once. Validation and its post-validation build callback share one local
|
||||
Go settings owner. Each Go acquisition checks inherited and persistent inputs;
|
||||
settings are rediscovered when subsequent Go work needs them. An unavailable
|
||||
persistent-settings snapshot disables reuse. The candidate package owns builds and local-state
|
||||
rechecks; publication owns endpoint guards, tag creation, push, and recovery
|
||||
around that same candidate validation path. `internal/validation.CandidateTree` reads
|
||||
committed blobs lazily and resolves local destinations from committed entries;
|
||||
it does not consult neighboring files or traverse submodule checkouts.
|
||||
See the [shared validation guide](validation.md) for checker, Go command, and
|
||||
candidate-file integration mechanics.
|
||||
|
||||
Publication records and recovery follow a separate path from candidate
|
||||
validation. `internal/publish` captures and saves attempt evidence before the
|
||||
tag push, lists local records, and observes explicitly selected evidence through
|
||||
`internal/git`; the root facade owns the reusable Go evidence and result types.
|
||||
The CLI's `reconcile` and `publication-attempts` commands load, present, and
|
||||
select records without loading a profile or choosing an attempt automatically.
|
||||
These operations do not rerun candidate checks or hosted delivery and do not
|
||||
change local or remote state. The [publication consumer guide](../consumers/publish.md)
|
||||
owns storage and API use; the [record format guide](../integrations/publication-records.md)
|
||||
owns the private and CLI JSON formats; the [CLI contract](../cli.md) owns command
|
||||
semantics and statuses.
|
||||
|
||||
The root facade selects the backend explicitly and passes a configured
|
||||
`internal/forge.Backend` into `internal/delivery`. Delivery performs cheap
|
||||
request and source checks, then read-only backend preflight before managed
|
||||
builds or full local artifact verification. Artifact size and digest
|
||||
verification completes before hosted writes and is reused for upload streams.
|
||||
Shared delivery code owns release-page matching and creation recovery, remote
|
||||
asset comparison, upload sequencing, and partial or uncertain outcomes.
|
||||
`internal/gitea` implements only the Gitea protocol operations behind the
|
||||
neutral contract. `internal/artifact` and `internal/forge` do not depend on the
|
||||
adapter.
|
||||
|
||||
## Capability owners and behavioral evidence
|
||||
|
||||
The following tests are representative evidence from the current offline suite,
|
||||
@@ -78,19 +117,22 @@ not a separate release matrix:
|
||||
| Capability | Implementation owner | Existing evidence |
|
||||
| --- | --- | --- |
|
||||
| Runtime version lookup and injected application version | `buildinfo`, `internal/runtimeinfo`, `internal/versioncontract`, `internal/build` | `TestVersionInConsumerExecutable`, `TestVersion` |
|
||||
| Candidate capture, shared validation, public diagnostics, additional checks, and rechecks | `releasekit.Check`, `releasekit.Publish`, `internal/candidate`, `internal/validation`, `cmd/releasekit/internal/cli` | `TestRunUsesOneSuiteWithSelectedRaceSetting`, `TestRunReportsRacePrerequisiteFailureWithoutFallback`, `TestRunExecutesRaceEnabledSuiteOnHost`, `TestRunCompilesTargetsAfterTestAndVetInSelectionOrder`, `TestRunAttributesTargetCompileFailureAndStops`, `TestRunCompilesSourceOnlyAndExecutablePackagesWithoutArtifacts`, `TestCandidateRequestMapsGoValidation`, `TestCandidateRequestPreservesMarkdownObjectSelection`, `TestLoadSettingsReadsGoValidation`, `TestLoadSettingsPreservesMarkdownObjectSelection`, `TestCheckUsesSelectedRaceSuiteBeforeAdditionalChecks`, `TestCheckCapturesCandidateAndCallsAdditionalChecksOnce`, `TestCheckReturnsPublicValidationError`, `TestMarkdownValidationRunsThroughCheckAndPublish`, `TestCheckStopsBeforeProductAndBuildCallbacksWhenMarkdownBoundaryFails`, `TestCheckCommandBindsConfiguredChecksToCapturedCandidate`, `TestPublishCommandPublishesConfiguredCandidate`, `TestCandidateCommandsPresentValidationDiagnosticsOnce`, `TestDeliverPageOnlyCreatesAndReusesRelease` |
|
||||
| Candidate capture, shared validation, public diagnostics, additional checks, and rechecks | `releasekit.Check`, `releasekit.Publish`, `internal/candidate`, `internal/validation`, `cmd/releasekit/internal/cli` | `TestRunUsesOneSuiteWithGoValidationSettings`, `TestRunReportsRacePrerequisiteFailureWithoutFallback`, `TestRunExecutesRaceEnabledSuiteOnHost`, `TestRunCompilesTargetsAfterTestAndVetInSelectionOrder`, `TestRunAttributesTargetCompileFailureAndStops`, `TestRunCompilesSourceOnlyAndExecutablePackagesWithoutArtifacts`, `TestCandidateRequestMapsGoValidation`, `TestCandidateRequestPreservesMarkdownObjectSelection`, `TestLoadSettingsReadsGoValidation`, `TestLoadSettingsPreservesMarkdownObjectSelection`, `TestCheckUsesSelectedRaceSuiteBeforeAdditionalChecks`, `TestCheckCapturesCandidateAndCallsAdditionalChecksOnce`, `TestCheckReturnsPublicValidationError`, `TestMarkdownValidationRunsThroughCheckAndPublish`, `TestCheckStopsBeforeProductAndBuildCallbacksWhenMarkdownBoundaryFails`, `TestCheckCommandBindsConfiguredChecksToCapturedCandidate`, `TestPublishCommandPublishesConfiguredCandidate`, `TestCandidateCommandsPresentValidationDiagnosticsOnce`, `TestDeliverPageOnlyCreatesAndReusesRelease` |
|
||||
| Committed-file validation: formatting, workspace files, local replacements, and file size | `internal/validation`, `internal/candidate`, `releasekit.Check`, `releasekit.Publish`, CLI profile conversion | `TestCheckGoFormatUsesCapturedRegularGoBlobs`, `TestCheckWorkspaceFilesReportsCommittedBlobNames`, `TestCheckLocalReplacementsParsesCommittedModuleDeclarations`, `TestCheckLocalReplacementsFollowsCommittedModuleSymlinks`, `TestCheckFileSizeUsesStrictLimitsAndDefault`, `TestCheckFileSizeAppliesLiteralPathExclusions`, `TestCheckFileSizeUsesCommittedBlobSizes`, `TestCheckFileSizeUsesOnlyCandidateFilesIndividually` |
|
||||
| Internal Markdown parsing, committed destinations, fragments, boundary observations, and public selection | `releasekit.Check`, `releasekit.Publish`, `internal/candidate`, `internal/validation`, `cmd/releasekit/internal/cli` | `TestParseMarkdownLinksAndSourceLocations`, `TestParseMarkdownDecodesEntitiesInDestinations`, `TestParseMarkdownHeadingAnchors`, `TestMarkdownCacheKeepsParsedDocumentsPerCandidatePath`, `TestCheckMarkdownLinksResolvesCommittedDestinationsAndFragments`, `TestCheckMarkdownLinksReportsMissingPathsAnchorsAndCycles`, `TestCheckMarkdownLinksUsesResolvedMarkdownIdentity`, `TestCheckMarkdownLinksReportsBoundaryAndSubmoduleObservations`, `TestCheckMarkdownLinksPreservesResolverCauseAndCancellation`, `TestCheckMarkdownLinksPreservesAnchorReadCause`, `TestRunSelectsMarkdownWithCombinedGoChecksAndReportsOutOfScopeLinks`, `TestMarkdownValidationRunsThroughCheckAndPublish`, `TestLoadSettingsPreservesMarkdownObjectSelection`, `TestValidationSpecPreservesMarkdownObjectSelection` |
|
||||
| Shared Go settings for validation and builds | `internal/gotool`, `internal/process`, `internal/candidate`, `internal/build` | `TestDefaultValidationDoesNotInheritGOFLAGSRunFilter`, `TestNativeAndStaticCommandsUseOwnedBaseline`, `TestPersistentSettingsPreserveCachesAndNativeCTools`, `TestBuildIgnoresAmbientAndPersistentArchitectureTuning` |
|
||||
| Internal Markdown parsing, committed destinations, fragments, boundary observations, and public selection | `releasekit.Check`, `releasekit.Publish`, `internal/candidate`, `internal/validation`, `cmd/releasekit/internal/cli` | `TestParseMarkdownLinksAndSourceLocations`, `TestParseMarkdownDecodesEntitiesInDestinations`, `TestParseMarkdownHeadingAnchors`, `TestMarkdownDocumentsParseIdenticalAndDistinctBlobs`, `TestCheckMarkdownLinksResolvesCommittedDestinationsAndFragments`, `TestCheckMarkdownLinksReportsMissingPathsAnchorsAndCycles`, `TestCheckMarkdownLinksUsesResolvedMarkdownIdentity`, `TestCheckMarkdownLinksReportsBoundaryAndSubmoduleObservations`, `TestCheckMarkdownLinksPreservesResolverCauseAndCancellation`, `TestCheckMarkdownLinksPreservesAnchorReadCause`, `TestRunSelectsMarkdownWithCombinedGoChecksAndReportsOutOfScopeLinks`, `TestMarkdownValidationRunsThroughCheckAndPublish`, `TestLoadSettingsPreservesMarkdownObjectSelection`, `TestValidationSpecPreservesMarkdownObjectSelection` |
|
||||
| Shared Go settings for validation and builds | `internal/gotool`, `internal/process`, `internal/candidate`, `internal/build` | `TestDefaultValidationDoesNotInheritGOFLAGSRunFilter`, `TestNativeAndStaticCommandsUseOwnedBaseline`, `TestPersistentSettingsPreserveCachesAndNativeCTools`, `TestOwnerReusesSettingsUntilInheritedEnvironmentChanges`, `TestOwnerRefreshesWhenPersistentSettingsChange`, `TestCheckSharesGoDiscoveryWithAfterValidateCallback`, `TestCheckBuildsAfterValidationAndKeepsOutputOutsideWorktree`, `TestRunValidatesOnlyTheSelectedModule`, `TestBuildIgnoresAmbientAndPersistentArchitectureTuning` |
|
||||
| Batched local Git blob reads | `internal/git`, `internal/process` | `TestBlobReaderReadsLooseAndPackedObjects`, `TestBlobReaderMissingObjectKeepsBatchSessionUsable`, `TestCandidateObjectReadsStayLocalInPartialClones` |
|
||||
| Piped child-process exchanges and cancellation cleanup | `internal/process` | `TestStartPipedExchangesBeforeInputEOFAndPreservesSettings`, `TestStartPipedCancellationAfterReadinessReapsChild`, `TestStartPipedPreservesNonzeroExit` |
|
||||
| Authoritative endpoint and exact annotated tag publication | `releasekit.Publish`, `internal/publish`, `internal/git` | `TestPublishPushesOnlyTheCapturedAnnotatedTag`, `TestPublishRejectsUnexpectedPushURLBeforeValidation`, `TestPublishComparesExpectedURLWithResolvedInsteadOfDestination`, `TestPublishExpectedPushURLUsesPushURLWhenFetchAndPushDiffer`, `TestCheckIgnoresExpectedPushURL`, `TestResolveUsesPushURLAndQueriesWithoutMutation` |
|
||||
| Publication partial and uncertain recovery | `internal/publish`, `internal/git` | `TestPublishRejectedPushKeepsLocalTagAndReportsNotPublished`, `TestPublishLostAcknowledgmentConfirmsExactRemoteObject`, `TestPublishLostAcknowledgmentWithChangedEndpointRemainsUnknown`, `TestPublishUnavailableReconciliationRemainsUnknownAndPreservesPushError` |
|
||||
| Cross-builds, version smoke checks, empty target sets, and partial outputs | `releasekit.Build`, `internal/build`, `buildinfo` | `TestBuildCreatesSelectedTargetsAndInjectsVersion`, `TestBuildWithNoTargetsDoesNotInvokeCompiler`, `TestBuildReturnsPartialArtifactsAfterTargetFailure` |
|
||||
| Page-only and managed or prebuilt binary delivery | `releasekit.Deliver`, `internal/delivery`, `internal/gitea`, CLI | `TestDeliverPageOnlySkipsBuildAndHostedAssets`, `TestDeliverManagedBuildUploadsArtifactsAndCleansTemporaryOutput`, `TestDeliverBinaryConsumerWithBuildinfoAndSelectedTargets`, `TestDeliverPrebuiltArtifactsRemainCallerOwned`, `TestDeliverRejectsSameSizePrebuiltTamperingBeforeHostedWrites`, `TestDeliverManagedBuildFailureCleansTemporaryOutputBeforeHostedWrites`, `TestDeliverManagedBuildCancellationCleansTemporaryOutput`, `TestDeliverBuildsTaggedArtifactsAndReusesAssets`, `TestDeliverRejectsTamperedAssetsAndStaleReceiptBeforeRemoteWrites` |
|
||||
| Tagged checkout and build dependency preparation | `releasekit.PrepareTaggedCheckout`, `releasekit.PrepareBuildDependencies`, `internal/preparation`, `internal/git`, `internal/gotool` | `TestPrepareTaggedCheckoutFetchesExpectedCommitAndDetaches`, `TestPrepareTaggedCheckoutRejectsWrongCommitBeforeCheckout`, `TestPrepareTaggedCheckoutReportsLocalCheckoutConflict`, `TestPrepareTaggedCheckoutReportsConflictingLocalTag`, `TestPrepareBuildDependenciesPreservesPreparationEnvironment`, `TestPrepareBuildDependenciesPropagatesCommandFailure`, `TestPrepareBuildDependenciesPropagatesCancellation` |
|
||||
| Page, manifest, asset comparison, and additive retry outcomes | `internal/gitea` | `TestEnsureReleaseCreatesMissingPageFromCommittedNote`, `TestInspectAssetsDetectsSameNameAndSizeWithDifferentBytes`, `TestUploadMissingPartialFailureThenRerunOnlyMissingAssets` |
|
||||
| CLI profiles and prepared Woodpecker sequences | `cmd/releasekit`, `cmd/releasekit/internal/cli`, `examples/woodpecker/` | `TestLoadSettingsRejectsInvalidProfiles`, `TestWoodpeckerTagDeliveryTemplate`, `TestWoodpeckerTagDeliveryUsesTaggedModuleVersion`, `TestWoodpeckerSourceDeliveryTemplateSelfBootstraps`, `TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout` |
|
||||
| Saved attempt recording, discovery, explicit later reconciliation, and read-only recovery | `releasekit`, `internal/publish`, `internal/git`, `cmd/releasekit` | `TestLostPublicationOutputCanBeRecoveredFromExplicitRecords`, `TestBuiltPublishRecoveryCommandSelectsItsRecordAmongOtherAttempts`, `TestRecoveryFacadeLoadsPartialEvidenceAndPreservesCause`, `TestRecoveryFacadeErrorUnwrapsCancellation`, `TestListPublicationAttemptsReadsExplicitExternalStore` |
|
||||
| Cross-builds, version smoke checks, module paths, empty target sets, and partial outputs | `releasekit.Build`, `internal/build`, `internal/artifact`, `internal/tempdir`, `buildinfo` | `TestBuildCreatesSelectedTargetsAndInjectsVersion`, `TestBuildUsesNestedWorkingTreeModuleAndModuleRelativeOutput`, `TestBuildResolvesDirtyWorkingTreeDeclaration`, `TestBuildWithNoTargetsDoesNotInvokeCompiler`, `TestBuildReturnsPartialArtifactsAfterTargetFailure`, `TestNormalizeSettingsKeepsBuildInputsAndNormalizesTargets`, `TestOutsideFallsBackWhenTemporaryDirectoryIsInsideWorktree` |
|
||||
| Explicit destination selection, standalone and automatic preflight, and delivery ordering | `releasekit`, `internal/delivery`, `internal/gitea`, CLI | `TestDeliveryForgeSelectionIsExplicit`, `TestPreflightDeliveryChecksAuthenticatedRepositoryWithoutCheckout`, `TestPreflightDeliveryPreservesPublicFailureKindsAndCauses`, `TestAutomaticPreflightFailurePrecedesPrebuiltArtifactHashing`, `TestDeliverUnavailablePreflightStopsBeforeManagedBuild`, `TestCIDeliverUnavailablePreflightStopsBeforeDependencyPreparation`, `TestCIDeliverPageOnlyReportsUnavailablePreflightWithStatusOne` |
|
||||
| Page-only and managed or prebuilt binary delivery | `releasekit.Deliver`, `internal/delivery`, `internal/gitea`, CLI | `TestDeliverPageOnlySkipsBuildAndHostedAssets`, `TestDeliverUsesCommittedModuleIdentityForSeparatePages`, `TestDeliverRejectsPrebuiltArtifactsForAnotherModuleBeforeHostedRequests`, `TestDeliverManagedBuildUploadsArtifactsAndCleansTemporaryOutput`, `TestDeliverBinaryConsumerWithBuildinfoAndSelectedTargets`, `TestDeliverPrebuiltArtifactsRemainCallerOwned`, `TestDeliverRejectsSameSizePrebuiltTamperingBeforeHostedWrites`, `TestDeliverManagedBuildFailureCleansTemporaryOutputBeforeHostedWrites`, `TestDeliverManagedBuildCancellationCleansTemporaryOutput`, `TestDeliverBuildsTaggedArtifactsAndReusesAssets`, `TestDeliverRejectsTamperedAssetsAndStaleReceiptBeforeRemoteWrites` |
|
||||
| Tagged checkout and build dependency preparation | `releasekit.PrepareTaggedCheckout`, `releasekit.PrepareBuildDependencies`, `internal/preparation`, `internal/git`, `internal/gotool` | `TestPrepareTaggedCheckoutFetchesExpectedCommitAndDetaches`, `TestPrepareTaggedCheckoutRejectsWrongCommitBeforeCheckout`, `TestPrepareTaggedCheckoutReportsLocalCheckoutConflict`, `TestPrepareTaggedCheckoutReportsConflictingLocalTag`, `TestPrepareBuildDependenciesUsesSelectedModuleDirectory`, `TestPrepareBuildDependenciesPreservesPreparationEnvironment`, `TestPrepareBuildDependenciesPropagatesCommandFailure`, `TestPrepareBuildDependenciesPropagatesCancellation` |
|
||||
| Shared module identity and tag derivation | `internal/releaseidentity`, `internal/candidate`, `internal/build`, `internal/delivery` | `TestDeriveUsesModuleDeclarationAndPhysicalLayout`, `TestCommittedAndWorkingTreeDeclarationsUseTheirOwnSources`, `TestSelectedNestedModuleDoesNotRequireRootDeclaration`, `TestBuildResolvesDirtyWorkingTreeDeclaration`, `TestDeliverUsesCommittedModuleIdentityForSeparatePages` |
|
||||
| Shared page, manifest, asset comparison, and additive retry policy | `internal/delivery` | `TestCoordinateReleaseCreatesWithFullNoteAndVerifiesRequestedTitle`, `TestCoordinateReleaseReconcilesCreateOutcomes`, `TestInspectRemoteAssetsComparesContentAndPreservesUnrelatedAssets`, `TestUploadMissingAssetsReconcilesOnceAndKeepsLaterAssetsPending` |
|
||||
| CLI profiles and prepared Woodpecker sequences | `cmd/releasekit`, `cmd/releasekit/internal/cli`, `examples/woodpecker/`, `examples/multi-module/` | `TestLoadSettingsRejectsInvalidProfiles`, `TestWoodpeckerTagDeliveryTemplate`, `TestWoodpeckerTagDeliveryUsesTaggedModuleVersion`, `TestWoodpeckerSourceDeliveryTemplateSelfBootstraps`, `TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout`, `TestMultiModuleSelectorMapsSelectorsAndTags`, `TestMultiModuleLauncherUsesSelectedModuleAndProfile`, `TestMultiModuleWoodpeckerDelivery` |
|
||||
|
||||
Run the complete suite with `go test ./...`. The public API and import boundary
|
||||
check is `go run ./internal/apicheck`. Local HTTP and Git fixtures exercise
|
||||
|
||||
@@ -8,30 +8,50 @@ post-validation build callback and local-state recheck. `internal/publish`
|
||||
adds its endpoint guards, tag creation, push, and recovery around that same
|
||||
candidate path.
|
||||
|
||||
The executor runs one offline Go suite, optionally with the race detector when
|
||||
selected. When full vet is selected, it disables test-time vet for that suite
|
||||
and runs native `go vet -mod=readonly ./...` after the suite succeeds. It then
|
||||
runs `go build -mod=readonly -o <os.DevNull> ./...` in static mode for each
|
||||
selected package-compilation target, preserving target order and stopping on
|
||||
the first failure. This compiles source without producing an artifact or
|
||||
executing a target binary. Test, vet, and package-compilation failures retain
|
||||
their `go-test`, `go-vet`, and `package-compile` identities, selected target
|
||||
where applicable, and underlying causes. Its
|
||||
The executor runs one offline Go suite from the captured module directory,
|
||||
optionally with the race detector when selected. When full vet is selected, it
|
||||
disables test-time vet for that suite and runs native
|
||||
`go vet -mod=readonly ./...` from the same directory after the suite succeeds.
|
||||
It then runs `go build -mod=readonly -o <os.DevNull> ./...` there in static mode
|
||||
for each selected package-compilation target, preserving target order and
|
||||
stopping on the first failure. This compiles source without producing an
|
||||
artifact or executing a target binary. Test, vet, and package-compilation
|
||||
failures retain their `go-test`, `go-vet`, and `package-compile` identities,
|
||||
selected target where applicable, and underlying causes. Its
|
||||
request carries the captured repository directory and commit, output writer,
|
||||
and internal settings. When selected, the Go-format check loads the candidate
|
||||
tree once, reads regular Go blobs from the captured commit, and compares them
|
||||
with go/format output. It includes vendor and nested-module files, skips
|
||||
symlink blobs, reports all unformatted paths, and stops with a contextual cause
|
||||
and internal settings. The Go commands run before the committed-tree sequence,
|
||||
which owns its reader's lifetime and close-error attribution. When selected,
|
||||
the Go-format check loads the candidate tree once, reads regular Go blobs from
|
||||
the captured commit, and compares them with go/format output. It uses the
|
||||
selected inputs, including vendor and explicit shared files, skips symlink
|
||||
blobs, reports all unformatted paths, and stops with a contextual cause
|
||||
on parse or inspection errors. It runs before product checks and build callbacks.
|
||||
`Request.ReadCandidateTree` lets selected file checks request candidate
|
||||
contents; the Go-only path does not enumerate the tree.
|
||||
|
||||
## Selected validation inputs
|
||||
|
||||
`CandidateTree` keeps the full committed repository lookup separate from the
|
||||
ordered file input set. The selected module's committed inputs
|
||||
exclude independently released nested modules, while vendored contents stay
|
||||
in scope. Selection indexes boundary directories once and checks each entry's
|
||||
ancestors, so unrelated boundaries are not scanned for each file. The
|
||||
[scope benchmark](../../internal/validation/scope_performance_test.go) varies
|
||||
boundary count while retaining 20,000 input files.
|
||||
Explicit shared-file selections are normalized from repository-root
|
||||
paths, added as individual files, and deduplicated with module inputs by path.
|
||||
File-size exclusions are normalized from the selected module directory. Link
|
||||
resolution can still inspect a committed destination outside the selected input
|
||||
set without adding that destination's content to the checks. The public
|
||||
selection, nil/empty behavior, and profile path bases belong to the
|
||||
[configuration reference](../config.md) and the root facade's GoDoc.
|
||||
|
||||
The workspace-file check uses that same candidate inventory and reports blob
|
||||
entries named go.work or go.work.sum, including nested paths and symlink blobs.
|
||||
It does not read workspace contents or depend on the workspace selected for Go
|
||||
commands.
|
||||
The local-replacement check parses every committed go.mod blob with
|
||||
`golang.org/x/mod/modfile`, including nested modules and vendor declarations.
|
||||
The local-replacement check parses selected go.mod blobs with
|
||||
`golang.org/x/mod/modfile`, including vendor and explicitly shared declarations.
|
||||
It follows committed symlink declarations through the captured tree and fails
|
||||
with an inspection cause when their selected contents are unavailable. A
|
||||
replacement with no parsed version is reported with its go.mod path, line,
|
||||
@@ -40,22 +60,28 @@ workspace-file check using the same candidate inventory. Resolved module bodies
|
||||
are parsed once per blob object ID; only owned filesystem-replacement targets
|
||||
and line numbers remain cached. Each declaration path receives findings from
|
||||
that summary in its own path context.
|
||||
The optional file-size check uses each blob's captured Git size, including
|
||||
symlink link-text bytes, and skips entries without a blob size such as gitlinks.
|
||||
It applies normalized literal file/directory exclusions with path-boundary
|
||||
matching, then returns the first oversized path with `FileSizeMeasurement`.
|
||||
The optional forbidden-file check uses the captured tree's full path lookup
|
||||
before the other file checks. It normalizes the explicitly selected
|
||||
repository-relative names and reports matching entries through `forbidden-files`
|
||||
without loading their blobs. Candidate-tree cleanup covers this failure path.
|
||||
The optional file-size check applies normalized literal file/directory
|
||||
exclusions with path-boundary matching, then requests local Git sizes for the
|
||||
remaining selected blobs. Sizes include symlink link-text bytes; gitlinks are
|
||||
omitted. The check returns the first oversized path with `FileSizeMeasurement`.
|
||||
The optional Markdown check follows file-size inspection and uses the same
|
||||
candidate tree. It parses regular Markdown blobs, resolves local destinations,
|
||||
and checks supported anchors; outside-checkout and submodule observations are
|
||||
written to the shared output writer. A nil writer keeps library use quiet.
|
||||
`CandidateTree` gets metadata and bytes from Git objects, reads blob bytes
|
||||
lazily, and resolves destinations without consulting the worktree or
|
||||
neighboring files. Each tree owns one lazy Git blob reader; direct tree users
|
||||
must close it when finished. The shared validation executor closes its tree on
|
||||
every return before product checks or build callbacks run. A metadata-only
|
||||
selection never starts the reader. Per-read contexts cancel an in-flight blob
|
||||
exchange. The context supplied when creating the tree governs the reader
|
||||
lifetime, including shutdown and child reaping.
|
||||
`CandidateTree` enumerates full repository path, type, mode, and object metadata
|
||||
without requiring blob contents or sizes. Checks acquire sizes and bytes for
|
||||
their selected inputs and required references. Unreferenced blobs in excluded
|
||||
modules remain outside those reads. Destinations resolve without consulting
|
||||
the worktree or neighboring files. Each tree owns one lazy Git blob reader;
|
||||
direct tree users must close it when finished. The shared validation executor
|
||||
closes its tree on every return before product checks or build callbacks run.
|
||||
A metadata-only selection never starts the reader. Per-read contexts cancel
|
||||
an in-flight blob exchange. The context supplied when creating the tree governs
|
||||
the reader lifetime, including shutdown and child reaping.
|
||||
Regular-file reads return independent caller-owned byte slices and are not
|
||||
retained by the tree. Symlink targets are retained as immutable owned strings
|
||||
by blob object ID; explicitly reading a symlink still returns independent
|
||||
@@ -84,10 +110,13 @@ observations remain out of scope under either setting. Observations go to the
|
||||
provided writer; a nil writer keeps library use quiet. Public selection is
|
||||
defined in the [configuration reference](../config.md) and GoDoc.
|
||||
|
||||
Committed-tree metadata and blob reads disable lazy fetching and Git transports
|
||||
for those child commands. Missing local objects produce inspection errors;
|
||||
source preparation retains its separate network-capable operations. See Git's
|
||||
ReleaseKit-owned Git commands inspect original objects even when replacement
|
||||
refs exist. Committed-tree metadata and blob reads also disable lazy fetching
|
||||
and Git transports for those child commands. Missing local objects produce
|
||||
inspection errors; source preparation retains its separate network-capable
|
||||
operations. See Git's
|
||||
[lazy-fetch controls](https://git-scm.com/docs/git) for the command mechanism.
|
||||
Candidate and delivery release-note reads use the same local object boundary.
|
||||
|
||||
Public validation errors convert their diagnostic fields to the internal
|
||||
failure model for shared formatting. Converted failures retain their original
|
||||
@@ -149,7 +178,8 @@ directories, missing paths, checkout boundaries, submodule paths, and symlink
|
||||
cycles; the caller selects which observations fail validation or are reported
|
||||
as out of scope.
|
||||
|
||||
Resolution walks committed components and symlink targets in order. Active
|
||||
The shared Git path resolver walks committed components and symlink targets
|
||||
in order using the tree's indexed metadata and lazy symlink reader. Active
|
||||
symlink expansion detects cycles, and traversal honors cancellation. Absolute
|
||||
destinations and symlink targets within the repository directory map back to
|
||||
candidate-relative paths; existence still comes from committed entries.
|
||||
|
||||
@@ -2,28 +2,30 @@
|
||||
|
||||
## 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.
|
||||
|
||||
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
|
||||
|
||||
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.
|
||||
|
||||
SPDX-License-Identifier: MIT
|
||||
|
||||
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
|
||||
|
||||
|
||||
@@ -77,6 +77,17 @@ and orchestration bookkeeping belong behind that boundary. Additional public
|
||||
packages and extension interfaces require a deliberate decision grounded in a
|
||||
durable consumer need.
|
||||
|
||||
Hosted delivery follows a neutral internal contract. The root facade selects a
|
||||
backend explicitly and constructs it; `internal/forge` defines the backend
|
||||
operations and neutral observations, failures, and write evidence;
|
||||
`internal/delivery` owns shared page and asset policy; and `internal/gitea`
|
||||
adapts the Gitea protocol. `internal/delivery`, `internal/forge`, and
|
||||
`internal/artifact` must not depend on the Gitea adapter. Artifact declaration
|
||||
and local content verification remain independent of delivery policy and forge
|
||||
protocols. The compiled dependency check protects this transitive boundary.
|
||||
See [ADR 0006](../adr/0006-neutral-forge-delivery-and-preflight.md) for the
|
||||
selected delivery and preflight design.
|
||||
|
||||
Go declarations and GoDoc own exact API contracts. Compiled-export checks,
|
||||
dependency checks, and external-package behavioral tests protect the selected
|
||||
facade boundaries.
|
||||
|
||||
188
docs/release.md
188
docs/release.md
@@ -1,18 +1,36 @@
|
||||
# ReleaseKit release procedure
|
||||
|
||||
ReleaseKit's deliverables are its source tag and a hosted Gitea page containing
|
||||
the complete checked-in release note. The page is delivered asynchronously by
|
||||
the prepared [Woodpecker workflow](../examples/woodpecker/releasekit-source-delivery.yml);
|
||||
it is not a source-release completion check and carries no binary assets. The
|
||||
authoritative repository is `origin` at
|
||||
`https://gitea.maximumdirect.net/eric/ReleaseKit.git`, and the release branch
|
||||
is `main`. A release completes when the intended annotated tag is successfully
|
||||
the complete checked-in release note. Deliver the page locally after publication
|
||||
or asynchronously through the prepared
|
||||
[Woodpecker workflow](../examples/woodpecker/releasekit-source-delivery.yml).
|
||||
Hosted-page delivery has a separate status from source-release completion and
|
||||
carries no binary assets. The authoritative repository is `origin` at
|
||||
`ssh://git@forge.maximumdirect.net:22222/base-layer/releasekit.git`, and the release
|
||||
branch is `main`. The hosted Gitea destination is
|
||||
`https://forge.maximumdirect.net/base-layer/releasekit`. A release completes
|
||||
when the intended annotated tag is successfully
|
||||
pushed, or when one exact-object recovery query confirms that the push
|
||||
succeeded. CI and consumer installation are not completion checks.
|
||||
|
||||
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
|
||||
|
||||
Use a clean clone on `main`. The chosen build toolchain is Go 1.26.8. Make that
|
||||
For local hosted-page delivery, save a Gitea personal access token in
|
||||
`.releasekit/gitea-token` with owner-only file permissions. The file contains
|
||||
only the token. ReleaseKit's profile selects this file for local delivery and
|
||||
`RELEASEKIT_GITEA_TOKEN` for CI; `.releasekit/` is already ignored. Its optional
|
||||
`validation.forbidden_files` selection checks that this path is absent from the
|
||||
committed candidate. Source publication requires no delivery token. The
|
||||
[configuration reference](config.md) owns credential selection and validator
|
||||
semantics.
|
||||
|
||||
Use a clean clone on `main`. The chosen build toolchain is Go 1.27.4. Make that
|
||||
local installation the active `go` command for preparation, building the release
|
||||
executable, and candidate validation:
|
||||
|
||||
@@ -28,16 +46,12 @@ The maintained [source-delivery image](../examples/woodpecker/releasekit-source-
|
||||
and [consumer template image](../examples/woodpecker/tag-delivery.yml) follow the
|
||||
chosen build toolchain; update them together when that selection changes.
|
||||
|
||||
The current consumer minimum is declared in [go.mod](../go.mod). When preparing
|
||||
a release that raises it to Go 1.26, the normal declaration is:
|
||||
|
||||
```sh
|
||||
go mod edit -go=1.26.0
|
||||
```
|
||||
|
||||
Retain any higher patch minimum required by dependencies or a specific fix.
|
||||
Make module changes before committing the candidate. A release preserving the
|
||||
existing minimum keeps its current declaration. Minimum increases must fit the
|
||||
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
|
||||
series under the [Go support policy](policy/release.md#consumer-minimum-and-release-toolchain).
|
||||
When increasing it, update `go.mod` to the first stable version of the selected
|
||||
series, or to a higher patch when a dependency or specific fix requires one.
|
||||
Make module changes before committing the candidate. Minimum increases must fit the
|
||||
[compatibility policy](policy/release.md#versioning-and-compatibility); before
|
||||
v1.0.0, an increase belongs in a minor release.
|
||||
|
||||
@@ -47,9 +61,9 @@ the exact version. Summarize the change and any compatibility or upgrade impact.
|
||||
End the note with the three license links at the immutable source tag:
|
||||
|
||||
```markdown
|
||||
[COPYRIGHT](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/vX.Y.Z/COPYRIGHT) |
|
||||
[LICENSE](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/vX.Y.Z/LICENSE) |
|
||||
[ATTRIBUTION](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/vX.Y.Z/docs/oss/attribution.md)
|
||||
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/vX.Y.Z/COPYRIGHT) |
|
||||
[LICENSE](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/vX.Y.Z/LICENSE) |
|
||||
[ATTRIBUTION](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/vX.Y.Z/docs/oss/attribution.md)
|
||||
```
|
||||
|
||||
Replace every `vX.Y.Z` with the selected version. These are links to the same
|
||||
@@ -100,59 +114,119 @@ for ReleaseKit's first release before any released ReleaseKit executable
|
||||
exists. It uses the local Go toolchain. Preparation must finish before the
|
||||
offline validation begins.
|
||||
|
||||
## Resolve failures
|
||||
## Deliver the hosted release page
|
||||
|
||||
A failed push triggers a URL-resolution check against the captured endpoint,
|
||||
then at most one exact authoritative tag query. If the endpoint no longer
|
||||
resolves to itself, recovery reports `unknown` without querying the rewritten
|
||||
destination. An exact tag-object match confirms publication even when Git
|
||||
reported an error. A proven absent tag is `not_published`; a different object
|
||||
is a conflict; an unreadable query is `unknown`. The command retains its local
|
||||
tag and reports the state, phase,
|
||||
candidate commit, tag object, and captured publication endpoint when available.
|
||||
Do not retry an unknown result until you resolve the authoritative ref at that
|
||||
exact endpoint. Copy the reported endpoint value into the variable below using
|
||||
normal shell quoting; retain the version and tag object from the same result.
|
||||
The command checks that Git URL rewriting still resolves this value to itself;
|
||||
the manual check below applies the same rule before querying:
|
||||
After source publication succeeds, deliver the hosted page locally when
|
||||
Woodpecker automation is inactive. From the same repository root, keep the
|
||||
worktree clean and `HEAD` at the published tag's commit. Reuse the executable
|
||||
built by the publication command:
|
||||
|
||||
```sh
|
||||
releasekit_endpoint='COPY_CAPTURED_ENDPOINT'
|
||||
releasekit_version='vX.Y.Z'
|
||||
test "$(git ls-remote --get-url -- "$releasekit_endpoint")" = "$releasekit_endpoint" &&
|
||||
git ls-remote --refs -- "$releasekit_endpoint" "refs/tags/$releasekit_version"
|
||||
.releasekit/bin/releasekit deliver vX.Y.Z
|
||||
```
|
||||
|
||||
A failed URL-equality check or remote query leaves the outcome unresolved.
|
||||
Correct transport configuration before continuing. The reported endpoint may
|
||||
be different from `origin`'s fetch URL or its current push URL; querying either
|
||||
of those does not establish absence at the captured endpoint.
|
||||
The command uses the configured Gitea destination and token source to deliver
|
||||
the complete checked-in release note. Report its result separately from the
|
||||
completed source release. For failed or uncertain delivery, follow the recovery
|
||||
instructions below using the same immutable version.
|
||||
|
||||
Compare the returned object ID with the tag object reported by the command.
|
||||
An exact match confirms publication. If the ref is absent, the version was not
|
||||
published; only then may you deliberately remove the unpublished local tag
|
||||
with `git tag -d vX.Y.Z` before correcting the candidate or retrying. Do not
|
||||
move, overwrite, or delete a tag that exists remotely. If a different object
|
||||
uses the version, choose a new version after resolving the conflict.
|
||||
## Resolve publication failures
|
||||
|
||||
Each publication invocation attempts to save its captured identity before the
|
||||
tag push. The CLI reports the saved record path separately from publication
|
||||
success or failure and, after a push or immediate-reconciliation error, prints a
|
||||
copyable command that selects that exact record. Run that command, or use the
|
||||
source-built executable prepared above, to make a separate later observation:
|
||||
|
||||
```sh
|
||||
./.releasekit/bin/releasekit reconcile --record '/absolute/path/to/attempt-record.json'
|
||||
```
|
||||
|
||||
The saved evidence fixes the original endpoint and tag identity. Later recovery
|
||||
uses current supported transport settings for the recorded remote name, but it
|
||||
does not substitute the current remote URL, inspect the local tag or current
|
||||
HEAD, load a profile, rerun checks, or change repository state. A completed
|
||||
observation reports `published`, `not_published`, or `conflict`; an incomplete
|
||||
observation reports `unknown` with diagnostic context. Resolve an unknown result
|
||||
by correcting the identified endpoint rewrite, transport configuration, or
|
||||
missing evidence. For incomplete saved identity, select another record with the
|
||||
required fields or use complete typed evidence through the Go API.
|
||||
|
||||
If command output was lost, list local attempts and explicitly select the
|
||||
matching record by its module, full tag, and saved identity:
|
||||
|
||||
```sh
|
||||
./.releasekit/bin/releasekit publication-attempts --repo "$PWD"
|
||||
./.releasekit/bin/releasekit reconcile --record '/absolute/path/from-the-list/attempt-record.json'
|
||||
```
|
||||
|
||||
Discovery only reads the local store. It neither queries remotes nor chooses an
|
||||
attempt automatically. If the original recovery entry point is unavailable,
|
||||
select another supported ReleaseKit CLI and pass the same record path explicitly.
|
||||
An older record may lack the endpoint, tag-object ID, candidate commit, or
|
||||
another field required for a conclusive result.
|
||||
|
||||
A later observation that the tag is absent describes the remote at that time;
|
||||
it does not prove the version was never published. Never reuse a version known
|
||||
to have been published, and preserve published tags and contents as immutable.
|
||||
Keep removal of an unpublished local tag, candidate correction, and retry as
|
||||
explicit operator decisions after reviewing the record and authoritative
|
||||
remote state. A conflicting object requires resolving the conflict and selecting
|
||||
an unused version when appropriate; do not move, overwrite, or delete a
|
||||
published tag.
|
||||
|
||||
If record storage fails, ReleaseKit reports the recording warning separately;
|
||||
the warning does not change the actual publication outcome. The saved handoff is
|
||||
then unavailable. A Go caller that retained `PublicationResult.Evidence` can
|
||||
still pass that typed evidence directly to `ReconcilePublication`. Process
|
||||
termination before the record is written, removed storage, and older incomplete
|
||||
records can leave no sufficient saved evidence for later recovery.
|
||||
|
||||
Later reconciliation adds no successful-push read-back, polling, CI, consumer
|
||||
installation, or hosted-delivery gate. Hosted page delivery remains separate.
|
||||
|
||||
If validation or a guard fails before this invocation pushes, correct and
|
||||
commit the candidate, publish `main`, and run the command again. A retained
|
||||
local tag still requires the authoritative-state check above before removal;
|
||||
a concurrent publisher may already have published the version. The prepared
|
||||
local tag still requires reviewing the selected record and authoritative state
|
||||
before deciding whether to remove it. The prepared
|
||||
Woodpecker workflow builds the CLI from the tagged checkout, then uses
|
||||
`ci-deliver` for page-only delivery. To activate it after configuring the
|
||||
destination and secret, copy it to `.woodpecker/releasekit-source-delivery.yml`
|
||||
and add the Woodpecker repository secret `releasekit_gitea_token`. If page
|
||||
delivery fails or is uncertain, inspect the hosted release and retry the same
|
||||
immutable version from its tag:
|
||||
immutable version from its tag. The retry requires a clean tagged checkout
|
||||
before preparing or building the tool:
|
||||
|
||||
```sh
|
||||
git fetch origin "refs/tags/vX.Y.Z:refs/tags/vX.Y.Z"
|
||||
git checkout --detach "vX.Y.Z"
|
||||
GOTOOLCHAIN=local go mod download
|
||||
mkdir -p .releasekit/bin
|
||||
GOTOOLCHAIN=local GOPROXY=off GOSUMDB=off go build -o .releasekit/bin/releasekit ./cmd/releasekit
|
||||
RELEASEKIT_GITEA_TOKEN="$GITEA_TOKEN" .releasekit/bin/releasekit deliver "vX.Y.Z"
|
||||
(
|
||||
set -e
|
||||
version=vX.Y.Z
|
||||
tag_ref="refs/tags/$version"
|
||||
git fetch origin "$tag_ref:$tag_ref"
|
||||
tag_commit=$(git rev-parse --verify "$tag_ref^{commit}")
|
||||
git checkout --detach "$tag_commit"
|
||||
worktree_status=$(git status --porcelain --untracked-files=all)
|
||||
if [ -n "$worktree_status" ]; then
|
||||
printf '%s\n' 'Delivery retry requires a clean tagged checkout.' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
releasekit_host_os=$(GOTOOLCHAIN=local go env GOHOSTOS)
|
||||
releasekit_host_arch=$(GOTOOLCHAIN=local go env GOHOSTARCH)
|
||||
export GOOS="$releasekit_host_os" GOARCH="$releasekit_host_arch"
|
||||
GOTOOLCHAIN=local go mod download
|
||||
mkdir -p .releasekit/bin
|
||||
GOTOOLCHAIN=local GOPROXY=off GOSUMDB=off go build -o .releasekit/bin/releasekit ./cmd/releasekit
|
||||
.releasekit/bin/releasekit deliver "$version"
|
||||
)
|
||||
```
|
||||
|
||||
For an older tag whose CLI predates `token_file`, build the tagged executable
|
||||
as above, then supply the token through its environment variable when retrying:
|
||||
|
||||
```sh
|
||||
RELEASEKIT_GITEA_TOKEN="$(cat .releasekit/gitea-token)" \
|
||||
.releasekit/bin/releasekit deliver "vX.Y.Z"
|
||||
```
|
||||
|
||||
The root ignore file excludes `.releasekit/`. Delivery uses the committed note
|
||||
|
||||
35
docs/releases/v0.10.0.md
Normal file
35
docs/releases/v0.10.0.md
Normal 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
112
docs/releases/v0.11.0.md
Normal 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)
|
||||
141
docs/releases/v0.4.0.md
Normal file
141
docs/releases/v0.4.0.md
Normal file
@@ -0,0 +1,141 @@
|
||||
# ReleaseKit v0.4.0
|
||||
|
||||
## Summary
|
||||
|
||||
ReleaseKit supports releasing individual Go modules within a repository, with
|
||||
module-specific validation, builds, tags, and Gitea release pages. Root-module
|
||||
consumers retain the simple default configuration. This release also improves
|
||||
path resolution, offline source inspection, failure diagnostics, and efficiency.
|
||||
|
||||
## Changes
|
||||
|
||||
- `Check`, `Publish`, `Build`, and `Deliver` accept `ModuleDir` and expose the
|
||||
resolved module directory, declared module path, and complete tag in their
|
||||
results. Each operation resolves its module identity once. Product commands
|
||||
receive repository and module context, and candidate callbacks receive module
|
||||
identity.
|
||||
- Release tags follow the selected module's physical location and declared major
|
||||
version. For example, `v2.1.0` for
|
||||
`example.com/project/integrations/core/v2` uses
|
||||
`integrations/core/v2.1.0` whether its physical directory is
|
||||
`integrations/core` or `integrations/core/v2`. Its note remains at that physical
|
||||
module's `docs/releases/v2.1.0.md`. Binary version output and asset names retain
|
||||
the semantic version; Git publication and Gitea delivery use the complete tag.
|
||||
- Profiles add `module_dir`. Go checks and configured product commands run from
|
||||
the selected module. Automatic committed-file inputs stop at independent
|
||||
nested modules; vendored files remain included. Nested fixtures remain
|
||||
available to the parent module's product tests.
|
||||
- `ValidationSpec.SharedFiles` and profile `validation.shared_files` select
|
||||
repository-relative literal files for optional file checks. Omission selects
|
||||
the available root copyright, license, and attribution defaults; an explicit
|
||||
list replaces them, and an explicit empty list selects none. Explicit files
|
||||
must exist even with checks disabled. Selection preserves the enabled checks
|
||||
and Go test scope; reference inspection can read destinations elsewhere in
|
||||
the captured repository.
|
||||
- Module releases receive separate Gitea pages, including source-only modules.
|
||||
Relative build output and prebuilt delivery paths share the selected module
|
||||
as their base. Prebuilt receipts bind artifacts to module identity, semantic
|
||||
version, complete tag, source commit, and normalized build settings.
|
||||
- `ci-deliver` accepts the complete event tag. Prepared mode verifies a checkout
|
||||
already detached at that tag, and expected-module and expected-tag checks bind
|
||||
delivery to the CI selection before building or contacting Gitea. The
|
||||
multi-module example shares a module map between its local launcher and
|
||||
Woodpecker workflow. The workflow verifies the tag before reading the mapping,
|
||||
profile, or tool selection, preserving the tagged configuration for retries.
|
||||
|
||||
## Reliability and efficiency
|
||||
|
||||
- Operations resolve the containing Git checkout root when invoked from a child
|
||||
directory. Working-tree and committed module paths resolve symlinks consistently,
|
||||
including paths containing `..`. Committed identity comes from Git objects;
|
||||
page-only delivery can use committed module metadata absent from the worktree.
|
||||
Valid local main-module paths are accepted.
|
||||
- Build failures preserve available identity and settings alongside completed
|
||||
artifacts. Invalid versions retain the public error identity and the CLI's
|
||||
usage-error status. Prebuilt delivery accepts equivalent checkout paths while
|
||||
retaining source and module verification.
|
||||
- Committed release-note and validation reads remain offline in partial clones.
|
||||
Validation reads blob contents and sizes as needed for selected inputs and
|
||||
referenced destinations. Unavailable blobs outside that inspection scope do
|
||||
not prevent applicable checks.
|
||||
- Module-file selection uses ancestor boundary lookups. Operations reuse Go
|
||||
environment discovery while its inputs remain suitable for reuse and acquire
|
||||
Go settings only when Go work needs them. Delivery reuses its local asset
|
||||
verification when uploading missing assets, removing a repeated hashing pass.
|
||||
|
||||
These improvements depend on the repository and workload. Artifact verification,
|
||||
exact remote comparisons, additive retries, and partial-delivery reporting retain
|
||||
their behavior.
|
||||
|
||||
## Compatibility
|
||||
|
||||
This pre-1.0 minor release introduces a clean API and receipt cutover:
|
||||
|
||||
- `TaggedCheckoutRequest.Version` becomes `Tag`, containing the complete Git
|
||||
tag. `VerifyOnly` adds verification of an already prepared checkout.
|
||||
- `PrepareBuildDependencies` now accepts `DependencyPreparationRequest` with
|
||||
repository and module directories.
|
||||
- The private build receipt requires schema version 1 and module identity.
|
||||
Existing receipts must be regenerated before prebuilt delivery.
|
||||
- Root-module committed-file checks exclude independent nested modules. Select
|
||||
those modules separately when their files need release validation.
|
||||
|
||||
The Go minimum remains 1.26.0. Root-module releases retain their existing note
|
||||
path, unprefixed tags, profile defaults, and ordinary workflow without a module
|
||||
map. The root orchestration facade and separate lightweight `buildinfo` facade
|
||||
retain their roles; runtime version access requires no migration.
|
||||
|
||||
Source-tag publication remains the source-release completion point. Hosted page
|
||||
and asset delivery remains asynchronous and can be retried from the same
|
||||
immutable tag. ReleaseKit's deliverables remain its source tag and hosted note
|
||||
page.
|
||||
|
||||
## Upgrade guidance
|
||||
|
||||
1. Select v0.4.0 in each consumer module that uses ReleaseKit. For API consumers:
|
||||
|
||||
```sh
|
||||
go get gitea.maximumdirect.net/eric/ReleaseKit@v0.4.0
|
||||
go mod tidy
|
||||
```
|
||||
|
||||
For consumers using the CLI as a Go tool dependency:
|
||||
|
||||
```sh
|
||||
go get -tool gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit@v0.4.0
|
||||
go mod tidy
|
||||
```
|
||||
|
||||
Review and commit the resulting module and checksum changes together with
|
||||
caller, profile, and workflow updates. Keep historical tag retries paired
|
||||
with the tool and workflow recorded at that tag.
|
||||
|
||||
2. Update preparation API calls for `Tag` and `DependencyPreparationRequest`.
|
||||
For nested modules, set `ModuleDir` or profile `module_dir` to the physical
|
||||
module location, with its own `go.mod` declaration. Keep ordinary `Version`
|
||||
arguments as semantic versions. Use result `ModuleDir`, `ModulePath`, and
|
||||
`Tag` where module identity is needed. Product commands can distinguish their
|
||||
contexts through `RELEASEKIT_REPOSITORY_DIR` and `RELEASEKIT_MODULE_DIR`.
|
||||
|
||||
3. Update `ci-deliver` invocations to pass the full event tag and required
|
||||
`--commit OID`. Use `--prepared` after bootstrap verification and
|
||||
`--expected-module DIR` for mapped launchers. Prepare and commit each binary
|
||||
module's checksums before tagging so dependency preparation leaves tagged
|
||||
source clean. Root-only consumers can retain the ordinary tag workflow.
|
||||
|
||||
4. Rebuild existing prebuilt outputs with the v0.4.0 `build` command before
|
||||
`deliver --assets DIR`. Relative output and asset paths both resolve from the
|
||||
selected module. Review optional shared-file selections and nested-module
|
||||
validation coverage, then run the consumer's ordinary checks.
|
||||
|
||||
See the
|
||||
[adoption guide](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.4.0/docs/consumers/adoption.md),
|
||||
[configuration reference](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.4.0/docs/config.md),
|
||||
[CLI contract](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.4.0/docs/cli.md),
|
||||
[delivery guide](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.4.0/docs/consumers/delivery.md),
|
||||
and [multi-module example](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.4.0/examples/multi-module/README.md)
|
||||
for supported usage.
|
||||
|
||||
[COPYRIGHT](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.4.0/COPYRIGHT) |
|
||||
[LICENSE](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.4.0/LICENSE) |
|
||||
[ATTRIBUTION](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.4.0/docs/oss/attribution.md)
|
||||
29
docs/releases/v0.4.1.md
Normal file
29
docs/releases/v0.4.1.md
Normal file
@@ -0,0 +1,29 @@
|
||||
# ReleaseKit v0.4.1
|
||||
|
||||
## Summary
|
||||
|
||||
This patch synchronizes shared state in the delivery and Gitea HTTP test
|
||||
fixtures. It makes the test suite reliable under concurrent request handling
|
||||
and the Go race detector. Production code and public behavior are unchanged.
|
||||
|
||||
## Changes
|
||||
|
||||
- Protect delivery fixture state with mutexes and independent snapshots; use
|
||||
atomic observations for independent Gitea fixture counters and flags.
|
||||
- Keep fatal test assertions in the test goroutine and ensure release test
|
||||
servers close with their owning tests.
|
||||
- Preserve existing delivery, conflict, retry, and source-tag assertions while
|
||||
exercising the synchronized fixtures.
|
||||
|
||||
## Compatibility
|
||||
|
||||
There are no API, configuration, or runtime behavior changes, and no consumer
|
||||
migration is required. The Go minimum remains 1.26.0. The published v0.4.0 tag
|
||||
and its contents are unchanged.
|
||||
|
||||
Consumers may upgrade to v0.4.1 with their existing API, profile, and workflow
|
||||
configuration.
|
||||
|
||||
[COPYRIGHT](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.4.1/COPYRIGHT) |
|
||||
[LICENSE](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.4.1/LICENSE) |
|
||||
[ATTRIBUTION](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.4.1/docs/oss/attribution.md)
|
||||
36
docs/releases/v0.4.2.md
Normal file
36
docs/releases/v0.4.2.md
Normal file
@@ -0,0 +1,36 @@
|
||||
# ReleaseKit v0.4.2
|
||||
|
||||
## Summary
|
||||
|
||||
This patch corrects Woodpecker delivery bootstrap for events whose
|
||||
`CI_COMMIT_SHA` identifies an annotated tag object. The maintained workflows
|
||||
resolve the event object to its source commit before verification and delivery.
|
||||
|
||||
## Changes
|
||||
|
||||
- Correct module-selected, multi-module, and ReleaseKit source delivery
|
||||
workflows to resolve event and tag commits independently and pass the
|
||||
resolved event commit to `ci-deliver`.
|
||||
- Report both commit identities when an event and its selected tag disagree.
|
||||
- Extend executable-workflow regression coverage for annotated tag-object
|
||||
events, annotated and lightweight commit events, resolved delivery arguments,
|
||||
and rejection of unrelated commits.
|
||||
|
||||
## Compatibility and upgrade guidance
|
||||
|
||||
Public APIs, CLI contracts, configuration formats, and the Go 1.26.0 consumer
|
||||
minimum retain their v0.4 definitions. `ci-deliver --commit` continues to accept
|
||||
the expected source commit ID.
|
||||
|
||||
Update copied workflow YAML from the maintained examples when adopting this
|
||||
patch. Upgrading the ReleaseKit dependency alone leaves copied workflows
|
||||
unchanged. The [delivery guide](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.4.2/docs/consumers/delivery.md#woodpecker-tag-workflows)
|
||||
describes event resolution, workflow adoption, and delivery recovery.
|
||||
|
||||
Existing published tags and contents remain unchanged. Recover a failed older
|
||||
workflow from its original tagged source using the resolved event commit through
|
||||
the documented delivery command, preserving existing hosted content.
|
||||
|
||||
[COPYRIGHT](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.4.2/COPYRIGHT) |
|
||||
[LICENSE](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.4.2/LICENSE) |
|
||||
[ATTRIBUTION](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.4.2/docs/oss/attribution.md)
|
||||
59
docs/releases/v0.5.0.md
Normal file
59
docs/releases/v0.5.0.md
Normal file
@@ -0,0 +1,59 @@
|
||||
# ReleaseKit v0.5.0
|
||||
|
||||
## Summary
|
||||
|
||||
ReleaseKit adopts `go.maximumdirect.net/releasekit` as its Go module identifier.
|
||||
The vanity path resolves to the Gitea repository at
|
||||
`https://forge.maximumdirect.net/base-layer/releasekit`.
|
||||
|
||||
## Changes
|
||||
|
||||
- The orchestration facade is `go.maximumdirect.net/releasekit`, the runtime
|
||||
facade is `go.maximumdirect.net/releasekit/buildinfo`, and the executable
|
||||
package is `go.maximumdirect.net/releasekit/cmd/releasekit`.
|
||||
- Imports, version-injection linkage, compiled API checks, consumer fixtures,
|
||||
and maintained release launchers and Woodpecker workflows use the new module
|
||||
identity.
|
||||
- ReleaseKit's hosted-page delivery profile and maintainer guidance use Gitea
|
||||
at `forge.maximumdirect.net`, owner `base-layer`, repository `releasekit`.
|
||||
|
||||
## Compatibility
|
||||
|
||||
This pre-1.0 minor release changes package import paths and requires consumer
|
||||
migration. Facade roles, command behavior, configuration formats, and the Go
|
||||
1.26.0 consumer minimum retain their existing definitions. The runtime version
|
||||
accessor and builder use the new module's runtime implementation for injection.
|
||||
|
||||
Packages imported through different module paths have distinct Go identities.
|
||||
Coordinate import changes in packages that exchange ReleaseKit facade types,
|
||||
and update builders and applications using `buildinfo` together.
|
||||
|
||||
Published versions through v0.4.2 retain the original
|
||||
`gitea.maximumdirect.net/eric/ReleaseKit` module declaration. Those versions
|
||||
continue to describe their original source and use their matching historical
|
||||
instructions. A vanity-path download of an older tag does not change its module
|
||||
declaration.
|
||||
|
||||
## Upgrade guidance
|
||||
|
||||
1. Update application, library, test, and generated imports for the root facade
|
||||
and `buildinfo` to the new paths. Select v0.5.0 or a later compatible release
|
||||
using the [adoption guide](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.5.0/docs/consumers/adoption.md#migrating-from-the-original-module-path).
|
||||
2. For CLI tool dependencies, remove the old tool declaration and register
|
||||
`go.maximumdirect.net/releasekit/cmd/releasekit` at the selected version.
|
||||
3. Update copied launchers and Woodpecker workflows together with the module
|
||||
selection. The maintained examples use
|
||||
`releasekit_module=go.maximumdirect.net/releasekit`.
|
||||
4. Run `go mod tidy`, review any old-path dependencies retained transitively,
|
||||
and commit module and workflow changes together. Keep existing consumer tags
|
||||
intact; their delivery retries use their recorded module files and matching
|
||||
workflows.
|
||||
|
||||
Source repository and hosted release URLs use the Gitea host; Go imports and
|
||||
tool dependencies use the vanity path. ReleaseKit's source publication and
|
||||
hosted-page delivery retain their separate outcomes under the
|
||||
[maintainer procedure](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.5.0/docs/release.md).
|
||||
|
||||
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.5.0/COPYRIGHT) |
|
||||
[LICENSE](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.5.0/LICENSE) |
|
||||
[ATTRIBUTION](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.5.0/docs/oss/attribution.md)
|
||||
125
docs/releases/v0.6.0.md
Normal file
125
docs/releases/v0.6.0.md
Normal file
@@ -0,0 +1,125 @@
|
||||
# ReleaseKit v0.6.0
|
||||
|
||||
## Summary
|
||||
|
||||
ReleaseKit adds file-based delivery credentials, optional checks for forbidden
|
||||
committed files, neutral delivery coordination with explicit Gitea selection, and
|
||||
authenticated, read-only credential preflight. It also corrects dependency
|
||||
preparation, publication recovery, and build cancellation handling.
|
||||
|
||||
## Changes
|
||||
|
||||
- Delivery profiles can select a plain token file through `token_file`.
|
||||
Relative paths resolve from the checkout root; a nonblank token environment
|
||||
value takes precedence. The CLI trims file contents and reports unreadable
|
||||
or blank files as credential-loading failures. Library callers continue to
|
||||
supply the token explicitly through the destination.
|
||||
- `ValidationSpec.ForbiddenFiles` and `validation.forbidden_files` select
|
||||
literal repository-relative paths that must be absent from the committed
|
||||
candidate. This optional check can protect a local token-file path. It
|
||||
inspects committed path metadata independently of module/shared-file inputs;
|
||||
it does not inspect file contents or history.
|
||||
- `releasekit.DeliveryRequest.Destination` now uses the facade-owned
|
||||
`releasekit.DeliveryDestination`. Set `Forge: releasekit.ForgeGitea` for
|
||||
Gitea delivery. The removed `GiteaDestination` type has no compatibility
|
||||
alias.
|
||||
- Delivery profiles must include `"forge": "gitea"`. The selection is
|
||||
required only when `deliver` or `ci-deliver` is requested; the URL does not
|
||||
infer a backend. `check`, `build`, and source `publish` remain independent of
|
||||
delivery selection and credentials.
|
||||
- `releasekit.PreflightDelivery` allows callers to check a destination without
|
||||
a checkout or tag. `Deliver` performs the same read-only preflight
|
||||
automatically. For Gitea, the check authenticates through repository-scoped
|
||||
reads and makes no test release or asset writes.
|
||||
- `DeliveryPreflightError` exposes classified failures and retains the
|
||||
underlying cause. Successful preflight confirms authentication and repository
|
||||
access plus available permission evidence; it does not guarantee future
|
||||
release or asset writes. Gitea's code-push permission metadata does not
|
||||
establish release-write or asset-write permission.
|
||||
- The CLI keeps `RELEASEKIT_GITEA_TOKEN` as its default token environment
|
||||
setting and preserves configured environment/file precedence. Selection,
|
||||
local credential-loading, and classified preflight configuration/access
|
||||
errors return status 2; unavailable preflight and cancellation during
|
||||
preflight/preparation return status 1. Later authorization failures follow
|
||||
delivery outcomes. An unresolved write returns status 3, including when
|
||||
cancellation prevents reconciliation; known delivery failures return 1.
|
||||
- Binary `ci-deliver` checks credentials before application dependency
|
||||
downloads and checks again during delivery. The automatic check now precedes
|
||||
full local artifact size and digest verification; those checks still finish
|
||||
before hosted writes.
|
||||
|
||||
## Correctness and efficiency
|
||||
|
||||
- Dependency preparation now resolves the containing checkout root, including
|
||||
when called from a subdirectory or filesystem alias. `ModuleDir` is relative
|
||||
to that root, and empty selection prepares the root module. Standalone use
|
||||
retains the supplied directory as its base, including Go-only use when Git
|
||||
is unavailable. Damaged checkout metadata and operational discovery failures
|
||||
remain errors before dependency downloads.
|
||||
- Preparation overrides alternate module-file selection from inherited or
|
||||
persistent `GOFLAGS`, while retaining other effective Go settings. Downloads
|
||||
therefore use the selected module's ordinary metadata.
|
||||
- Candidate checking rejects a derived release tag that Git cannot create
|
||||
before running validation. CI delivery also validates the selected module's
|
||||
complete tag before dependency preparation.
|
||||
- Publication recovery treats a peeled-only tag observation as unresolved,
|
||||
retains the original push failure, and reports `PublicationUnknown` with CLI
|
||||
status 3. Complete tag observations retain their existing recovery behavior.
|
||||
- Cancellation and deadline expiration during build source inspection remain
|
||||
identifiable through `errors.Is`; partial results retain completed artifacts.
|
||||
Local artifact inspection errors also retain their underlying causes through
|
||||
delivery.
|
||||
- Gitea asset operations classify a missing or nonpositive service release ID
|
||||
as a malformed observation before making an asset request. Page-only release
|
||||
lookup retains its existing minimal response requirements.
|
||||
- Asset delivery uses linear pending-asset bookkeeping and sorts only missing
|
||||
assets once, reducing repeated work during uploads and reconciliation.
|
||||
|
||||
## Compatibility
|
||||
|
||||
This pre-1.0 minor release changes the public destination type and requires
|
||||
explicit forge selection for delivery. Gitea is the supported backend.
|
||||
Preparation callers that previously used a checkout subdirectory as their
|
||||
implicit module selection must now select that module with `ModuleDir`.
|
||||
Ambient `GOFLAGS` no longer redirects preparation to an alternate module file.
|
||||
|
||||
The module identifier remains `go.maximumdirect.net/releasekit`, and the Go
|
||||
consumer minimum remains 1.26.0. Receipt schemas and the separate source
|
||||
publication and hosted-delivery outcomes retain their existing definitions.
|
||||
|
||||
## Upgrade guidance
|
||||
|
||||
Select v0.6.0 for library and CLI dependencies, then update integrations as
|
||||
follows:
|
||||
|
||||
1. Replace `releasekit.GiteaDestination` with
|
||||
`releasekit.DeliveryDestination` and set
|
||||
`Forge: releasekit.ForgeGitea` in each API request.
|
||||
2. Add `"forge": "gitea"` to every profile used for `deliver` or
|
||||
`ci-deliver`, including profiles loaded from a tagged CI checkout. Keep the
|
||||
existing `base_url`, owner, repository, token environment, and token file
|
||||
settings.
|
||||
3. If handling preflight failures in Go, use `errors.As` to inspect
|
||||
`*releasekit.DeliveryPreflightError` and use `errors.Is` or `errors.As` on
|
||||
its unwrapped cause as needed.
|
||||
4. Continue to treat successful preflight as evidence of repository access,
|
||||
not a guarantee that a later write will be accepted. Source publication
|
||||
continues to use Git authentication and does not require hosted delivery
|
||||
credentials.
|
||||
5. For dependency preparation of a nested module, supply its repository-relative
|
||||
path through `DependencyPreparationRequest.ModuleDir`, even when
|
||||
`RepositoryDir` already points inside that module. Root-module consumers can
|
||||
keep `ModuleDir` empty.
|
||||
6. To adopt file-based credentials, store the token in an ignored local file
|
||||
and configure `delivery.token_file`. Optionally add that same
|
||||
repository-relative path to `validation.forbidden_files`. Credential loading
|
||||
and candidate file validation are independent selections; configuring the
|
||||
file alone does not enable the validator.
|
||||
|
||||
See the [delivery guide](../consumers/delivery.md), [configuration reference](../config.md),
|
||||
[CLI contract](../cli.md), and [Gitea integration guide](../integrations/gitea.md)
|
||||
for current behavior.
|
||||
|
||||
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.6.0/COPYRIGHT) |
|
||||
[LICENSE](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.6.0/LICENSE) |
|
||||
[ATTRIBUTION](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.6.0/docs/oss/attribution.md)
|
||||
106
docs/releases/v0.7.0.md
Normal file
106
docs/releases/v0.7.0.md
Normal file
@@ -0,0 +1,106 @@
|
||||
# ReleaseKit v0.7.0
|
||||
|
||||
## Summary
|
||||
|
||||
ReleaseKit improves source-publication integrity, cancellation, credential-safe
|
||||
diagnostics, partial-result reporting, and temporary-file cleanup. It also bounds
|
||||
retained Go failure diagnostics and remote attachment comparison work while
|
||||
preserving the existing public facades and configuration formats.
|
||||
|
||||
## Publication and Git operations
|
||||
|
||||
- Exact tag pushes disable submodule recursion, correcting inherited
|
||||
`push.recurseSubmodules=only` settings that could report success without
|
||||
publishing the release tag.
|
||||
- ReleaseKit-owned Git inspection and preparation use original objects when
|
||||
replacement refs exist. Committed module identity, release notes, validation
|
||||
inputs, and build source eligibility use that consistent view. Ordinary dirty
|
||||
builds remain supported, with their source eligibility reported separately.
|
||||
- A verified local tag object remains available in `PublicationResult.TagObject`
|
||||
when later inspection fails. Errors identify a possibly retained local ref
|
||||
when its object ID could not be established. Failed verification stops before
|
||||
a push.
|
||||
- HTTP(S) userinfo is masked in owned Git diagnostics and CLI output, including
|
||||
literal apostrophes in credentials and failed CI checkout preparation. Native
|
||||
Git authentication, exact endpoint comparisons, and the raw captured
|
||||
`PublicationResult.Endpoint` value retain their existing behavior.
|
||||
- Child environment overlays preserve the working-directory-derived `PWD` on
|
||||
POSIX systems. Native Git hooks now receive the expected directory environment
|
||||
when ReleaseKit is invoked from another checkout or module subdirectory.
|
||||
|
||||
## Cancellation and diagnostic retention
|
||||
|
||||
- Buffered subprocess output has bounded I/O teardown after cancellation or
|
||||
child exit, including when descendants retain inherited output descriptors.
|
||||
Piped Git-reader cancellation closes owned pipes and joins child cleanup.
|
||||
Cancellation remains recognizable through `errors.Is`; ordinary execution
|
||||
failures preserve their underlying causes.
|
||||
- A queued blob read rechecks cancellation after acquiring the reader mutex,
|
||||
preserving a healthy batch session for later reads.
|
||||
- Status-only Go commands and dependency preparation retain a 1 MiB diagnostic
|
||||
tail. Failed commands identify omitted earlier output. Existing streaming
|
||||
output continues to be forwarded in full, and commands requiring returned
|
||||
output keep their complete capture.
|
||||
|
||||
## Builds and hosted delivery
|
||||
|
||||
- Completed build artifacts are reported only after hashing succeeds. A hashing
|
||||
failure identifies the affected output and preserves earlier completed
|
||||
artifacts and their digests.
|
||||
- Temporary allocation and cleanup failures retain their paths and underlying
|
||||
causes, including candidate builds, native version checks, delivery builds,
|
||||
tag-message files, and build receipts.
|
||||
- A managed-build cleanup failure after confirmed hosted delivery returns an
|
||||
error alongside `DeliveryComplete` and the confirmed asset observations. The
|
||||
CLI reports completed remote work and the local cleanup failure, returning
|
||||
operational status 1.
|
||||
- Gitea attachment downloads follow at most ten redirects, retaining cycle
|
||||
detection and per-origin authorization handling. Limit exhaustion is
|
||||
unverifiable content.
|
||||
- Remote attachment comparison reads at most the locally verified expected size
|
||||
plus one byte. Shorter or longer content conflicts; equal-length content still
|
||||
requires the expected digest. Read, close, and cancellation errors remain
|
||||
inspection failures, with existing attempted-write reconciliation preserved.
|
||||
|
||||
Shared Git observations, validation sequencing, artifact declaration matching,
|
||||
and CLI workflows were consolidated internally. Consumer-facing types continue
|
||||
to belong to the root `releasekit` and runtime `buildinfo` facades.
|
||||
|
||||
## Compatibility and upgrade guidance
|
||||
|
||||
The module identifier remains `go.maximumdirect.net/releasekit`, and the Go
|
||||
consumer minimum remains 1.26.0. Existing v0.6.0 API calls, profile fields, and
|
||||
build receipt formats remain supported. This minor release changes operational
|
||||
behavior through the diagnostic and redirect budgets and cleanup-error reporting
|
||||
described above.
|
||||
|
||||
When adopting v0.7.0:
|
||||
|
||||
1. Update library and CLI dependencies to v0.7.0 using the existing import paths
|
||||
and profiles.
|
||||
2. Handle a delivery error together with `DeliveryResult.State`. For
|
||||
`DeliveryComplete`, address the reported local cleanup path; the confirmed
|
||||
hosted delivery is already complete. Continue to resolve partial, conflicting,
|
||||
and unknown outcomes through their existing recovery guidance.
|
||||
3. Retain candidate validation's streamed `Output` when complete test diagnostics
|
||||
are needed. Status-only failure text now contains the retained tail and an
|
||||
omission notice when applicable.
|
||||
4. When using Git replacement refs, expect release evidence to be evaluated
|
||||
against original committed objects. A build of dirty or replacement-derived
|
||||
working content can succeed while remaining ineligible for binary delivery.
|
||||
5. Inspect the reported local tag ref after a tag-creation or verification
|
||||
failure, including when `TagObject` is empty. Continue to treat the raw
|
||||
`PublicationResult.Endpoint` as sensitive when handling it in application
|
||||
output or logs.
|
||||
|
||||
See the [publication guide](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.7.0/docs/consumers/publish.md),
|
||||
[build guide](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.7.0/docs/consumers/build.md),
|
||||
[delivery guide](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.7.0/docs/consumers/delivery.md),
|
||||
[CLI contract](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.7.0/docs/cli.md),
|
||||
and [Gitea integration guide](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.7.0/docs/integrations/gitea.md)
|
||||
for current behavior. Source publication and hosted delivery retain their
|
||||
separate outcomes under the [maintainer procedure](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.7.0/docs/release.md).
|
||||
|
||||
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.7.0/COPYRIGHT) |
|
||||
[LICENSE](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.7.0/LICENSE) |
|
||||
[ATTRIBUTION](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.7.0/docs/oss/attribution.md)
|
||||
54
docs/releases/v0.8.0.md
Normal file
54
docs/releases/v0.8.0.md
Normal file
@@ -0,0 +1,54 @@
|
||||
# ReleaseKit v0.8.0
|
||||
|
||||
## Summary
|
||||
|
||||
ReleaseKit adds read-only recovery for source-publication attempts. It attempts
|
||||
to retain evidence before a tag push, lets operators discover and explicitly
|
||||
select a saved attempt, and observes the original destination without repeating
|
||||
candidate validation or changing tags. Source publication and hosted delivery
|
||||
continue to have separate outcomes.
|
||||
|
||||
## Publication recovery
|
||||
|
||||
- `Publish` returns reusable `PublicationEvidence` and attempts to save a
|
||||
private record. The result reports the saved path or a recording error
|
||||
separately from the publication outcome. Go callers can load or list records
|
||||
and reconcile retained evidence through the root facade.
|
||||
- The CLI adds `publication-attempts` for local discovery and `reconcile` for
|
||||
an explicitly selected record. Both support human-readable and structured
|
||||
output. `publish --record-dir` selects an alternate record directory, and
|
||||
failed publication can print a recovery command for the saved attempt.
|
||||
- Recovery uses the captured endpoint and full tag with current supported Git
|
||||
transport settings. It reports publication, current absence, conflict, or an
|
||||
unresolved observation. Current absence does not prove that a version was
|
||||
never published; published versions and their contents remain immutable.
|
||||
- Records preserve exact endpoint and path bytes. Ordinary UTF-8 evidence uses
|
||||
record format 1; format 2 preserves other bytes. Recovery diagnostics redact
|
||||
HTTP(S) URL userinfo, while private records and typed evidence can contain
|
||||
sensitive endpoints. Operators control record retention and removal.
|
||||
|
||||
## Consumer tools and compatibility
|
||||
|
||||
The module path remains `go.maximumdirect.net/releasekit`, and the Go consumer
|
||||
minimum remains 1.26.0. Existing publication calls and release profiles remain
|
||||
supported. Publication now attempts to write a private record by default; a
|
||||
storage failure is reported separately and does not change the publication
|
||||
result. Applications handling results should inspect `RecordError` when a saved
|
||||
recovery handoff matters.
|
||||
|
||||
Consumers with the CLI registered as a Go tool in their module can run it with
|
||||
`go tool releasekit`.
|
||||
The maintained multi-module launcher and Woodpecker examples use the selected
|
||||
module's tool version. Register the CLI before generating a vendor tree when
|
||||
using a vendored tool. Older recovery CLIs that only support record format 1
|
||||
cannot load format 2 records; use a CLI that supports format 2.
|
||||
|
||||
See the [publication guide](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.8.0/docs/consumers/publish.md),
|
||||
[CLI reference](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.8.0/docs/cli.md),
|
||||
[publication record formats](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.8.0/docs/integrations/publication-records.md),
|
||||
and [consumer adoption guide](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.8.0/docs/consumers/adoption.md)
|
||||
for usage and recovery details.
|
||||
|
||||
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.8.0/COPYRIGHT) |
|
||||
[LICENSE](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.8.0/LICENSE) |
|
||||
[ATTRIBUTION](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.8.0/docs/oss/attribution.md)
|
||||
41
docs/releases/v0.9.0.md
Normal file
41
docs/releases/v0.9.0.md
Normal file
@@ -0,0 +1,41 @@
|
||||
# ReleaseKit v0.9.0
|
||||
|
||||
ReleaseKit's maintained launchers and generated Go recovery commands now
|
||||
prepare and run the release tool for the Go host when inherited `GOOS` and
|
||||
`GOARCH` select another target. Release profiles still select the targets for
|
||||
application builds.
|
||||
|
||||
## Launcher, delivery, and recovery fixes
|
||||
|
||||
- Local launchers and Woodpecker templates select the host before preparing
|
||||
tool dependencies or compiling the CLI. Module-based launchers invoke
|
||||
ReleaseKit by its full Go package path, so another registered tool named
|
||||
`releasekit` does not make the invocation ambiguous.
|
||||
- Generated Go recovery commands select the host when run in a POSIX shell
|
||||
and find the Go executable through `PATH`. Recovery for API-only consumers
|
||||
preserves both wildcard and version-specific module replacements when
|
||||
relocating relative paths, fixing a panic after a failed publication.
|
||||
- The manual hosted-page retry stops if fetching or checking out the tag fails,
|
||||
or if local edits remain. It checks the tagged checkout before downloading
|
||||
dependencies or building the CLI.
|
||||
|
||||
## Compatibility and upgrade
|
||||
|
||||
The module path remains `go.maximumdirect.net/releasekit` and the Go consumer
|
||||
minimum remains 1.26.0. Public Go APIs, release profiles, and publication
|
||||
record formats are unchanged.
|
||||
|
||||
Update copied launchers and CI templates to get the host and tool selection
|
||||
fixes. Updating the module dependency alone does not update those files.
|
||||
Configured product checks inherit the launcher's host target; if a check
|
||||
needs an application target, set it explicitly in the check's `env` map
|
||||
or command.
|
||||
|
||||
See the [adoption guide](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.9.0/docs/consumers/adoption.md),
|
||||
[delivery guide](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.9.0/docs/consumers/delivery.md),
|
||||
and [maintainer runbook](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.9.0/docs/release.md)
|
||||
for updated recipes.
|
||||
|
||||
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.9.0/COPYRIGHT) |
|
||||
[LICENSE](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.9.0/LICENSE) |
|
||||
[ATTRIBUTION](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.9.0/docs/oss/attribution.md)
|
||||
67
docs/roadmap/deferred-resources.md
Normal file
67
docs/roadmap/deferred-resources.md
Normal file
@@ -0,0 +1,67 @@
|
||||
# Deferred resource work
|
||||
|
||||
These two proposals remain deferred after the completed audit remediation for
|
||||
v0.7.0. Their assessments are complete; production limits and exclusion indexing
|
||||
await a future decision supported by consumer needs. The assessment evidence
|
||||
was recorded in commit `9dc87ae`.
|
||||
|
||||
## Forge JSON response budgets
|
||||
|
||||
**Status:** Deferred; local sizing assessment complete.
|
||||
|
||||
Forge JSON decoding can consume memory proportional to response size. Release
|
||||
notes and unpaginated attachment lists have no established supported maximum.
|
||||
A future proposal should establish an appropriate response envelope before
|
||||
selecting byte/time budgets or configuration. Any limit must retain context
|
||||
cancellation, useful error classification, and uncertain-write reconciliation:
|
||||
a rejected response does not establish that a create or upload failed remotely.
|
||||
|
||||
The [Gitea fixtures](../../internal/gitea/backend_test.go) construct repository,
|
||||
release, tag, and attachment responses. Representative encoded fixtures measured
|
||||
81 bytes for repository identity, 136 with permissions, 125 for a sparse release,
|
||||
144 for a populated release, 73 for a one-item attachment list, and 62 for an
|
||||
upload response, including the encoder's newline. Four literal release-ID
|
||||
fixtures measured 21, 28, 29, and 29 bytes without a newline. Generated URLs,
|
||||
notes, and lists vary with fixture inputs.
|
||||
|
||||
The checked-in v0.1.0–v0.6.0 release notes measured 1,235–7,899 bytes during the
|
||||
assessment. These observations describe local examples and establish no
|
||||
deployment or protocol maximum. Production response caps remain deferred.
|
||||
|
||||
## File-size exclusion indexing
|
||||
|
||||
**Status:** Deferred; benchmark assessment complete.
|
||||
|
||||
The current [exclusion scan](../../internal/validation/file_size.go) compares
|
||||
each selected file with the normalized exclusions until a match is found.
|
||||
The adoption decision weighs measured speedups against allocation and
|
||||
path-walking costs for consumer workloads. Preserve literal component boundaries,
|
||||
module-relative normalization, shared inputs, and the first oversized-file result.
|
||||
|
||||
The [benchmark-only prototype](../../internal/validation/file_size_benchmark_test.go)
|
||||
compares the scan with a normalized set and ancestor lookups. It covers 1,000
|
||||
and 10,000 paths, 1/10/100/1,000 exclusions, shallow/deep paths, early matches,
|
||||
and nonmatches. Each measured operation includes normalization and one index
|
||||
construction where applicable; fixture strings are prepared outside timing.
|
||||
|
||||
On Linux/amd64, Go 1.26.8, Intel Core i5-7260U, 64 combinations ran with three
|
||||
samples each using:
|
||||
|
||||
```sh
|
||||
GOTOOLCHAIN=local GOPROXY=off GOSUMDB=off go test ./internal/validation \
|
||||
-run '^$' -bench '^BenchmarkFileSizeExclusions$' -benchtime=100ms -count=3
|
||||
```
|
||||
|
||||
Representative median times and allocations were:
|
||||
|
||||
| Paths / exclusions / case | Scan | Index |
|
||||
| --- | --- | --- |
|
||||
| 1,000 / 1 / shallow early match | 24.5 µs, 16 B, 1 allocation | 44.0 µs, 16 B, 1 allocation |
|
||||
| 1,000 / 1 / deep nonmatch | 25.7 µs, 16 B, 1 allocation | 119.0 µs, 16 B, 1 allocation |
|
||||
| 10,000 / 1,000 / shallow early match | 270 µs, 16,384 B, 1 allocation | 564 µs, 70,992 B, 6 allocations |
|
||||
| 10,000 / 1,000 / shallow nonmatch | 227.0 ms, 16,384 B, 1 allocation | 521 µs, 70,992 B, 6 allocations |
|
||||
| 10,000 / 1,000 / deep nonmatch | 233.4 ms, 16,384 B, 1 allocation | 1.36 ms, 70,992 B, 6 allocations |
|
||||
|
||||
The prototype was slower for small lists and early matches, and faster for
|
||||
large nonmatching lists with higher allocation costs. Production matching
|
||||
remains unchanged pending an adoption decision.
|
||||
1
examples/multi-module/.gitignore
vendored
Normal file
1
examples/multi-module/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
.releasekit/
|
||||
1
examples/multi-module/.releasekit-version
Normal file
1
examples/multi-module/.releasekit-version
Normal file
@@ -0,0 +1 @@
|
||||
v0.11.0
|
||||
172
examples/multi-module/README.md
Normal file
172
examples/multi-module/README.md
Normal file
@@ -0,0 +1,172 @@
|
||||
# Multi-module release example
|
||||
|
||||
This example maps selectors and complete event tags to a physical Go module
|
||||
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
|
||||
selects the corresponding profile and checkout directory.
|
||||
|
||||
Copy the contents of this directory into a consumer repository root, keeping
|
||||
the listed module directories and profile paths at those locations, then run
|
||||
the launcher from that checkout.
|
||||
|
||||
The sample modules declare Go 1.27.0, matching the current ReleaseKit consumer
|
||||
minimum.
|
||||
|
||||
## Select the release tool
|
||||
|
||||
The module files are setup skeletons. Set `RELEASEKIT_TOOL_VERSION` to a released
|
||||
ReleaseKit version that supports the selected source and rehearsal features,
|
||||
then register that tool in each consumer module before running the launcher or
|
||||
workflow. Version v0.11.0 supplies these interfaces:
|
||||
|
||||
```sh
|
||||
RELEASEKIT_TOOL_VERSION=v0.11.0
|
||||
for module_dir in . integrations/ckconfig integrations/core/v2; do
|
||||
go -C "$module_dir" get -tool "go.maximumdirect.net/releasekit/cmd/releasekit@${RELEASEKIT_TOOL_VERSION}"
|
||||
go -C "$module_dir" mod tidy
|
||||
done
|
||||
```
|
||||
|
||||
Review and commit the generated tool, dependency, and checksum declarations.
|
||||
The [adoption guide](../../docs/consumers/adoption.md) owns tool registration and
|
||||
coordinated tool/workflow upgrades. The
|
||||
[v0.4.0 release note](../../docs/releases/v0.4.0.md) describes module-release
|
||||
support and migration from earlier versions.
|
||||
|
||||
## Module mapping and publication
|
||||
|
||||
`release-modules.tsv` is literal tab-separated text with four columns:
|
||||
|
||||
1. Local selector.
|
||||
2. Shell pattern matched against a complete event tag.
|
||||
3. Repository-relative tool module directory (`.` means the root module); `-` selects the installed tool from `.releasekit-version`.
|
||||
4. Repository-relative profile path.
|
||||
|
||||
The checked-in patterns are `v[01].*`, `integrations/ckconfig/v*`,
|
||||
`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
|
||||
matches are configuration errors. Module and profile paths may contain spaces.
|
||||
The `core-v2` row places the Go module physically under `integrations/core/v2`
|
||||
and declares a `/v2` module path. ReleaseKit derives the versioned tag under
|
||||
`integrations/core`, while the table retains the full physical path.
|
||||
|
||||
Before running candidate checks offline, prepare each module's dependencies in
|
||||
its own directory:
|
||||
|
||||
```sh
|
||||
go -C . mod download
|
||||
go -C integrations/ckconfig mod download
|
||||
go -C integrations/core/v2 mod download
|
||||
```
|
||||
|
||||
Commit each generated `go.sum` with its module files. The binary delivery
|
||||
profile prepares application dependencies in the tagged module before building;
|
||||
the committed sums keep that prepared checkout clean for delivery verification.
|
||||
|
||||
Then select a module and semantic version with the shared launcher:
|
||||
|
||||
```sh
|
||||
./release.sh root v1.2.3
|
||||
./release.sh ckconfig v1.2.3
|
||||
./release.sh core-v2 v2.1.0
|
||||
./release.sh config 2026-12-05
|
||||
```
|
||||
|
||||
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
|
||||
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
|
||||
package path with the alternate module file to run `publish` with the repository
|
||||
profile and `--expected-module` so the library can verify that the profile agrees with
|
||||
the selected table row. Go builds and caches the executable and preserves its
|
||||
exit status; the launcher removes the temporary metadata on exit. As with any
|
||||
`publish` invocation, commit the selected module's release note and prepare its
|
||||
repository before publishing.
|
||||
|
||||
If an integration depends on a sibling release, publish the dependency first,
|
||||
then publish the integration with the version that consumes it. For example,
|
||||
publish the core release before an integration that requires that release.
|
||||
This declaration does not infer dependency order or rerun the standard suite.
|
||||
|
||||
The maintained [Woodpecker example](woodpecker.yml) uses the same map and
|
||||
selector for root, `ckconfig`, and major-version tags. It verifies and detaches
|
||||
the literal event tag before selecting the module, copies that module's metadata
|
||||
outside the checkout, and runs the selected ReleaseKit tool by its full package
|
||||
path. It passes `ci-deliver --prepared`, the mapped profile, and the expected
|
||||
physical module to the tool.
|
||||
The `core-v2` profile demonstrates binary delivery; the other profiles are
|
||||
page-only. Before enabling the workflow, replace the example forge and Woodpecker
|
||||
destinations and repository ID in each profile. Configure separate local forge
|
||||
and Woodpecker token files, then add the Woodpecker repository secret
|
||||
`releasekit_gitea_token`; the workflow exposes it as
|
||||
`RELEASEKIT_GITEA_TOKEN` only in the delivery step.
|
||||
|
||||
Retries use the selected tag's module files and matching workflow. Tags whose
|
||||
tool predates this interface use their corresponding historical workflow.
|
||||
|
||||
## Local source verification
|
||||
|
||||
For verification before a compatible release is published, copy this example
|
||||
into a disposable consumer checkout. Set `RELEASEKIT_SOURCE` to the absolute
|
||||
path of a prepared ReleaseKit checkout, then select its source in those fixture
|
||||
modules:
|
||||
|
||||
```sh
|
||||
: "${RELEASEKIT_SOURCE:?Set the absolute ReleaseKit checkout path}"
|
||||
for module_dir in . integrations/ckconfig integrations/core/v2; do
|
||||
go -C "$module_dir" mod edit \
|
||||
-require=go.maximumdirect.net/releasekit@v0.0.0 \
|
||||
-replace="go.maximumdirect.net/releasekit=$RELEASEKIT_SOURCE" \
|
||||
-tool=go.maximumdirect.net/releasekit/cmd/releasekit
|
||||
GOTOOLCHAIN=local GOWORK=off go -C "$module_dir" mod tidy
|
||||
done
|
||||
```
|
||||
|
||||
Here `v0.0.0` is a fixture placeholder resolved by the local replacement.
|
||||
Keep these declarations in the disposable checkout. Add representative product
|
||||
source and each selected product's module-local release note, then commit the
|
||||
fixture and run the source-selected tool without publishing:
|
||||
|
||||
```sh
|
||||
(
|
||||
cd . || exit $?
|
||||
releasekit_host_os=$(go env GOHOSTOS) || exit $?
|
||||
releasekit_host_arch=$(go env GOHOSTARCH) || exit $?
|
||||
export GOOS="$releasekit_host_os" GOARCH="$releasekit_host_arch"
|
||||
go tool go.maximumdirect.net/releasekit/cmd/releasekit check --config releasekit-root.json v1.2.3
|
||||
)
|
||||
(
|
||||
cd ./integrations/ckconfig || exit $?
|
||||
releasekit_host_os=$(go env GOHOSTOS) || exit $?
|
||||
releasekit_host_arch=$(go env GOHOSTARCH) || exit $?
|
||||
export GOOS="$releasekit_host_os" GOARCH="$releasekit_host_arch"
|
||||
go tool go.maximumdirect.net/releasekit/cmd/releasekit check --config releasekit-ckconfig.json v1.2.3
|
||||
)
|
||||
(
|
||||
cd ./integrations/core/v2 || exit $?
|
||||
releasekit_host_os=$(go env GOHOSTOS) || exit $?
|
||||
releasekit_host_arch=$(go env GOHOSTARCH) || exit $?
|
||||
export GOOS="$releasekit_host_os" GOARCH="$releasekit_host_arch"
|
||||
go tool go.maximumdirect.net/releasekit/cmd/releasekit check --config releasekit-core-v2.json v2.1.0
|
||||
)
|
||||
```
|
||||
|
||||
These commands use the repository-root profile paths even when invoked from a
|
||||
child module. The core profile also verifies the native binary and injected
|
||||
version. Prepared dependencies allow this verification with `GOPROXY=off` and
|
||||
`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.
|
||||
4
examples/multi-module/configuration/config.json
Normal file
4
examples/multi-module/configuration/config.json
Normal file
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"service": "example",
|
||||
"enabled": true
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
# Example Configuration 2026-12-05
|
||||
|
||||
Initial configuration release.
|
||||
3
examples/multi-module/go.mod
Normal file
3
examples/multi-module/go.mod
Normal file
@@ -0,0 +1,3 @@
|
||||
module example.com/multi-module-consumer
|
||||
|
||||
go 1.27.0
|
||||
3
examples/multi-module/integrations/ckconfig/go.mod
Normal file
3
examples/multi-module/integrations/ckconfig/go.mod
Normal file
@@ -0,0 +1,3 @@
|
||||
module example.com/multi-module-consumer/integrations/ckconfig
|
||||
|
||||
go 1.27.0
|
||||
3
examples/multi-module/integrations/core/v2/go.mod
Normal file
3
examples/multi-module/integrations/core/v2/go.mod
Normal file
@@ -0,0 +1,3 @@
|
||||
module example.com/multi-module-consumer/integrations/core/v2
|
||||
|
||||
go 1.27.0
|
||||
11
examples/multi-module/integrations/core/v2/main.go
Normal file
11
examples/multi-module/integrations/core/v2/main.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"go.maximumdirect.net/releasekit/buildinfo"
|
||||
)
|
||||
|
||||
func main() {
|
||||
fmt.Printf("core %s\n", buildinfo.Version())
|
||||
}
|
||||
5
examples/multi-module/release-modules.tsv
Normal file
5
examples/multi-module/release-modules.tsv
Normal file
@@ -0,0 +1,5 @@
|
||||
# selector<TAB>tag pattern<TAB>tool module directory<TAB>profile path
|
||||
root v[01].* . releasekit-root.json
|
||||
ckconfig integrations/ckconfig/v* integrations/ckconfig releasekit-ckconfig.json
|
||||
core-v2 integrations/core/v2.* integrations/core/v2 releasekit-core-v2.json
|
||||
config configuration/20* - releasekit-config.json
|
||||
|
55
examples/multi-module/release.sh
Executable file
55
examples/multi-module/release.sh
Executable file
@@ -0,0 +1,55 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
usage() {
|
||||
echo "usage: release.sh SELECTOR VERSION" >&2
|
||||
exit 2
|
||||
}
|
||||
|
||||
[ "$#" -eq 2 ] || usage
|
||||
selector=$1
|
||||
version=$2
|
||||
script_dir=$(CDPATH= cd "$(dirname "$0")" && pwd)
|
||||
repository_dir=$(git -C "$script_dir" rev-parse --show-toplevel)
|
||||
|
||||
bootstrap_dir=$(mktemp -d "$(dirname "$repository_dir")/.releasekit-bootstrap.XXXXXX")
|
||||
selection_file=$bootstrap_dir/module-selection.tsv
|
||||
trap 'rm -rf "$bootstrap_dir"' EXIT
|
||||
"$script_dir/select-module.sh" selector "$selector" > "$selection_file"
|
||||
|
||||
tab=$(printf '\t')
|
||||
IFS="$tab" read -r selected_selector tag_pattern module_dir profile_path < "$selection_file"
|
||||
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
|
||||
if [ "$module_dir" != . ]; then
|
||||
module_path=$repository_dir/$module_dir
|
||||
fi
|
||||
|
||||
cp "$module_path/go.mod" "$bootstrap_dir/releasekit.mod"
|
||||
if [ -f "$module_path/go.sum" ]; then
|
||||
cp "$module_path/go.sum" "$bootstrap_dir/releasekit.sum"
|
||||
else
|
||||
: > "$bootstrap_dir/releasekit.sum"
|
||||
fi
|
||||
|
||||
releasekit_module=go.maximumdirect.net/releasekit
|
||||
(
|
||||
cd "$module_path"
|
||||
export GOWORK=off
|
||||
export GOTOOLCHAIN=local
|
||||
releasekit_host_os=$(go env GOHOSTOS) || exit $?
|
||||
releasekit_host_arch=$(go env GOHOSTARCH) || exit $?
|
||||
export GOOS="$releasekit_host_os" GOARCH="$releasekit_host_arch"
|
||||
go list -mod=mod -modfile="$bootstrap_dir/releasekit.mod" -m "$releasekit_module"
|
||||
go mod edit -modfile="$bootstrap_dir/releasekit.mod" -tool="$releasekit_module/cmd/releasekit"
|
||||
go list -mod=mod -modfile="$bootstrap_dir/releasekit.mod" -deps "$releasekit_module/cmd/releasekit" > /dev/null
|
||||
go tool -modfile="$bootstrap_dir/releasekit.mod" "$releasekit_module/cmd/releasekit" publish \
|
||||
--repo "$repository_dir" \
|
||||
--config "$profile_path" \
|
||||
--expected-module "$module_dir" \
|
||||
"$version"
|
||||
)
|
||||
28
examples/multi-module/releasekit-ckconfig.json
Normal file
28
examples/multi-module/releasekit-ckconfig.json
Normal file
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"product": "Example Consumer Integration",
|
||||
"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"
|
||||
}
|
||||
}
|
||||
}
|
||||
25
examples/multi-module/releasekit-config.json
Normal file
25
examples/multi-module/releasekit-config.json
Normal 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"
|
||||
}
|
||||
}
|
||||
}
|
||||
35
examples/multi-module/releasekit-core-v2.json
Normal file
35
examples/multi-module/releasekit-core-v2.json
Normal file
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"product": "Example Consumer Core v2",
|
||||
"module_dir": "integrations/core/v2",
|
||||
"build": {
|
||||
"main_package": ".",
|
||||
"binary_name": "core",
|
||||
"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"
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user