48 Commits

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

View File

@@ -2,9 +2,8 @@
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.
@@ -14,9 +13,9 @@ explains the v0.5.0 migration from the original Gitea module path.
The [v0.6.0 release note](docs/releases/v0.6.0.md) describes the delivery API
and profile migration.
Release operations can select one Go module within a repository. The repository
root remains the default; a selected module's declared import path and physical
directory determine its complete Git tag and module-local release note. See the
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/).
@@ -40,8 +39,7 @@ 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
@@ -62,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`.
@@ -71,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

View File

@@ -2,6 +2,7 @@ package releasekit
import (
"context"
"errors"
"fmt"
"io"
@@ -31,7 +32,10 @@ type BuildRequest struct {
// ModuleDir selects a repository-relative module directory; empty selects
// the repository root.
ModuleDir string
Version string // stable vMAJOR.MINOR.PATCH value injected at link time.
// 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.
@@ -47,11 +51,19 @@ type BuildArtifact struct {
// BuildResult describes the source and artifacts reached by Build.
type BuildResult struct {
RepositoryDir string // absolute source repository path.
ModuleDir string // absolute selected module directory.
ModulePath string // selected module's declared Go path.
Tag string // complete tag derived for this version.
CandidateCommit string // Git HEAD observed when the build started.
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
@@ -79,7 +91,7 @@ func Build(ctx context.Context, request BuildRequest) (BuildResult, error) {
result.Settings = artifact.NormalizeSettings(spec.MainPackage, spec.BinaryName, spec.Targets)
return publicBuildResult(result), err
}
if !versioncontract.ValidStableVersion(request.Version) {
if request.Source == nil && !versioncontract.ValidStableVersion(request.Version) {
return failure(fmt.Errorf("%w: %q", ErrInvalidVersion, request.Version))
}
repositoryDir, err := git.RepositoryRoot(ctx, request.RepositoryDir)
@@ -87,9 +99,13 @@ func Build(ctx context.Context, request BuildRequest) (BuildResult, error) {
return failure(err)
}
result.RepositoryDir = repositoryDir
identity, err := releaseidentity.FromWorkingTree(ctx, repositoryDir, request.ModuleDir, request.Version)
identity, err := releaseidentity.FromWorkingSource(ctx, repositoryDir, request.ModuleDir, request.Version, internalSourceSpec(request.Source))
result.Identity = identity
result.ModuleDir, result.ModulePath, result.Tag = identity.ModuleDir, identity.ModulePath, identity.Tag
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{
@@ -104,6 +120,14 @@ func Build(ctx context.Context, request BuildRequest) (BuildResult, error) {
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,
@@ -146,6 +170,7 @@ func internalBuildResult(result BuildResult) *internalbuild.Result {
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})
}

View File

@@ -10,7 +10,7 @@ import (
"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,15 +18,22 @@ var ErrInvalidVersion = candidate.ErrInvalidVersion
var ErrUnexpectedPushURL = publish.ErrUnexpectedPushURL
// Candidate identifies one committed local source revision selected for
// validation. ModuleDir is the absolute selected module directory, ModulePath
// is its declared Go import path, and Tag is the complete derived Git tag.
// 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 // selected stable semantic version.
Version string // selected production identifier.
}
// ReleaseRequest contains the inputs used to validate and optionally build one
@@ -39,9 +46,12 @@ type ReleaseRequest struct {
// ModuleDir selects a repository-relative module directory; empty selects
// the repository root.
ModuleDir string
Product string
Version string // stable semantic version, independent of the derived Git tag.
Remote 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.
@@ -137,12 +147,10 @@ type GoValidationSpec struct {
}
// Check validates one local, committed release candidate. It requires a clean
// worktree and index on main, a selected module declaration and module-local
// committed note matching Product and Version, and an unused local tag. An
// empty ModuleDir selects the repository root. The module declaration
// determines the full Git tag for the semantic Version. It always runs the
// offline Go test suite with the available compatible local Go toolchain and
// Go host target, then calls
// 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
@@ -166,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
@@ -182,6 +190,12 @@ func Check(ctx context.Context, request ReleaseRequest) (Candidate, error) {
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,
@@ -191,32 +205,38 @@ func publicCandidate(checked candidate.Candidate) Candidate {
}
func candidateRequest(request ReleaseRequest) candidate.Request {
fileSize := internalFileSizeSettings(request.Validation.FileSize)
result := candidate.Request{
RepositoryDir: request.RepositoryDir,
ModuleDir: request.ModuleDir,
Product: request.Product,
Version: request.Version,
Validation: validation.Settings{
Race: request.Validation.Go.Race,
FullVet: request.Validation.Go.FullVet,
CompileTargets: make([]validation.Target, len(request.Validation.Go.CompileTargets)),
SharedFiles: copyStringSlice(request.Validation.SharedFiles),
ForbiddenFiles: copyStringSlice(request.Validation.ForbiddenFiles),
GoFormat: request.Validation.GoFormat,
Markdown: internalMarkdownSettings(request.Validation.Markdown),
ModuleDistribution: validation.ModuleDistributionSettings{
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
}

View File

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

View File

@@ -49,7 +49,7 @@ func TestCIDeliveryRejectsModuleTagMismatchBeforePreparation(t *testing.T) {
t.Setenv("PATH", shimDir+string(os.PathListSeparator)+os.Getenv("PATH"))
var stdout, stderr bytes.Buffer
status := run(context.Background(), []string{"ci-deliver", "--repo", repository, "--prepared", "--commit", commit, "--expected-module", "child", "v1.2.3"}, &stdout, &stderr)
if status != 1 || !strings.Contains(stderr.String(), `expected delivery tag "v1.2.3"`) || !strings.Contains(stderr.String(), `selected module tag "child/v1.2.3"`) {
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) {

View File

@@ -23,7 +23,7 @@ func TestInvalidDeliveryDestinationStopsBeforePreparation(t *testing.T) {
http.Error(w, "unexpected request", http.StatusInternalServerError)
}))
defer server.Close()
destination := &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example", TokenEnv: "RELEASEKIT_TEST_DELIVERY_TOKEN"}
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"

View File

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

View File

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

View File

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

View File

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

View File

@@ -3,6 +3,7 @@
package cli
import (
"bytes"
"context"
"encoding/json"
"errors"
@@ -12,17 +13,19 @@ import (
"os"
"path/filepath"
"strings"
"time"
"go.maximumdirect.net/releasekit/internal/process"
"go.maximumdirect.net/releasekit/internal/versioncontract"
"go.maximumdirect.net/releasekit/internal/releaseidentity"
)
const Usage = "usage: releasekit version\n releasekit check [--repo DIR] [--config FILE] VERSION\n releasekit publish [--repo DIR] [--config FILE] [--record-dir DIR] [--expected-module DIR] VERSION\n releasekit build [--repo DIR] [--config FILE] [--output DIR] VERSION\n releasekit deliver [--repo DIR] [--config FILE] [--assets DIR] VERSION\n releasekit ci-deliver [--repo DIR] [--config FILE] [--remote NAME] [--prepared] [--expected-module DIR] --commit OID TAG\n releasekit reconcile --record FILE [--json]\n releasekit publication-attempts [--repo DIR] [--record-dir DIR] [--json]"
const Usage = "usage: releasekit version\n releasekit validate [--repo DIR] [--config FILE] [--context local|ci] [--operation NAME ...] [--offline] [--assets DIR] [--json]\n releasekit check [--repo DIR] [--config FILE] VERSION\n releasekit publish [--repo DIR] [--config FILE] [--record-dir DIR] [--expected-module DIR] [--expected-source DIR] VERSION\n releasekit build [--repo DIR] [--config FILE] [--output DIR] VERSION\n releasekit deliver [--repo DIR] [--config FILE] [--assets DIR] VERSION\n releasekit ci-deliver [--repo DIR] [--config FILE] [--remote NAME] [--prepared] [--expected-module DIR] [--expected-source DIR] --commit OID TAG\n releasekit test [--repo DIR] [--config FILE] [--ref REF] [--record-dir DIR] [--timeout DURATION] [--cleanup-timeout DURATION] [--json]\n releasekit test-resume --record FILE [--token-file FILE] [--woodpecker-token-file FILE] [--timeout DURATION] [--cleanup-timeout DURATION] [--json]\n releasekit test-cleanup --record FILE [--token-file FILE] [--woodpecker-token-file FILE] [--cleanup-timeout DURATION] [--json]\n releasekit reconcile --record FILE [--json]\n releasekit publication-attempts [--repo DIR] [--record-dir DIR] [--json]"
type Command string
const (
VersionCommand Command = "version"
ValidateAction Command = "validate"
CheckAction Command = "check"
PublishAction Command = "publish"
BuildAction Command = "build"
@@ -30,24 +33,54 @@ const (
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
ExpectedModule string
ExpectedTag string
Prepared bool
RecordPath string
RecordDir string
JSON bool
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.
@@ -56,6 +89,63 @@ 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)
@@ -101,8 +191,10 @@ func Parse(args []string) (Invocation, error) {
}
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 {
@@ -134,18 +226,12 @@ func Parse(args []string) (Invocation, error) {
if slash := strings.LastIndex(version, "/"); slash >= 0 {
version = version[slash+1:]
}
if !versioncontract.ValidStableVersion(version) {
return Invocation{}, errors.New("ci-deliver TAG must end in a stable vMAJOR.MINOR.PATCH version")
}
}
if !versioncontract.ValidStableVersion(version) {
return Invocation{}, errors.New("VERSION must be a stable vMAJOR.MINOR.PATCH version")
}
parsedRemote := ""
if remote != nil {
parsedRemote = *remote
}
return Invocation{Command: action, Repository: *repository, ConfigPath: *configPath, OutputDir: outputDir, AssetsDir: assetsDir, Remote: parsedRemote, Commit: expectedCommit, Version: version, ExpectedModule: expectedModule, ExpectedTag: expectedTag, Prepared: prepared, RecordDir: recordDir}, nil
return Invocation{Command: action, Repository: *repository, ConfigPath: *configPath, OutputDir: outputDir, AssetsDir: assetsDir, Remote: parsedRemote, Commit: expectedCommit, Version: version, ExpectedModule: expectedModule, ExpectedSource: expectedSource, ExpectedTag: expectedTag, Prepared: prepared, RecordDir: recordDir}, nil
default:
return Invocation{}, fmt.Errorf("unknown command %q", args[0])
}
@@ -172,14 +258,80 @@ 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"`
ModuleDir string `json:"module_dir,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"`
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.
@@ -231,12 +383,26 @@ type GoValidationSettings struct {
// DeliverySettings selects the hosted forge release destination.
type DeliverySettings struct {
Forge string `json:"forge,omitempty"`
BaseURL string `json:"base_url"`
Owner string `json:"owner"`
Repository string `json:"repository"`
TokenEnv string `json:"token_env,omitempty"`
TokenFile string `json:"token_file,omitempty"`
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.
@@ -265,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)
@@ -283,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"
}

View File

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

View File

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

View File

@@ -2,21 +2,24 @@ package cli
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path"
"path/filepath"
"strings"
"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 = 1
const BuildReceiptSchemaVersion = 2
type ReceiptTarget struct {
OS string `json:"os"`
@@ -34,6 +37,14 @@ type ReceiptArtifact struct {
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"`
@@ -113,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)
}
@@ -169,11 +179,8 @@ func validateBuildReceipt(receipt BuildReceipt) error {
if receipt.SchemaVersion != BuildReceiptSchemaVersion {
return fmt.Errorf("unsupported or missing build receipt schema version %d", receipt.SchemaVersion)
}
if !versioncontract.ValidStableVersion(receipt.Version) {
return fmt.Errorf("build receipt has invalid version %q", receipt.Version)
}
if !filepath.IsAbs(receipt.RepositoryDir) || !filepath.IsAbs(receipt.ModuleDir) || !filepath.IsAbs(receipt.OutputDir) {
return errors.New("build receipt repository, module, and output directories must be absolute")
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")
@@ -215,16 +222,65 @@ func validateBuildReceipt(receipt BuildReceipt) error {
func validateRecordedIdentity(receipt BuildReceipt) error {
repositoryDir := filepath.Clean(receipt.RepositoryDir)
moduleDir := filepath.Clean(receipt.ModuleDir)
relative, err := filepath.Rel(repositoryDir, moduleDir)
sourceDir := filepath.Clean(receipt.SourceDir)
relative, err := filepath.Rel(repositoryDir, sourceDir)
if err != nil {
return fmt.Errorf("relate module directory to repository: %w", err)
}
if relative == ".." || strings.HasPrefix(relative, ".."+string(filepath.Separator)) || filepath.IsAbs(relative) {
return errors.New("module directory is outside repository")
return errors.New("source directory is outside repository")
}
if relative == "" {
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,

View File

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

View File

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

View File

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

View File

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

View File

@@ -19,6 +19,7 @@ import (
"go.maximumdirect.net/releasekit/internal/git"
"go.maximumdirect.net/releasekit/internal/gotool"
"go.maximumdirect.net/releasekit/internal/releaseidentity"
"go.maximumdirect.net/releasekit/internal/versioncontract"
)
func main() {
@@ -37,6 +38,12 @@ func run(ctx context.Context, args []string, stdout, stderr io.Writer) int {
if invocation.Command == cli.ReconcileAction || invocation.Command == cli.PublicationAttemptsAction {
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 {
@@ -69,8 +76,8 @@ func runCheckOrPublish(ctx context.Context, invocation cli.Invocation, stdout, s
}
request := candidateRequest(invocation, settings, stderr)
if invocation.Command == cli.PublishAction {
if err := checkExpectedModule(ctx, invocation.Repository, invocation.ExpectedModule, settings.ModuleDir); err != nil {
fmt.Fprintf(stderr, "profile module selection: %v\n", err)
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
@@ -168,6 +175,10 @@ func publicationOffersRecovery(phase releasekit.PublicationPhase) bool {
}
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)
@@ -184,7 +195,7 @@ func publicationRecoveryCommand(recordPath string) (string, error) {
if err != nil {
return "", fmt.Errorf("resolve publication record path: %w", err)
}
return shellQuote(executable) + " reconcile --record " + shellQuote(recordPath), nil
return shellQuote(executable) + " " + command + " --record " + shellQuote(recordPath), nil
}
func shellQuote(argument string) string {
@@ -204,6 +215,7 @@ func runBuild(ctx context.Context, invocation cli.Invocation, stdout, stderr io.
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,
@@ -252,10 +264,22 @@ func runBuild(ctx context.Context, invocation cli.Invocation, stdout, stderr io.
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,
@@ -266,10 +290,11 @@ 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.ModuleDir, checks, map[string]string{
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,
@@ -324,28 +349,40 @@ func candidateFailureText(err error) string {
return err.Error()
}
func checkExpectedModule(ctx context.Context, repositoryDir, expectedModule, profileModule string) error {
if expectedModule == "" {
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
}
expected, err := releaseidentity.ResolveCommittedSelection(ctx, repositoryDir, expectedModule, commit)
selected, err := releaseidentity.ResolveCommittedSource(ctx, repositoryDir, settings.ModuleDir, commit, settings.SourceSpec())
if err != nil {
return fmt.Errorf("normalize expected module %q: %w", expectedModule, err)
return fmt.Errorf("normalize profile source: %w", err)
}
selected, err := releaseidentity.ResolveCommittedSelection(ctx, repositoryDir, profileModule, commit)
if err != nil {
return fmt.Errorf("normalize profile module %q: %w", profileModule, err)
}
if expected.ModuleSubdir != selected.ModuleSubdir {
return fmt.Errorf("expected module %q resolves to %q, but the profile selects %q", expectedModule, expected.ModuleSubdir, selected.ModuleSubdir)
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 "."
@@ -385,25 +422,36 @@ 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
}
if err := checkExpectedModule(ctx, invocation.Repository, invocation.ExpectedModule, settings.ModuleDir); err != nil {
fmt.Fprintf(stderr, "profile module selection: %v\n", err)
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.FromCommitted(ctx, invocation.Repository, settings.ModuleDir, invocation.Version, invocation.Commit)
identity, err := releaseidentity.FromCommittedSource(ctx, invocation.Repository, settings.ModuleDir, invocation.Version, invocation.Commit, settings.SourceSpec())
if err != nil {
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 module tag %q\n", invocation.ExpectedTag, identity.Tag)
fmt.Fprintf(stderr, "expected delivery tag %q does not match selected source tag %q\n", invocation.ExpectedTag, identity.Tag)
return 1
}
destination, status := deliveryDestination(invocation.Repository, settings, stderr)
if !identity.GoEnabled && settings.Build != nil && len(settings.Build.Targets) != 0 {
fmt.Fprintln(stderr, "build targets require Go capability")
return 2
}
destination, status := deliveryDestination(invocation.Repository, settings, cli.CICredentials, stderr)
if status != 0 {
return status
}
@@ -414,7 +462,7 @@ func runCIDelivery(ctx context.Context, invocation cli.Invocation, stdout, stder
}
if err := releasekit.PrepareBuildDependencies(ctx, releasekit.DependencyPreparationRequest{
RepositoryDir: invocation.Repository,
ModuleDir: settings.ModuleDir,
ModuleDir: identity.ModuleSubdir,
}); err != nil {
fmt.Fprintf(stderr, "prepare build dependencies: %v\n", err)
return 1
@@ -426,14 +474,14 @@ func runCIDelivery(ctx context.Context, invocation cli.Invocation, stdout, stder
// deliverWithSettings adapts prepared CLI state to the public delivery facade.
// 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(invocation.Repository, 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(repositoryDir string, settings cli.Settings, stderr io.Writer) (releasekit.DeliveryDestination, int) {
func deliveryDestination(repositoryDir string, settings cli.Settings, context cli.CredentialContext, stderr io.Writer) (releasekit.DeliveryDestination, int) {
delivery := settings.Delivery
if delivery == nil {
fmt.Fprintln(stderr, "deliver requires an explicit delivery.forge selection in the profile")
@@ -452,29 +500,9 @@ func deliveryDestination(repositoryDir string, settings cli.Settings, stderr io.
fmt.Fprintln(stderr, "deliver requires base_url, owner, and repository in the profile delivery settings")
return releasekit.DeliveryDestination{}, 2
}
tokenEnv := delivery.TokenEnv
if strings.TrimSpace(tokenEnv) == "" {
tokenEnv = "RELEASEKIT_GITEA_TOKEN"
}
token, ok := os.LookupEnv(tokenEnv)
if (!ok || strings.TrimSpace(token) == "") && delivery.TokenFile != "" {
name := delivery.TokenFile
if !filepath.IsAbs(name) {
name = filepath.Join(repositoryDir, name)
}
contents, err := os.ReadFile(name)
if err != nil {
fmt.Fprintf(stderr, "read delivery token file: %v\n", err)
return releasekit.DeliveryDestination{}, 2
}
token = strings.TrimSpace(string(contents))
if token == "" {
fmt.Fprintln(stderr, "delivery token file is empty or blank")
return releasekit.DeliveryDestination{}, 2
}
}
if strings.TrimSpace(token) == "" {
fmt.Fprintf(stderr, "deliver requires a non-empty token in environment variable %s\n", tokenEnv)
token, _, err := cli.ResolveDeliveryCredential(repositoryDir, delivery.Credentials, context)
if err != nil {
fmt.Fprintln(stderr, err)
return releasekit.DeliveryDestination{}, 2
}
return releasekit.DeliveryDestination{Forge: releasekit.ForgeGitea, BaseURL: delivery.BaseURL, Owner: delivery.Owner, Repository: delivery.Repository, Token: token}, 0
@@ -498,7 +526,7 @@ func deliverWithDestination(ctx context.Context, invocation cli.Invocation, sett
fmt.Fprintf(stderr, "capture asset source commit: %v\n", err)
return 1
}
selection, err := releaseidentity.ResolveCommittedSelection(ctx, invocation.Repository, settings.ModuleDir, commit)
selection, err := releaseidentity.ResolveCommittedSource(ctx, invocation.Repository, settings.ModuleDir, commit, settings.SourceSpec())
if err != nil {
fmt.Fprintf(stderr, "resolve asset module directory: %v\n", err)
return 1
@@ -520,6 +548,7 @@ 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,
@@ -611,6 +640,9 @@ func writeDeliveryRecovery(output io.Writer, result releasekit.DeliveryResult) {
func buildResultFromReceipt(receipt cli.BuildReceipt) *releasekit.BuildResult {
result := &releasekit.BuildResult{
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,
@@ -647,6 +679,14 @@ 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,

View File

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

View File

@@ -27,6 +27,9 @@ func TestMultiModuleSelectorMapsSelectorsAndTags(t *testing.T) {
{mode: "tag", value: "integrations/ckconfig/v1.2.3", want: "ckconfig\tintegrations/ckconfig/v*\tintegrations/ckconfig\treleasekit-ckconfig.json"},
{mode: "tag", value: "integrations/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, "")
@@ -46,10 +49,22 @@ func TestMultiModuleSelectorMapsSelectorsAndTags(t *testing.T) {
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 {

View File

@@ -19,6 +19,8 @@ import (
"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) {
@@ -33,7 +35,7 @@ func TestMultiModuleWoodpeckerDelivery(t *testing.T) {
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.*"} {
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)
}
@@ -41,6 +43,83 @@ func TestMultiModuleWoodpeckerDelivery(t *testing.T) {
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)
@@ -220,6 +299,7 @@ func newMappedDeliveryFixture(t *testing.T, tag string) *mappedDeliveryFixture {
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"))
}
@@ -388,7 +468,7 @@ func workflowModuleFile(module, version string) string {
}
func workflowDeliverySettings(baseURL string) *cli.DeliverySettings {
return &cli.DeliverySettings{Forge: "gitea", BaseURL: baseURL, Owner: "owner", Repository: "example", TokenEnv: "RELEASEKIT_GITEA_TOKEN"}
return &cli.DeliverySettings{Forge: "gitea", BaseURL: baseURL, Owner: "owner", Repository: "example", Credentials: &cli.DeliveryCredentials{CI: &cli.CICredential{TokenEnvironmentVariable: "RELEASEKIT_GITEA_TOKEN"}}}
}
func writeMappedProfile(t *testing.T, repository, name string, settings cli.Settings) {

View File

@@ -22,6 +22,44 @@ import (
"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")

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

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

View File

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

View File

@@ -22,6 +22,14 @@ type recoveryDiagnostic struct {
type safeEvidence struct {
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"`
@@ -61,6 +69,14 @@ type attemptsDocument struct {
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),

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

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

View File

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

View File

@@ -79,11 +79,11 @@ func TestReleaseCandidate(t *testing.T) {
"product": "ReleaseKit",
"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{
"forge": "gitea",
"base_url": "https://forge.maximumdirect.net",
"owner": "base-layer",
"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)

View File

@@ -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://forge.maximumdirect.net" || profile.Delivery.Owner != "base-layer" || profile.Delivery.Repository != "releasekit" || profile.Delivery.TokenEnv != "RELEASEKIT_GITEA_TOKEN" {
if profile.Delivery == nil || profile.Delivery.BaseURL != "https://forge.maximumdirect.net" || profile.Delivery.Owner != "base-layer" || profile.Delivery.Repository != "releasekit" || profile.Delivery.Credentials == nil || profile.Delivery.Credentials.CI == nil || profile.Delivery.Credentials.CI.TokenEnvironmentVariable != "RELEASEKIT_GITEA_TOKEN" {
t.Fatalf("ReleaseKit delivery profile = %#v", profile.Delivery)
}
repository := filepath.Join(t.TempDir(), "tagged ReleaseKit")
@@ -34,6 +34,16 @@ func TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout(t *testing.T) {
}
cliGitRun(t, repository, "config", "user.name", "ReleaseKit Test")
cliGitRun(t, repository, "config", "user.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" +
@@ -47,7 +57,7 @@ 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{data: deliveryServerData{product: "ReleaseKit"}}

View File

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

View File

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

View File

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

View File

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

View File

@@ -181,6 +181,31 @@ func TestWoodpeckerTagDeliveryTemplate(t *testing.T) {
})
}
func TestSingleProductWorkflowClassifiesCompleteDiagnosticTags(t *testing.T) {
for _, file := range []string{"examples/woodpecker/tag-delivery.yml", "examples/woodpecker/releasekit-source-delivery.yml", "examples/source-only/.woodpecker/delivery.yml"} {
t.Run(file, func(t *testing.T) {
body := readWorkflowFile(t, cliRepositoryRoot(t), file)
block, err := extractWoodpeckerCommand(body, "deliver")
if err != nil {
t.Fatal(err)
}
guard, _, ok := strings.Cut(block, "git check-ref-format")
if !ok {
t.Fatal("workflow has no tag preparation boundary")
}
guard = strings.ReplaceAll(guard, "$${", "${")
for _, tag := range []string{"releasekit-test/product/v1.2.3", "releasekit-test/product/2026-12-01", "releasekit-test/root/" + strings.Repeat("a", 32)} {
if output, err := executeWoodpeckerBlock(guard, t.TempDir(), map[string]string{"CI_COMMIT_TAG": tag, "CI_COMMIT_SHA": strings.Repeat("b", 40)}); err != nil {
t.Fatalf("valid tag=%s output=%s error=%v", tag, output, err)
}
}
if output, err := executeWoodpeckerBlock(guard, t.TempDir(), map[string]string{"CI_COMMIT_TAG": "releasekit-test/foreign/" + strings.Repeat("a", 32), "CI_COMMIT_SHA": strings.Repeat("b", 40)}); err == nil {
t.Fatalf("foreign selector accepted: %s", output)
}
})
}
}
func TestWoodpeckerTagDeliveryUsesTaggedModuleVersion(t *testing.T) {
// Synthetic downloads must leave the caller's module cache untouched.
callerCache := t.TempDir()

View File

@@ -101,8 +101,11 @@ type DeliveryRequest struct {
// ModuleDir selects a repository-relative module directory; empty selects
// the repository root.
ModuleDir string
Product string
Version 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
@@ -122,10 +125,16 @@ type DeliveryRequest struct {
// failures may leave some declared assets unreported.
type DeliveryResult struct {
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 stable semantic version.
Version string // selected production or diagnostic identifier.
CandidateCommit string
ReleaseURL string
State DeliveryState
@@ -165,6 +174,7 @@ 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,
ExpectedTag: request.ExpectedTag,
@@ -173,7 +183,18 @@ func Deliver(ctx context.Context, request DeliveryRequest) (DeliveryResult, erro
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
@@ -185,7 +206,7 @@ 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, publicPreflightError(err)
return result
}
// PreflightDelivery checks destination credentials and repository access using

View File

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

View File

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

View File

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

View File

@@ -1,6 +1,6 @@
# Command line
ReleaseKit currently provides eight commands. The exit statuses below belong
The exit statuses below belong
to the native executable. `go run` examples are convenient for source execution,
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.
@@ -22,26 +22,28 @@ 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` 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 (with `-race` when
local Git state, runs the standard offline Go test suite when Go is selected (with `-race` when
`validation.go.race` is true), and runs a separate `go vet -mod=readonly ./...`
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.
The profile's optional `module_dir` selects a repository-relative physical
module directory; omission selects the root module. Validation and configured
product checks use that module selection. Additional check commands run with
the selected module as their working directory and receive
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_MODULE_DIR`, `RELEASEKIT_MODULE_PATH`, and `RELEASEKIT_TAG` in their
`RELEASEKIT_SOURCE_DIR`, `RELEASEKIT_MODULE_DIR`, `RELEASEKIT_MODULE_PATH`, and `RELEASEKIT_TAG` in their
environment. These values are added to each child environment without changing
the ReleaseKit process environment.
the ReleaseKit process environment. Module values are empty for source-only
selections.
When `validation.go.compile_targets` is selected, `check` compiles all packages
for each configured `GOOS/GOARCH` pair after tests and full vet, using static
@@ -77,20 +79,20 @@ Unsupported argument sequences print usage to standard error.
Publish a source tag:
```sh
go run ./cmd/releasekit publish [--repo DIR] [--config FILE] [--expected-module DIR] [--record-dir DIR] VERSION
go run ./cmd/releasekit publish [--repo DIR] [--config FILE] [--expected-module DIR] [--expected-source DIR] [--record-dir DIR] VERSION
```
`publish` reads the same product, remote, validation, and additional-check
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 full tag object. It prints the confirmed semantic
version, full tag, 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. HTTP(S) endpoint
@@ -129,10 +131,11 @@ It reports outside-checkout links to standard error unless boundary enforcement
is selected; submodule contents remain out of scope. Markdown failures stop
publication before product checks or tag creation.
`--expected-module DIR` optionally checks a launcher's selected physical module
against the profile's `module_dir` before candidate work. Both paths are
normalized relative to the repository; the profile remains the source of module
selection. The root selection is `.`.
`--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;
@@ -230,12 +233,26 @@ output directory are invalidated; no new receipt is written. An
empty target list returns the source commit without building or writing a
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.
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
@@ -243,8 +260,8 @@ go run ./cmd/releasekit deliver [--repo DIR] [--config FILE] [--assets DIR] VERS
```
`deliver` requires a `delivery` profile object with an explicit
`"forge": "gitea"` selection and a token loaded from its configured environment
variable or token file. The destination URL does not select a forge. Selection
`"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,
@@ -301,23 +318,23 @@ 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] [--prepared] [--expected-module DIR] --commit OID TAG
releasekit ci-deliver [--repo DIR] [--config FILE] [--remote NAME] [--prepared] [--expected-module DIR] [--expected-source DIR] --commit OID TAG
```
`TAG` is the complete Git tag name, including any module path prefix. Its last
path component must be a stable semantic version; other commands continue to
take a semantic `VERSION`. By default, `ci-deliver` fetches the exact `TAG` from
`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. `--expected-module`
optionally checks that the profile selects the module chosen by a launcher;
module selection itself remains profile-owned. The command compares the selected
module's derived release tag with the full event tag before forge access or
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 token. For binary profiles, it performs a read-only repository
the configured CI environment token. For binary profiles, it performs a read-only repository
preflight before downloading application
dependencies; delivery performs a fresh check after dependency preparation.
Source-only profiles rely on delivery's automatic preflight and skip dependency
@@ -351,3 +368,40 @@ consumers without a declared
ReleaseKit module dependency can use the separately installed-tool command.
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.

View File

@@ -10,21 +10,50 @@ The current profile fields are:
| Field | Required | Behavior |
| --- | --- | --- |
| `product` | Yes | Product name used by release operations. |
| `module_dir` | No | Repository-relative physical Go module directory with its own `go.mod`; omission selects `.` (the repository root). |
| `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 selected forge and destination fields for tagged-source delivery. |
| `readiness` | No | Optional explicit files to check during readiness. |
| `rehearsal` | No | Diagnostic selector and Woodpecker observation settings, required for a rehearsal. |
`module_dir` names the selected module's physical location in the repository;
When Go is selected, `module_dir` names the module's physical location;
ReleaseKit reads its declared import path from that module's own `go.mod`. The
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
not parse a shell command string. Select a shell explicitly when a check needs
@@ -45,9 +74,11 @@ exist in the candidate, even when no file checks are enabled. Paths are literal,
repository-relative files with no glob semantics and may select a file outside
the chosen module. ReleaseKit deduplicates them with module inputs by path. This
field does not enable any checks or expand Go test, vet, or package-compilation
scope. Automatic file inputs stop at independent nested-module boundaries;
vendored files remain included. Reference inspection can read destinations
elsewhere in the captured repository without adding them to those inputs.
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
@@ -59,6 +90,8 @@ This source compatibility check does not name or produce binaries, run a target
executable, or create an artifact manifest. Omitted or empty `compile_targets`
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 uses the selected file inputs, including vendor and
explicit shared files, and ignores
@@ -153,21 +186,38 @@ local files to exist, or inspect Git history. Existing clean-index/worktree
requirements still apply to candidate operations. An ignore rule alone does
not remove a previously committed file from the candidate.
The `delivery` object contains `forge`, `base_url`, `owner`, `repository`, and
optional `token_env` and `token_file`. A delivery request must set `forge` to
`"gitea"`; omission, an empty or whitespace-only value, and unsupported values
are errors when `deliver` or `ci-deliver` is requested. The URL does not select
the forge. These semantic checks run only for delivery, so `check`, `publish`,
and `build` do not require a delivery object, selection, or credentials.
`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).
`token_env` names the environment variable containing the Gitea token and
defaults to `RELEASEKIT_GITEA_TOKEN`. A nonblank environment value takes
precedence. When it is unset or blank, `token_file` selects a plain
token-containing file; relative paths resolve from the Git repository root,
and absolute paths are used as supplied. The CLI trims leading and trailing
whitespace from file contents. An unreadable or blank file, or the absence of
both credential sources, returns status 2. Omission of `token_file` retains
environment-only loading.
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
@@ -180,8 +230,9 @@ delivery-permission deficiency. It does not guarantee later release or asset
writes. Local artifact size and digest checks follow preflight and still finish
before hosted writes.
Credential loading runs only for `deliver` and `ci-deliver`. `check`, `publish`,
and `build` do not read the token file or require a token. The CLI passes the
`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
@@ -195,16 +246,17 @@ such as `insteadOf` are resolved before comparison. A mismatch fails preflight;
omitting the field keeps the selected remote's existing behavior. `check` is
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.
@@ -236,9 +288,11 @@ 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` takes a full Git `TAG`; its final path component is the stable
semantic version and the complete value is checked against the profile's
derived tag. By default it fetches the selected tag, confirms its peeled commit
`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

View File

@@ -1,8 +1,22 @@
# 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
@@ -15,6 +29,8 @@ go mod tidy
```
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;

View File

@@ -36,9 +36,9 @@ func build(ctx context.Context) error {
}
```
`Build` resolves `ModuleDir` and the selected module's working-tree declaration
once, records the repository's current `HEAD`, injects the selected stable
version into `buildinfo.Version`, and returns repository/module identity, the
`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
@@ -47,6 +47,10 @@ target pair is built once, at its first position. Local builds may use modified
source. `SourceVerified` is true only after a complete build observes clean
source 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.
Go commands run from `ModuleDir`, so `MainPackage` is interpreted within that
module. The default output directory is `<module>/dist`; a relative `OutputDir`

View File

@@ -33,13 +33,26 @@ example, both `integrations/core/v2` and `integrations/core` can declare
`<module>/docs/releases/<version>.md`.
The repository must have a clean index and worktree on `main`, and the selected
version must be stable `vMAJOR.MINOR.PATCH`. The module-local committed
version must match the selected format. With the module shorthand it must be
stable `vMAJOR.MINOR.PATCH`. The module-local committed
`<module>/docs/releases/<version>.md` note must have a first Markdown H1 containing the
product name and exact version as complete title elements. No local tag with
the derived complete tag may already exist. Different modules may use the same
semantic version with distinct notes and tags.
ReleaseKit runs one `go test -mod=readonly -count=1 ./...` suite from the
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
@@ -93,9 +106,9 @@ standard suite, selected vet/format/distribution checks, or Markdown navigation
checks in `AdditionalChecks` or profile `checks`. Keep release-note rules and
consumer-specific assertions—such as tests of maintained examples—in those
product-owned checks.
The `Candidate` supplies both `RepositoryDir` and `ModuleDir`, plus the declared
`ModulePath`, semantic `Version`, and full `Tag`; use its module directory for
module-local product checks. ReleaseKit calls `AdditionalChecks` once after
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

View File

@@ -9,12 +9,16 @@ The operation accepts historical lightweight and annotated tags, including a
detached checkout, when the checked-out `HEAD` identifies the selected tag
commit. It does not require the old remote `main` to match.
Delivery resolves the selected module's declaration and release note from the
captured commit. `Version` remains the semantic version; the full tag includes
the selected module's repository-relative physical path when it is nested. The
profile or API request selects the physical module directory. The optional API
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.
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
@@ -74,7 +78,10 @@ Add a Gitea destination to the profile:
"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"}
}
}
}
```
@@ -83,11 +90,11 @@ 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 resolves the token for delivery using the configured environment
variable or token file. 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.
@@ -106,15 +113,15 @@ as `.releasekit/gitea-token` and configure:
"base_url": "https://gitea.example",
"owner": "example",
"repository": "example",
"token_file": ".releasekit/gitea-token"
"credentials": {"local": {"token_file": ".releasekit/gitea-token"}}
}
}
```
Add `.releasekit/` to the consumer's ignore rules and use owner-only file
permissions for the saved token. Then run `releasekit deliver v1.2.3` from the
tagged checkout. CI can continue supplying the environment token. See the
[configuration reference](../config.md) for precedence, path resolution, and the
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
@@ -131,17 +138,18 @@ 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 its schema, repository, commit, version, resolved
module directory and path, full tag, normalized build settings, and artifact
declarations. Old receipts must be regenerated with the updated `build`
command. Delivery verifies the artifact bytes and sizes after read-only
`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.
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.

View File

@@ -31,6 +31,13 @@ physical location. `Version` remains the stable semantic version. The note is
the note path but is removed from the tag prefix only when the module path ends
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
@@ -44,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

View File

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

View File

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

View File

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

View File

@@ -40,6 +40,10 @@ declared module stored at `integrations/core` derives the same tag. ReleaseKit
removes a final physical `/v2` directory from the tag prefix only when the
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

View File

@@ -13,9 +13,17 @@ Each saved attempt is one complete JSON document with this versioned envelope:
```json
{
"format_version": 1,
"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",
@@ -34,20 +42,20 @@ stopped before they were captured; loading preserves that partial evidence and
does not fill fields from the current checkout. Additional fields in a
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 supports versions 1 and 2; no migration from
as record-format errors. The codec reads versions 1, 2, and 3; no migration from
an unsupported version is performed.
Ordinary UTF-8 evidence uses version 1. Evidence containing other pathname or
endpoint bytes uses version 2 with the same `evidence` object and an additional
`evidence_bytes` object. Each entry in `evidence_bytes` uses an evidence field
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 every evidence field and preserves the same identity as typed Go evidence.
Older CLIs that support only version 1 report an unsupported version for these
byte-containing records; use a CLI supporting version 2 to load them.
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
@@ -65,7 +73,8 @@ not private attempt records or a Go serialization of public structs.
was read. Available `observed_tag_object` and `observed_commit` fields are
included when present. A `diagnostic` is included for unresolved observation
or record loading failure. Loading failure omits evidence, state, and observed
IDs.
IDs. Safe evidence may include source, capability, publication, and version
selection fields when those were captured.
`publication-attempts` includes `record_dir`, an `attempts` array with each
`record_path` and safe `evidence`, and a `diagnostics` array. A top-level

View File

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

View File

@@ -3,24 +3,29 @@
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`, `reconcile`, `publication-attempts`, `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.
@@ -33,15 +38,15 @@ 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` | Resolved-identity builds, normalized settings, selected-module compilation, version injection, external native smoke output, and artifact digests. |
| `internal/candidate` | Stable-version, note, repository-state, candidate capture, and post-validation checks. |
| `internal/delivery` | Read-only backend preflight, captured-commit module identity and note selection, literal-tag checkout checks, prebuilt identity binding, managed builds in disposable storage outside the checkout, artifact declaration, manifest assembly, shared page and asset policy, streamed comparisons, write recovery, and delivery outcomes. |
| `internal/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. |
@@ -49,11 +54,15 @@ reports these implemented packages:
| `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/releaseidentity` | Committed-object and working-tree module selection, declaration reading, and semantic-version-to-tag derivation. |
| `internal/readiness` | Working/committed input inspection and read-only setup observations for explicitly selected capabilities. |
| `internal/recordstore` | Shared private-record location and worktree safety checks. |
| `internal/rehearsal` | Diagnostic tag manifests, private attempt evidence, dispatch, and exact CI job observation for rehearsal recovery. |
| `internal/releaseidentity` | Committed and working source and optional Go module selection, declaration reading, and production/diagnostic tag and note identity. |
| `internal/validation` | Shared Go validation with optional race, full-vet, and static package-compilation target selections, formatting, workspace-file and filesystem-replacement checks, per-blob size limits, and selected Markdown destination and fragment checking; `internal/candidate` retains capture, callback sequencing, and local-state rechecks. |
| `internal/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

View File

@@ -13,12 +13,18 @@ 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
For local hosted-page delivery, save a Gitea personal access token in
`.releasekit/gitea-token` with owner-only file permissions. The file contains
only the token. ReleaseKit's profile selects this file as a fallback to
`RELEASEKIT_GITEA_TOKEN`; `.releasekit/` is already ignored. Its optional
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

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

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

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

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

View File

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

View File

@@ -1,7 +1,7 @@
# Multi-module release example
This example maps selectors and complete event tags to a physical Go module
directory and a repository-root profile. The library derives the release tag
directory or installed tool and a repository-root profile. The library derives the release tag
from the selected module declaration and physical location; the table only
selects the corresponding profile and checkout directory.
@@ -15,11 +15,12 @@ minimum.
## Select the release tool
The module files are setup skeletons. Set `RELEASEKIT_TOOL_VERSION` to a released
ReleaseKit version at or after the v0.5.0 vanity-path migration, then register
that tool in each consumer module before running the launcher or workflow:
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:?Select a ReleaseKit release with module-release support}"
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
@@ -38,11 +39,12 @@ support and migration from earlier versions.
1. Local selector.
2. Shell pattern matched against a complete event tag.
3. Repository-relative physical module directory (`.` means the root module).
3. Repository-relative tool module directory (`.` means the root module); `-` selects the installed tool from `.releasekit-version`.
4. Repository-relative profile path.
The checked-in patterns are `v[01].*`, `integrations/ckconfig/v*`, and
`integrations/core/v2.*`. The helper passes pattern text to the shell's `case`
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`
@@ -68,9 +70,14 @@ Then select a module and semantic version with the shared launcher:
./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
```
The launcher copies the selected module's `go.mod` and `go.sum` to temporary
For a source-only row, the launcher installs the pinned tool with
`scripts/releasekit-tool` and passes the selected profile without interpreting
`-` as a source directory. The checked-in pin selects v0.11.0.
For Go rows, the launcher copies the selected module's `go.mod` and `go.sum` to temporary
alternate module files outside the checkout, resolves ReleaseKit from that
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
@@ -93,9 +100,9 @@ outside the checkout, and runs the selected ReleaseKit tool by its full package
path. It passes `ci-deliver --prepared`, the mapped profile, and the expected
physical module to the tool.
The `core-v2` profile demonstrates binary delivery; the other profiles are
page-only. Before enabling the workflow, configure each selected profile's
`delivery` object with `"forge": "gitea"`, its `base_url`, owner, and repository,
then add the Woodpecker repository secret
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.
@@ -153,3 +160,13 @@ These commands use the repository-root profile paths even when invoked from a
child module. The core profile also verifies the native binary and injected
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.

View File

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

View File

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

View File

@@ -1,4 +1,5 @@
# selector<TAB>tag pattern<TAB>module directory<TAB>profile path
# selector<TAB>tag pattern<TAB>tool module directory<TAB>profile path
root v[01].* . releasekit-root.json
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
1 # selector<TAB>tag pattern<TAB>module directory<TAB>profile path # selector<TAB>tag pattern<TAB>tool module directory<TAB>profile path
2 root root
3 ckconfig ckconfig
4 core-v2 core-v2
5 config

View File

@@ -19,6 +19,11 @@ trap 'rm -rf "$bootstrap_dir"' EXIT
tab=$(printf '\t')
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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -4,13 +4,33 @@
"build": {
"main_package": "./cmd/example",
"binary_name": "example",
"targets": ["linux/amd64", "linux/arm64", "darwin/arm64"]
"targets": [
"linux/amd64",
"linux/arm64",
"darwin/arm64"
]
},
"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"
}
}
},
"rehearsal": {
"woodpecker": {
"base_url": "https://ci.example",
"repository_id": 42,
"workflow": "delivery",
"step": "deliver",
"token_file": ".releasekit/woodpecker-token"
}
}
}

View File

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

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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,50 @@
package delivery
import (
"context"
"errors"
"fmt"
"go.maximumdirect.net/releasekit/internal/artifact"
"go.maximumdirect.net/releasekit/internal/forge"
"go.maximumdirect.net/releasekit/internal/git"
"go.maximumdirect.net/releasekit/internal/releaseidentity"
)
// verifyDiagnostic re-reads the complete page and each declared asset before
// managed output is removed. Local declarations have already been verified.
func verifyDiagnostic(ctx context.Context, backend forge.Backend, identity releaseidentity.Identity, note string, assets []artifact.ExpectedAsset) (int64, []VerifiedAsset, error) {
diagnostic, ok := backend.(forge.DiagnosticBackend)
if !ok {
return 0, nil, errors.New("diagnostic release observation is unavailable")
}
commit, err := backend.TagCommit(ctx, identity.Tag)
if err != nil {
return 0, nil, err
}
if !git.EqualObjectID(commit, identity.Commit) {
return 0, nil, errors.New("hosted diagnostic tag changed during delivery")
}
page, err := diagnostic.FindDiagnosticRelease(ctx, identity.Tag)
if err != nil {
return 0, nil, err
}
if page.ID <= 0 || page.Release.Tag != identity.Tag || page.Release.Title != releaseNoteTitle(note) || page.Release.Body != note || page.Release.Draft || page.Release.Prerelease {
return page.ID, nil, errors.New("hosted diagnostic page does not match expected title and content")
}
if len(assets) == 0 {
return page.ID, []VerifiedAsset{}, nil
}
inspection, err := inspectRemoteAssets(ctx, backend, page.Release.Handle, assets)
if err != nil {
return page.ID, nil, err
}
verified := make([]VerifiedAsset, 0, len(assets))
for _, item := range inspection.Assets {
if item.State != AssetMatching {
return page.ID, verified, fmt.Errorf("hosted diagnostic asset %q is %s", item.Expected.Filename, item.State)
}
verified = append(verified, VerifiedAsset{Name: item.Expected.Filename, Size: item.Expected.Size, SHA256: item.Expected.SHA256})
}
return page.ID, verified, nil
}

View File

@@ -0,0 +1,17 @@
package forge
import "context"
// DiagnosticBackend supports observation and deletion of recorded temporary
// releases. Callers must establish ownership before asking for deletion.
type DiagnosticBackend interface {
FindDiagnosticRelease(context.Context, string) (DiagnosticRelease, error)
ObserveDiagnosticRelease(context.Context, int64) (DiagnosticRelease, error)
DeleteDiagnosticRelease(context.Context, int64, string) (WriteEvidence, error)
}
// DiagnosticRelease carries a stable remote ID and the normal observed handle.
type DiagnosticRelease struct {
ID int64
Release Release
}

112
internal/git/diagnostic.go Normal file
View File

@@ -0,0 +1,112 @@
package git
import (
"context"
"errors"
"fmt"
"os/exec"
"strings"
)
// QueryLocalDiagnosticTag distinguishes an absent local ref from an unreadable
// or non-annotated ref; an error never establishes absence.
func QueryLocalDiagnosticTag(ctx context.Context, repo, tag string) (RefState, AnnotatedTag, error) {
if !strings.HasPrefix(tag, "releasekit-test/") {
return RefUnreadable, AnnotatedTag{}, errors.New("diagnostic tag is required")
}
if err := CheckTagRef(ctx, repo, tag); err != nil {
return RefUnreadable, AnnotatedTag{}, err
}
_, err := run(ctx, repo, nil, "show-ref", "--verify", "--quiet", "refs/tags/"+tag)
if err != nil {
var exit *exec.ExitError
if errors.As(err, &exit) && exit.ExitCode() == 1 && ctx.Err() == nil {
return RefAbsent, AnnotatedTag{}, nil
}
return RefUnreadable, AnnotatedTag{}, err
}
observed, err := ReadAnnotatedTag(ctx, repo, tag)
if err != nil {
return RefUnreadable, AnnotatedTag{}, err
}
return RefPresent, observed, nil
}
func checkDiagnosticTag(ctx context.Context, repo, tag, object, commit string) error {
if !strings.HasPrefix(tag, "releasekit-test/") || !ValidObjectID(object) || !ValidObjectID(commit) {
return errors.New("a diagnostic tag and exact tag object and commit are required")
}
return CheckTagRef(ctx, repo, tag)
}
// PushDiagnosticTag publishes a verified local diagnostic object without
// moving a conflicting remote ref. Callers reconcile an error by observation.
func (endpoint Endpoint) PushDiagnosticTag(ctx context.Context, repo, tag, object, commit string) (resultErr error) {
delegated := false
defer func() {
if resultErr != nil && !delegated {
resultErr = &PushError{PushNotAttempted, resultErr}
}
}()
if err := checkDiagnosticTag(ctx, repo, tag, object, commit); err != nil {
return err
}
local, err := ReadAnnotatedTag(ctx, repo, tag)
if err != nil {
return err
}
if !EqualObjectID(local.Object, object) || !EqualObjectID(local.Commit, commit) {
return errors.New("local diagnostic tag differs from recorded object or commit")
}
remote, err := endpoint.QueryTag(ctx, repo, tag)
if err != nil {
return err
}
if remote.State == RefPresent && EqualObjectID(remote.Object, object) && EqualObjectID(remote.Peeled, commit) {
return nil
}
if remote.State != RefAbsent {
return fmt.Errorf("diagnostic tag already exists with different evidence: %w", ErrRemoteTagConflict)
}
delegated = true
return endpoint.PushTag(ctx, repo, tag, object)
}
// DeleteDiagnosticTag deletes only the recorded remote annotated tag object.
// A failed push remains uncertain; callers must query the endpoint again.
func (endpoint Endpoint) DeleteDiagnosticTag(ctx context.Context, repo, tag, object, commit string) error {
if err := checkDiagnosticTag(ctx, repo, tag, object, commit); err != nil {
return err
}
observed, err := endpoint.QueryTag(ctx, repo, tag)
if err != nil {
return err
}
if observed.State == RefAbsent {
return nil
}
if observed.State != RefPresent || !EqualObjectID(observed.Object, object) || !EqualObjectID(observed.Peeled, commit) {
return fmt.Errorf("diagnostic tag differs from recorded object or commit: %w", ErrRemoteTagConflict)
}
ref := "refs/tags/" + tag
if _, err := run(ctx, repo, endpoint.scopedConfig(), "push", "--no-follow-tags", "--recurse-submodules=no", "--porcelain", "--force-with-lease="+ref+":"+object, endpoint.ScopedName, ":"+ref); err != nil {
return fmt.Errorf("delete diagnostic tag %s at %s: %w", tag, DisplayURL(endpoint.PushURL), err)
}
return nil
}
// DeleteLocalDiagnosticTag uses Git's atomic expected-old-object check.
func DeleteLocalDiagnosticTag(ctx context.Context, repo, tag, object, commit string) error {
if err := checkDiagnosticTag(ctx, repo, tag, object, commit); err != nil {
return err
}
observed, err := ReadAnnotatedTag(ctx, repo, tag)
if err != nil {
return err
}
if !EqualObjectID(observed.Object, object) || !EqualObjectID(observed.Commit, commit) {
return errors.New("local diagnostic tag differs from recorded object or commit")
}
_, err = run(ctx, repo, nil, "update-ref", "-d", "refs/tags/"+tag, object)
return err
}

View File

@@ -0,0 +1,91 @@
package git
import (
"errors"
"os"
"path/filepath"
"strings"
"testing"
)
func TestDiagnosticPushRetainsNonDispatchEvidence(t *testing.T) {
fixture := newRemoteFixture(t)
endpoint, err := Resolve(t.Context(), fixture.work, "origin")
if err != nil {
t.Fatal(err)
}
tag := "releasekit-test/root/" + strings.Repeat("b", 32)
object, err := CreateAnnotatedTag(t.Context(), fixture.work, tag, fixture.commit, []byte("diagnostic\n"))
if err != nil {
t.Fatal(err)
}
var failure *PushError
err = endpoint.PushDiagnosticTag(t.Context(), fixture.work, tag, strings.Repeat("c", len(object)), fixture.commit)
if !errors.As(err, &failure) || failure.Disposition != PushNotAttempted {
t.Fatalf("pre-dispatch error=%v evidence=%+v", err, failure)
}
if err := os.WriteFile(filepath.Join(fixture.bare, "hooks", "pre-receive"), []byte("#!/bin/sh\nexit 1\n"), 0700); err != nil {
t.Fatal(err)
}
err = endpoint.PushDiagnosticTag(t.Context(), fixture.work, tag, object, fixture.commit)
if !errors.As(err, &failure) || failure.Disposition != PushRejected {
t.Fatalf("rejected error=%v evidence=%+v", err, failure)
}
observed, err := endpoint.QueryTag(t.Context(), fixture.work, tag)
if err != nil || observed.State != RefAbsent {
t.Fatalf("rejected ref=%+v error=%v", observed, err)
}
}
func TestPushRejectionRequiresDefinitiveExactRefStatus(t *testing.T) {
ref := "refs/tags/releasekit-test/root/" + strings.Repeat("a", 32)
for _, test := range []struct {
summary, destination string
want bool
}{
{"[remote rejected] (pre-receive hook declined)", ref, true},
{"[rejected] (already exists)", ref, true},
{"[remote failure] (remote failed to report status)", ref, false},
{"[remote rejected] (pre-receive hook declined)", "refs/tags/foreign", false},
} {
if got := rejectedPush("!\tobject:"+test.destination+"\t"+test.summary+"\n", ref); got != test.want {
t.Fatalf("summary=%q destination=%q result=%t", test.summary, test.destination, got)
}
}
}
func TestDiagnosticTagDeletionRequiresRecordedObjectAndCommit(t *testing.T) {
fixture := newRemoteFixture(t)
ctx := t.Context()
endpoint, err := Resolve(ctx, fixture.work, "origin")
if err != nil {
t.Fatal(err)
}
tag := "releasekit-test/root/" + strings.Repeat("a", 32)
object, err := CreateAnnotatedTag(ctx, fixture.work, tag, fixture.commit, []byte("diagnostic\n"))
if err != nil {
t.Fatal(err)
}
if err := endpoint.PushDiagnosticTag(ctx, fixture.work, tag, object, fixture.commit); err != nil {
t.Fatal(err)
}
if err := endpoint.PushDiagnosticTag(ctx, fixture.work, tag, object, fixture.commit); err != nil {
t.Fatalf("identical push: %v", err)
}
if err := endpoint.DeleteDiagnosticTag(ctx, fixture.work, tag, object, strings.Repeat("b", 40)); !errors.Is(err, ErrRemoteTagConflict) {
t.Fatalf("incorrect commit error=%v", err)
}
if err := DeleteLocalDiagnosticTag(ctx, fixture.work, tag, strings.Repeat("b", 40), fixture.commit); err == nil {
t.Fatal("deleted tag with incorrect object")
}
if err := endpoint.DeleteDiagnosticTag(ctx, fixture.work, tag, object, fixture.commit); err != nil {
t.Fatal(err)
}
ref, err := endpoint.QueryTag(ctx, fixture.work, tag)
if err != nil || ref.State != RefAbsent {
t.Fatalf("remote=%+v error=%v", ref, err)
}
if err := DeleteLocalDiagnosticTag(ctx, fixture.work, tag, object, fixture.commit); err != nil {
t.Fatal(err)
}
}

View File

@@ -139,6 +139,30 @@ func (endpoint Endpoint) Recheck(ctx context.Context, repositoryDir string) erro
return endpoint.verifyScopedURLs(ctx, repositoryDir)
}
// QueryMain reads authoritative main without requiring a release tag or
// comparing the branch to a candidate commit.
func (endpoint Endpoint) QueryMain(ctx context.Context, repositoryDir string) (RemoteRef, error) {
const mainRef = "refs/heads/main"
output, err := run(ctx, repositoryDir, endpoint.scopedConfig(), "ls-remote", endpoint.ScopedName, mainRef)
if err != nil {
return RemoteRef{State: RefUnreadable}, fmt.Errorf("%w: query authoritative main at %s: %w", ErrRemoteStateUnreadable, DisplayURL(endpoint.PushURL), err)
}
main := RemoteRef{State: RefAbsent}
for _, line := range strings.Split(strings.TrimSuffix(output, "\n"), "\n") {
if line == "" {
continue
}
object, name, ok := strings.Cut(line, "\t")
if !ok || !validObjectID(object) {
return RemoteRef{State: RefUnreadable}, fmt.Errorf("%w: malformed ls-remote output %q", ErrRemoteStateUnreadable, displayDiagnostic(line))
}
if name == mainRef {
main = mergeRef(main, object, false)
}
}
return main, nil
}
// Query reads exact main and tag refs. A command failure is unreadable,
// never evidence that a ref is absent.
func (endpoint Endpoint) Query(ctx context.Context, repositoryDir, tag string) (Snapshot, error) {
@@ -267,6 +291,14 @@ func pushURLs(ctx context.Context, repositoryDir, remoteName string) ([]string,
}
func run(ctx context.Context, dir string, config []string, args ...string) (string, error) {
return runWithEnvironment(ctx, dir, config, nil, args...)
}
func runWithEnvironment(ctx context.Context, dir string, config []string, environment map[string]string, args ...string) (string, error) {
if environment == nil {
environment = make(map[string]string)
}
environment["GIT_NO_REPLACE_OBJECTS"] = "1"
commandArgs := make([]string, 0, len(config)*2+len(args))
for _, value := range config {
commandArgs = append(commandArgs, "-c", value)
@@ -276,7 +308,7 @@ func run(ctx context.Context, dir string, config []string, args ...string) (stri
err := process.Run(ctx, process.Invocation{
Args: append([]string{"git"}, commandArgs...),
Dir: dir,
Env: map[string]string{"GIT_NO_REPLACE_OBJECTS": "1"},
Env: environment,
Stdout: &stdout,
Stderr: &stderr,
})

View File

@@ -10,6 +10,23 @@ import (
"testing"
)
func TestQueryMainDoesNotRequireAReleaseTag(t *testing.T) {
repo := newRemoteFixture(t)
endpoint, err := Resolve(context.Background(), repo.work, "origin")
if err != nil {
t.Fatal(err)
}
main, err := endpoint.QueryMain(context.Background(), repo.work)
if err != nil || main.State != RefPresent || main.Object != repo.commit {
t.Fatalf("main = %#v, error = %v", main, err)
}
gitRun(t, repo.bare, "update-ref", "-d", "refs/heads/main")
main, err = endpoint.QueryMain(context.Background(), repo.work)
if err != nil || main.State != RefAbsent {
t.Fatalf("missing main = %#v, error = %v", main, err)
}
}
func TestResolveUsesPushURLAndQueriesWithoutMutation(t *testing.T) {
repo := newRemoteFixture(t)
configBefore := gitText(t, repo.work, "config", "--get-all", "remote.origin.url") + "\x00" + gitText(t, repo.work, "config", "--get-all", "remote.origin.pushurl")

View File

@@ -47,6 +47,30 @@ func RepositoryRoot(ctx context.Context, directory string) (string, error) {
return normalizeRepositoryRoot(root)
}
// ResolveCommit resolves a revision to its full commit ID without changing the checkout.
func ResolveCommit(ctx context.Context, repositoryDir, revision string) (string, error) {
if revision == "" {
revision = "HEAD"
}
output, err := run(ctx, repositoryDir, nil, "rev-parse", "--verify", "--end-of-options", revision+"^{commit}")
if err != nil {
return "", fmt.Errorf("resolve selected revision: %w", err)
}
commit := strings.TrimSpace(output)
if !validObjectID(commit) {
return "", fmt.Errorf("selected revision did not resolve to a full commit ID")
}
return commit, nil
}
// CheckTaggerIdentity checks Git's native committer identity without creating a tag.
func CheckTaggerIdentity(ctx context.Context, directory string) error {
if _, err := run(ctx, directory, nil, "var", "GIT_COMMITTER_IDENT"); err != nil {
return fmt.Errorf("resolve Git tagger identity: %w", err)
}
return nil
}
func normalizeRepositoryRoot(root string) (string, error) {
root = strings.TrimSuffix(root, "\n")
resolved, err := filepath.EvalSymlinks(root)
@@ -362,6 +386,30 @@ func ReadTree(ctx context.Context, repositoryDir, commit string) ([]TreeEntry, e
return entries, nil
}
// ReadTreeDirectory lists immediate entries of a resolved repository-relative
// directory in a captured commit. Entry paths remain repository-relative.
func ReadTreeDirectory(ctx context.Context, repositoryDir, commit, directory string) ([]TreeEntry, error) {
if !validObjectID(commit) {
return nil, fmt.Errorf("invalid commit object ID %q", commit)
}
if directory == "" || path.IsAbs(directory) || path.Clean(directory) != directory || directory == ".." || strings.HasPrefix(directory, "../") {
return nil, fmt.Errorf("invalid committed directory %q", directory)
}
args := []string{"--literal-pathspecs", "ls-tree", "-z", "--full-tree", commit}
if directory != "." {
args = append(args, "--", directory+"/")
}
output, err := readLocalObjects(ctx, repositoryDir, nil, args...)
if err != nil {
return nil, fmt.Errorf("enumerate committed directory %q: %w", directory, err)
}
entries, err := parseTreeEntries(output)
if err != nil {
return nil, fmt.Errorf("parse committed directory %q: %w", directory, err)
}
return entries, nil
}
// ReadBlob reads the bytes for a Git blob object ID without consulting the
// worktree.
func ReadBlob(ctx context.Context, repositoryDir, objectID string) ([]byte, error) {

View File

@@ -6,10 +6,50 @@ import (
"os"
"os/exec"
"path/filepath"
"slices"
"strings"
"testing"
)
func TestReadTreeDirectoryListsOnlyImmediateCapturedEntries(t *testing.T) {
fixture := newRemoteFixture(t)
for _, name := range []string{"pkg[literal]/main.go", "pkg[literal]/nested/deep.go", "unrelated/elsewhere.txt"} {
filename := filepath.Join(fixture.work, filepath.FromSlash(name))
if err := os.MkdirAll(filepath.Dir(filename), 0700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filename, []byte("captured"), 0600); err != nil {
t.Fatal(err)
}
}
gitRun(t, fixture.work, "add", "--all")
gitRun(t, fixture.work, "commit", "-m", "capture package inputs")
commit := strings.TrimSpace(gitText(t, fixture.work, "rev-parse", "HEAD"))
if err := os.Remove(filepath.Join(fixture.work, "pkg[literal]", "main.go")); err != nil {
t.Fatal(err)
}
for _, test := range []struct {
directory string
want []string
}{
{directory: ".", want: []string{"pkg[literal]", "source.txt", "unrelated"}},
{directory: "pkg[literal]", want: []string{"pkg[literal]/main.go", "pkg[literal]/nested"}},
{directory: "pkg[literal]/nested", want: []string{"pkg[literal]/nested/deep.go"}},
} {
entries, err := ReadTreeDirectory(t.Context(), fixture.work, commit, test.directory)
if err != nil {
t.Fatal(err)
}
var names []string
for _, entry := range entries {
names = append(names, entry.Path)
}
if !slices.Equal(names, test.want) {
t.Fatalf("directory %q entries=%v want=%v", test.directory, names, test.want)
}
}
}
func TestInspectTaggedSourceSupportsLightweightAndAnnotatedTags(t *testing.T) {
fixture := newRemoteFixture(t)
gitRun(t, fixture.work, "tag", "v1.2.3")

View File

@@ -6,9 +6,95 @@ import (
"errors"
"fmt"
"os"
"os/exec"
"strings"
)
// AnnotatedTag is the immutable tag object and its direct commit target.
type AnnotatedTag struct {
Object string
Commit string
Message []byte
}
// ReadAnnotatedTag reads an exact local tag and requires a direct commit target.
func ReadAnnotatedTag(ctx context.Context, repositoryDir, tag string) (AnnotatedTag, error) {
if err := CheckTagRef(ctx, repositoryDir, tag); err != nil {
return AnnotatedTag{}, err
}
ref := "refs/tags/" + tag
object, err := run(ctx, repositoryDir, nil, "rev-parse", "--verify", ref)
if err != nil {
return AnnotatedTag{}, fmt.Errorf("resolve annotated tag: %w", err)
}
object = strings.TrimSpace(object)
if !validObjectID(object) {
return AnnotatedTag{}, errors.New("invalid annotated tag object")
}
return ReadAnnotatedTagObject(ctx, repositoryDir, tag, object)
}
// ReadAnnotatedTagObject verifies an explicitly recorded tag object even if
// its local ref has already been removed.
func ReadAnnotatedTagObject(ctx context.Context, repositoryDir, tag, object string) (AnnotatedTag, error) {
if err := CheckTagRef(ctx, repositoryDir, tag); err != nil {
return AnnotatedTag{}, err
}
if !validObjectID(object) {
return AnnotatedTag{}, errors.New("invalid annotated tag object")
}
tagType, err := run(ctx, repositoryDir, nil, "cat-file", "-t", object)
if err != nil {
return AnnotatedTag{}, fmt.Errorf("inspect annotated tag: %w", err)
}
if strings.TrimSpace(tagType) != "tag" {
return AnnotatedTag{}, errors.New("diagnostic reference is not an annotated tag")
}
contents, err := run(ctx, repositoryDir, nil, "cat-file", "tag", object)
if err != nil {
return AnnotatedTag{}, fmt.Errorf("read annotated tag: %w", err)
}
header, message, ok := strings.Cut(contents, "\n\n")
if !ok {
return AnnotatedTag{}, errors.New("annotated tag has no message")
}
var target, targetType, tagName string
for _, line := range strings.Split(header, "\n") {
key, value, ok := strings.Cut(line, " ")
if !ok {
continue
}
switch key {
case "object":
if target != "" {
return AnnotatedTag{}, errors.New("annotated tag repeats its target")
}
target = value
case "type":
if targetType != "" {
return AnnotatedTag{}, errors.New("annotated tag repeats its type")
}
targetType = value
case "tag":
if tagName != "" {
return AnnotatedTag{}, errors.New("annotated tag repeats its name")
}
tagName = value
}
}
if !validObjectID(target) || targetType != "commit" || tagName != tag {
return AnnotatedTag{}, errors.New("annotated tag target or name does not match")
}
actualType, err := run(ctx, repositoryDir, nil, "cat-file", "-t", target)
if err != nil {
return AnnotatedTag{}, fmt.Errorf("inspect annotated tag target: %w", err)
}
if strings.TrimSpace(actualType) != "commit" {
return AnnotatedTag{}, errors.New("annotated tag target is not a commit")
}
return AnnotatedTag{Object: object, Commit: target, Message: []byte(message)}, nil
}
// CreateAnnotatedTag records the captured note as an unsigned annotated tag
// on the captured commit. Once its type and ID are established, the ID is
// returned even if a later verification fails.
@@ -118,17 +204,64 @@ func (endpoint Endpoint) QueryTag(ctx context.Context, repositoryDir, tag string
return finalizeRef(remoteTag), nil
}
// PushDisposition describes evidence from one exact tag push.
type PushDisposition string
const (
PushNotAttempted PushDisposition = "not_attempted"
PushRejected PushDisposition = "rejected"
PushUnknown PushDisposition = "unknown"
)
// PushError preserves the cause and evidence about whether dispatch occurred.
type PushError struct {
Disposition PushDisposition
Err error
}
func (err *PushError) Error() string { return err.Err.Error() }
func (err *PushError) Unwrap() error { return err.Err }
// PushTag publishes only the captured tag object to its exact tag ref.
func (endpoint Endpoint) PushTag(ctx context.Context, repositoryDir, tag, tagObject string) error {
if err := CheckTagRef(ctx, repositoryDir, tag); err != nil {
return err
return &PushError{PushNotAttempted, err}
}
if !validObjectID(tagObject) {
return fmt.Errorf("invalid tag publication object %q at %q", tagObject, tag)
return &PushError{PushNotAttempted, fmt.Errorf("invalid tag publication object %q at %q", tagObject, tag)}
}
refspec := tagObject + ":refs/tags/" + tag
if _, err := run(ctx, repositoryDir, endpoint.scopedConfig(), "push", "--no-follow-tags", "--recurse-submodules=no", "--porcelain", endpoint.ScopedName, refspec); err != nil {
return fmt.Errorf("push annotated tag %s to %s: %w", tag, DisplayURL(endpoint.PushURL), err)
if err := ctx.Err(); err != nil {
return &PushError{PushNotAttempted, err}
}
return nil
ref := "refs/tags/" + tag
output, err := runWithEnvironment(ctx, repositoryDir, endpoint.scopedConfig(), map[string]string{"LC_ALL": "C"}, "push", "--no-follow-tags", "--recurse-submodules=no", "--porcelain", endpoint.ScopedName, tagObject+":"+ref)
if err == nil {
return nil
}
disposition := PushUnknown
var start *exec.Error
var pathError *os.PathError
if errors.As(err, &start) || errors.As(err, &pathError) {
disposition = PushNotAttempted
} else if rejectedPush(output, ref) {
disposition = PushRejected
}
return &PushError{disposition, fmt.Errorf("push annotated tag %s to %s: %w", tag, DisplayURL(endpoint.PushURL), err)}
}
func rejectedPush(output, ref string) bool {
count, rejected := 0, false
for _, line := range strings.Split(output, "\n") {
fields := strings.SplitN(line, "\t", 3)
if len(fields) != 3 {
continue
}
_, destination, ok := strings.Cut(fields[1], ":")
if !ok || destination != ref {
continue
}
count++
rejected = fields[0] == "!" && (strings.HasPrefix(fields[2], "[rejected]") || strings.HasPrefix(fields[2], "[remote rejected]"))
}
return count == 1 && rejected
}

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