Compare commits
60 Commits
3cbb3f3406
...
v0.1.0
| Author | SHA1 | Date | |
|---|---|---|---|
| 5e60fe3113 | |||
| dab4fdf2b3 | |||
| e6def4ed7b | |||
| ceb7e2847a | |||
| 55333b08ae | |||
| 21294404d7 | |||
| c6a5db8aeb | |||
| d970aac709 | |||
| 579daa9485 | |||
| a67a00a733 | |||
| c9afc8dd12 | |||
| 0eec4a30ed | |||
| 3e9b5c1b99 | |||
| 08093124af | |||
| 12e866a94a | |||
| b240e3cfa9 | |||
| a0cb466395 | |||
| e4be7fa699 | |||
| 85b2b39fb6 | |||
| e146a5c61e | |||
| 536a57916f | |||
| af1a76a2f7 | |||
| 1af589dbe8 | |||
| f07545810b | |||
| bb5a8288e6 | |||
| f4d9cf20ec | |||
| ce3a85e3e6 | |||
| 791152370c | |||
| 1d06ba019c | |||
| 685cd8a64d | |||
| 6b777dd861 | |||
| 8b417760c6 | |||
| 4dee2841e0 | |||
| b4d348dd1f | |||
| b744346210 | |||
| 91712fd900 | |||
| a1ee067b53 | |||
| 1d6611601c | |||
| 539877ecc7 | |||
| d0247d1ccb | |||
| 9e619c98a4 | |||
| bdf6a155b5 | |||
| eb2cab78bb | |||
| 692a503c26 | |||
| 717d6d0d04 | |||
| e98ee0f7b9 | |||
| 5d6a6d10bd | |||
| c83313b3b9 | |||
| 7481dd0fd2 | |||
| 3757d40ac4 | |||
| 7d2c0c10d4 | |||
| 617c243923 | |||
| be225cf634 | |||
| 22a3dfe9bc | |||
| d692607e2b | |||
| 9e855c81a6 | |||
| cc7ca47469 | |||
| 6c2695f870 | |||
| 43c20b0f61 | |||
| 4f914f10cf |
5
.gitignore
vendored
5
.gitignore
vendored
@@ -105,6 +105,9 @@ $RECYCLE.BIN/
|
|||||||
|
|
||||||
# Local History for Visual Studio Code
|
# Local History for Visual Studio Code
|
||||||
.history/
|
.history/
|
||||||
|
|
||||||
|
# ReleaseKit build output
|
||||||
|
/dist/
|
||||||
|
/.releasekit/
|
||||||
|
|
||||||
# Built Visual Studio Code Extensions
|
# Built Visual Studio Code Extensions
|
||||||
*.vsix
|
|
||||||
|
|||||||
30
AGENTS.md
Normal file
30
AGENTS.md
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
<!-- codebase-memory-mcp:start -->
|
||||||
|
# Codebase Knowledge Graph (codebase-memory-mcp)
|
||||||
|
|
||||||
|
This project uses codebase-memory-mcp to maintain a knowledge graph of the codebase.
|
||||||
|
ALWAYS prefer MCP graph tools over grep/glob/file-search for code discovery.
|
||||||
|
|
||||||
|
## Priority Order
|
||||||
|
1. `search_graph` — find functions, classes, routes, variables by pattern
|
||||||
|
2. `trace_path` — trace who calls a function or what it calls
|
||||||
|
3. `get_code_snippet` — read specific function/class source code
|
||||||
|
4. `query_graph` — run Cypher queries for complex patterns
|
||||||
|
5. `get_architecture` — high-level project summary
|
||||||
|
|
||||||
|
## When to fall back to grep/glob
|
||||||
|
- Searching for string literals, error messages, config values
|
||||||
|
- Searching non-code files (Dockerfiles, shell scripts, configs)
|
||||||
|
- When MCP tools return insufficient results
|
||||||
|
|
||||||
|
## Examples
|
||||||
|
- Find a handler: `search_graph(name_pattern=".*OrderHandler.*")`
|
||||||
|
- Who calls it: `trace_path(function_name="OrderHandler", direction="inbound")`
|
||||||
|
- Read source: `get_code_snippet(qualified_name="pkg/orders.OrderHandler")`
|
||||||
|
<!-- codebase-memory-mcp:end -->
|
||||||
|
|
||||||
|
Start with `docs/development.md` for orientation and use its policy reading guide
|
||||||
|
to select the policies applicable to the task. Do not read the entire suite by
|
||||||
|
default.
|
||||||
|
|
||||||
|
Read and follow `docs/policy/agents.md` before recommending, planning, or
|
||||||
|
implementing repository changes.
|
||||||
25
COPYRIGHT
Normal file
25
COPYRIGHT
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
ReleaseKit
|
||||||
|
|
||||||
|
Copyright (C) 2026 Eric Rakestraw
|
||||||
|
|
||||||
|
SPDX-License-Identifier: LGPL-3.0-or-later
|
||||||
|
|
||||||
|
This library is free software: you can redistribute it and/or modify it
|
||||||
|
under the terms of the GNU Lesser General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
The GNU Lesser General Public License version 3 and its incorporated
|
||||||
|
GNU General Public License version 3 text are provided in LICENSE.
|
||||||
|
|
||||||
|
This library is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU Lesser General Public License for more details.
|
||||||
|
|
||||||
|
Third-party code and assets are subject to their respective license terms.
|
||||||
|
|
||||||
|
Policy documents adapted from Standard Repository Policies, the root AGENTS.md
|
||||||
|
orientation, and the Policy Reading Guide in docs/development.md remain licensed
|
||||||
|
under CC-BY-SA-4.0. See docs/oss/attribution.md for the affected material,
|
||||||
|
upstream credit, and license links.
|
||||||
76
README.md
76
README.md
@@ -1,3 +1,77 @@
|
|||||||
# ReleaseKit
|
# ReleaseKit
|
||||||
|
|
||||||
ReleaseKit is an opinionated Go library that bundles common scripts and functions for releasing applications.
|
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
|
||||||
|
maintainer procedure and prepared Woodpecker workflow for hosted note-page
|
||||||
|
delivery are documented. ReleaseKit does not declare binary deliverables. The
|
||||||
|
[product roadmap](docs/roadmap/releasekit.md) records remaining adoption and
|
||||||
|
deployment work.
|
||||||
|
|
||||||
|
See the [v0.1.0 release note](docs/releases/v0.1.0.md) for the initial baseline
|
||||||
|
and installation commands.
|
||||||
|
|
||||||
|
Run the offline Go test suite from the repository root with:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go test ./...
|
||||||
|
```
|
||||||
|
|
||||||
|
The version command prints ReleaseKit's version:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go run ./cmd/releasekit version
|
||||||
|
```
|
||||||
|
|
||||||
|
The local candidate check validates a committed release note, runs the standard
|
||||||
|
offline Go test suite, and then runs any configured additional checks:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go run ./cmd/releasekit check v1.2.3
|
||||||
|
```
|
||||||
|
|
||||||
|
Publish the source tag from a committed candidate with:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
./scripts/release v1.2.3
|
||||||
|
```
|
||||||
|
|
||||||
|
See the [ReleaseKit maintainer procedure](docs/release.md) for preparation and
|
||||||
|
failure recovery.
|
||||||
|
|
||||||
|
## Documentation
|
||||||
|
|
||||||
|
- [Product roadmap](docs/roadmap/releasekit.md): consumer adoption goals and
|
||||||
|
remaining release and deployment work.
|
||||||
|
- [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.
|
||||||
|
- [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`.
|
||||||
|
- [Build guidance](docs/consumers/build.md): compile selected Go targets with an
|
||||||
|
injected application version.
|
||||||
|
- [Delivery guidance](docs/consumers/delivery.md): deliver tagged source and
|
||||||
|
report hosted page and asset status.
|
||||||
|
- [Gitea integration](docs/integrations/gitea.md): hosted release-page
|
||||||
|
operations and their failure behavior.
|
||||||
|
- [Candidate check guidance](docs/consumers/check.md): local candidate validation
|
||||||
|
through the Go API and CLI.
|
||||||
|
- [Source publication guidance](docs/consumers/publish.md): validate and publish
|
||||||
|
the exact annotated source tag through the Go API.
|
||||||
|
- [Maintainer release procedure](docs/release.md): ReleaseKit's source-only
|
||||||
|
publication workflow and recovery.
|
||||||
|
- [Internal package inventory](docs/internal/overview.md): implemented internal
|
||||||
|
components and their responsibilities.
|
||||||
|
- [Architecture policy](docs/policy/architecture.md): responsibility and dependency
|
||||||
|
boundaries for development.
|
||||||
|
- [ADR 0001](docs/adr/0001-public-facade.md): the accepted public facade decision.
|
||||||
|
- [Policy provenance](docs/policy/meta.md): adopted policy sources and update
|
||||||
|
guidance.
|
||||||
|
|
||||||
|
ReleaseKit is licensed under the [LGPL v3.0 or later](COPYRIGHT).
|
||||||
|
|
||||||
|
[Open Source attribution notices](docs/oss/attribution.md) are available.
|
||||||
|
|||||||
116
build.go
Normal file
116
build.go
Normal file
@@ -0,0 +1,116 @@
|
|||||||
|
package releasekit
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"io"
|
||||||
|
|
||||||
|
internalbuild "gitea.maximumdirect.net/eric/ReleaseKit/internal/build"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Target identifies one explicit Go operating-system and architecture pair.
|
||||||
|
type Target struct {
|
||||||
|
OS string // Go operating system name, such as "linux".
|
||||||
|
Arch string // Go architecture name, such as "amd64".
|
||||||
|
}
|
||||||
|
|
||||||
|
// BuildSpec selects the application package, output name, and target pairs.
|
||||||
|
type BuildSpec struct {
|
||||||
|
MainPackage string // Go package path to build, such as "./cmd/app".
|
||||||
|
BinaryName string // filename component used in output artifacts.
|
||||||
|
Targets []Target // selected target pairs; duplicates are removed in order.
|
||||||
|
}
|
||||||
|
|
||||||
|
// BuildRequest contains the source and output settings for Build.
|
||||||
|
type BuildRequest struct {
|
||||||
|
RepositoryDir string // source repository whose current HEAD is recorded.
|
||||||
|
Version string // stable vMAJOR.MINOR.PATCH value injected at link time.
|
||||||
|
Spec BuildSpec // application package, artifact name, and targets.
|
||||||
|
OutputDir string // output location; empty selects <repository>/dist.
|
||||||
|
Output io.Writer // optional build progress destination.
|
||||||
|
}
|
||||||
|
|
||||||
|
// BuildArtifact identifies one generated binary and its SHA-256 digest.
|
||||||
|
type BuildArtifact struct {
|
||||||
|
Path string // absolute path to the generated binary.
|
||||||
|
Filename string // generated filename.
|
||||||
|
Target Target // Go target used for this artifact.
|
||||||
|
SHA256 string // lowercase hexadecimal digest of the complete file.
|
||||||
|
}
|
||||||
|
|
||||||
|
// BuildResult describes the source and artifacts reached by Build.
|
||||||
|
type BuildResult struct {
|
||||||
|
RepositoryDir string // absolute source repository path.
|
||||||
|
CandidateCommit string // Git HEAD observed when the build started.
|
||||||
|
// 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
|
||||||
|
Version string // requested injected version.
|
||||||
|
MainPackage string // Go package path built.
|
||||||
|
BinaryName string // artifact name prefix.
|
||||||
|
OutputDir string // resolved output directory.
|
||||||
|
Targets []Target // normalized target pairs.
|
||||||
|
Artifacts []BuildArtifact // completed output files, including partial success.
|
||||||
|
Compiler string // output of the selected local Go toolchain's version command.
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build compiles the selected targets with Version injected through buildinfo.
|
||||||
|
// It uses the available compatible local Go toolchain, applies ReleaseKit's
|
||||||
|
// readonly offline build settings, preserves effective cache and tool settings,
|
||||||
|
// and verifies the version command on the Go host before succeeding. An empty
|
||||||
|
// target set records source identity without running the Go toolchain. Errors
|
||||||
|
// return partial build facts in the result.
|
||||||
|
func Build(ctx context.Context, request BuildRequest) (BuildResult, error) {
|
||||||
|
result, err := internalbuild.Build(ctx, internalbuild.Request{
|
||||||
|
RepositoryDir: request.RepositoryDir,
|
||||||
|
Version: request.Version,
|
||||||
|
Spec: *internalBuildSpec(&request.Spec),
|
||||||
|
OutputDir: request.OutputDir,
|
||||||
|
Output: request.Output,
|
||||||
|
})
|
||||||
|
public := BuildResult{
|
||||||
|
RepositoryDir: result.RepositoryDir,
|
||||||
|
CandidateCommit: result.CandidateCommit,
|
||||||
|
SourceVerified: result.SourceVerified,
|
||||||
|
Version: result.Version,
|
||||||
|
MainPackage: result.MainPackage,
|
||||||
|
BinaryName: result.BinaryName,
|
||||||
|
OutputDir: result.OutputDir,
|
||||||
|
Compiler: result.Compiler,
|
||||||
|
Targets: make([]Target, 0, len(result.Targets)),
|
||||||
|
Artifacts: make([]BuildArtifact, 0, len(result.Artifacts)),
|
||||||
|
}
|
||||||
|
for _, target := range result.Targets {
|
||||||
|
public.Targets = append(public.Targets, Target{OS: target.OS, Arch: target.Arch})
|
||||||
|
}
|
||||||
|
for _, artifact := range result.Artifacts {
|
||||||
|
public.Artifacts = append(public.Artifacts, BuildArtifact{
|
||||||
|
Path: artifact.Path,
|
||||||
|
Filename: artifact.Filename,
|
||||||
|
Target: Target{OS: artifact.Target.OS, Arch: artifact.Target.Arch},
|
||||||
|
SHA256: artifact.SHA256,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return public, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func internalBuildSpec(spec *BuildSpec) *internalbuild.Spec {
|
||||||
|
if spec == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
result := &internalbuild.Spec{MainPackage: spec.MainPackage, BinaryName: spec.BinaryName}
|
||||||
|
for _, target := range spec.Targets {
|
||||||
|
result.Targets = append(result.Targets, internalbuild.Target{OS: target.OS, Arch: target.Arch})
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func internalBuildResult(result BuildResult) *internalbuild.Result {
|
||||||
|
converted := &internalbuild.Result{RepositoryDir: result.RepositoryDir, CandidateCommit: result.CandidateCommit, SourceVerified: result.SourceVerified, Version: result.Version, MainPackage: result.MainPackage, BinaryName: result.BinaryName, OutputDir: result.OutputDir, Compiler: result.Compiler}
|
||||||
|
for _, target := range result.Targets {
|
||||||
|
converted.Targets = append(converted.Targets, internalbuild.Target{OS: target.OS, Arch: target.Arch})
|
||||||
|
}
|
||||||
|
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})
|
||||||
|
}
|
||||||
|
return converted
|
||||||
|
}
|
||||||
650
build_test.go
Normal file
650
build_test.go
Normal file
@@ -0,0 +1,650 @@
|
|||||||
|
package releasekit_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
releasekit "gitea.maximumdirect.net/eric/ReleaseKit"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestBuildCreatesSelectedTargetsAndInjectsVersion(t *testing.T) {
|
||||||
|
repository := newBuildConsumer(t, `package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
if len(os.Args) == 2 && os.Args[1] == "version" {
|
||||||
|
fmt.Printf("fixture %s\n", buildinfo.Version())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`)
|
||||||
|
outputDir := filepath.Join(t.TempDir(), "artifacts")
|
||||||
|
t.Setenv("GOOS", "windows")
|
||||||
|
t.Setenv("GOARCH", "arm64")
|
||||||
|
t.Setenv("GOFLAGS", "-race")
|
||||||
|
var progress bytes.Buffer
|
||||||
|
result, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Spec: releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/app",
|
||||||
|
BinaryName: "fixture",
|
||||||
|
Targets: []releasekit.Target{
|
||||||
|
{OS: "linux", Arch: "amd64"},
|
||||||
|
{OS: "linux", Arch: "arm64"},
|
||||||
|
{OS: "darwin", Arch: "arm64"},
|
||||||
|
{OS: "linux", Arch: "amd64"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
OutputDir: outputDir,
|
||||||
|
Output: &progress,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Build() error = %v; partial result = %#v", err, result)
|
||||||
|
}
|
||||||
|
if result.CandidateCommit == "" || result.CandidateCommit != buildGit(t, repository, "rev-parse", "HEAD") {
|
||||||
|
t.Fatalf("candidate commit = %q", result.CandidateCommit)
|
||||||
|
}
|
||||||
|
if result.Compiler == "" || len(result.Targets) != 3 || len(result.Artifacts) != 3 {
|
||||||
|
t.Fatalf("build result = %#v", result)
|
||||||
|
}
|
||||||
|
wantNames := []string{
|
||||||
|
"fixture-v1.2.3-linux-amd64",
|
||||||
|
"fixture-v1.2.3-linux-arm64",
|
||||||
|
"fixture-v1.2.3-darwin-arm64",
|
||||||
|
}
|
||||||
|
for index, artifact := range result.Artifacts {
|
||||||
|
if artifact.Filename != wantNames[index] || artifact.Target != result.Targets[index] {
|
||||||
|
t.Fatalf("artifact %d = %#v", index, artifact)
|
||||||
|
}
|
||||||
|
contents, err := os.ReadFile(artifact.Path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
digest := sha256.Sum256(contents)
|
||||||
|
if artifact.SHA256 != hex.EncodeToString(digest[:]) {
|
||||||
|
t.Fatalf("artifact digest = %q, want %x", artifact.SHA256, digest)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !strings.Contains(progress.String(), "checking fixture version output") {
|
||||||
|
t.Fatalf("build progress = %q", progress.String())
|
||||||
|
}
|
||||||
|
for _, artifact := range result.Artifacts {
|
||||||
|
if artifact.Target != (releasekit.Target{OS: runtime.GOOS, Arch: runtime.GOARCH}) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
command := exec.Command(artifact.Path, "version")
|
||||||
|
output, err := command.CombinedOutput()
|
||||||
|
if err != nil || string(output) != "fixture v1.2.3\n" {
|
||||||
|
t.Fatalf("native version command output = %q, error = %v", output, err)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildUsesGoHostDespiteAmbientTargetEnvironment(t *testing.T) {
|
||||||
|
repository := newBuildConsumer(t, `package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
if len(os.Args) == 2 && os.Args[1] == "version" { fmt.Printf("fixture %s\n", buildinfo.Version()) }
|
||||||
|
}
|
||||||
|
`)
|
||||||
|
t.Setenv("GOOS", "windows")
|
||||||
|
t.Setenv("GOARCH", "arm64")
|
||||||
|
result, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Version: "v2.3.4",
|
||||||
|
Spec: releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/app",
|
||||||
|
BinaryName: "fixture",
|
||||||
|
Targets: []releasekit.Target{{OS: "windows", Arch: "arm64"}},
|
||||||
|
},
|
||||||
|
OutputDir: filepath.Join(t.TempDir(), "artifacts"),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Build() error = %v; partial result = %#v", err, result)
|
||||||
|
}
|
||||||
|
if len(result.Artifacts) != 1 || result.Artifacts[0].Filename != "fixture-v2.3.4-windows-arm64.exe" {
|
||||||
|
t.Fatalf("build artifacts = %#v", result.Artifacts)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildIgnoresAmbientAndPersistentArchitectureTuning(t *testing.T) {
|
||||||
|
repository := newBuildConsumer(t, `package main
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo"
|
||||||
|
)
|
||||||
|
func main() { if len(os.Args) == 2 && os.Args[1] == "version" { fmt.Printf("fixture %s\n", buildinfo.Version()) } }
|
||||||
|
`)
|
||||||
|
|
||||||
|
for _, source := range []string{"process environment", "Go environment file"} {
|
||||||
|
t.Run(source, func(t *testing.T) {
|
||||||
|
unsetBuildEnv(t, "GOCACHE")
|
||||||
|
unsetBuildEnv(t, "GOAMD64")
|
||||||
|
unsetBuildEnv(t, "GOEXPERIMENT")
|
||||||
|
unsetBuildEnv(t, "GOFLAGS")
|
||||||
|
cache := filepath.Join(t.TempDir(), "configured-cache")
|
||||||
|
goEnv := filepath.Join(t.TempDir(), "go-env")
|
||||||
|
if source == "Go environment file" {
|
||||||
|
contents := fmt.Sprintf("GOAMD64=v2\nGOEXPERIMENT=loopvar\nGOFLAGS=-run=^$\nGOCACHE=%s\n", cache)
|
||||||
|
if err := os.WriteFile(goEnv, []byte(contents), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if err := os.WriteFile(goEnv, nil, 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Setenv("GOAMD64", "v2")
|
||||||
|
t.Setenv("GOEXPERIMENT", "loopvar")
|
||||||
|
t.Setenv("GOFLAGS", "-run=^$")
|
||||||
|
}
|
||||||
|
t.Setenv("GOENV", goEnv)
|
||||||
|
|
||||||
|
result, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Version: "v2.3.4",
|
||||||
|
Spec: releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/app",
|
||||||
|
BinaryName: "fixture",
|
||||||
|
Targets: []releasekit.Target{{OS: "linux", Arch: "amd64"}},
|
||||||
|
},
|
||||||
|
OutputDir: filepath.Join(t.TempDir(), "artifacts"),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Build() error = %v; partial result = %#v", err, result)
|
||||||
|
}
|
||||||
|
metadata := goBuildMetadata(t, result.Artifacts[0].Path)
|
||||||
|
if !strings.Contains(metadata, "GOAMD64=v1") || strings.Contains(metadata, "GOAMD64=v2") || strings.Contains(metadata, "GOEXPERIMENT=loopvar") {
|
||||||
|
t.Fatalf("build metadata includes ambient tuning:\n%s", metadata)
|
||||||
|
}
|
||||||
|
if source == "Go environment file" {
|
||||||
|
entries, err := os.ReadDir(cache)
|
||||||
|
if err != nil || len(entries) == 0 {
|
||||||
|
t.Fatalf("configured persistent cache was not used: entries=%d error=%v", len(entries), err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func goBuildMetadata(t *testing.T, binary string) string {
|
||||||
|
t.Helper()
|
||||||
|
t.Setenv("GOENV", "off")
|
||||||
|
t.Setenv("GOFLAGS", "")
|
||||||
|
t.Setenv("GOEXPERIMENT", "")
|
||||||
|
t.Setenv("GOAMD64", "")
|
||||||
|
t.Setenv("GOOS", "")
|
||||||
|
t.Setenv("GOARCH", "")
|
||||||
|
output, err := exec.Command("go", "version", "-m", binary).CombinedOutput()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("go version -m: %v\n%s", err, output)
|
||||||
|
}
|
||||||
|
return string(output)
|
||||||
|
}
|
||||||
|
|
||||||
|
func unsetBuildEnv(t *testing.T, key string) {
|
||||||
|
t.Helper()
|
||||||
|
value, exists := os.LookupEnv(key)
|
||||||
|
if err := os.Unsetenv(key); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() {
|
||||||
|
if exists {
|
||||||
|
_ = os.Setenv(key, value)
|
||||||
|
} else {
|
||||||
|
_ = os.Unsetenv(key)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildWithNoTargetsDoesNotInvokeCompiler(t *testing.T) {
|
||||||
|
repository := newBuildConsumer(t, `package main
|
||||||
|
func main() {}
|
||||||
|
`)
|
||||||
|
outputDir := filepath.Join(t.TempDir(), "must-not-be-created")
|
||||||
|
result, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Version: "v1.2.3",
|
||||||
|
OutputDir: outputDir,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Build() error = %v", err)
|
||||||
|
}
|
||||||
|
if result.CandidateCommit == "" || result.Compiler != "" || len(result.Targets) != 0 || len(result.Artifacts) != 0 {
|
||||||
|
t.Fatalf("empty build result = %#v", result)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(outputDir); !errors.Is(err, os.ErrNotExist) {
|
||||||
|
t.Fatalf("empty build created output directory: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildRegeneratesOwnedOutputsAndPreservesUnrelatedFiles(t *testing.T) {
|
||||||
|
const source = `package main
|
||||||
|
import("fmt";"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo")
|
||||||
|
func main(){fmt.Println("fixture",buildinfo.Version())}
|
||||||
|
`
|
||||||
|
repository := newBuildConsumer(t, source)
|
||||||
|
outputDir := t.TempDir()
|
||||||
|
unrelated := filepath.Join(outputDir, "keep.txt")
|
||||||
|
if err := os.WriteFile(unrelated, []byte("keep this file"), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
request := releasekit.BuildRequest{RepositoryDir: repository, Version: "v1.2.3", Spec: releasekit.BuildSpec{MainPackage: "./cmd/app", BinaryName: "fixture", Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}}}, OutputDir: outputDir}
|
||||||
|
unsafe := request
|
||||||
|
unsafe.Spec.BinaryName = "../unsafe"
|
||||||
|
if _, err := releasekit.Build(context.Background(), unsafe); err == nil {
|
||||||
|
t.Fatal("unsafe binary name accepted")
|
||||||
|
}
|
||||||
|
first, err := releasekit.Build(context.Background(), request)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
repeated, err := releasekit.Build(context.Background(), request)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if repeated.Artifacts[0].SHA256 != first.Artifacts[0].SHA256 {
|
||||||
|
t.Fatal("identical build changed output")
|
||||||
|
}
|
||||||
|
writeBuildFixture(t, repository, "cmd/app/main.go", source+"\nfunc init(){if len([]byte(buildinfo.Version()))==0 {panic(\"changed build\")}}\n")
|
||||||
|
changed, err := releasekit.Build(context.Background(), request)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if changed.Artifacts[0].SHA256 == first.Artifacts[0].SHA256 {
|
||||||
|
t.Fatal("changed source did not regenerate binary")
|
||||||
|
}
|
||||||
|
content, err := os.ReadFile(unrelated)
|
||||||
|
if err != nil || string(content) != "keep this file" {
|
||||||
|
t.Fatalf("unrelated file=%q %v", content, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildReturnsPartialArtifactsAfterTargetFailure(t *testing.T) {
|
||||||
|
repository := newBuildConsumer(t, "package main\nfunc main() {}\n")
|
||||||
|
result, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Spec: releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/app",
|
||||||
|
BinaryName: "fixture",
|
||||||
|
Targets: []releasekit.Target{
|
||||||
|
{OS: runtime.GOOS, Arch: runtime.GOARCH},
|
||||||
|
{OS: "invalid-os", Arch: "invalid-arch"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
OutputDir: filepath.Join(t.TempDir(), "artifacts"),
|
||||||
|
})
|
||||||
|
if err == nil || len(result.Artifacts) != 1 {
|
||||||
|
t.Fatalf("Build() result = %#v, error = %v; want one retained artifact", result, err)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(result.Artifacts[0].Path); err != nil {
|
||||||
|
t.Fatalf("partial artifact was not retained: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildReportsMissingMainPackage(t *testing.T) {
|
||||||
|
repository := newBuildConsumer(t, "package main\nfunc main() {}\n")
|
||||||
|
result, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Spec: releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/missing",
|
||||||
|
BinaryName: "fixture",
|
||||||
|
Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}},
|
||||||
|
},
|
||||||
|
OutputDir: filepath.Join(t.TempDir(), "artifacts"),
|
||||||
|
})
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "cmd/missing") || len(result.Artifacts) != 0 {
|
||||||
|
t.Fatalf("Build() result = %#v, error = %v; want missing-package failure", result, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildReportsIncorrectVersionOutputAndRetainsBinary(t *testing.T) {
|
||||||
|
repository := newBuildConsumer(t, `package main
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
)
|
||||||
|
func main() { if len(os.Args) == 2 && os.Args[1] == "version" { fmt.Println("wrong") } }
|
||||||
|
`)
|
||||||
|
outputDir := filepath.Join(t.TempDir(), "artifacts")
|
||||||
|
result, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Spec: releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/app",
|
||||||
|
BinaryName: "fixture",
|
||||||
|
Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}},
|
||||||
|
},
|
||||||
|
OutputDir: outputDir,
|
||||||
|
})
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "native version output") || len(result.Artifacts) != 1 {
|
||||||
|
t.Fatalf("Build() result = %#v, error = %v; want retained-binary smoke failure", result, err)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(result.Artifacts[0].Path); err != nil {
|
||||||
|
t.Fatalf("built artifact was not retained after smoke failure: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildCancellationReturnsCompletedArtifacts(t *testing.T) {
|
||||||
|
repository := newBuildConsumer(t, "package main\nfunc main() {}\n")
|
||||||
|
realGo, err := exec.LookPath("go")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
wrapperDir := t.TempDir()
|
||||||
|
wrapper := filepath.Join(wrapperDir, "go")
|
||||||
|
callCount := filepath.Join(wrapperDir, "build-count")
|
||||||
|
blocked := filepath.Join(wrapperDir, "second-build-started")
|
||||||
|
contents := "#!/bin/sh\n" +
|
||||||
|
"for argument do\n" +
|
||||||
|
" if [ \"$argument\" = build ]; then\n" +
|
||||||
|
" count=0\n" +
|
||||||
|
" if [ -f \"$RELEASEKIT_BUILD_COUNT\" ]; then count=$(cat \"$RELEASEKIT_BUILD_COUNT\"); fi\n" +
|
||||||
|
" count=$((count + 1))\n" +
|
||||||
|
" printf '%s\\n' \"$count\" > \"$RELEASEKIT_BUILD_COUNT\"\n" +
|
||||||
|
" if [ \"$count\" -eq 2 ]; then : > \"$RELEASEKIT_BUILD_BLOCKED\"; exec sleep 30; fi\n" +
|
||||||
|
" fi\n" +
|
||||||
|
"done\n" +
|
||||||
|
"exec \"$RELEASEKIT_BUILD_REAL_GO\" \"$@\"\n"
|
||||||
|
if err := os.WriteFile(wrapper, []byte(contents), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Setenv("PATH", wrapperDir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||||
|
t.Setenv("RELEASEKIT_BUILD_COUNT", callCount)
|
||||||
|
t.Setenv("RELEASEKIT_BUILD_BLOCKED", blocked)
|
||||||
|
t.Setenv("RELEASEKIT_BUILD_REAL_GO", realGo)
|
||||||
|
secondTarget := releasekit.Target{OS: "darwin", Arch: "arm64"}
|
||||||
|
if secondTarget == (releasekit.Target{OS: runtime.GOOS, Arch: runtime.GOARCH}) {
|
||||||
|
secondTarget = releasekit.Target{OS: "linux", Arch: "amd64"}
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
done := make(chan struct {
|
||||||
|
result releasekit.BuildResult
|
||||||
|
err error
|
||||||
|
}, 1)
|
||||||
|
go func() {
|
||||||
|
result, err := releasekit.Build(ctx, releasekit.BuildRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Spec: releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/app",
|
||||||
|
BinaryName: "fixture",
|
||||||
|
Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}, secondTarget},
|
||||||
|
},
|
||||||
|
OutputDir: filepath.Join(t.TempDir(), "artifacts"),
|
||||||
|
})
|
||||||
|
done <- struct {
|
||||||
|
result releasekit.BuildResult
|
||||||
|
err error
|
||||||
|
}{result: result, err: err}
|
||||||
|
}()
|
||||||
|
ticker := time.NewTicker(10 * time.Millisecond)
|
||||||
|
defer ticker.Stop()
|
||||||
|
deadline := time.NewTimer(30 * time.Second)
|
||||||
|
defer deadline.Stop()
|
||||||
|
for {
|
||||||
|
if _, err := os.Stat(blocked); err == nil {
|
||||||
|
cancel()
|
||||||
|
break
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case outcome := <-done:
|
||||||
|
cancel()
|
||||||
|
t.Fatalf("Build() ended before cancellation: result=%#v error=%v", outcome.result, outcome.err)
|
||||||
|
case <-deadline.C:
|
||||||
|
cancel()
|
||||||
|
outcome := <-done
|
||||||
|
t.Fatalf("second build did not start: result=%#v error=%v", outcome.result, outcome.err)
|
||||||
|
case <-ticker.C:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
outcome := <-done
|
||||||
|
if !errors.Is(outcome.err, context.Canceled) || len(outcome.result.Artifacts) != 1 {
|
||||||
|
t.Fatalf("canceled build result=%#v error=%v; want one retained artifact", outcome.result, outcome.err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckBuildsAfterValidationAndKeepsOutputOutsideWorktree(t *testing.T) {
|
||||||
|
repository := newPublishFixture(t)
|
||||||
|
prepareCandidateBuild(t, repository.work, `package main
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo"
|
||||||
|
)
|
||||||
|
func main() { if len(os.Args) == 2 && os.Args[1] == "version" { fmt.Printf("fixture %s\n", buildinfo.Version()) } }
|
||||||
|
`)
|
||||||
|
var validations int
|
||||||
|
candidate, err := releasekit.Check(context.Background(), releasekit.ReleaseRequest{
|
||||||
|
RepositoryDir: repository.work,
|
||||||
|
Product: "Sample App",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
AdditionalChecks: func(context.Context, releasekit.Candidate) error {
|
||||||
|
validations++
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
Build: &releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/app",
|
||||||
|
BinaryName: "fixture",
|
||||||
|
Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Check() error = %v", err)
|
||||||
|
}
|
||||||
|
if validations != 1 || candidate.Commit != gitText(t, repository.work, "rev-parse", "HEAD") {
|
||||||
|
t.Fatalf("candidate = %#v, validation calls = %d", candidate, validations)
|
||||||
|
}
|
||||||
|
if got := gitText(t, repository.work, "status", "--porcelain"); got != "" {
|
||||||
|
t.Fatalf("candidate build dirtied worktree: %s", got)
|
||||||
|
}
|
||||||
|
if paths, err := filepath.Glob(filepath.Join(filepath.Dir(repository.work), ".releasekit-candidate-build-*")); err != nil || len(paths) != 0 {
|
||||||
|
t.Fatalf("temporary candidate output remains: %v, error=%v", paths, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPublishBuildFailurePreventsTagCreation(t *testing.T) {
|
||||||
|
repository := newPublishFixture(t)
|
||||||
|
prepareCandidateBuild(t, repository.work, "package main\nfunc main() {}\n")
|
||||||
|
var validations int
|
||||||
|
result, err := releasekit.Publish(context.Background(), releasekit.ReleaseRequest{
|
||||||
|
RepositoryDir: repository.work,
|
||||||
|
Product: "Sample App",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
AdditionalChecks: func(context.Context, releasekit.Candidate) error {
|
||||||
|
validations++
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
Build: &releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/missing",
|
||||||
|
BinaryName: "fixture",
|
||||||
|
Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "build candidate") || result.TagObject != "" {
|
||||||
|
t.Fatalf("Publish() result=%#v error=%v; want build failure before tag creation", result, err)
|
||||||
|
}
|
||||||
|
if validations != 1 {
|
||||||
|
t.Fatalf("validation calls = %d, want 1", validations)
|
||||||
|
}
|
||||||
|
if _, err := exec.Command("git", "--git-dir", repository.bare, "show-ref", "--verify", "--quiet", "refs/tags/v1.2.3").CombinedOutput(); err == nil {
|
||||||
|
t.Fatal("build failure published the release tag")
|
||||||
|
}
|
||||||
|
if _, err := exec.Command("git", "-C", repository.work, "show-ref", "--verify", "--quiet", "refs/tags/v1.2.3").CombinedOutput(); err == nil {
|
||||||
|
t.Fatal("build failure created a local release tag")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func newBuildConsumer(t *testing.T, mainSource string) string {
|
||||||
|
t.Helper()
|
||||||
|
repository, err := os.MkdirTemp("", "releasekit-build-consumer-")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _ = os.RemoveAll(repository) })
|
||||||
|
root, err := filepath.Abs(".")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
module := fmt.Sprintf("module example.com/buildfixture\n\ngo 1.25.0\n\nrequire gitea.maximumdirect.net/eric/ReleaseKit v0.0.0\n\nreplace gitea.maximumdirect.net/eric/ReleaseKit => %s\n", filepath.ToSlash(root))
|
||||||
|
writeBuildFixture(t, repository, "go.mod", module)
|
||||||
|
writeBuildFixture(t, repository, "cmd/app/main.go", mainSource)
|
||||||
|
writeBuildFixture(t, repository, "cmd/app/main_test.go", "package main\nimport \"testing\"\nfunc TestCandidateFixture(t *testing.T) {}\n")
|
||||||
|
buildGit(t, repository, "init", "--initial-branch=main")
|
||||||
|
buildGit(t, repository, "config", "user.name", "ReleaseKit Build Test")
|
||||||
|
buildGit(t, repository, "config", "user.email", "releasekit-build@example.test")
|
||||||
|
buildGit(t, repository, "add", "--all")
|
||||||
|
buildGit(t, repository, "commit", "-m", "build fixture")
|
||||||
|
return repository
|
||||||
|
}
|
||||||
|
|
||||||
|
func prepareCandidateBuild(t *testing.T, repository, mainSource string) {
|
||||||
|
t.Helper()
|
||||||
|
root, err := filepath.Abs(".")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
module := fmt.Sprintf("module example.com/candidatebuild\n\ngo 1.25.0\n\nrequire gitea.maximumdirect.net/eric/ReleaseKit v0.0.0\n\nreplace gitea.maximumdirect.net/eric/ReleaseKit => %s\n", filepath.ToSlash(root))
|
||||||
|
writeFile(t, repository, "go.mod", module)
|
||||||
|
writeFile(t, repository, ".gitignore", "dist/\n")
|
||||||
|
writeFile(t, repository, "cmd/app/main.go", mainSource)
|
||||||
|
writeFile(t, repository, "cmd/app/main_test.go", "package main\nimport \"testing\"\nfunc TestCandidateFixture(t *testing.T) {}\n")
|
||||||
|
gitRun(t, repository, "add", "--all")
|
||||||
|
gitRun(t, repository, "commit", "-m", "add buildable candidate")
|
||||||
|
gitRun(t, repository, "config", "remote.origin.mirror", "false")
|
||||||
|
gitRun(t, repository, "push", "origin", "HEAD:refs/heads/main")
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeBuildFixture(t *testing.T, directory, name, contents string) {
|
||||||
|
t.Helper()
|
||||||
|
path := filepath.Join(directory, filepath.FromSlash(name))
|
||||||
|
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildGit(t *testing.T, directory string, args ...string) string {
|
||||||
|
t.Helper()
|
||||||
|
command := exec.Command("git", append([]string{"-C", directory}, args...)...)
|
||||||
|
output, err := command.CombinedOutput()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("git %v: %v\n%s", args, err, output)
|
||||||
|
}
|
||||||
|
return strings.TrimSpace(string(output))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildSourceEligibilitySurvivesLaterCheckoutCleanup(t *testing.T) {
|
||||||
|
const source = `package main
|
||||||
|
import("fmt";"os";"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo")
|
||||||
|
func main(){ if len(os.Args)>1 && os.Args[1]=="version" {fmt.Println("fixture",buildinfo.Version())} }
|
||||||
|
`
|
||||||
|
for _, mode := range []string{"clean", "dirty before build", "changed during build", "commit during build"} {
|
||||||
|
t.Run(mode, func(t *testing.T) {
|
||||||
|
repository := newBuildConsumer(t, source)
|
||||||
|
writeBuildFixture(t, repository, "docs/releases/v1.2.3.md", "# Fixture v1.2.3\n")
|
||||||
|
buildGit(t, repository, "add", "--all")
|
||||||
|
buildGit(t, repository, "commit", "-m", "release note")
|
||||||
|
buildGit(t, repository, "tag", "v1.2.3")
|
||||||
|
mutate := func() { writeBuildFixture(t, repository, "cmd/app/main.go", source+"\n// local change\n") }
|
||||||
|
if mode == "dirty before build" {
|
||||||
|
mutate()
|
||||||
|
}
|
||||||
|
var writer *sourceChangeWriter
|
||||||
|
request := releasekit.BuildRequest{RepositoryDir: repository, Version: "v1.2.3", Spec: releasekit.BuildSpec{MainPackage: "./cmd/app", BinaryName: "fixture", Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}}}, OutputDir: t.TempDir()}
|
||||||
|
if mode == "changed during build" || mode == "commit during build" {
|
||||||
|
writer = &sourceChangeWriter{change: func() {
|
||||||
|
mutate()
|
||||||
|
if mode == "commit during build" {
|
||||||
|
buildGit(t, repository, "add", "--all")
|
||||||
|
buildGit(t, repository, "commit", "-m", "source advanced during compilation")
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
request.Output = writer
|
||||||
|
}
|
||||||
|
result, err := releasekit.Build(context.Background(), request)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if result.SourceVerified != (mode == "clean") {
|
||||||
|
t.Fatalf("source eligibility=%t for %s", result.SourceVerified, mode)
|
||||||
|
}
|
||||||
|
if mode == "clean" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
buildGit(t, repository, "restore", "cmd/app/main.go")
|
||||||
|
buildGit(t, repository, "checkout", "--detach", "v1.2.3")
|
||||||
|
delivered, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{RepositoryDir: repository, Product: "Fixture", Version: "v1.2.3", Prebuilt: &result})
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "build source") || delivered.State != releasekit.DeliveryNotAttempted {
|
||||||
|
t.Fatalf("dirty source delivered: %#v %v", delivered, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type sourceChangeWriter struct{ change func() }
|
||||||
|
|
||||||
|
func (w *sourceChangeWriter) Write(p []byte) (int, error) {
|
||||||
|
if w.change != nil {
|
||||||
|
w.change()
|
||||||
|
w.change = nil
|
||||||
|
}
|
||||||
|
return len(p), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCandidateBuildDoesNotRequireWritableRepositoryParent(t *testing.T) {
|
||||||
|
if runtime.GOOS == "windows" || os.Getuid() == 0 {
|
||||||
|
t.Skip("requires ordinary Unix permission checks")
|
||||||
|
}
|
||||||
|
repository := newBuildConsumer(t, `package main
|
||||||
|
import("fmt";"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo")
|
||||||
|
func main(){fmt.Println("fixture",buildinfo.Version())}
|
||||||
|
`)
|
||||||
|
writeBuildFixture(t, repository, "docs/releases/v1.2.3.md", "# Fixture v1.2.3\n")
|
||||||
|
buildGit(t, repository, "add", "--all")
|
||||||
|
buildGit(t, repository, "commit", "-m", "note")
|
||||||
|
parent := t.TempDir()
|
||||||
|
moved := filepath.Join(parent, "repo")
|
||||||
|
if err := os.Rename(repository, moved); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.Chmod(parent, 0555); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { os.Chmod(parent, 0700) })
|
||||||
|
_, err := releasekit.Check(context.Background(), releasekit.ReleaseRequest{RepositoryDir: moved, Product: "Fixture", Version: "v1.2.3", AdditionalChecks: func(context.Context, releasekit.Candidate) error { return nil }, Build: &releasekit.BuildSpec{MainPackage: "./cmd/app", BinaryName: "fixture", Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}}}})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if status := buildGit(t, moved, "status", "--porcelain"); status != "" {
|
||||||
|
t.Fatalf("candidate dirtied: %s", status)
|
||||||
|
}
|
||||||
|
}
|
||||||
12
buildinfo/version.go
Normal file
12
buildinfo/version.go
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
// Package buildinfo provides runtime version information for applications
|
||||||
|
// built with ReleaseKit.
|
||||||
|
package buildinfo
|
||||||
|
|
||||||
|
import "gitea.maximumdirect.net/eric/ReleaseKit/internal/runtimeinfo"
|
||||||
|
|
||||||
|
// Version returns the injected release identifier when available. Otherwise,
|
||||||
|
// it returns the executable's main module version, or "dev" when that metadata
|
||||||
|
// is unavailable or identifies a development build.
|
||||||
|
func Version() string {
|
||||||
|
return runtimeinfo.Version()
|
||||||
|
}
|
||||||
81
buildinfo/version_integration_test.go
Normal file
81
buildinfo/version_integration_test.go
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
package buildinfo_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/versioncontract"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestVersionInConsumerExecutable(t *testing.T) {
|
||||||
|
repo, err := filepath.Abs("..")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
dir := t.TempDir()
|
||||||
|
module := fmt.Sprintf(`module example.com/versionfixture
|
||||||
|
|
||||||
|
go 1.25.0
|
||||||
|
|
||||||
|
require gitea.maximumdirect.net/eric/ReleaseKit v0.0.0
|
||||||
|
|
||||||
|
replace gitea.maximumdirect.net/eric/ReleaseKit => %s
|
||||||
|
`, filepath.ToSlash(repo))
|
||||||
|
if err := os.WriteFile(filepath.Join(dir, "go.mod"), []byte(module), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
program := `package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() { fmt.Print(buildinfo.Version()) }
|
||||||
|
`
|
||||||
|
if err := os.WriteFile(filepath.Join(dir, "main.go"), []byte(program), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, test := range []struct {
|
||||||
|
name string
|
||||||
|
linkerArgs []string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{name: "development build", want: "dev"},
|
||||||
|
{
|
||||||
|
name: "injected release version",
|
||||||
|
linkerArgs: []string{"-X", versioncontract.InjectedVersionLinkerSymbol + "=v1.2.3"},
|
||||||
|
want: "v1.2.3",
|
||||||
|
},
|
||||||
|
} {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
binary := filepath.Join(t.TempDir(), "versionfixture")
|
||||||
|
args := []string{"build", "-o", binary}
|
||||||
|
if len(test.linkerArgs) > 0 {
|
||||||
|
args = append(args, "-ldflags", fmt.Sprint(test.linkerArgs[0], " ", test.linkerArgs[1]))
|
||||||
|
}
|
||||||
|
args = append(args, ".")
|
||||||
|
|
||||||
|
build := exec.Command("go", args...)
|
||||||
|
build.Dir = dir
|
||||||
|
build.Env = append(os.Environ(), "GOTOOLCHAIN=local", "GOPROXY=off", "GOSUMDB=off")
|
||||||
|
if output, err := build.CombinedOutput(); err != nil {
|
||||||
|
t.Fatalf("build consumer fixture: %v\n%s", err, output)
|
||||||
|
}
|
||||||
|
|
||||||
|
command := exec.Command(binary)
|
||||||
|
output, err := command.CombinedOutput()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("run consumer fixture: %v\n%s", err, output)
|
||||||
|
}
|
||||||
|
if string(output) != test.want {
|
||||||
|
t.Fatalf("version output = %q, want %q", output, test.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
71
check.go
Normal file
71
check.go
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
package releasekit
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"io"
|
||||||
|
|
||||||
|
internalbuild "gitea.maximumdirect.net/eric/ReleaseKit/internal/build"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/candidate"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ErrInvalidVersion reports a version that is not stable vMAJOR.MINOR.PATCH.
|
||||||
|
var ErrInvalidVersion = candidate.ErrInvalidVersion
|
||||||
|
|
||||||
|
// Candidate identifies one committed local source revision selected for
|
||||||
|
// validation.
|
||||||
|
type Candidate struct {
|
||||||
|
RepositoryDir string
|
||||||
|
Commit string
|
||||||
|
Version string
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReleaseRequest contains the inputs used to validate and optionally build one
|
||||||
|
// local candidate. Remote is retained for publication operations; Check makes
|
||||||
|
// no remote availability claim.
|
||||||
|
type ReleaseRequest struct {
|
||||||
|
RepositoryDir string
|
||||||
|
Product string
|
||||||
|
Version string
|
||||||
|
Remote string
|
||||||
|
// AdditionalChecks optionally runs product checks after the standard suite.
|
||||||
|
AdditionalChecks func(context.Context, Candidate) error
|
||||||
|
Build *BuildSpec // optional selected-target build after validation.
|
||||||
|
Output io.Writer
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check validates one local, committed release candidate. It requires a clean
|
||||||
|
// worktree and index on main, a committed note matching Product and Version,
|
||||||
|
// and an unused local tag. It always runs the offline Go test suite with the
|
||||||
|
// available compatible local Go toolchain and Go host target, then calls
|
||||||
|
// AdditionalChecks when supplied. 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
|
||||||
|
// candidate evidence only; it does not establish remote availability.
|
||||||
|
func Check(ctx context.Context, request ReleaseRequest) (Candidate, error) {
|
||||||
|
var validate func(context.Context, candidate.Candidate) error
|
||||||
|
if request.AdditionalChecks != nil {
|
||||||
|
validate = func(ctx context.Context, captured candidate.Candidate) error {
|
||||||
|
return request.AdditionalChecks(ctx, Candidate{
|
||||||
|
RepositoryDir: captured.RepositoryDir,
|
||||||
|
Commit: captured.Commit,
|
||||||
|
Version: captured.Version,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
checked, err := candidate.Check(ctx, candidate.Request{
|
||||||
|
RepositoryDir: request.RepositoryDir,
|
||||||
|
Product: request.Product,
|
||||||
|
Version: request.Version,
|
||||||
|
AdditionalChecks: validate,
|
||||||
|
AfterValidate: internalbuild.CandidateCallback(internalBuildSpec(request.Build), request.Output),
|
||||||
|
Output: request.Output,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return Candidate{}, err
|
||||||
|
}
|
||||||
|
return Candidate{
|
||||||
|
RepositoryDir: checked.RepositoryDir,
|
||||||
|
Commit: checked.Commit,
|
||||||
|
Version: checked.Version,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
235
cmd/releasekit/internal/cli/config.go
Normal file
235
cmd/releasekit/internal/cli/config.go
Normal file
@@ -0,0 +1,235 @@
|
|||||||
|
// Package cli owns command parsing, profile settings, and child-command
|
||||||
|
// adaptation for the ReleaseKit executable.
|
||||||
|
package cli
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/process"
|
||||||
|
)
|
||||||
|
|
||||||
|
const Usage = "usage: releasekit version\n releasekit check [--repo DIR] [--config FILE] VERSION\n releasekit publish [--repo DIR] [--config FILE] VERSION\n releasekit build [--repo DIR] [--config FILE] [--output DIR] VERSION\n releasekit deliver [--repo DIR] [--config FILE] [--assets DIR] VERSION\n releasekit ci-deliver [--repo DIR] [--config FILE] [--remote NAME] --commit OID VERSION"
|
||||||
|
|
||||||
|
type Command string
|
||||||
|
|
||||||
|
const (
|
||||||
|
VersionCommand Command = "version"
|
||||||
|
CheckAction Command = "check"
|
||||||
|
PublishAction Command = "publish"
|
||||||
|
BuildAction Command = "build"
|
||||||
|
DeliveryAction Command = "deliver"
|
||||||
|
CIDeliveryAction Command = "ci-deliver"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 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
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse accepts only commands that have been implemented by the executable.
|
||||||
|
func Parse(args []string) (Invocation, error) {
|
||||||
|
if len(args) == 0 {
|
||||||
|
return Invocation{}, errors.New("a command is required")
|
||||||
|
}
|
||||||
|
switch args[0] {
|
||||||
|
case string(VersionCommand):
|
||||||
|
if len(args) != 1 {
|
||||||
|
return Invocation{}, errors.New("version takes no arguments")
|
||||||
|
}
|
||||||
|
return Invocation{Command: VersionCommand}, nil
|
||||||
|
case string(CheckAction), string(PublishAction), string(BuildAction), string(DeliveryAction), string(CIDeliveryAction):
|
||||||
|
action := Command(args[0])
|
||||||
|
flags := flag.NewFlagSet(string(action), flag.ContinueOnError)
|
||||||
|
flags.SetOutput(io.Discard)
|
||||||
|
repository := flags.String("repo", ".", "repository directory")
|
||||||
|
configPath := flags.String("config", "", "profile path")
|
||||||
|
var outputDir string
|
||||||
|
if action == BuildAction {
|
||||||
|
flags.StringVar(&outputDir, "output", "", "build output directory")
|
||||||
|
}
|
||||||
|
var assetsDir string
|
||||||
|
if action == DeliveryAction {
|
||||||
|
flags.StringVar(&assetsDir, "assets", "", "verified build assets directory")
|
||||||
|
}
|
||||||
|
var remote *string
|
||||||
|
expectedCommit := ""
|
||||||
|
if action == CIDeliveryAction {
|
||||||
|
remote = flags.String("remote", "origin", "Git remote")
|
||||||
|
flags.StringVar(&expectedCommit, "commit", "", "expected tagged commit")
|
||||||
|
}
|
||||||
|
if err := flags.Parse(args[1:]); err != nil {
|
||||||
|
return Invocation{}, err
|
||||||
|
}
|
||||||
|
if flags.NArg() != 1 {
|
||||||
|
return Invocation{}, fmt.Errorf("%s requires one version argument", action)
|
||||||
|
}
|
||||||
|
if action == CIDeliveryAction && expectedCommit == "" {
|
||||||
|
return Invocation{}, errors.New("ci-deliver requires --commit OID")
|
||||||
|
}
|
||||||
|
if action == CIDeliveryAction && !validGitObjectID(expectedCommit) {
|
||||||
|
return Invocation{}, errors.New("ci-deliver --commit must be a full Git object ID")
|
||||||
|
}
|
||||||
|
parsedRemote := ""
|
||||||
|
if remote != nil {
|
||||||
|
parsedRemote = *remote
|
||||||
|
}
|
||||||
|
return Invocation{Command: action, Repository: *repository, ConfigPath: *configPath, OutputDir: outputDir, AssetsDir: assetsDir, Remote: parsedRemote, Commit: expectedCommit, Version: flags.Arg(0)}, nil
|
||||||
|
default:
|
||||||
|
return Invocation{}, fmt.Errorf("unknown command %q", args[0])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func validGitObjectID(value string) bool {
|
||||||
|
if len(value) != 40 && len(value) != 64 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, char := range value {
|
||||||
|
if (char < '0' || char > '9') && (char < 'a' || char > 'f') && (char < 'A' || char > 'F') {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// CheckCommand contains one direct child-process invocation from a profile.
|
||||||
|
type CheckCommand struct {
|
||||||
|
Args []string `json:"args"`
|
||||||
|
Env map[string]string `json:"env,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Settings contains the product, remote, and check commands read from a
|
||||||
|
// releasekit.json profile.
|
||||||
|
type Settings struct {
|
||||||
|
Product string `json:"product"`
|
||||||
|
Remote string `json:"remote,omitempty"`
|
||||||
|
Checks []CheckCommand `json:"checks,omitempty"`
|
||||||
|
Build *BuildSettings `json:"build,omitempty"`
|
||||||
|
Delivery *DeliverySettings `json:"delivery,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeliverySettings selects the hosted Gitea release destination.
|
||||||
|
type DeliverySettings struct {
|
||||||
|
BaseURL string `json:"base_url"`
|
||||||
|
Owner string `json:"owner"`
|
||||||
|
Repository string `json:"repository"`
|
||||||
|
TokenEnv string `json:"token_env,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// BuildSettings selects the Go application package, artifact name, and targets.
|
||||||
|
type BuildSettings struct {
|
||||||
|
MainPackage string `json:"main_package,omitempty"`
|
||||||
|
BinaryName string `json:"binary_name,omitempty"`
|
||||||
|
Targets []string `json:"targets,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// LoadSettings reads a profile path relative to repoDir unless it is absolute.
|
||||||
|
// An empty configPath selects <repoDir>/releasekit.json.
|
||||||
|
func LoadSettings(repoDir, configPath string) (Settings, error) {
|
||||||
|
resolvedRepo, err := filepath.Abs(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
return Settings{}, fmt.Errorf("resolve repository directory %q: %w", repoDir, err)
|
||||||
|
}
|
||||||
|
if configPath == "" {
|
||||||
|
configPath = "releasekit.json"
|
||||||
|
}
|
||||||
|
if !filepath.IsAbs(configPath) {
|
||||||
|
configPath = filepath.Join(resolvedRepo, configPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
file, err := os.Open(configPath)
|
||||||
|
if err != nil {
|
||||||
|
return Settings{}, fmt.Errorf("open profile %q: %w", configPath, err)
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
|
||||||
|
var settings Settings
|
||||||
|
decoder := json.NewDecoder(file)
|
||||||
|
decoder.DisallowUnknownFields()
|
||||||
|
if err := decoder.Decode(&settings); err != nil {
|
||||||
|
return Settings{}, fmt.Errorf("decode profile %q: %w", configPath, err)
|
||||||
|
}
|
||||||
|
var extra any
|
||||||
|
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
|
||||||
|
if err == nil {
|
||||||
|
return Settings{}, fmt.Errorf("decode profile %q: multiple JSON values", configPath)
|
||||||
|
}
|
||||||
|
return Settings{}, fmt.Errorf("decode profile %q: %w", configPath, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.TrimSpace(settings.Product) == "" {
|
||||||
|
return Settings{}, fmt.Errorf("profile %q: product is required", configPath)
|
||||||
|
}
|
||||||
|
if settings.Remote == "" {
|
||||||
|
settings.Remote = "origin"
|
||||||
|
}
|
||||||
|
for i, check := range settings.Checks {
|
||||||
|
if len(check.Args) == 0 || check.Args[0] == "" {
|
||||||
|
return Settings{}, fmt.Errorf("profile %q: checks[%d].args must include a command", configPath, i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if settings.Build != nil {
|
||||||
|
if len(settings.Build.Targets) != 0 {
|
||||||
|
if strings.TrimSpace(settings.Build.MainPackage) == "" {
|
||||||
|
return Settings{}, fmt.Errorf("profile %q: build.main_package is required when targets are selected", configPath)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(settings.Build.BinaryName) == "" {
|
||||||
|
return Settings{}, fmt.Errorf("profile %q: build.binary_name is required when targets are selected", configPath)
|
||||||
|
}
|
||||||
|
if strings.ContainsAny(settings.Build.BinaryName, "/\\\r\n") {
|
||||||
|
return Settings{}, fmt.Errorf("profile %q: build.binary_name must be a filename component", configPath)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for i, target := range settings.Build.Targets {
|
||||||
|
if strings.Count(target, "/") != 1 {
|
||||||
|
return Settings{}, fmt.Errorf("profile %q: build.targets[%d] must be GOOS/GOARCH", configPath, i)
|
||||||
|
}
|
||||||
|
goos, goarch, _ := strings.Cut(target, "/")
|
||||||
|
if strings.TrimSpace(goos) == "" || strings.TrimSpace(goarch) == "" {
|
||||||
|
return Settings{}, fmt.Errorf("profile %q: build.targets[%d] must be GOOS/GOARCH", configPath, i)
|
||||||
|
}
|
||||||
|
if strings.ContainsAny(goos+goarch, "\\\r\n") {
|
||||||
|
return Settings{}, fmt.Errorf("profile %q: build.targets[%d] contains an unsafe filename component", configPath, i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return settings, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// RunChecks runs configured argument vectors in repoDir. Each command receives
|
||||||
|
// its own environment overlay and inherits the remaining process environment.
|
||||||
|
func RunChecks(ctx context.Context, repoDir string, checks []CheckCommand, ownedEnv map[string]string, stdout, stderr io.Writer) error {
|
||||||
|
for i, check := range checks {
|
||||||
|
environment := make(map[string]string, len(check.Env)+len(ownedEnv))
|
||||||
|
for key, value := range check.Env {
|
||||||
|
environment[key] = value
|
||||||
|
}
|
||||||
|
for key, value := range ownedEnv {
|
||||||
|
environment[key] = value
|
||||||
|
}
|
||||||
|
if err := process.Run(ctx, process.Invocation{
|
||||||
|
Args: check.Args,
|
||||||
|
Dir: repoDir,
|
||||||
|
Env: environment,
|
||||||
|
Stdout: stdout,
|
||||||
|
Stderr: stderr,
|
||||||
|
}); err != nil {
|
||||||
|
return fmt.Errorf("run check %d: %w", i+1, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
255
cmd/releasekit/internal/cli/config_test.go
Normal file
255
cmd/releasekit/internal/cli/config_test.go
Normal file
@@ -0,0 +1,255 @@
|
|||||||
|
package cli
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestParse(t *testing.T) {
|
||||||
|
invocation, err := Parse([]string{"version"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if invocation.Command != VersionCommand {
|
||||||
|
t.Fatalf("Parse() command = %q, want %q", invocation.Command, VersionCommand)
|
||||||
|
}
|
||||||
|
check, err := Parse([]string{"check", "--repo", "repository with spaces", "--config", "profiles/release config.json", "v1.2.3"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if check.Command != CheckAction || check.Repository != "repository with spaces" || check.ConfigPath != "profiles/release config.json" || check.Version != "v1.2.3" {
|
||||||
|
t.Fatalf("Parse(check) = %#v", check)
|
||||||
|
}
|
||||||
|
publish, err := Parse([]string{"publish", "--repo", "candidate", "--config", "releasekit.json", "v1.2.4"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if publish.Command != PublishAction || publish.Repository != "candidate" || publish.ConfigPath != "releasekit.json" || publish.Version != "v1.2.4" {
|
||||||
|
t.Fatalf("Parse(publish) = %#v", publish)
|
||||||
|
}
|
||||||
|
build, err := Parse([]string{"build", "--repo", "candidate", "--config", "releasekit.json", "--output", "output with spaces", "v1.2.5"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if build.Command != BuildAction || build.Repository != "candidate" || build.ConfigPath != "releasekit.json" || build.OutputDir != "output with spaces" || build.Version != "v1.2.5" {
|
||||||
|
t.Fatalf("Parse(build) = %#v", build)
|
||||||
|
}
|
||||||
|
deliver, err := Parse([]string{"deliver", "--repo", "candidate", "--config", "releasekit.json", "--assets", "assets with spaces", "v1.2.6"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if deliver.Command != DeliveryAction || deliver.Repository != "candidate" || deliver.ConfigPath != "releasekit.json" || deliver.AssetsDir != "assets with spaces" || deliver.Version != "v1.2.6" {
|
||||||
|
t.Fatalf("Parse(deliver) = %#v", deliver)
|
||||||
|
}
|
||||||
|
ciDelivery, err := Parse([]string{"ci-deliver", "--repo", "candidate", "--config", "profiles/release config.json", "--remote", "upstream", "--commit", "0123456789abcdef0123456789abcdef01234567", "v1.2.7"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if ciDelivery.Command != CIDeliveryAction || ciDelivery.Repository != "candidate" || ciDelivery.ConfigPath != "profiles/release config.json" || ciDelivery.Remote != "upstream" || ciDelivery.Commit != "0123456789abcdef0123456789abcdef01234567" || ciDelivery.Version != "v1.2.7" {
|
||||||
|
t.Fatalf("Parse(ci-deliver) = %#v", ciDelivery)
|
||||||
|
}
|
||||||
|
ciDefault, err := Parse([]string{"ci-deliver", "--commit", "0123456789abcdef0123456789abcdef01234567", "v1.2.8"})
|
||||||
|
if err != nil || ciDefault.Remote != "origin" {
|
||||||
|
t.Fatalf("Parse(ci-deliver defaults) = %#v, error = %v", ciDefault, err)
|
||||||
|
}
|
||||||
|
if _, err := Parse([]string{"ci-deliver", "v1.2.3"}); err == nil || !strings.Contains(err.Error(), "--commit") {
|
||||||
|
t.Fatalf("Parse(ci-deliver without commit) error = %v, want required commit", err)
|
||||||
|
}
|
||||||
|
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{"check", "v1.2.3", "--repo", "repository"}); err == nil {
|
||||||
|
t.Fatal("Parse accepted a flag after the version")
|
||||||
|
}
|
||||||
|
if _, err := Parse([]string{"ci-deliver", "--commit", "0123456789abcdef0123456789abcdef01234567", "v1.2.3", "--repo", "repository"}); err == nil {
|
||||||
|
t.Fatal("Parse accepted a ci-deliver flag after the version")
|
||||||
|
}
|
||||||
|
if _, err := Parse(nil); err == nil || !strings.Contains(err.Error(), "command is required") {
|
||||||
|
t.Fatalf("Parse(nil) error = %v, want missing-command error", err)
|
||||||
|
}
|
||||||
|
if _, err := Parse([]string{"unknown"}); err == nil || !strings.Contains(err.Error(), "unknown command") {
|
||||||
|
t.Fatalf("Parse(unknown) error = %v, want unknown-command error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadSettingsResolvesPathsAndPreservesArguments(t *testing.T) {
|
||||||
|
repoDir := filepath.Join(t.TempDir(), "repository with spaces")
|
||||||
|
profileDir := filepath.Join(repoDir, "profiles with spaces")
|
||||||
|
if err := os.MkdirAll(profileDir, 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
want := Settings{
|
||||||
|
Product: "Example Product",
|
||||||
|
Remote: "upstream",
|
||||||
|
Checks: []CheckCommand{{
|
||||||
|
Args: []string{"sh", "scripts/check release.sh", "two words"},
|
||||||
|
Env: map[string]string{"RELEASE_MODE": "candidate check"},
|
||||||
|
}},
|
||||||
|
}
|
||||||
|
contents, err := json.Marshal(want)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(filepath.Join(profileDir, "release profile.json"), contents, 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
got, err := LoadSettings(repoDir, filepath.Join("profiles with spaces", "release profile.json"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got.Product != want.Product || got.Remote != want.Remote || len(got.Checks) != 1 {
|
||||||
|
t.Fatalf("LoadSettings() = %#v, want product, remote, and one check", got)
|
||||||
|
}
|
||||||
|
if got.Checks[0].Args[1] != "scripts/check release.sh" || got.Checks[0].Args[2] != "two words" {
|
||||||
|
t.Fatalf("check arguments were changed: %#v", got.Checks[0].Args)
|
||||||
|
}
|
||||||
|
if got.Checks[0].Env["RELEASE_MODE"] != "candidate check" {
|
||||||
|
t.Fatalf("check environment = %#v", got.Checks[0].Env)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadSettingsDefaultsRemoteAndConfigPath(t *testing.T) {
|
||||||
|
repoDir := t.TempDir()
|
||||||
|
contents := `{"product":"Example"}`
|
||||||
|
profilePath := filepath.Join(repoDir, "releasekit.json")
|
||||||
|
if err := os.WriteFile(profilePath, []byte(contents), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, test := range []struct {
|
||||||
|
name string
|
||||||
|
path string
|
||||||
|
}{
|
||||||
|
{name: "default path"},
|
||||||
|
{name: "absolute path", path: profilePath},
|
||||||
|
} {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
settings, err := LoadSettings(repoDir, test.path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if settings.Remote != "origin" {
|
||||||
|
t.Fatalf("default remote = %q, want origin", settings.Remote)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExampleProfileLoads(t *testing.T) {
|
||||||
|
repoDir, err := filepath.Abs(filepath.Join("..", "..", "..", ".."))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
settings, err := LoadSettings(repoDir, filepath.Join("examples", "releasekit.json"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if settings.Product != "Example" || settings.Remote != "origin" || len(settings.Checks) != 0 {
|
||||||
|
t.Fatalf("example settings = %#v", settings)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildProfileLoads(t *testing.T) {
|
||||||
|
repoDir := t.TempDir()
|
||||||
|
path := filepath.Join(repoDir, "profile.json")
|
||||||
|
if err := os.WriteFile(path, []byte(`{"product":"Example","build":{"main_package":"./cmd/app","binary_name":"example","targets":["linux/amd64","darwin/arm64"]}}`), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
settings, err := LoadSettings(repoDir, path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if settings.Build == nil || settings.Build.MainPackage != "./cmd/app" || settings.Build.BinaryName != "example" || len(settings.Build.Targets) != 2 {
|
||||||
|
t.Fatalf("build settings = %#v", settings.Build)
|
||||||
|
}
|
||||||
|
repoDir, err = filepath.Abs(filepath.Join("..", "..", "..", ".."))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
example, err := LoadSettings(repoDir, filepath.Join("examples", "releasekit-binary.json"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if example.Build == nil || len(example.Build.Targets) != 3 {
|
||||||
|
t.Fatalf("binary example settings = %#v", example.Build)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadSettingsRejectsInvalidProfiles(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
content string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{name: "missing product", content: `{}`, want: "product is required"},
|
||||||
|
{name: "unknown top-level field", content: `{"product":"Example","future":{}}`, want: "unknown field"},
|
||||||
|
{name: "build package required", content: `{"product":"Example","build":{"binary_name":"example","targets":["linux/amd64"]}}`, want: "build.main_package is required"},
|
||||||
|
{name: "build target format", content: `{"product":"Example","build":{"main_package":".","binary_name":"example","targets":["linux"]}}`, want: "must be GOOS/GOARCH"},
|
||||||
|
{name: "unsafe binary name", content: `{"product":"Example","build":{"main_package":".","binary_name":"../example","targets":["linux/amd64"]}}`, want: "filename component"},
|
||||||
|
{name: "unknown command field", content: `{"product":"Example","checks":[{"args":["true"],"shell":true}]}`, want: "unknown field"},
|
||||||
|
{name: "command is required", content: `{"product":"Example","checks":[{"args":[]}]}`, want: "must include a command"},
|
||||||
|
{name: "multiple JSON values", content: `{"product":"Example"}{"product":"Other"}`, want: "multiple JSON values"},
|
||||||
|
}
|
||||||
|
for _, test := range tests {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
repoDir := t.TempDir()
|
||||||
|
path := filepath.Join(repoDir, "profile.json")
|
||||||
|
if err := os.WriteFile(path, []byte(test.content), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := LoadSettings(repoDir, path); err == nil || !strings.Contains(err.Error(), test.want) {
|
||||||
|
t.Fatalf("LoadSettings() error = %v, want text %q", err, test.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRunChecksUsesConfiguredArgumentsEnvironmentAndDirectory(t *testing.T) {
|
||||||
|
workdir := filepath.Join(t.TempDir(), "repo with spaces")
|
||||||
|
if err := os.Mkdir(workdir, 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
err := RunChecks(context.Background(), workdir, []CheckCommand{{
|
||||||
|
Args: []string{helperExecutable(t), "-test.run=TestConfiguredCommandHelper", "--", "argument with spaces"},
|
||||||
|
Env: map[string]string{
|
||||||
|
"RELEASEKIT_CONFIGURED_HELPER": "1",
|
||||||
|
"RELEASEKIT_CONFIGURED_VALUE": "selected value",
|
||||||
|
"RELEASEKIT_VERSION": "profile value",
|
||||||
|
},
|
||||||
|
}}, map[string]string{"RELEASEKIT_VERSION": "captured version", "RELEASEKIT_CANDIDATE": "captured commit"}, &stdout, &stderr)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
want := fmt.Sprintf("%s|argument with spaces|selected value|captured version|captured commit", workdir)
|
||||||
|
if stdout.String() != want {
|
||||||
|
t.Fatalf("stdout = %q, want %q", stdout.String(), want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfiguredCommandHelper(t *testing.T) {
|
||||||
|
if os.Getenv("RELEASEKIT_CONFIGURED_HELPER") != "1" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
workdir, err := os.Getwd()
|
||||||
|
if err != nil {
|
||||||
|
os.Exit(9)
|
||||||
|
}
|
||||||
|
fmt.Fprintf(os.Stdout, "%s|%s|%s|%s|%s", workdir, os.Args[len(os.Args)-1], os.Getenv("RELEASEKIT_CONFIGURED_VALUE"), os.Getenv("RELEASEKIT_VERSION"), os.Getenv("RELEASEKIT_CANDIDATE"))
|
||||||
|
os.Exit(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
func helperExecutable(t *testing.T) string {
|
||||||
|
t.Helper()
|
||||||
|
executable, err := os.Executable()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return executable
|
||||||
|
}
|
||||||
277
cmd/releasekit/internal/cli/receipt.go
Normal file
277
cmd/releasekit/internal/cli/receipt.go
Normal file
@@ -0,0 +1,277 @@
|
|||||||
|
package cli
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/artifact"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/versioncontract"
|
||||||
|
)
|
||||||
|
|
||||||
|
const BuildReceiptName = ".releasekit-build.json"
|
||||||
|
|
||||||
|
type ReceiptTarget struct {
|
||||||
|
OS string `json:"os"`
|
||||||
|
Arch string `json:"arch"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ReceiptArtifact struct {
|
||||||
|
Path string `json:"path"`
|
||||||
|
Filename string `json:"filename"`
|
||||||
|
Target ReceiptTarget `json:"target"`
|
||||||
|
SHA256 string `json:"sha256"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// BuildReceipt is private local coordination data for generated binaries.
|
||||||
|
type BuildReceipt struct {
|
||||||
|
RepositoryDir string `json:"repository_dir"`
|
||||||
|
CandidateCommit string `json:"candidate_commit"`
|
||||||
|
SourceVerified bool `json:"source_verified"`
|
||||||
|
Version string `json:"version"`
|
||||||
|
MainPackage string `json:"main_package"`
|
||||||
|
BinaryName string `json:"binary_name"`
|
||||||
|
OutputDir string `json:"output_dir"`
|
||||||
|
Targets []ReceiptTarget `json:"targets"`
|
||||||
|
Compiler string `json:"compiler"`
|
||||||
|
Artifacts []ReceiptArtifact `json:"artifacts"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func WriteBuildReceipt(outputDir string, receipt BuildReceipt) (string, error) {
|
||||||
|
resolvedDir, err := filepath.Abs(outputDir)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("resolve build receipt directory: %w", err)
|
||||||
|
}
|
||||||
|
receipt.OutputDir = resolvedDir
|
||||||
|
if err := validateBuildReceipt(receipt, true); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
contents, err := json.MarshalIndent(receipt, "", " ")
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("encode build receipt: %w", err)
|
||||||
|
}
|
||||||
|
contents = append(contents, '\n')
|
||||||
|
temporary, err := os.CreateTemp(resolvedDir, ".releasekit-build-receipt-*")
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("create temporary build receipt: %w", err)
|
||||||
|
}
|
||||||
|
temporaryPath := temporary.Name()
|
||||||
|
defer os.Remove(temporaryPath)
|
||||||
|
if _, err := temporary.Write(contents); err != nil {
|
||||||
|
_ = temporary.Close()
|
||||||
|
return "", fmt.Errorf("write build receipt: %w", err)
|
||||||
|
}
|
||||||
|
if err := temporary.Close(); err != nil {
|
||||||
|
return "", fmt.Errorf("close build receipt: %w", err)
|
||||||
|
}
|
||||||
|
path := filepath.Join(resolvedDir, BuildReceiptName)
|
||||||
|
if err := os.Rename(temporaryPath, path); err != nil {
|
||||||
|
if _, statErr := os.Lstat(path); statErr != nil {
|
||||||
|
return "", fmt.Errorf("install build receipt: %w", err)
|
||||||
|
}
|
||||||
|
if removeErr := os.Remove(path); removeErr != nil {
|
||||||
|
return "", fmt.Errorf("replace prior build receipt: %w", removeErr)
|
||||||
|
}
|
||||||
|
if err := os.Rename(temporaryPath, path); err != nil {
|
||||||
|
return "", fmt.Errorf("install build receipt: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return path, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func LoadBuildReceipt(path string) (BuildReceipt, error) {
|
||||||
|
resolvedPath, err := filepath.Abs(path)
|
||||||
|
if err != nil {
|
||||||
|
return BuildReceipt{}, fmt.Errorf("resolve build receipt path: %w", err)
|
||||||
|
}
|
||||||
|
if filepath.Base(resolvedPath) != BuildReceiptName {
|
||||||
|
return BuildReceipt{}, fmt.Errorf("build receipt filename must be %s", BuildReceiptName)
|
||||||
|
}
|
||||||
|
file, err := os.Open(resolvedPath)
|
||||||
|
if err != nil {
|
||||||
|
return BuildReceipt{}, fmt.Errorf("open build receipt: %w", err)
|
||||||
|
}
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
var extra any
|
||||||
|
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
|
||||||
|
if err == nil {
|
||||||
|
return BuildReceipt{}, errors.New("decode build receipt: multiple JSON values")
|
||||||
|
}
|
||||||
|
return BuildReceipt{}, fmt.Errorf("decode build receipt: %w", err)
|
||||||
|
}
|
||||||
|
if err := validateBuildReceipt(receipt, true); err != nil {
|
||||||
|
return BuildReceipt{}, err
|
||||||
|
}
|
||||||
|
if filepath.Clean(receipt.OutputDir) != filepath.Dir(resolvedPath) {
|
||||||
|
return BuildReceipt{}, errors.New("build receipt output directory does not match its location")
|
||||||
|
}
|
||||||
|
return receipt, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (receipt BuildReceipt) MatchesBuild(repositoryDir, commit, version string, settings BuildSettings) bool {
|
||||||
|
resolvedRepo, err := filepath.Abs(repositoryDir)
|
||||||
|
if err != nil || filepath.Clean(receipt.RepositoryDir) != filepath.Clean(resolvedRepo) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if receipt.CandidateCommit != commit || receipt.Version != version || receipt.MainPackage != settings.MainPackage || receipt.BinaryName != settings.BinaryName {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
want := normalizeReceiptTargets(settings.Targets)
|
||||||
|
if len(want) != len(receipt.Targets) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for i, target := range want {
|
||||||
|
if target != receipt.Targets[i] {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateBuildReceipt(receipt BuildReceipt, verifyFiles bool) error {
|
||||||
|
if !versioncontract.ValidStableVersion(receipt.Version) {
|
||||||
|
return fmt.Errorf("build receipt has invalid version %q", receipt.Version)
|
||||||
|
}
|
||||||
|
if !filepath.IsAbs(receipt.RepositoryDir) || !filepath.IsAbs(receipt.OutputDir) {
|
||||||
|
return errors.New("build receipt repository and output directories must be absolute")
|
||||||
|
}
|
||||||
|
if !validCommitID(receipt.CandidateCommit) {
|
||||||
|
return errors.New("build receipt has invalid candidate commit")
|
||||||
|
}
|
||||||
|
if receipt.MainPackage == "" || !artifact.ValidComponent(receipt.BinaryName) || receipt.Compiler == "" {
|
||||||
|
return errors.New("build receipt is missing build identity")
|
||||||
|
}
|
||||||
|
if len(receipt.Targets) == 0 || len(receipt.Artifacts) != len(receipt.Targets) {
|
||||||
|
return errors.New("build receipt target and artifact counts do not match")
|
||||||
|
}
|
||||||
|
seenTargets := make(map[ReceiptTarget]bool, len(receipt.Targets))
|
||||||
|
seenArtifacts := make(map[ReceiptTarget]bool, len(receipt.Artifacts))
|
||||||
|
targets := make([]artifact.Target, 0, len(receipt.Targets))
|
||||||
|
for _, target := range receipt.Targets {
|
||||||
|
if !artifact.ValidComponent(target.OS) || !artifact.ValidComponent(target.Arch) {
|
||||||
|
return fmt.Errorf("build receipt has unsafe target %q/%q", target.OS, target.Arch)
|
||||||
|
}
|
||||||
|
if seenTargets[target] {
|
||||||
|
return fmt.Errorf("build receipt repeats target %s/%s", target.OS, target.Arch)
|
||||||
|
}
|
||||||
|
seenTargets[target] = true
|
||||||
|
targets = append(targets, artifact.Target{OS: target.OS, Arch: target.Arch})
|
||||||
|
}
|
||||||
|
declarations := artifact.ExpectedBuild(receipt.BinaryName, receipt.Version, targets)
|
||||||
|
wantByTarget := make(map[ReceiptTarget]string, len(declarations))
|
||||||
|
for _, declaration := range declarations {
|
||||||
|
target := ReceiptTarget{OS: declaration.Target.OS, Arch: declaration.Target.Arch}
|
||||||
|
wantByTarget[target] = declaration.Filename
|
||||||
|
}
|
||||||
|
for _, artifact := range receipt.Artifacts {
|
||||||
|
if !seenTargets[artifact.Target] || seenArtifacts[artifact.Target] {
|
||||||
|
return fmt.Errorf("build receipt has an unexpected artifact target %s/%s", artifact.Target.OS, artifact.Target.Arch)
|
||||||
|
}
|
||||||
|
seenArtifacts[artifact.Target] = true
|
||||||
|
wantName := wantByTarget[artifact.Target]
|
||||||
|
if artifact.Filename != wantName || filepath.Base(artifact.Filename) != artifact.Filename {
|
||||||
|
return fmt.Errorf("build receipt has invalid artifact filename %q", artifact.Filename)
|
||||||
|
}
|
||||||
|
wantPath := filepath.Join(receipt.OutputDir, artifact.Filename)
|
||||||
|
if !filepath.IsAbs(artifact.Path) || filepath.Clean(artifact.Path) != filepath.Clean(wantPath) {
|
||||||
|
return fmt.Errorf("build receipt artifact path does not match filename %q", artifact.Filename)
|
||||||
|
}
|
||||||
|
if !validSHA256(artifact.SHA256) {
|
||||||
|
return fmt.Errorf("build receipt has invalid SHA-256 for %q", artifact.Filename)
|
||||||
|
}
|
||||||
|
if verifyFiles {
|
||||||
|
if err := verifyReceiptArtifact(artifact); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func verifyReceiptArtifact(artifact ReceiptArtifact) error {
|
||||||
|
info, err := os.Lstat(artifact.Path)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("inspect build artifact %q: %w", artifact.Path, err)
|
||||||
|
}
|
||||||
|
if !info.Mode().IsRegular() {
|
||||||
|
return fmt.Errorf("build artifact %q is not a regular file", artifact.Path)
|
||||||
|
}
|
||||||
|
file, err := os.Open(artifact.Path)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("open build artifact %q: %w", artifact.Path, err)
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
hash := sha256.New()
|
||||||
|
if _, err := io.Copy(hash, file); err != nil {
|
||||||
|
return fmt.Errorf("hash build artifact %q: %w", artifact.Path, err)
|
||||||
|
}
|
||||||
|
if actual := hex.EncodeToString(hash.Sum(nil)); actual != artifact.SHA256 {
|
||||||
|
return fmt.Errorf("build artifact %q hash changed: got %s, expected %s", artifact.Path, actual, artifact.SHA256)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizeReceiptTargets(targets []string) []ReceiptTarget {
|
||||||
|
parsed := make([]artifact.Target, 0, len(targets))
|
||||||
|
for _, value := range targets {
|
||||||
|
goos, goarch, ok := strings.Cut(value, "/")
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
parsed = append(parsed, artifact.Target{OS: goos, Arch: goarch})
|
||||||
|
}
|
||||||
|
normalized := artifact.NormalizeTargets(parsed)
|
||||||
|
result := make([]ReceiptTarget, 0, len(normalized))
|
||||||
|
for _, target := range normalized {
|
||||||
|
result = append(result, ReceiptTarget{OS: target.OS, Arch: target.Arch})
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func validCommitID(value string) bool {
|
||||||
|
if len(value) != 40 && len(value) != 64 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, char := range value {
|
||||||
|
if !(char >= '0' && char <= '9' || char >= 'a' && char <= 'f') {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func validSHA256(value string) bool {
|
||||||
|
if len(value) != sha256.Size*2 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, char := range value {
|
||||||
|
if !(char >= '0' && char <= '9' || char >= 'a' && char <= 'f') {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// RemoveBuildReceipt invalidates prior CLI coordination data after a rebuild.
|
||||||
|
func RemoveBuildReceipt(outputDir string) error {
|
||||||
|
err := os.Remove(filepath.Join(outputDir, BuildReceiptName))
|
||||||
|
if errors.Is(err, os.ErrNotExist) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("invalidate prior build receipt: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
84
cmd/releasekit/internal/cli/receipt_test.go
Normal file
84
cmd/releasekit/internal/cli/receipt_test.go
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
package cli
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestBuildReceiptRoundTripBindsFilesAndBuildInputs(t *testing.T) {
|
||||||
|
outputDir := t.TempDir()
|
||||||
|
repositoryDir := t.TempDir()
|
||||||
|
filename := "example-v1.2.3-linux-amd64"
|
||||||
|
artifactPath := filepath.Join(outputDir, filename)
|
||||||
|
contents := []byte("built application")
|
||||||
|
if err := os.WriteFile(artifactPath, contents, 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
digest := sha256.Sum256(contents)
|
||||||
|
receipt := BuildReceipt{
|
||||||
|
RepositoryDir: repositoryDir,
|
||||||
|
CandidateCommit: strings.Repeat("a", 40),
|
||||||
|
Version: "v1.2.3",
|
||||||
|
MainPackage: "./cmd/example",
|
||||||
|
BinaryName: "example",
|
||||||
|
Targets: []ReceiptTarget{{OS: "linux", Arch: "amd64"}},
|
||||||
|
Compiler: "go version go1.25.0 linux/amd64",
|
||||||
|
Artifacts: []ReceiptArtifact{{
|
||||||
|
Path: artifactPath,
|
||||||
|
Filename: filename,
|
||||||
|
Target: ReceiptTarget{OS: "linux", Arch: "amd64"},
|
||||||
|
SHA256: hex.EncodeToString(digest[:]),
|
||||||
|
}},
|
||||||
|
}
|
||||||
|
path, err := WriteBuildReceipt(outputDir, receipt)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
loaded, err := LoadBuildReceipt(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
settings := BuildSettings{
|
||||||
|
MainPackage: "./cmd/example",
|
||||||
|
BinaryName: "example",
|
||||||
|
Targets: []string{"linux/amd64", "linux/amd64"},
|
||||||
|
}
|
||||||
|
if !loaded.MatchesBuild(repositoryDir, strings.Repeat("a", 40), "v1.2.3", settings) {
|
||||||
|
t.Fatalf("receipt does not match normalized build settings: %#v", loaded)
|
||||||
|
}
|
||||||
|
settings.BinaryName = "other"
|
||||||
|
if loaded.MatchesBuild(repositoryDir, strings.Repeat("a", 40), "v1.2.3", settings) {
|
||||||
|
t.Fatal("receipt matched changed build settings")
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(artifactPath, []byte("changed artifact"), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := LoadBuildReceipt(path); err == nil || !strings.Contains(err.Error(), "hash changed") {
|
||||||
|
t.Fatalf("LoadBuildReceipt() error = %v, want changed-file hash error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadBuildReceiptRejectsUnknownFieldsAndMultipleValues(t *testing.T) {
|
||||||
|
for _, test := range []struct {
|
||||||
|
name string
|
||||||
|
body string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{name: "unknown field", body: `{"unexpected":true}`, want: "unknown field"},
|
||||||
|
{name: "multiple values", body: `{} {}`, want: "multiple JSON values"},
|
||||||
|
} {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
path := filepath.Join(t.TempDir(), BuildReceiptName)
|
||||||
|
if err := os.WriteFile(path, []byte(test.body), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := LoadBuildReceipt(path); err == nil || !strings.Contains(err.Error(), test.want) {
|
||||||
|
t.Fatalf("LoadBuildReceipt() error = %v, want %q", err, test.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
369
cmd/releasekit/main.go
Normal file
369
cmd/releasekit/main.go
Normal file
@@ -0,0 +1,369 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"syscall"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit/internal/cli"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||||
|
code := run(ctx, os.Args[1:], os.Stdout, os.Stderr)
|
||||||
|
stop()
|
||||||
|
os.Exit(code)
|
||||||
|
}
|
||||||
|
|
||||||
|
func run(ctx context.Context, args []string, stdout, stderr io.Writer) int {
|
||||||
|
invocation, err := cli.Parse(args)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "%v\n%s\n", err, cli.Usage)
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
|
||||||
|
switch invocation.Command {
|
||||||
|
case cli.VersionCommand:
|
||||||
|
fmt.Fprintf(stdout, "releasekit %s\n", buildinfo.Version())
|
||||||
|
return 0
|
||||||
|
case cli.CheckAction, cli.PublishAction:
|
||||||
|
settings, err := cli.LoadSettings(invocation.Repository, invocation.ConfigPath)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "load profile: %v\n", err)
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
request := releasekit.ReleaseRequest{
|
||||||
|
RepositoryDir: invocation.Repository,
|
||||||
|
Product: settings.Product,
|
||||||
|
Version: invocation.Version,
|
||||||
|
Remote: settings.Remote,
|
||||||
|
Build: configuredBuildSpec(settings.Build),
|
||||||
|
Output: stderr,
|
||||||
|
}
|
||||||
|
if len(settings.Checks) != 0 {
|
||||||
|
checks := settings.Checks
|
||||||
|
request.AdditionalChecks = func(ctx context.Context, candidate releasekit.Candidate) error {
|
||||||
|
return cli.RunChecks(ctx, candidate.RepositoryDir, checks, map[string]string{
|
||||||
|
"RELEASEKIT_VERSION": candidate.Version,
|
||||||
|
"RELEASEKIT_CANDIDATE": candidate.Commit,
|
||||||
|
}, stderr, stderr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if invocation.Command == cli.PublishAction {
|
||||||
|
fmt.Fprintf(stderr, "validating and publishing %s\n", invocation.Version)
|
||||||
|
result, err := releasekit.Publish(ctx, request)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "publication state=%s phase=%s version=%s commit=%s tag-object=%s endpoint=%q: %v\n", result.State, result.Phase, result.Version, result.CandidateCommit, result.TagObject, result.Endpoint, err)
|
||||||
|
if errors.Is(err, releasekit.ErrInvalidVersion) {
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
if result.State == releasekit.PublicationUnknown {
|
||||||
|
return 3
|
||||||
|
}
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
fmt.Fprintf(stdout, "published %s at %s (tag object %s)\n", result.Version, result.CandidateCommit, result.TagObject)
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
candidate, err := releasekit.Check(ctx, request)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "check failed: %v\n", err)
|
||||||
|
if errors.Is(err, releasekit.ErrInvalidVersion) {
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
fmt.Fprintf(stdout, "local candidate %s at %s is valid\n", candidate.Version, candidate.Commit)
|
||||||
|
return 0
|
||||||
|
case cli.BuildAction:
|
||||||
|
settings, err := cli.LoadSettings(invocation.Repository, invocation.ConfigPath)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "load profile: %v\n", err)
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
if settings.Build == nil {
|
||||||
|
fmt.Fprintln(stderr, "build requires build settings in the profile")
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
result, err := releasekit.Build(ctx, releasekit.BuildRequest{
|
||||||
|
RepositoryDir: invocation.Repository,
|
||||||
|
Version: invocation.Version,
|
||||||
|
Spec: *configuredBuildSpec(settings.Build),
|
||||||
|
OutputDir: invocation.OutputDir,
|
||||||
|
Output: stderr,
|
||||||
|
})
|
||||||
|
if result.OutputDir != "" && len(result.Targets) != 0 {
|
||||||
|
if receiptErr := cli.RemoveBuildReceipt(result.OutputDir); receiptErr != nil {
|
||||||
|
fmt.Fprintf(stderr, "%v\n", receiptErr)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "build failed at %s: %v\n", result.CandidateCommit, err)
|
||||||
|
for _, artifact := range result.Artifacts {
|
||||||
|
fmt.Fprintf(stderr, "built %s %s\n", artifact.Filename, artifact.SHA256)
|
||||||
|
}
|
||||||
|
if errors.Is(err, releasekit.ErrInvalidVersion) {
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
if len(result.Targets) == 0 {
|
||||||
|
fmt.Fprintf(stdout, "no build targets selected for %s at %s\n", result.Version, result.CandidateCommit)
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
receipt := receiptFromBuild(result)
|
||||||
|
receiptPath, err := cli.WriteBuildReceipt(result.OutputDir, receipt)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "write build receipt: %v\n", err)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
stored, err := cli.LoadBuildReceipt(receiptPath)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "verify build receipt: %v\n", err)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
if !stored.MatchesBuild(result.RepositoryDir, result.CandidateCommit, result.Version, *settings.Build) {
|
||||||
|
fmt.Fprintln(stderr, "build receipt does not match the selected source and build settings")
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
fmt.Fprintf(stdout, "built %d artifacts for %s at %s with %s\n", len(result.Artifacts), result.Version, result.CandidateCommit, result.Compiler)
|
||||||
|
for _, artifact := range result.Artifacts {
|
||||||
|
fmt.Fprintf(stdout, "%s %s\n", artifact.Filename, artifact.SHA256)
|
||||||
|
}
|
||||||
|
fmt.Fprintf(stdout, "build receipt: %s\n", receiptPath)
|
||||||
|
return 0
|
||||||
|
case cli.DeliveryAction:
|
||||||
|
return runDelivery(ctx, invocation, stdout, stderr)
|
||||||
|
case cli.CIDeliveryAction:
|
||||||
|
return runCIDelivery(ctx, invocation, stdout, stderr)
|
||||||
|
}
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
|
||||||
|
func runDelivery(ctx context.Context, invocation cli.Invocation, stdout, stderr io.Writer) int {
|
||||||
|
settings, err := cli.LoadSettings(invocation.Repository, invocation.ConfigPath)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "load profile: %v\n", err)
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
return deliverWithSettings(ctx, invocation, settings, stdout, stderr)
|
||||||
|
}
|
||||||
|
|
||||||
|
func runCIDelivery(ctx context.Context, invocation cli.Invocation, stdout, stderr io.Writer) int {
|
||||||
|
err := releasekit.PrepareTaggedCheckout(ctx, releasekit.TaggedCheckoutRequest{
|
||||||
|
RepositoryDir: invocation.Repository,
|
||||||
|
Version: invocation.Version,
|
||||||
|
Remote: invocation.Remote,
|
||||||
|
ExpectedCommit: invocation.Commit,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "prepare tagged checkout: %v\n", err)
|
||||||
|
if errors.Is(err, releasekit.ErrInvalidVersion) {
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
settings, err := cli.LoadSettings(invocation.Repository, invocation.ConfigPath)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "load profile: %v\n", err)
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
destination, status := deliveryDestination(settings, stderr)
|
||||||
|
if status != 0 {
|
||||||
|
return status
|
||||||
|
}
|
||||||
|
if settings.Build != nil && len(settings.Build.Targets) != 0 {
|
||||||
|
if err := releasekit.PrepareBuildDependencies(ctx, invocation.Repository); err != nil {
|
||||||
|
fmt.Fprintf(stderr, "prepare build dependencies: %v\n", err)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return deliverWithDestination(ctx, invocation, settings, destination, stdout, stderr)
|
||||||
|
}
|
||||||
|
|
||||||
|
// deliverWithSettings adapts prepared CLI state to the public delivery facade.
|
||||||
|
// CI entry points can reuse it after preparing the checkout and loading its profile.
|
||||||
|
func deliverWithSettings(ctx context.Context, invocation cli.Invocation, settings cli.Settings, stdout, stderr io.Writer) int {
|
||||||
|
destination, status := deliveryDestination(settings, stderr)
|
||||||
|
if status != 0 {
|
||||||
|
return status
|
||||||
|
}
|
||||||
|
return deliverWithDestination(ctx, invocation, settings, destination, stdout, stderr)
|
||||||
|
}
|
||||||
|
|
||||||
|
func deliveryDestination(settings cli.Settings, stderr io.Writer) (releasekit.GiteaDestination, int) {
|
||||||
|
delivery := settings.Delivery
|
||||||
|
if delivery == nil || strings.TrimSpace(delivery.BaseURL) == "" || strings.TrimSpace(delivery.Owner) == "" || strings.TrimSpace(delivery.Repository) == "" {
|
||||||
|
fmt.Fprintln(stderr, "deliver requires base_url, owner, and repository in the profile delivery settings")
|
||||||
|
return releasekit.GiteaDestination{}, 2
|
||||||
|
}
|
||||||
|
tokenEnv := delivery.TokenEnv
|
||||||
|
if strings.TrimSpace(tokenEnv) == "" {
|
||||||
|
tokenEnv = "RELEASEKIT_GITEA_TOKEN"
|
||||||
|
}
|
||||||
|
token, ok := os.LookupEnv(tokenEnv)
|
||||||
|
if !ok || strings.TrimSpace(token) == "" {
|
||||||
|
fmt.Fprintf(stderr, "deliver requires a non-empty token in environment variable %s\n", tokenEnv)
|
||||||
|
return releasekit.GiteaDestination{}, 2
|
||||||
|
}
|
||||||
|
return releasekit.GiteaDestination{BaseURL: delivery.BaseURL, Owner: delivery.Owner, Repository: delivery.Repository, Token: token}, 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func deliverWithDestination(ctx context.Context, invocation cli.Invocation, settings cli.Settings, destination releasekit.GiteaDestination, stdout, stderr io.Writer) int {
|
||||||
|
hasTargets := settings.Build != nil && len(settings.Build.Targets) != 0
|
||||||
|
if invocation.AssetsDir != "" && !hasTargets {
|
||||||
|
fmt.Fprintln(stderr, "--assets requires build targets in the profile")
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
var buildSpec *releasekit.BuildSpec
|
||||||
|
var prebuilt *releasekit.BuildResult
|
||||||
|
if invocation.AssetsDir == "" && settings.Build != nil {
|
||||||
|
buildSpec = configuredBuildSpec(settings.Build)
|
||||||
|
}
|
||||||
|
if hasTargets {
|
||||||
|
if invocation.AssetsDir != "" {
|
||||||
|
assetsDir := invocation.AssetsDir
|
||||||
|
if !filepath.IsAbs(assetsDir) {
|
||||||
|
assetsDir = filepath.Join(invocation.Repository, assetsDir)
|
||||||
|
}
|
||||||
|
receipt, err := cli.LoadBuildReceipt(filepath.Join(assetsDir, cli.BuildReceiptName))
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "load verified build receipt: %v\n", err)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
if !receipt.MatchesBuild(invocation.Repository, receipt.CandidateCommit, invocation.Version, *settings.Build) {
|
||||||
|
fmt.Fprintln(stderr, "build receipt does not match the selected repository, version, or build settings")
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
prebuilt = buildResultFromReceipt(receipt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := releasekit.Deliver(ctx, releasekit.DeliveryRequest{
|
||||||
|
RepositoryDir: invocation.Repository,
|
||||||
|
Product: settings.Product,
|
||||||
|
Version: invocation.Version,
|
||||||
|
Destination: destination,
|
||||||
|
Build: buildSpec,
|
||||||
|
Prebuilt: prebuilt,
|
||||||
|
Output: stderr,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "delivery state=%s version=%s commit=%s url=%s: %v\n", result.State, result.Version, result.CandidateCommit, result.ReleaseURL, err)
|
||||||
|
writeDeliveryAssets(stderr, result)
|
||||||
|
writeDeliveryRecovery(stderr, result)
|
||||||
|
if errors.Is(err, releasekit.ErrInvalidVersion) {
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
if result.State == releasekit.DeliveryUnknown {
|
||||||
|
return 3
|
||||||
|
}
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
fmt.Fprintf(stdout, "delivered %s at %s (state %s)\n", result.Version, result.CandidateCommit, result.State)
|
||||||
|
if result.ReleaseURL != "" {
|
||||||
|
fmt.Fprintf(stdout, "release: %s\n", result.ReleaseURL)
|
||||||
|
}
|
||||||
|
writeDeliveryAssets(stdout, result)
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeDeliveryAssets(output io.Writer, result releasekit.DeliveryResult) {
|
||||||
|
for _, group := range []struct {
|
||||||
|
label string
|
||||||
|
assets []releasekit.DeliveryAsset
|
||||||
|
}{{"matching", result.Matching}, {"uploaded", result.Uploaded}, {"pending", result.Pending}, {"conflicting", result.Conflicting}, {"uncertain", result.Uncertain}} {
|
||||||
|
for _, asset := range group.assets {
|
||||||
|
fmt.Fprintf(output, "%s %s %s\n", group.label, asset.Filename, asset.SHA256)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeDeliveryRecovery(output io.Writer, result releasekit.DeliveryResult) {
|
||||||
|
switch result.State {
|
||||||
|
case releasekit.DeliveryNotAttempted:
|
||||||
|
fmt.Fprintln(output, "recovery: fix the local or preflight failure before retrying; no remote write was attempted")
|
||||||
|
case releasekit.DeliveryPartial:
|
||||||
|
fmt.Fprintln(output, "recovery: fix the reported cause, then retry this version")
|
||||||
|
case releasekit.DeliveryConflict:
|
||||||
|
fmt.Fprintln(output, "recovery: investigate conflicting hosted content; use a new version if the source or published contents need correction")
|
||||||
|
case releasekit.DeliveryUnknown:
|
||||||
|
fmt.Fprintln(output, "recovery: resolve the remote state before retrying")
|
||||||
|
default:
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(result.Matching)+len(result.Uploaded)+len(result.Conflicting)+len(result.Uncertain) != 0 {
|
||||||
|
fmt.Fprintln(output, "if rebuilding could change asset bytes already on the server, retain the original build artifacts and retry with deliver --assets DIR")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildResultFromReceipt(receipt cli.BuildReceipt) *releasekit.BuildResult {
|
||||||
|
result := &releasekit.BuildResult{
|
||||||
|
RepositoryDir: receipt.RepositoryDir, CandidateCommit: receipt.CandidateCommit, SourceVerified: receipt.SourceVerified,
|
||||||
|
Version: receipt.Version, MainPackage: receipt.MainPackage, BinaryName: receipt.BinaryName,
|
||||||
|
OutputDir: receipt.OutputDir, Compiler: receipt.Compiler,
|
||||||
|
}
|
||||||
|
for _, target := range receipt.Targets {
|
||||||
|
result.Targets = append(result.Targets, releasekit.Target{OS: target.OS, Arch: target.Arch})
|
||||||
|
}
|
||||||
|
for _, artifact := range receipt.Artifacts {
|
||||||
|
result.Artifacts = append(result.Artifacts, releasekit.BuildArtifact{
|
||||||
|
Path: artifact.Path, Filename: artifact.Filename,
|
||||||
|
Target: releasekit.Target{OS: artifact.Target.OS, Arch: artifact.Target.Arch}, SHA256: artifact.SHA256,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func configuredBuildSpec(settings *cli.BuildSettings) *releasekit.BuildSpec {
|
||||||
|
if settings == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
spec := &releasekit.BuildSpec{
|
||||||
|
MainPackage: settings.MainPackage,
|
||||||
|
BinaryName: settings.BinaryName,
|
||||||
|
Targets: make([]releasekit.Target, 0, len(settings.Targets)),
|
||||||
|
}
|
||||||
|
for _, value := range settings.Targets {
|
||||||
|
goos, goarch, _ := strings.Cut(value, "/")
|
||||||
|
spec.Targets = append(spec.Targets, releasekit.Target{OS: goos, Arch: goarch})
|
||||||
|
}
|
||||||
|
return spec
|
||||||
|
}
|
||||||
|
|
||||||
|
func receiptFromBuild(result releasekit.BuildResult) cli.BuildReceipt {
|
||||||
|
receipt := cli.BuildReceipt{
|
||||||
|
RepositoryDir: result.RepositoryDir,
|
||||||
|
CandidateCommit: result.CandidateCommit,
|
||||||
|
SourceVerified: result.SourceVerified,
|
||||||
|
Version: result.Version,
|
||||||
|
MainPackage: result.MainPackage,
|
||||||
|
BinaryName: result.BinaryName,
|
||||||
|
OutputDir: result.OutputDir,
|
||||||
|
Compiler: result.Compiler,
|
||||||
|
Targets: make([]cli.ReceiptTarget, 0, len(result.Targets)),
|
||||||
|
Artifacts: make([]cli.ReceiptArtifact, 0, len(result.Artifacts)),
|
||||||
|
}
|
||||||
|
for _, target := range result.Targets {
|
||||||
|
receipt.Targets = append(receipt.Targets, cli.ReceiptTarget{OS: target.OS, Arch: target.Arch})
|
||||||
|
}
|
||||||
|
for _, artifact := range result.Artifacts {
|
||||||
|
receipt.Artifacts = append(receipt.Artifacts, cli.ReceiptArtifact{
|
||||||
|
Path: artifact.Path,
|
||||||
|
Filename: artifact.Filename,
|
||||||
|
Target: cli.ReceiptTarget{OS: artifact.Target.OS, Arch: artifact.Target.Arch},
|
||||||
|
SHA256: artifact.SHA256,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return receipt
|
||||||
|
}
|
||||||
1130
cmd/releasekit/main_test.go
Normal file
1130
cmd/releasekit/main_test.go
Normal file
File diff suppressed because it is too large
Load Diff
220
cmd/releasekit/release_wrapper_test.go
Normal file
220
cmd/releasekit/release_wrapper_test.go
Normal file
@@ -0,0 +1,220 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestReleaseWrapperPreservesNativeExitStatuses(t *testing.T) {
|
||||||
|
if runtime.GOOS == "windows" {
|
||||||
|
t.Skip("POSIX release entry point")
|
||||||
|
}
|
||||||
|
_, source, _, _ := runtime.Caller(0)
|
||||||
|
root := filepath.Clean(filepath.Join(filepath.Dir(source), "../.."))
|
||||||
|
originalPath := os.Getenv("PATH")
|
||||||
|
realGit, err := exec.LookPath("git")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
sources := releaseWrapperSources(t, root)
|
||||||
|
for _, mode := range []struct {
|
||||||
|
name string
|
||||||
|
status int
|
||||||
|
version string
|
||||||
|
}{{"success", 0, "v1.2.3"}, {"invalid", 2, "invalid"}, {"rejected", 1, "v1.2.3"}, {"unknown", 3, "v1.2.3"}} {
|
||||||
|
t.Run(mode.name, func(t *testing.T) {
|
||||||
|
repository := filepath.Join(t.TempDir(), "source")
|
||||||
|
for path, contents := range sources {
|
||||||
|
name := filepath.Join(repository, path)
|
||||||
|
if err := os.MkdirAll(filepath.Dir(name), 0700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(name, contents, 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := os.Chmod(filepath.Join(repository, "scripts/release"), 0755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
cliGitRun(t, repository, "init", "--initial-branch=main")
|
||||||
|
cliGitRun(t, repository, "config", "user.name", "ReleaseKit Test")
|
||||||
|
cliGitRun(t, repository, "config", "user.email", "fixture@example.test")
|
||||||
|
cliGitRun(t, repository, "config", "commit.gpgsign", "false")
|
||||||
|
validationLog := filepath.Join(t.TempDir(), "validation.log")
|
||||||
|
t.Setenv("RELEASEKIT_TEST_CANDIDATE_LOG", validationLog)
|
||||||
|
candidateTest := `package releasekit
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestReleaseCandidate(t *testing.T) {
|
||||||
|
f, err := os.OpenFile(os.Getenv("RELEASEKIT_TEST_CANDIDATE_LOG"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
if _, err := f.WriteString("validated\n"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`
|
||||||
|
if err := os.WriteFile(filepath.Join(repository, "candidate_test.go"), []byte(candidateTest), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.MkdirAll(filepath.Join(repository, "docs/releases"), 0700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(filepath.Join(repository, "docs/releases/v1.2.3.md"), []byte("# ReleaseKit v1.2.3\n"), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
profile := map[string]any{
|
||||||
|
"product": "ReleaseKit",
|
||||||
|
"checks": []map[string]any{{"args": []string{"sh", "-c", "if [ -n \"$RELEASEKIT_TEST_ARM_GIT_SHIM\" ]; then : > \"$RELEASEKIT_TEST_ARM_GIT_SHIM\"; fi"}}},
|
||||||
|
"delivery": map[string]any{
|
||||||
|
"base_url": "https://gitea.maximumdirect.net",
|
||||||
|
"owner": "eric",
|
||||||
|
"repository": "ReleaseKit",
|
||||||
|
"token_env": "RELEASEKIT_GITEA_TOKEN",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
content, _ := json.Marshal(profile)
|
||||||
|
if err := os.WriteFile(filepath.Join(repository, "releasekit.json"), content, 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
cliGitRun(t, repository, "add", "--all")
|
||||||
|
cliGitRun(t, repository, "commit", "-m", "prepare wrapper fixture")
|
||||||
|
remote := filepath.Join(t.TempDir(), "origin.git")
|
||||||
|
cliGitRun(t, repository, "init", "--bare", remote)
|
||||||
|
cliGitRun(t, repository, "remote", "add", "origin", remote)
|
||||||
|
cliGitRun(t, repository, "push", "origin", "HEAD:refs/heads/main")
|
||||||
|
fetch := filepath.Join(t.TempDir(), "fetch.git")
|
||||||
|
cliGitRun(t, repository, "init", "--bare", fetch)
|
||||||
|
cliGitRun(t, repository, "remote", "set-url", "origin", fetch)
|
||||||
|
cliGitRun(t, repository, "remote", "set-url", "--push", "origin", remote)
|
||||||
|
if mode.name == "rejected" {
|
||||||
|
if err := os.WriteFile(filepath.Join(remote, "hooks/pre-receive"), []byte("#!/bin/sh\nexit 1\n"), 0755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if mode.name == "unknown" {
|
||||||
|
bin := t.TempDir()
|
||||||
|
marker := filepath.Join(bin, "push-started")
|
||||||
|
armMarker := filepath.Join(bin, "arm-git-shim")
|
||||||
|
shim := `#!/bin/sh
|
||||||
|
if [ -f "$RELEASEKIT_TEST_ARM_GIT_SHIM" ]; then
|
||||||
|
for arg do
|
||||||
|
if [ "$arg" = push ]; then
|
||||||
|
"$RELEASEKIT_TEST_REAL_GIT" "$@" || exit 1
|
||||||
|
"$RELEASEKIT_TEST_REAL_GIT" remote set-url --push origin "$RELEASEKIT_TEST_MOVED_ENDPOINT"
|
||||||
|
: > "$RELEASEKIT_TEST_PUSH_MARKER"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
if [ -f "$RELEASEKIT_TEST_ARM_GIT_SHIM" ] && [ -f "$RELEASEKIT_TEST_PUSH_MARKER" ]; then
|
||||||
|
for arg do if [ "$arg" = ls-remote ]; then exit 128; fi; done
|
||||||
|
fi
|
||||||
|
exec "$RELEASEKIT_TEST_REAL_GIT" "$@"
|
||||||
|
`
|
||||||
|
if err := os.WriteFile(filepath.Join(bin, "git"), []byte(shim), 0755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||||
|
t.Setenv("RELEASEKIT_TEST_REAL_GIT", realGit)
|
||||||
|
t.Setenv("RELEASEKIT_TEST_PUSH_MARKER", marker)
|
||||||
|
t.Setenv("RELEASEKIT_TEST_MOVED_ENDPOINT", fetch)
|
||||||
|
t.Setenv("RELEASEKIT_TEST_ARM_GIT_SHIM", armMarker)
|
||||||
|
}
|
||||||
|
command := exec.Command("./scripts/release", mode.version)
|
||||||
|
command.Dir = repository
|
||||||
|
output, err := command.CombinedOutput()
|
||||||
|
status := 0
|
||||||
|
if err != nil {
|
||||||
|
exit, ok := err.(*exec.ExitError)
|
||||||
|
if !ok {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
status = exit.ExitCode()
|
||||||
|
}
|
||||||
|
if status != mode.status {
|
||||||
|
t.Fatalf("status=%d want=%d output=%s", status, mode.status, output)
|
||||||
|
}
|
||||||
|
validated, readErr := os.ReadFile(validationLog)
|
||||||
|
if mode.name == "invalid" {
|
||||||
|
if !os.IsNotExist(readErr) {
|
||||||
|
t.Fatalf("invalid input ran candidate validation: %q, %v", validated, readErr)
|
||||||
|
}
|
||||||
|
} else if readErr != nil || string(validated) != "validated\n" {
|
||||||
|
t.Fatalf("candidate suite must run once: %q, %v", validated, readErr)
|
||||||
|
}
|
||||||
|
if mode.name == "unknown" {
|
||||||
|
if !strings.Contains(string(output), fmt.Sprintf("endpoint=%q", remote)) {
|
||||||
|
t.Fatalf("captured endpoint missing: %s", output)
|
||||||
|
}
|
||||||
|
t.Setenv("PATH", originalPath)
|
||||||
|
// Execute the runbook's guarded recovery commands verbatim.
|
||||||
|
recovery := `test "$(git ls-remote --get-url -- "$releasekit_endpoint")" = "$releasekit_endpoint" &&
|
||||||
|
git ls-remote --refs -- "$releasekit_endpoint" "refs/tags/$releasekit_version"`
|
||||||
|
query := exec.Command("sh", "-c", recovery)
|
||||||
|
query.Dir = repository
|
||||||
|
query.Env = append(os.Environ(), "releasekit_endpoint="+remote, "releasekit_version=v1.2.3")
|
||||||
|
found, err := query.Output()
|
||||||
|
if err != nil || len(found) == 0 {
|
||||||
|
t.Fatalf("captured endpoint recovery failed: %q %v", found, err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(string(found), cliGitOutput(t, repository, "rev-parse", "refs/tags/v1.2.3")) {
|
||||||
|
t.Fatalf("wrong recovered tag: %s", found)
|
||||||
|
}
|
||||||
|
cliGitRun(t, repository, "config", "url."+fetch+".insteadOf", remote)
|
||||||
|
blocked := exec.Command("sh", "-c", recovery)
|
||||||
|
blocked.Dir = repository
|
||||||
|
blocked.Env = query.Env
|
||||||
|
if output, err := blocked.Output(); err == nil || len(output) != 0 {
|
||||||
|
t.Fatalf("rewritten endpoint should block query: %q %v", output, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchQuery := exec.Command(realGit, "ls-remote", "--refs", "origin", "refs/tags/v1.2.3")
|
||||||
|
fetchQuery.Dir = repository
|
||||||
|
stale, err := fetchQuery.Output()
|
||||||
|
if err != nil || len(stale) != 0 {
|
||||||
|
t.Fatalf("fetch fixture unexpectedly found tag: %q %v", stale, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Capture current, nonignored source once, including worktree changes. The
|
||||||
|
// candidate gets one small test instead of the project's full test suite.
|
||||||
|
func releaseWrapperSources(t *testing.T, root string) map[string][]byte {
|
||||||
|
t.Helper()
|
||||||
|
list := exec.Command("git", "ls-files", "-z", "--cached", "--others", "--exclude-standard")
|
||||||
|
list.Dir = root
|
||||||
|
paths, err := list.Output()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
sources := make(map[string][]byte)
|
||||||
|
for _, path := range strings.Split(string(paths), "\x00") {
|
||||||
|
if path == "" || strings.HasSuffix(path, "_test.go") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
contents, err := os.ReadFile(filepath.Join(root, path))
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
continue // Tracked files removed from the current worktree.
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
sources[path] = contents
|
||||||
|
}
|
||||||
|
return sources
|
||||||
|
}
|
||||||
137
cmd/releasekit/releasekit_delivery_workflow_test.go
Normal file
137
cmd/releasekit/releasekit_delivery_workflow_test.go
Normal file
@@ -0,0 +1,137 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit/internal/cli"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout(t *testing.T) {
|
||||||
|
_, sourceFile, _, ok := runtime.Caller(0)
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("locate integration test source")
|
||||||
|
}
|
||||||
|
root := filepath.Clean(filepath.Join(filepath.Dir(sourceFile), "../.."))
|
||||||
|
profile, err := cli.LoadSettings(root, "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("load ReleaseKit source-only profile: %v", err)
|
||||||
|
}
|
||||||
|
if profile.Build != nil && len(profile.Build.Targets) != 0 {
|
||||||
|
t.Fatalf("ReleaseKit profile declares binary targets: %#v", profile.Build.Targets)
|
||||||
|
}
|
||||||
|
if profile.Delivery == nil || profile.Delivery.BaseURL != "https://gitea.maximumdirect.net" || profile.Delivery.Owner != "eric" || profile.Delivery.Repository != "ReleaseKit" || profile.Delivery.TokenEnv != "RELEASEKIT_GITEA_TOKEN" {
|
||||||
|
t.Fatalf("ReleaseKit delivery profile = %#v", profile.Delivery)
|
||||||
|
}
|
||||||
|
repository := filepath.Join(t.TempDir(), "tagged ReleaseKit")
|
||||||
|
clone := exec.Command("git", "clone", "--local", "--no-hardlinks", root, repository)
|
||||||
|
if output, err := clone.CombinedOutput(); err != nil {
|
||||||
|
t.Fatalf("clone ReleaseKit source: %v\n%s", err, output)
|
||||||
|
}
|
||||||
|
cliGitRun(t, repository, "config", "user.name", "ReleaseKit Test")
|
||||||
|
cliGitRun(t, repository, "config", "user.email", "releasekit@example.test")
|
||||||
|
|
||||||
|
const version = "v1.2.3"
|
||||||
|
note := "# ReleaseKit v1.2.3\n\nSource-only delivery fixture.\n\n" +
|
||||||
|
"[COPYRIGHT](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v1.2.3/COPYRIGHT) |\n" +
|
||||||
|
"[LICENSE](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v1.2.3/LICENSE) |\n" +
|
||||||
|
"[ATTRIBUTION](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v1.2.3/docs/oss/attribution.md)\n"
|
||||||
|
notePath := filepath.Join(repository, "docs", "releases", version+".md")
|
||||||
|
if err := os.MkdirAll(filepath.Dir(notePath), 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(notePath, []byte(note), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
ignore, err := os.OpenFile(filepath.Join(repository, ".gitignore"), os.O_APPEND|os.O_WRONLY, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := ignore.WriteString("\n/.releasekit/\n"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := ignore.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
cliGitRun(t, repository, "add", "docs/releases/"+version+".md", ".gitignore")
|
||||||
|
cliGitRun(t, repository, "commit", "-m", "prepare source-only delivery")
|
||||||
|
|
||||||
|
state := &deliveryServerState{product: "ReleaseKit"}
|
||||||
|
server := newDeliveryServer(t, state)
|
||||||
|
defer server.Close()
|
||||||
|
writeDeliveryProfile(t, repository, cli.Settings{
|
||||||
|
Product: "ReleaseKit",
|
||||||
|
Delivery: &cli.DeliverySettings{BaseURL: server.URL, Owner: "owner", Repository: "example"},
|
||||||
|
})
|
||||||
|
state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD")
|
||||||
|
cliGitRun(t, repository, "tag", "-a", version, "-m", "ReleaseKit v1.2.3")
|
||||||
|
|
||||||
|
remote := filepath.Join(t.TempDir(), "origin.git")
|
||||||
|
initRemote := exec.Command("git", "init", "--bare", remote)
|
||||||
|
if output, err := initRemote.CombinedOutput(); err != nil {
|
||||||
|
t.Fatalf("initialize local delivery remote: %v\n%s", err, output)
|
||||||
|
}
|
||||||
|
cliGitRun(t, repository, "remote", "set-url", "origin", remote)
|
||||||
|
cliGitRun(t, repository, "push", "origin", "HEAD:refs/heads/main", "refs/tags/"+version)
|
||||||
|
|
||||||
|
tool := filepath.Join(repository, ".releasekit", "bin", "releasekit")
|
||||||
|
template, err := os.ReadFile(filepath.Join(root, "examples", "woodpecker", "releasekit-source-delivery.yml"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
buildBlock, err := extractWoodpeckerCommand(string(template), "build-tool")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
deliveryBlock, err := extractWoodpeckerCommand(string(template), "deliver-page")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
env := map[string]string{
|
||||||
|
"CI_WORKSPACE": repository,
|
||||||
|
"CI_COMMIT_SHA": state.commit,
|
||||||
|
"CI_COMMIT_TAG": version,
|
||||||
|
"RELEASEKIT_GITEA_TOKEN": "fixture-token",
|
||||||
|
"GOPROXY": "off",
|
||||||
|
"GOSUMDB": "off",
|
||||||
|
}
|
||||||
|
runWoodpeckerBlock(t, strings.ReplaceAll(buildBlock, "$${", "${"), repository, env)
|
||||||
|
if got := cliGitOutput(t, repository, "rev-parse", "HEAD"); got != state.commit {
|
||||||
|
t.Fatalf("template checkout = %s, want %s", got, state.commit)
|
||||||
|
}
|
||||||
|
|
||||||
|
state.remoteCommit = strings.Repeat("f", 40)
|
||||||
|
failure := exec.Command(tool, "deliver", "--repo", repository, version)
|
||||||
|
failure.Dir = repository
|
||||||
|
failure.Env = append(os.Environ(), "RELEASEKIT_GITEA_TOKEN=fixture-token")
|
||||||
|
if output, err := failure.CombinedOutput(); err == nil {
|
||||||
|
t.Fatalf("delivery with a mismatched hosted tag succeeded: %s", output)
|
||||||
|
}
|
||||||
|
if state.releaseCreates != 0 || cliGitOutput(t, repository, "rev-parse", "refs/tags/"+version+"^{commit}") != state.commit {
|
||||||
|
t.Fatal("delivery failure changed hosted release state or source tag")
|
||||||
|
}
|
||||||
|
state.remoteCommit = ""
|
||||||
|
|
||||||
|
for attempt := 0; attempt < 2; attempt++ {
|
||||||
|
output := runWoodpeckerBlock(t, strings.ReplaceAll(deliveryBlock, "$${", "${"), repository, env)
|
||||||
|
if !strings.Contains(output, "state complete") {
|
||||||
|
t.Fatalf("delivery attempt %d output = %q", attempt+1, output)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if state.releaseCreates != 1 || state.assetUploads != 0 || state.assetListReads != 0 {
|
||||||
|
t.Fatalf("page-only workflow calls = creates:%d uploads:%d asset reads:%d", state.releaseCreates, state.assetUploads, state.assetListReads)
|
||||||
|
}
|
||||||
|
if state.noteBody != note {
|
||||||
|
t.Fatalf("hosted note body = %q, want complete note %q", state.noteBody, note)
|
||||||
|
}
|
||||||
|
if got := cliGitOutput(t, repository, "rev-parse", "refs/tags/"+version+"^{commit}"); got != state.commit {
|
||||||
|
t.Fatalf("source tag moved after delivery: %s, want %s", got, state.commit)
|
||||||
|
}
|
||||||
|
if status := cliGitOutput(t, repository, "status", "--porcelain"); status != "" {
|
||||||
|
t.Fatalf("tagged checkout became dirty after delivery: %s", status)
|
||||||
|
}
|
||||||
|
}
|
||||||
237
cmd/releasekit/woodpecker_test.go
Normal file
237
cmd/releasekit/woodpecker_test.go
Normal file
@@ -0,0 +1,237 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit/internal/cli"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestWoodpeckerTagDeliveryTemplate(t *testing.T) {
|
||||||
|
root := cliRepositoryRoot(t)
|
||||||
|
templatePath := filepath.Join(root, "examples", "woodpecker", "tag-delivery.yml")
|
||||||
|
contents, err := os.ReadFile(templatePath)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
pin, err := woodpeckerMatrixValue(string(contents), "RELEASEKIT_VERSION")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
block, err := extractWoodpeckerCommand(string(contents), "deliver")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
command := strings.ReplaceAll(block, "${RELEASEKIT_VERSION}", pin)
|
||||||
|
command = strings.ReplaceAll(command, "$${", "${")
|
||||||
|
|
||||||
|
executable := filepath.Join(t.TempDir(), "releasekit")
|
||||||
|
build := exec.Command("go", "build", "-o", executable, "./cmd/releasekit")
|
||||||
|
build.Dir = root
|
||||||
|
if output, err := build.CombinedOutput(); err != nil {
|
||||||
|
t.Fatalf("build local ReleaseKit executable: %v\n%s", err, output)
|
||||||
|
}
|
||||||
|
|
||||||
|
module := "gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit@" + pin
|
||||||
|
t.Run("source-only", func(t *testing.T) {
|
||||||
|
repository := newCLIRepository(t)
|
||||||
|
writeRepositoryFile(t, repository, "go.mod", "module example.com/cli-candidate\n\ngo 1.25.0\n\nrequire example.com/unavailable/module v1.2.3\n")
|
||||||
|
cliGitRun(t, repository, "add", "go.mod")
|
||||||
|
cliGitRun(t, repository, "commit", "-m", "declare unavailable dependency")
|
||||||
|
state := &deliveryServerState{}
|
||||||
|
server := newDeliveryServer(t, state)
|
||||||
|
defer server.Close()
|
||||||
|
writeDeliveryProfile(t, repository, cli.Settings{
|
||||||
|
Product: "Example Product",
|
||||||
|
Delivery: &cli.DeliverySettings{BaseURL: server.URL, Owner: "owner", Repository: "example"},
|
||||||
|
})
|
||||||
|
commit := pushTaggedCLIRepository(t, repository)
|
||||||
|
state.commit = commit
|
||||||
|
|
||||||
|
shimDir, goLog := installGoBootstrapShim(t)
|
||||||
|
env := templateEnvironment(repository, commit, executable, module, shimDir, goLog)
|
||||||
|
for attempt := 0; attempt < 2; attempt++ {
|
||||||
|
output := runWoodpeckerBlock(t, command, repository, env)
|
||||||
|
if !strings.Contains(output, "state complete") {
|
||||||
|
t.Fatalf("delivery attempt %d output=%q", attempt+1, output)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if state.releaseCreates != 1 || state.assetUploads != 0 {
|
||||||
|
t.Fatalf("source-only calls = creates:%d uploads:%d", state.releaseCreates, state.assetUploads)
|
||||||
|
}
|
||||||
|
if log, err := os.ReadFile(goLog); err != nil || strings.Contains(string(log), "mod download") {
|
||||||
|
t.Fatalf("source-only command downloaded application dependencies: log=%q error=%v", log, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("binary", func(t *testing.T) {
|
||||||
|
repository := newDeliveryBuildRepository(t)
|
||||||
|
state := &deliveryServerState{}
|
||||||
|
server := newDeliveryServer(t, state)
|
||||||
|
defer server.Close()
|
||||||
|
writeDeliveryProfile(t, repository, cli.Settings{
|
||||||
|
Product: "Example Product",
|
||||||
|
Build: &cli.BuildSettings{
|
||||||
|
MainPackage: ".",
|
||||||
|
BinaryName: "helper",
|
||||||
|
Targets: []string{fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH)},
|
||||||
|
},
|
||||||
|
Delivery: &cli.DeliverySettings{BaseURL: server.URL, Owner: "owner", Repository: "example"},
|
||||||
|
})
|
||||||
|
commit := pushTaggedCLIRepository(t, repository)
|
||||||
|
state.commit = commit
|
||||||
|
|
||||||
|
shimDir, goLog := installGoBootstrapShim(t)
|
||||||
|
env := templateEnvironment(repository, commit, executable, module, shimDir, goLog)
|
||||||
|
for attempt := 0; attempt < 2; attempt++ {
|
||||||
|
output := runWoodpeckerBlock(t, command, repository, env)
|
||||||
|
if !strings.Contains(output, "state complete") {
|
||||||
|
t.Fatalf("delivery attempt %d output=%q", attempt+1, output)
|
||||||
|
}
|
||||||
|
if attempt == 1 && !strings.Contains(output, "matching SHA256SUMS") {
|
||||||
|
t.Fatalf("second delivery did not reuse matching assets: %q", output)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if state.releaseCreates != 1 || state.assetUploads != 2 {
|
||||||
|
t.Fatalf("binary calls = creates:%d uploads:%d", state.releaseCreates, state.assetUploads)
|
||||||
|
}
|
||||||
|
if _, ok := state.assets["helper-v1.2.3-"+runtime.GOOS+"-"+runtime.GOARCH]; !ok {
|
||||||
|
t.Fatalf("binary asset was not delivered: %#v", state.assets)
|
||||||
|
}
|
||||||
|
if _, ok := state.assets["SHA256SUMS"]; !ok {
|
||||||
|
t.Fatalf("checksum manifest was not delivered: %#v", state.assets)
|
||||||
|
}
|
||||||
|
if log, err := os.ReadFile(goLog); err != nil || !strings.Contains(string(log), "mod download") {
|
||||||
|
t.Fatalf("binary command did not prepare application dependencies: log=%q error=%v", log, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func cliRepositoryRoot(t *testing.T) string {
|
||||||
|
t.Helper()
|
||||||
|
_, sourceFile, _, ok := runtime.Caller(0)
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("locate integration test source")
|
||||||
|
}
|
||||||
|
return filepath.Clean(filepath.Join(filepath.Dir(sourceFile), "../.."))
|
||||||
|
}
|
||||||
|
|
||||||
|
func extractWoodpeckerCommand(contents, stepName string) (string, error) {
|
||||||
|
lines := strings.Split(contents, "\n")
|
||||||
|
stepHeader := " - name: " + stepName
|
||||||
|
for i, line := range lines {
|
||||||
|
if strings.TrimSpace(line) != strings.TrimSpace(stepHeader) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for j := i + 1; j < len(lines); j++ {
|
||||||
|
trimmed := strings.TrimSpace(lines[j])
|
||||||
|
if strings.HasPrefix(lines[j], " - name:") {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if trimmed != "- |" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
var block []string
|
||||||
|
for k := j + 1; k < len(lines); k++ {
|
||||||
|
current := lines[k]
|
||||||
|
if strings.TrimSpace(current) == "" {
|
||||||
|
block = append(block, "")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
indent := len(current) - len(strings.TrimLeft(current, " "))
|
||||||
|
if indent < 8 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
block = append(block, current[8:])
|
||||||
|
}
|
||||||
|
return strings.TrimSpace(strings.Join(block, "\n")), nil
|
||||||
|
}
|
||||||
|
return "", fmt.Errorf("step %q has no literal command block", stepName)
|
||||||
|
}
|
||||||
|
return "", fmt.Errorf("step %q was not found", stepName)
|
||||||
|
}
|
||||||
|
|
||||||
|
func woodpeckerMatrixValue(contents, key string) (string, error) {
|
||||||
|
for _, line := range strings.Split(contents, "\n") {
|
||||||
|
field, value, ok := strings.Cut(strings.TrimSpace(line), ":")
|
||||||
|
if ok && field == key {
|
||||||
|
return strings.TrimSpace(value), nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "", fmt.Errorf("matrix value %q was not found", key)
|
||||||
|
}
|
||||||
|
|
||||||
|
func installGoBootstrapShim(t *testing.T) (string, string) {
|
||||||
|
t.Helper()
|
||||||
|
shimDir := t.TempDir()
|
||||||
|
goLog := filepath.Join(shimDir, "go-commands")
|
||||||
|
shim := `#!/bin/sh
|
||||||
|
if [ "$1" = "run" ]; then
|
||||||
|
shift
|
||||||
|
[ "$1" = "$RELEASEKIT_EXPECTED_MODULE" ] || { echo "unexpected module: $1" >&2; exit 90; }
|
||||||
|
shift
|
||||||
|
[ "$1" = "ci-deliver" ] || { echo "unexpected command: $1" >&2; exit 91; }
|
||||||
|
[ "$2" = "--repo" ] && [ "$3" = "$CI_WORKSPACE" ] || { echo "unexpected repository arguments" >&2; exit 92; }
|
||||||
|
[ "$4" = "--commit" ] && [ "$5" = "$CI_COMMIT_SHA" ] || { echo "unexpected commit arguments" >&2; exit 93; }
|
||||||
|
[ "$6" = "$CI_COMMIT_TAG" ] && [ "$#" = 6 ] || { echo "unexpected version argument" >&2; exit 94; }
|
||||||
|
printf '%s\n' "run $RELEASEKIT_EXPECTED_MODULE" >> "$RELEASEKIT_GO_LOG"
|
||||||
|
exec "$RELEASEKIT_LOCAL_EXECUTABLE" "$@"
|
||||||
|
fi
|
||||||
|
printf '%s\n' "$*" >> "$RELEASEKIT_GO_LOG"
|
||||||
|
exec "$RELEASEKIT_REAL_GO" "$@"
|
||||||
|
`
|
||||||
|
if err := os.WriteFile(filepath.Join(shimDir, "go"), []byte(shim), 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return shimDir, goLog
|
||||||
|
}
|
||||||
|
|
||||||
|
func templateEnvironment(repository, commit, executable, module, shimDir, goLog string) map[string]string {
|
||||||
|
realGo, _ := exec.LookPath("go")
|
||||||
|
return map[string]string{
|
||||||
|
"CI_WORKSPACE": repository,
|
||||||
|
"CI_COMMIT_SHA": commit,
|
||||||
|
"CI_COMMIT_TAG": "v1.2.3",
|
||||||
|
"RELEASEKIT_GITEA_TOKEN": "fixture-token",
|
||||||
|
"RELEASEKIT_EXPECTED_MODULE": module,
|
||||||
|
"RELEASEKIT_LOCAL_EXECUTABLE": executable,
|
||||||
|
"RELEASEKIT_REAL_GO": realGo,
|
||||||
|
"RELEASEKIT_GO_LOG": goLog,
|
||||||
|
"GOTOOLCHAIN": "local",
|
||||||
|
"GOPROXY": "off",
|
||||||
|
"GOSUMDB": "off",
|
||||||
|
"GOFLAGS": "",
|
||||||
|
"PATH": shimDir + string(os.PathListSeparator) + os.Getenv("PATH"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func runWoodpeckerBlock(t *testing.T, block, repository string, environment map[string]string) string {
|
||||||
|
t.Helper()
|
||||||
|
command := exec.Command("sh", "-e", "-c", block)
|
||||||
|
command.Dir = repository
|
||||||
|
command.Env = os.Environ()
|
||||||
|
for key, value := range environment {
|
||||||
|
command.Env = setEnvironment(command.Env, key, value)
|
||||||
|
}
|
||||||
|
output, err := command.CombinedOutput()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Woodpecker command failed: %v\ncommand: %s\noutput: %s", err, block, output)
|
||||||
|
}
|
||||||
|
return string(output)
|
||||||
|
}
|
||||||
|
|
||||||
|
func setEnvironment(environment []string, key, value string) []string {
|
||||||
|
prefix := key + "="
|
||||||
|
for i, entry := range environment {
|
||||||
|
if strings.HasPrefix(entry, prefix) {
|
||||||
|
environment[i] = prefix + value
|
||||||
|
return environment
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return append(environment, prefix+value)
|
||||||
|
}
|
||||||
122
delivery.go
Normal file
122
delivery.go
Normal file
@@ -0,0 +1,122 @@
|
|||||||
|
package releasekit
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"io"
|
||||||
|
|
||||||
|
internalbuild "gitea.maximumdirect.net/eric/ReleaseKit/internal/build"
|
||||||
|
internaldelivery "gitea.maximumdirect.net/eric/ReleaseKit/internal/delivery"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/gitea"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DeliveryState describes the result of one delivery invocation.
|
||||||
|
type DeliveryState string
|
||||||
|
|
||||||
|
const (
|
||||||
|
// DeliveryNotAttempted means this invocation made no remote write.
|
||||||
|
DeliveryNotAttempted DeliveryState = "not_attempted"
|
||||||
|
// DeliveryComplete means the release page and all declared assets match.
|
||||||
|
DeliveryComplete DeliveryState = "complete"
|
||||||
|
// DeliveryPartial means a page or some assets were delivered, with work pending.
|
||||||
|
DeliveryPartial DeliveryState = "partial"
|
||||||
|
// DeliveryConflict means existing hosted content differs from the declaration.
|
||||||
|
DeliveryConflict DeliveryState = "conflict"
|
||||||
|
// DeliveryUnknown means a remote write may have succeeded but could not be resolved.
|
||||||
|
DeliveryUnknown DeliveryState = "unknown"
|
||||||
|
)
|
||||||
|
|
||||||
|
// GiteaDestination supplies the hosted repository and explicit access token.
|
||||||
|
type GiteaDestination struct {
|
||||||
|
BaseURL string
|
||||||
|
Owner string
|
||||||
|
Repository string
|
||||||
|
Token string
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeliveryAsset identifies a hosted asset by filename and SHA-256 digest.
|
||||||
|
type DeliveryAsset struct {
|
||||||
|
Filename string
|
||||||
|
SHA256 string
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeliveryRequest identifies a local tagged checkout and its explicit Gitea
|
||||||
|
// destination. Build selects a managed build; Prebuilt supplies caller-owned
|
||||||
|
// build output instead. They cannot both be set. Either may be nil for
|
||||||
|
// page-only delivery when both are nil. Build with no targets, or an empty
|
||||||
|
// Prebuilt result, also performs page-only delivery.
|
||||||
|
type DeliveryRequest struct {
|
||||||
|
RepositoryDir string
|
||||||
|
Product string
|
||||||
|
Version string
|
||||||
|
Destination GiteaDestination
|
||||||
|
// Build selects binaries to build in temporary storage outside the checkout.
|
||||||
|
Build *BuildSpec
|
||||||
|
// Prebuilt supplies an existing build whose files remain caller-owned.
|
||||||
|
Prebuilt *BuildResult
|
||||||
|
// Output receives progress from a managed build.
|
||||||
|
Output io.Writer
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeliveryResult reports hosted content and the state reached by this
|
||||||
|
// invocation. A partial result may accompany an error. The asset slices are
|
||||||
|
// current observations: an asset appears in at most one slice, and early
|
||||||
|
// failures may leave some declared assets unreported.
|
||||||
|
type DeliveryResult struct {
|
||||||
|
Version string
|
||||||
|
CandidateCommit string
|
||||||
|
ReleaseURL string
|
||||||
|
State DeliveryState
|
||||||
|
// Matching lists existing attachments with the declared content.
|
||||||
|
Matching []DeliveryAsset
|
||||||
|
// Uploaded lists assets whose uploads were confirmed during this invocation.
|
||||||
|
Uploaded []DeliveryAsset
|
||||||
|
// Pending lists assets known to be missing.
|
||||||
|
Pending []DeliveryAsset
|
||||||
|
// Conflicting lists assets with detected content conflicts.
|
||||||
|
Conflicting []DeliveryAsset
|
||||||
|
// Uncertain lists assets whose remote state could not be resolved.
|
||||||
|
Uncertain []DeliveryAsset
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deliver verifies the selected local tag and hosted source, then creates or
|
||||||
|
// finds its release page and adds any missing declared build assets. Build
|
||||||
|
// requests are compiled into temporary storage that Deliver removes on return.
|
||||||
|
// Prebuilt artifacts remain caller-owned and are not removed. Both paths
|
||||||
|
// validate source identity and artifact contents before hosted writes.
|
||||||
|
func Deliver(ctx context.Context, request DeliveryRequest) (DeliveryResult, error) {
|
||||||
|
result := DeliveryResult{Version: request.Version, State: DeliveryNotAttempted}
|
||||||
|
destination := gitea.Destination{
|
||||||
|
BaseURL: request.Destination.BaseURL, Owner: request.Destination.Owner,
|
||||||
|
Repository: request.Destination.Repository, Token: request.Destination.Token,
|
||||||
|
}
|
||||||
|
var prebuilt *internalbuild.Result
|
||||||
|
if request.Prebuilt != nil {
|
||||||
|
prebuilt = internalBuildResult(*request.Prebuilt)
|
||||||
|
}
|
||||||
|
internalResult, err := internaldelivery.Deliver(ctx, internaldelivery.Request{
|
||||||
|
RepositoryDir: request.RepositoryDir,
|
||||||
|
Product: request.Product,
|
||||||
|
Version: request.Version,
|
||||||
|
Destination: destination,
|
||||||
|
Build: internalBuildSpec(request.Build),
|
||||||
|
Prebuilt: prebuilt,
|
||||||
|
Output: request.Output,
|
||||||
|
})
|
||||||
|
result.CandidateCommit = internalResult.CandidateCommit
|
||||||
|
result.ReleaseURL = internalResult.ReleaseURL
|
||||||
|
result.State = DeliveryState(internalResult.State)
|
||||||
|
result.Matching = deliveryAssets(internalResult.Matching)
|
||||||
|
result.Uploaded = deliveryAssets(internalResult.Uploaded)
|
||||||
|
result.Pending = deliveryAssets(internalResult.Pending)
|
||||||
|
result.Conflicting = deliveryAssets(internalResult.Conflicting)
|
||||||
|
result.Uncertain = deliveryAssets(internalResult.Uncertain)
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func deliveryAssets(assets []gitea.AssetIdentity) []DeliveryAsset {
|
||||||
|
result := make([]DeliveryAsset, 0, len(assets))
|
||||||
|
for _, asset := range assets {
|
||||||
|
result = append(result, DeliveryAsset{Filename: asset.Filename, SHA256: asset.SHA256})
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
535
delivery_test.go
Normal file
535
delivery_test.go
Normal file
@@ -0,0 +1,535 @@
|
|||||||
|
package releasekit_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
releasekit "gitea.maximumdirect.net/eric/ReleaseKit"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestDeliverManagedBuildUploadsArtifactsAndCleansTemporaryOutput(t *testing.T) {
|
||||||
|
repository := newTaggedDeliveryConsumer(t)
|
||||||
|
temporaryRoot := t.TempDir()
|
||||||
|
t.Setenv("TMPDIR", temporaryRoot)
|
||||||
|
server, remote := newFacadeDeliveryServer(t, repository)
|
||||||
|
defer server.Close()
|
||||||
|
var progress strings.Builder
|
||||||
|
|
||||||
|
result, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Fixture",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Destination: facadeDeliveryDestination(server.URL),
|
||||||
|
Build: &releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/app",
|
||||||
|
BinaryName: "fixture",
|
||||||
|
Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}},
|
||||||
|
},
|
||||||
|
Output: &progress,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Deliver() error = %v; result = %#v", err, result)
|
||||||
|
}
|
||||||
|
if result.State != releasekit.DeliveryComplete || result.CandidateCommit != remote.commit {
|
||||||
|
t.Fatalf("delivery result = %#v", result)
|
||||||
|
}
|
||||||
|
if len(result.Uploaded) != 2 || len(remote.assets) != 2 {
|
||||||
|
t.Fatalf("uploaded = %#v; hosted assets = %v", result.Uploaded, mapKeys(remote.assets))
|
||||||
|
}
|
||||||
|
if !strings.Contains(progress.String(), "checking fixture version output") {
|
||||||
|
t.Fatalf("build progress = %q", progress.String())
|
||||||
|
}
|
||||||
|
if entries, err := os.ReadDir(temporaryRoot); err != nil || len(entries) != 0 {
|
||||||
|
t.Fatalf("managed build output remains: entries=%v error=%v", entries, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeliverBinaryConsumerWithBuildinfoAndSelectedTargets(t *testing.T) {
|
||||||
|
repository := newTaggedDeliveryConsumer(t)
|
||||||
|
server, remote := newFacadeDeliveryServer(t, repository)
|
||||||
|
defer server.Close()
|
||||||
|
var progress strings.Builder
|
||||||
|
|
||||||
|
result, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Fixture",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Destination: facadeDeliveryDestination(server.URL),
|
||||||
|
Build: &releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/app",
|
||||||
|
BinaryName: "fixture",
|
||||||
|
Targets: []releasekit.Target{
|
||||||
|
{OS: "linux", Arch: "amd64"},
|
||||||
|
{OS: "linux", Arch: "arm64"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Output: &progress,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Deliver() error = %v; result = %#v", err, result)
|
||||||
|
}
|
||||||
|
if result.State != releasekit.DeliveryComplete || result.CandidateCommit != remote.commit {
|
||||||
|
t.Fatalf("delivery result = %#v", result)
|
||||||
|
}
|
||||||
|
wantAssets := []string{
|
||||||
|
"fixture-v1.2.3-linux-amd64",
|
||||||
|
"fixture-v1.2.3-linux-arm64",
|
||||||
|
"SHA256SUMS",
|
||||||
|
}
|
||||||
|
if len(result.Uploaded) != len(wantAssets) || len(remote.assets) != len(wantAssets) {
|
||||||
|
t.Fatalf("uploaded = %#v; hosted assets = %v", result.Uploaded, mapKeys(remote.assets))
|
||||||
|
}
|
||||||
|
for _, name := range wantAssets {
|
||||||
|
if _, ok := remote.assets[name]; !ok {
|
||||||
|
t.Errorf("hosted assets omit %q: %v", name, mapKeys(remote.assets))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !strings.Contains(progress.String(), "checking fixture version output") {
|
||||||
|
t.Fatalf("build progress = %q", progress.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeliverPrebuiltArtifactsRemainCallerOwned(t *testing.T) {
|
||||||
|
repository := newTaggedDeliveryConsumer(t)
|
||||||
|
outputDir := filepath.Join(t.TempDir(), "caller-owned-assets")
|
||||||
|
prebuilt, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Spec: releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/app",
|
||||||
|
BinaryName: "fixture",
|
||||||
|
Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}},
|
||||||
|
},
|
||||||
|
OutputDir: outputDir,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Build() error = %v", err)
|
||||||
|
}
|
||||||
|
server, _ := newFacadeDeliveryServer(t, repository)
|
||||||
|
defer server.Close()
|
||||||
|
result, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Fixture",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Destination: facadeDeliveryDestination(server.URL),
|
||||||
|
Prebuilt: &prebuilt,
|
||||||
|
})
|
||||||
|
if err != nil || result.State != releasekit.DeliveryComplete {
|
||||||
|
t.Fatalf("Deliver() = %#v, %v", result, err)
|
||||||
|
}
|
||||||
|
for _, artifact := range prebuilt.Artifacts {
|
||||||
|
if _, err := os.Stat(artifact.Path); err != nil {
|
||||||
|
t.Errorf("caller-owned artifact %q was removed: %v", artifact.Path, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeliverPageOnlySkipsBuildAndHostedAssets(t *testing.T) {
|
||||||
|
for _, test := range []struct {
|
||||||
|
name string
|
||||||
|
build *releasekit.BuildSpec
|
||||||
|
prebuilt *releasekit.BuildResult
|
||||||
|
}{
|
||||||
|
{name: "no build"},
|
||||||
|
{name: "empty target set", build: &releasekit.BuildSpec{}},
|
||||||
|
{name: "empty prebuilt result", prebuilt: &releasekit.BuildResult{}},
|
||||||
|
} {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
repository := newTaggedDeliveryConsumer(t)
|
||||||
|
temporaryRoot := t.TempDir()
|
||||||
|
t.Setenv("TMPDIR", temporaryRoot)
|
||||||
|
server, remote := newFacadeDeliveryServer(t, repository)
|
||||||
|
defer server.Close()
|
||||||
|
var progress strings.Builder
|
||||||
|
|
||||||
|
result, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Fixture",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Destination: facadeDeliveryDestination(server.URL),
|
||||||
|
Build: test.build,
|
||||||
|
Prebuilt: test.prebuilt,
|
||||||
|
Output: &progress,
|
||||||
|
})
|
||||||
|
if err != nil || result.State != releasekit.DeliveryComplete {
|
||||||
|
t.Fatalf("Deliver() = %#v, %v", result, err)
|
||||||
|
}
|
||||||
|
if len(remote.assets) != 0 || len(result.Uploaded) != 0 || len(result.Pending) != 0 {
|
||||||
|
t.Fatalf("page-only delivery included assets: result=%#v assets=%v", result, mapKeys(remote.assets))
|
||||||
|
}
|
||||||
|
if progress.Len() != 0 {
|
||||||
|
t.Fatalf("page-only delivery emitted build progress: %q", progress.String())
|
||||||
|
}
|
||||||
|
if entries, err := os.ReadDir(temporaryRoot); err != nil || len(entries) != 0 {
|
||||||
|
t.Fatalf("page-only delivery allocated temporary output: entries=%v error=%v", entries, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeliverRejectsDirtyTaggedSourceBeforeBuildOrHostedWrites(t *testing.T) {
|
||||||
|
repository := newTaggedDeliveryConsumer(t)
|
||||||
|
writeBuildFixture(t, repository, "local-change.txt", "dirty source")
|
||||||
|
temporaryRoot := t.TempDir()
|
||||||
|
t.Setenv("TMPDIR", temporaryRoot)
|
||||||
|
server, remote := newFacadeDeliveryServer(t, repository)
|
||||||
|
defer server.Close()
|
||||||
|
var progress strings.Builder
|
||||||
|
|
||||||
|
result, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Fixture",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Destination: facadeDeliveryDestination(server.URL),
|
||||||
|
Build: &releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/app",
|
||||||
|
BinaryName: "fixture",
|
||||||
|
Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}},
|
||||||
|
},
|
||||||
|
Output: &progress,
|
||||||
|
})
|
||||||
|
if err == nil || result.State != releasekit.DeliveryNotAttempted || result.CandidateCommit != remote.commit {
|
||||||
|
t.Fatalf("Deliver() = %#v, %v; want preflight failure for known commit", result, err)
|
||||||
|
}
|
||||||
|
if progress.Len() != 0 {
|
||||||
|
t.Fatalf("build started before source eligibility passed: %q", progress.String())
|
||||||
|
}
|
||||||
|
if remote.requests != 0 {
|
||||||
|
t.Fatalf("hosted requests = %d, want none", remote.requests)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeliverRejectsCheckoutAwayFromTagBeforeBuildOrHostedWrites(t *testing.T) {
|
||||||
|
repository := newTaggedDeliveryConsumer(t)
|
||||||
|
writeBuildFixture(t, repository, "later-change.txt", "new commit")
|
||||||
|
buildGit(t, repository, "add", "--all")
|
||||||
|
buildGit(t, repository, "commit", "-m", "advance checkout after release tag")
|
||||||
|
temporaryRoot := t.TempDir()
|
||||||
|
t.Setenv("TMPDIR", temporaryRoot)
|
||||||
|
server, remote := newFacadeDeliveryServer(t, repository)
|
||||||
|
defer server.Close()
|
||||||
|
var progress strings.Builder
|
||||||
|
|
||||||
|
result, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Fixture",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Destination: facadeDeliveryDestination(server.URL),
|
||||||
|
Build: &releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/app",
|
||||||
|
BinaryName: "fixture",
|
||||||
|
Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}},
|
||||||
|
},
|
||||||
|
Output: &progress,
|
||||||
|
})
|
||||||
|
if err == nil || result.State != releasekit.DeliveryNotAttempted || result.CandidateCommit == remote.commit {
|
||||||
|
t.Fatalf("Deliver() = %#v, %v; want tag/HEAD mismatch", result, err)
|
||||||
|
}
|
||||||
|
if progress.Len() != 0 {
|
||||||
|
t.Fatalf("build started before tag/HEAD agreement: %q", progress.String())
|
||||||
|
}
|
||||||
|
if remote.requests != 0 {
|
||||||
|
t.Fatalf("hosted requests = %d, want none", remote.requests)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeliverRejectsInvalidCommittedNoteBeforeBuildOrHostedWrites(t *testing.T) {
|
||||||
|
repository := newTaggedDeliveryConsumerWithNote(t, "# Different Product v1.2.3\n\nWrong product.\n")
|
||||||
|
temporaryRoot := t.TempDir()
|
||||||
|
t.Setenv("TMPDIR", temporaryRoot)
|
||||||
|
server, remote := newFacadeDeliveryServer(t, repository)
|
||||||
|
defer server.Close()
|
||||||
|
var progress strings.Builder
|
||||||
|
|
||||||
|
result, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Fixture",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Destination: facadeDeliveryDestination(server.URL),
|
||||||
|
Build: &releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/app",
|
||||||
|
BinaryName: "fixture",
|
||||||
|
Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}},
|
||||||
|
},
|
||||||
|
Output: &progress,
|
||||||
|
})
|
||||||
|
if err == nil || result.State != releasekit.DeliveryNotAttempted || result.CandidateCommit != remote.commit {
|
||||||
|
t.Fatalf("Deliver() = %#v, %v; want committed-note preflight failure", result, err)
|
||||||
|
}
|
||||||
|
if progress.Len() != 0 {
|
||||||
|
t.Fatalf("build started before committed-note validation: %q", progress.String())
|
||||||
|
}
|
||||||
|
if remote.requests != 0 {
|
||||||
|
t.Fatalf("hosted requests = %d, want none", remote.requests)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeliverManagedBuildRejectsCheckoutMutationBeforeHostedWrites(t *testing.T) {
|
||||||
|
repository := newTaggedDeliveryConsumer(t)
|
||||||
|
temporaryRoot := t.TempDir()
|
||||||
|
t.Setenv("TMPDIR", temporaryRoot)
|
||||||
|
server, remote := newFacadeDeliveryServer(t, repository)
|
||||||
|
defer server.Close()
|
||||||
|
writer := &sourceChangeWriter{change: func() {
|
||||||
|
source, err := os.ReadFile(filepath.Join(repository, "cmd/app/main.go"))
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("read application source: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeBuildFixture(t, repository, "cmd/app/main.go", string(source)+"\n// changed during delivery build\n")
|
||||||
|
}}
|
||||||
|
|
||||||
|
result, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Fixture",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Destination: facadeDeliveryDestination(server.URL),
|
||||||
|
Build: &releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/app",
|
||||||
|
BinaryName: "fixture",
|
||||||
|
Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}},
|
||||||
|
},
|
||||||
|
Output: writer,
|
||||||
|
})
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "build source") || result.State != releasekit.DeliveryNotAttempted {
|
||||||
|
t.Fatalf("Deliver() = %#v, %v; want build-source eligibility failure", result, err)
|
||||||
|
}
|
||||||
|
if remote.requests != 0 {
|
||||||
|
t.Fatalf("hosted requests = %d, want none", remote.requests)
|
||||||
|
}
|
||||||
|
if entries, err := os.ReadDir(temporaryRoot); err != nil || len(entries) != 0 {
|
||||||
|
t.Fatalf("ineligible managed build output remains: entries=%v error=%v", entries, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeliverManagedBuildFailureCleansTemporaryOutputBeforeHostedWrites(t *testing.T) {
|
||||||
|
repository := newTaggedDeliveryConsumer(t)
|
||||||
|
temporaryRoot := t.TempDir()
|
||||||
|
t.Setenv("TMPDIR", temporaryRoot)
|
||||||
|
server, remote := newFacadeDeliveryServer(t, repository)
|
||||||
|
defer server.Close()
|
||||||
|
|
||||||
|
result, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Fixture",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Destination: facadeDeliveryDestination(server.URL),
|
||||||
|
Build: &releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/missing",
|
||||||
|
BinaryName: "fixture",
|
||||||
|
Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err == nil || result.State != releasekit.DeliveryNotAttempted || result.CandidateCommit != remote.commit {
|
||||||
|
t.Fatalf("Deliver() = %#v, %v; want managed build failure before hosted writes", result, err)
|
||||||
|
}
|
||||||
|
if remote.requests != 0 {
|
||||||
|
t.Fatalf("hosted requests = %d, want none", remote.requests)
|
||||||
|
}
|
||||||
|
if entries, err := os.ReadDir(temporaryRoot); err != nil || len(entries) != 0 {
|
||||||
|
t.Fatalf("failed managed build output remains: entries=%v error=%v", entries, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeliverManagedBuildCancellationCleansTemporaryOutput(t *testing.T) {
|
||||||
|
repository := newTaggedDeliveryConsumer(t)
|
||||||
|
temporaryRoot := t.TempDir()
|
||||||
|
t.Setenv("TMPDIR", temporaryRoot)
|
||||||
|
server, remote := newFacadeDeliveryServer(t, repository)
|
||||||
|
defer server.Close()
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
defer cancel()
|
||||||
|
writer := deliveryCancelWriter{cancel: cancel}
|
||||||
|
|
||||||
|
result, err := releasekit.Deliver(ctx, releasekit.DeliveryRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Fixture",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Destination: facadeDeliveryDestination(server.URL),
|
||||||
|
Build: &releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/app",
|
||||||
|
BinaryName: "fixture",
|
||||||
|
Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}},
|
||||||
|
},
|
||||||
|
Output: writer,
|
||||||
|
})
|
||||||
|
if !errors.Is(err, context.Canceled) || result.State != releasekit.DeliveryNotAttempted {
|
||||||
|
t.Fatalf("Deliver() = %#v, %v; want cancellation before hosted writes", result, err)
|
||||||
|
}
|
||||||
|
if remote.requests != 0 {
|
||||||
|
t.Fatalf("hosted requests = %d, want none", remote.requests)
|
||||||
|
}
|
||||||
|
if entries, err := os.ReadDir(temporaryRoot); err != nil || len(entries) != 0 {
|
||||||
|
t.Fatalf("canceled managed build output remains: entries=%v error=%v", entries, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeliverRejectsBothBuildSourcesBeforeHostedWrites(t *testing.T) {
|
||||||
|
repository := newTaggedDeliveryConsumer(t)
|
||||||
|
server, remote := newFacadeDeliveryServer(t, repository)
|
||||||
|
defer server.Close()
|
||||||
|
|
||||||
|
result, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Fixture",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Destination: facadeDeliveryDestination(server.URL),
|
||||||
|
Build: &releasekit.BuildSpec{},
|
||||||
|
Prebuilt: &releasekit.BuildResult{},
|
||||||
|
})
|
||||||
|
if err == nil || result.State != releasekit.DeliveryNotAttempted || !strings.Contains(err.Error(), "both") {
|
||||||
|
t.Fatalf("Deliver() = %#v, %v; want invalid build-source combination", result, err)
|
||||||
|
}
|
||||||
|
if remote.requests != 0 {
|
||||||
|
t.Fatalf("hosted requests = %d, want none", remote.requests)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func newTaggedDeliveryConsumer(t *testing.T) string {
|
||||||
|
return newTaggedDeliveryConsumerWithNote(t, "# Fixture v1.2.3\n\nDelivery fixture.\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
func newTaggedDeliveryConsumerWithNote(t *testing.T, note string) string {
|
||||||
|
t.Helper()
|
||||||
|
repository := newBuildConsumer(t, `package main
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo"
|
||||||
|
)
|
||||||
|
func main() { if len(os.Args) == 2 && os.Args[1] == "version" { fmt.Println("fixture", buildinfo.Version()) } }
|
||||||
|
`)
|
||||||
|
writeBuildFixture(t, repository, "docs/releases/v1.2.3.md", note)
|
||||||
|
buildGit(t, repository, "add", "--all")
|
||||||
|
buildGit(t, repository, "commit", "-m", "add release note")
|
||||||
|
buildGit(t, repository, "tag", "v1.2.3")
|
||||||
|
return repository
|
||||||
|
}
|
||||||
|
|
||||||
|
func facadeDeliveryDestination(baseURL string) releasekit.GiteaDestination {
|
||||||
|
return releasekit.GiteaDestination{BaseURL: baseURL, Owner: "owner", Repository: "example", Token: "fixture-token"}
|
||||||
|
}
|
||||||
|
|
||||||
|
type deliveryCancelWriter struct{ cancel context.CancelFunc }
|
||||||
|
|
||||||
|
func (writer deliveryCancelWriter) Write(content []byte) (int, error) {
|
||||||
|
writer.cancel()
|
||||||
|
return len(content), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type facadeDeliveryServer struct {
|
||||||
|
t *testing.T
|
||||||
|
commit string
|
||||||
|
page bool
|
||||||
|
requests int
|
||||||
|
assets map[string][]byte
|
||||||
|
url string
|
||||||
|
}
|
||||||
|
|
||||||
|
func newFacadeDeliveryServer(t *testing.T, repository string) (*httptest.Server, *facadeDeliveryServer) {
|
||||||
|
t.Helper()
|
||||||
|
state := &facadeDeliveryServer{t: t, commit: buildGit(t, repository, "rev-parse", "HEAD"), assets: make(map[string][]byte)}
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(state.serveHTTP))
|
||||||
|
state.url = server.URL
|
||||||
|
return server, state
|
||||||
|
}
|
||||||
|
|
||||||
|
func (state *facadeDeliveryServer) serveHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if strings.HasPrefix(r.URL.Path, "/api/") {
|
||||||
|
state.requests++
|
||||||
|
if r.Header.Get("Authorization") != "token fixture-token" {
|
||||||
|
state.t.Errorf("authorization = %q", r.Header.Get("Authorization"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
switch r.URL.Path {
|
||||||
|
case "/api/v1/repos/owner/example/tags/v1.2.3":
|
||||||
|
_, _ = fmt.Fprintf(w, `{"name":"v1.2.3","commit":{"sha":%q}}`, state.commit)
|
||||||
|
case "/api/v1/repos/owner/example/releases/tags/v1.2.3":
|
||||||
|
if !state.page {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
state.writeRelease(w)
|
||||||
|
case "/api/v1/repos/owner/example/releases":
|
||||||
|
var payload struct {
|
||||||
|
Tag string `json:"tag_name"`
|
||||||
|
Target string `json:"target_commitish"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Body string `json:"body"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
|
||||||
|
state.t.Errorf("decode release payload: %v", err)
|
||||||
|
http.Error(w, "invalid payload", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if payload.Tag != "v1.2.3" || payload.Target != state.commit || payload.Name != "Fixture v1.2.3" {
|
||||||
|
state.t.Errorf("release payload = %#v", payload)
|
||||||
|
}
|
||||||
|
state.page = true
|
||||||
|
state.writeRelease(w)
|
||||||
|
case "/api/v1/repos/owner/example/releases/10/assets":
|
||||||
|
if r.Method == http.MethodGet {
|
||||||
|
list := make([]map[string]any, 0, len(state.assets))
|
||||||
|
for name, content := range state.assets {
|
||||||
|
list = append(list, map[string]any{"id": len(list) + 1, "name": name, "size": len(content), "browser_download_url": state.url + "/files/" + name})
|
||||||
|
}
|
||||||
|
_ = json.NewEncoder(w).Encode(list)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
name := r.URL.Query().Get("name")
|
||||||
|
file, _, err := r.FormFile("attachment")
|
||||||
|
if err != nil {
|
||||||
|
state.t.Errorf("read upload %q: %v", name, err)
|
||||||
|
http.Error(w, "invalid multipart upload", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
content, err := io.ReadAll(file)
|
||||||
|
_ = file.Close()
|
||||||
|
if err != nil {
|
||||||
|
state.t.Errorf("read upload %q: %v", name, err)
|
||||||
|
}
|
||||||
|
state.assets[name] = content
|
||||||
|
w.WriteHeader(http.StatusCreated)
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"id": len(state.assets), "name": name, "size": len(content)})
|
||||||
|
default:
|
||||||
|
if strings.HasPrefix(r.URL.Path, "/files/") {
|
||||||
|
name := strings.TrimPrefix(r.URL.Path, "/files/")
|
||||||
|
content, ok := state.assets[name]
|
||||||
|
if !ok {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_, _ = w.Write(content)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
state.t.Errorf("unexpected delivery request %s %s", r.Method, r.URL)
|
||||||
|
http.NotFound(w, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (state *facadeDeliveryServer) writeRelease(w http.ResponseWriter) {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||||
|
"id": 10, "html_url": state.url + "/releases/10", "tag_name": "v1.2.3",
|
||||||
|
"target_commitish": state.commit, "name": "Fixture v1.2.3",
|
||||||
|
"body": "# Fixture v1.2.3\n\nDelivery fixture.\n", "draft": false, "prerelease": false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func mapKeys(values map[string][]byte) []string {
|
||||||
|
keys := make([]string, 0, len(values))
|
||||||
|
for key := range values {
|
||||||
|
keys = append(keys, key)
|
||||||
|
}
|
||||||
|
return keys
|
||||||
|
}
|
||||||
3
doc.go
Normal file
3
doc.go
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
// Package releasekit is the public facade for ReleaseKit's release process.
|
||||||
|
// Public operations are added as their behavior is implemented.
|
||||||
|
package releasekit
|
||||||
84
docs/adr/0001-public-facade.md
Normal file
84
docs/adr/0001-public-facade.md
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
# ADR 0001: Own public contracts through facades
|
||||||
|
|
||||||
|
## Status
|
||||||
|
|
||||||
|
Accepted.
|
||||||
|
|
||||||
|
## Date
|
||||||
|
|
||||||
|
2026-10-05
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
ReleaseKit is being designed as an opinionated Go library with a release
|
||||||
|
executable. Its responsibilities include publication, cross-builds, version
|
||||||
|
injection, and artifact delivery. Consuming applications also need lightweight
|
||||||
|
access to the version embedded in their binaries.
|
||||||
|
|
||||||
|
ConfigKit and PromptKit demonstrate a facade approach in which public packages
|
||||||
|
own consumer contracts and delegate to internal implementation. This gives
|
||||||
|
maintainers room to change internal structure while preserving supported type
|
||||||
|
identity, method sets, and behavior. ReleaseKit needs that boundary from its
|
||||||
|
first implementation.
|
||||||
|
|
||||||
|
## Decision
|
||||||
|
|
||||||
|
The root `releasekit` package is the public facade for release orchestration. A
|
||||||
|
separate public `buildinfo` package is the facade for runtime version information.
|
||||||
|
Each package exposes a cohesive set of operations and values justified by
|
||||||
|
consumer needs.
|
||||||
|
|
||||||
|
Each facade defines its public named types and owns their documented behavior.
|
||||||
|
Exported signatures, fields, callbacks, and method sets use facade-owned types
|
||||||
|
and deliberately selected public dependencies. Handles retain implementation
|
||||||
|
state in private fields and expose explicitly selected methods. Forwarding and
|
||||||
|
conversion code translates between public contracts and internal representations.
|
||||||
|
|
||||||
|
Implementation packages live under Go's `internal/` boundary. Dependency
|
||||||
|
direction runs from public facades into internal implementation. Contracts shared
|
||||||
|
between implementation packages belong inside that boundary. Git operations, Go
|
||||||
|
toolchain execution, Gitea integration, and orchestration bookkeeping remain
|
||||||
|
implementation responsibilities, with package layout chosen for cohesion.
|
||||||
|
|
||||||
|
The `buildinfo` facade has a lightweight dependency graph suitable for application
|
||||||
|
runtime imports. Its version accessor is a supported public contract. ReleaseKit's
|
||||||
|
builder and runtime implementation own the linker symbol and injection mechanism
|
||||||
|
together, allowing applications to obtain their version through the accessor.
|
||||||
|
|
||||||
|
The release executable invokes the supported orchestration facade and owns
|
||||||
|
command parsing, output, and exit codes. The library returns consumer-facing
|
||||||
|
errors and outcomes that describe publication state, including partial progress
|
||||||
|
and uncertainty.
|
||||||
|
|
||||||
|
Go declarations and GoDoc own exact public API contracts. Additional public
|
||||||
|
packages and extension interfaces require a deliberate decision grounded in a
|
||||||
|
durable consumer need. Compiled-export and dependency checks protect facade
|
||||||
|
ownership; external-package behavioral tests protect consumer semantics.
|
||||||
|
|
||||||
|
## Alternatives considered
|
||||||
|
|
||||||
|
- Keep implementation in public packages: reduces forwarding work and makes
|
||||||
|
implementation declarations part of the surface contributors must maintain.
|
||||||
|
- Use aliases or embedded implementation types: reduces conversion code while
|
||||||
|
coupling consumer type identity and method sets to implementation types.
|
||||||
|
- Provide one facade for orchestration and runtime version access: offers one
|
||||||
|
import path and a shared dependency graph for both responsibilities.
|
||||||
|
- Expose a public package for each implementation component: enables direct
|
||||||
|
component reuse and expands the compatibility surface across Git, build, and
|
||||||
|
delivery machinery.
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
|
||||||
|
Consumers depend on deliberate contracts in `releasekit` and `buildinfo`.
|
||||||
|
Internal algorithms, collaborators, and package boundaries can evolve while
|
||||||
|
those contracts remain stable. Both public packages participate in ReleaseKit's
|
||||||
|
versioning and compatibility obligations.
|
||||||
|
|
||||||
|
Explicit forwarding and conversions add maintenance work. They must preserve
|
||||||
|
error identity, value ownership, callback lifetime, and observable outcomes.
|
||||||
|
Boundary checks and representative consumer tests provide evidence for those
|
||||||
|
properties as implementation proceeds.
|
||||||
|
|
||||||
|
The separate `buildinfo` facade supports runtime use with a small dependency
|
||||||
|
surface. Its integration with the builder requires tests that verify the selected
|
||||||
|
release version is injected and reported correctly.
|
||||||
63
docs/adr/0002-routine-releases.md
Normal file
63
docs/adr/0002-routine-releases.md
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
# ADR 0002: Make routine releases a shared responsibility
|
||||||
|
|
||||||
|
## Status
|
||||||
|
|
||||||
|
Accepted.
|
||||||
|
|
||||||
|
## Date
|
||||||
|
|
||||||
|
2026-10-06
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
Applications in the suite repeat release code and require developers to manage
|
||||||
|
similar release decisions. ReleaseKit centralizes this work. Its value depends
|
||||||
|
on reducing application maintenance and the time developers spend on releases.
|
||||||
|
|
||||||
|
Build specialization, environment standardization, and detailed inspection can
|
||||||
|
serve particular consumers. Supporting them can also expand the API,
|
||||||
|
configuration, and release knowledge each application must maintain. ReleaseKit
|
||||||
|
needs a clear priority for evaluating these tradeoffs.
|
||||||
|
|
||||||
|
## Decision
|
||||||
|
|
||||||
|
ReleaseKit provides a standard, minimal API for routine releases. It minimizes
|
||||||
|
application-owned release code, duplication across applications, and the
|
||||||
|
decisions application developers must make.
|
||||||
|
|
||||||
|
ReleaseKit owns the common release procedure and sensible defaults. Applications
|
||||||
|
supply product facts, compatibility requirements, and product-specific checks.
|
||||||
|
|
||||||
|
Hardware-specific build options, strict build reproducibility, extensive build
|
||||||
|
inspection, and comparable specialization are non-goals to the extent that
|
||||||
|
supporting them conflicts with these primary goals.
|
||||||
|
|
||||||
|
Evaluate proposed capabilities by their effect on ordinary application
|
||||||
|
integration: the code applications maintain, the configuration they supply, and
|
||||||
|
the release decisions developers make. A demonstrated consumer need informs
|
||||||
|
that assessment; the selected approach must preserve the routine release model.
|
||||||
|
|
||||||
|
## Alternatives considered
|
||||||
|
|
||||||
|
- A broadly configurable release toolkit gives applications control over build
|
||||||
|
and release mechanics. Applications then own more composition code and
|
||||||
|
configuration decisions.
|
||||||
|
- A tightly standardized build environment prioritizes reproducibility and
|
||||||
|
detailed build records. It adds environment maintenance and coordination
|
||||||
|
responsibilities across applications.
|
||||||
|
|
||||||
|
The selected approach evaluates those capabilities by the application work and
|
||||||
|
developer effort they save.
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
|
||||||
|
Common release operations belong behind reusable orchestration. Shared defaults
|
||||||
|
reduce configuration and routine decisions. ReleaseKit can absorb internal
|
||||||
|
complexity when doing so keeps application integration small and maintainable.
|
||||||
|
|
||||||
|
New options carry implementation, maintenance, and decision costs. Consumer
|
||||||
|
needs justify evaluating an option; its adoption must support the primary goals.
|
||||||
|
|
||||||
|
The [architecture policy](../policy/architecture.md) owns current architectural
|
||||||
|
constraints. [ADR 0001](0001-public-facade.md) records the facade boundaries.
|
||||||
|
GoDoc owns exact API contracts.
|
||||||
154
docs/cli.md
Normal file
154
docs/cli.md
Normal file
@@ -0,0 +1,154 @@
|
|||||||
|
# Command line
|
||||||
|
|
||||||
|
ReleaseKit currently provides six commands. 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.
|
||||||
|
|
||||||
|
Print the executable version:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go run ./cmd/releasekit version
|
||||||
|
```
|
||||||
|
|
||||||
|
This prints `releasekit <version>` followed by a newline and exits with status 0.
|
||||||
|
The version comes from [`buildinfo.Version`](consumers/runtime-version.md).
|
||||||
|
|
||||||
|
Check a local candidate:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go run ./cmd/releasekit check [--repo DIR] [--config FILE] VERSION
|
||||||
|
```
|
||||||
|
|
||||||
|
`VERSION` must use stable `vMAJOR.MINOR.PATCH` syntax. Options must precede the
|
||||||
|
version. The repository defaults to the current directory, and the profile
|
||||||
|
defaults to `<repository>/releasekit.json`. A successful command prints the
|
||||||
|
captured local commit and version. It checks the committed release note, local
|
||||||
|
Git state, runs the standard offline Go test suite, and then runs any configured
|
||||||
|
additional checks in profile order. It does not inspect remote availability or
|
||||||
|
publish a tag.
|
||||||
|
|
||||||
|
`check` writes errors and diagnostics to standard error. It returns status 0
|
||||||
|
after local validation, 1 after a candidate validation failure, and 2 for usage,
|
||||||
|
profile, or invalid-version errors. Unsupported argument sequences print usage
|
||||||
|
to standard error.
|
||||||
|
|
||||||
|
Publish a source tag:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go run ./cmd/releasekit publish [--repo DIR] [--config FILE] VERSION
|
||||||
|
```
|
||||||
|
|
||||||
|
`publish` reads the same product, remote, and additional-check settings as
|
||||||
|
`check`. It checks the authoritative remote and validates the candidate: the
|
||||||
|
standard offline Go test suite runs first, followed by configured checks in
|
||||||
|
profile order. It then creates an annotated local tag and pushes only its exact
|
||||||
|
tag object. It prints the confirmed version, candidate commit, and tag object
|
||||||
|
on success. Validation
|
||||||
|
progress and failed publication state, including the captured publication
|
||||||
|
endpoint for recovery, are written to standard error. A signal
|
||||||
|
cancels the active operation; if it arrives during a push, the library's
|
||||||
|
bounded reconciliation determines whether the exact tag was accepted.
|
||||||
|
|
||||||
|
The command returns status 0 for confirmed publication, 1 for a known
|
||||||
|
publication failure or conflict, 2 for usage, profile, or invalid-version
|
||||||
|
errors, and 3 when the push outcome remains unknown. Unknown status must be
|
||||||
|
resolved against the authoritative remote before retrying. The
|
||||||
|
[maintainer procedure](release.md) selects the repository profile and gives
|
||||||
|
the source-release workflow.
|
||||||
|
|
||||||
|
Build selected application targets:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go run ./cmd/releasekit build [--repo DIR] [--config FILE] [--output DIR] VERSION
|
||||||
|
```
|
||||||
|
|
||||||
|
`build` requires a `build` object in the profile. It compiles the selected
|
||||||
|
targets with the requested version injected, checks the native `version`
|
||||||
|
invocation, and writes binaries plus the private `.releasekit-build.json`
|
||||||
|
receipt into `dist` by default. `--output` selects a different directory;
|
||||||
|
relative paths are resolved from the repository. Selected artifact filenames
|
||||||
|
are regenerated while unrelated files are preserved. A complete nonempty build
|
||||||
|
writes a receipt only after compilation and smoke checking succeed. On partial
|
||||||
|
failure, standard error lists completed outputs and prior receipts in that
|
||||||
|
output directory are invalidated; no new receipt is written. An
|
||||||
|
empty target list returns the source commit without building or writing a
|
||||||
|
receipt.
|
||||||
|
|
||||||
|
The command returns status 0 on completion, 1 for build or output failure, and
|
||||||
|
2 for usage, profile, or invalid-version errors. It builds the current source
|
||||||
|
tree and does not perform candidate validation or remote publication. `check`
|
||||||
|
and `publish` run the same configured build after their one candidate
|
||||||
|
validation, using temporary output outside the worktree.
|
||||||
|
|
||||||
|
Deliver a tagged source release to Gitea:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go run ./cmd/releasekit deliver [--repo DIR] [--config FILE] [--assets DIR] VERSION
|
||||||
|
```
|
||||||
|
|
||||||
|
`deliver` requires a `delivery` profile object and its configured token
|
||||||
|
environment variable, which defaults to `RELEASEKIT_GITEA_TOKEN`. It verifies
|
||||||
|
the local tag, clean tagged checkout, hosted tag, and committed release note,
|
||||||
|
then creates or finds the release page and reports delivery state separately
|
||||||
|
from source publication. Historical lightweight tags and detached checkouts
|
||||||
|
are supported when `HEAD` is the selected tag commit; delivery does not require
|
||||||
|
the former remote `main` to match.
|
||||||
|
|
||||||
|
When the profile has build targets and `--assets` is omitted, `deliver` passes
|
||||||
|
the configured build directly to the public delivery facade. The facade builds
|
||||||
|
the tagged source into temporary storage, removes it when the operation ends,
|
||||||
|
and uploads its binaries and complete `SHA256SUMS`. When `--assets DIR` is
|
||||||
|
supplied, that directory must contain the private `.releasekit-build.json`
|
||||||
|
receipt and matching unchanged artifacts; this keeps the caller's original
|
||||||
|
bytes available for retries. Profiles without targets use page-only delivery
|
||||||
|
and need no receipt, binary build, or manifest. `deliver` never runs candidate
|
||||||
|
checks or publishes a tag.
|
||||||
|
|
||||||
|
Use one `deliver` invocation for the normal workflow. To build without delivery
|
||||||
|
credentials, or to retain build output across retries, run `build --output DIR`
|
||||||
|
first and then run `deliver --assets DIR` with the token available. The ordinary
|
||||||
|
`deliver` command does not download application dependencies or change the
|
||||||
|
checkout.
|
||||||
|
|
||||||
|
The command returns 0 for complete delivery, 1 for a known failure, conflict,
|
||||||
|
or partial delivery, 2 for usage, profile, or missing-credential errors, and 3
|
||||||
|
when a remote write remains uncertain. The result lists matching, uploaded,
|
||||||
|
pending, conflicting, and uncertain assets as disjoint current observations;
|
||||||
|
early failures may leave some declared assets unreported. On failure, the CLI
|
||||||
|
prints state-based recovery guidance. Fix local or preflight failures before
|
||||||
|
retrying; fix the reported cause before retrying partial delivery; resolve an
|
||||||
|
unknown remote state before retrying; and investigate conflicts, using a new
|
||||||
|
version if the source or published contents need correction. If rebuilding
|
||||||
|
could change asset bytes already on the server, retain the original build
|
||||||
|
artifacts and retry with `--assets DIR`. Matching content is kept and only
|
||||||
|
known missing assets are added. See the
|
||||||
|
[delivery consumer guide](consumers/delivery.md) and
|
||||||
|
[Gitea integration guide](integrations/gitea.md).
|
||||||
|
|
||||||
|
Prepare a tagged CI checkout and deliver it:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
releasekit ci-deliver [--repo DIR] [--config FILE] [--remote NAME] --commit OID VERSION
|
||||||
|
```
|
||||||
|
|
||||||
|
`ci-deliver` fetches `VERSION` from the selected Git remote (default `origin`),
|
||||||
|
requires the tag's peeled commit to match the required full `--commit` object
|
||||||
|
ID, and checks out that commit detached. It then loads the profile from the
|
||||||
|
prepared checkout, validates delivery settings and the configured token, and
|
||||||
|
downloads application dependencies only when the profile selects build targets.
|
||||||
|
Binary profiles are built and delivered through the same facade path as
|
||||||
|
`deliver`; source-only profiles skip dependency downloads and binary builds.
|
||||||
|
`--config` follows the existing profile path rules: relative paths are resolved
|
||||||
|
from `--repo`, and absolute paths are used as-is. This command explicitly
|
||||||
|
prepares and changes the selected checkout. Ordinary `deliver` continues to
|
||||||
|
operate on already prepared source without fetching, checking out, or
|
||||||
|
downloading dependencies.
|
||||||
|
|
||||||
|
In Woodpecker, pass `CI_WORKSPACE`, `CI_COMMIT_SHA`, and `CI_COMMIT_TAG` as the
|
||||||
|
repository, expected commit, and version arguments. The CLI does not read
|
||||||
|
provider-specific environment variable names. Checkout and dependency
|
||||||
|
preparation failures return status 1; usage, profile, credential, and invalid
|
||||||
|
version errors return status 2. Final delivery uses the same statuses as
|
||||||
|
`deliver`: 0 for complete, 1 for known failure, conflict, or partial delivery,
|
||||||
|
and 3 for uncertain remote state.
|
||||||
65
docs/config.md
Normal file
65
docs/config.md
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
# Configuration
|
||||||
|
|
||||||
|
ReleaseKit reads a JSON profile from `<repository>/releasekit.json` by default.
|
||||||
|
The repository directory defaults to the current directory. A relative profile
|
||||||
|
path is resolved from that repository directory; an absolute path is used as-is.
|
||||||
|
|
||||||
|
The current profile fields are:
|
||||||
|
|
||||||
|
| Field | Required | Behavior |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `product` | Yes | Product name used by release operations. |
|
||||||
|
| `remote` | No | Selected Git remote; defaults to `origin`. |
|
||||||
|
| `checks` | No | Ordered additional child commands, each with an argument vector and optional environment map. |
|
||||||
|
| `build` | No | Optional main package, binary name, and selected `GOOS/GOARCH` target strings. |
|
||||||
|
| `delivery` | No | Optional Gitea `base_url`, `owner`, `repository`, and `token_env` settings for tagged-source delivery. |
|
||||||
|
|
||||||
|
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
|
||||||
|
shell syntax. Each `env` map overlays the current environment for that child.
|
||||||
|
The overlay does not modify the ReleaseKit process environment.
|
||||||
|
|
||||||
|
Unknown fields are rejected so a setting cannot be silently ignored. The
|
||||||
|
`build` object contains `main_package`, `binary_name`, and `targets`. A selected
|
||||||
|
target requires the package and binary name; each target is written as one
|
||||||
|
`GOOS/GOARCH` pair. An omitted or empty target list means no binary work.
|
||||||
|
|
||||||
|
The `delivery` object contains `base_url`, `owner`, `repository`, and optional
|
||||||
|
`token_env`. Its values are required when running `deliver`, but credentials are
|
||||||
|
not required for `check`, `publish`, or `build`. `token_env` names the
|
||||||
|
environment variable containing the Gitea token; it defaults to
|
||||||
|
`RELEASEKIT_GITEA_TOKEN`. The CLI reads this variable only for `deliver` and
|
||||||
|
passes its value explicitly to the library operation.
|
||||||
|
|
||||||
|
The `check` and `publish` commands always run
|
||||||
|
`go test -mod=readonly -count=1 ./...` with Go module and toolchain network
|
||||||
|
access disabled. They then run each configured `checks` command once, in order,
|
||||||
|
as an additional product check. Selected-target builds run after both. Do not
|
||||||
|
repeat the standard suite in `checks`; doing so runs it twice. The `build`
|
||||||
|
command uses the selected build settings and writes binaries to `dist` unless
|
||||||
|
`--output` selects another path.
|
||||||
|
The `deliver` command uses the delivery destination and token. By default it
|
||||||
|
passes selected targets to the delivery facade, which builds tagged-source
|
||||||
|
artifacts into temporary storage and removes them when delivery returns. An
|
||||||
|
absent build object or an empty target set selects page-only delivery. Use
|
||||||
|
`build --output DIR` followed by `deliver --assets DIR` when artifacts must be
|
||||||
|
retained for retries or when build and delivery credentials need separate
|
||||||
|
invocations. Ordinary `deliver` does not download application dependencies or
|
||||||
|
change the checkout.
|
||||||
|
|
||||||
|
`ci-deliver` uses the same profile after preparing the selected tag in the
|
||||||
|
checkout. It checks out the tag only after its peeled commit matches the
|
||||||
|
provider-supplied commit ID, then loads the profile and validates delivery
|
||||||
|
settings and credentials. It runs `go mod download` only when the profile has
|
||||||
|
selected build targets; source-only delivery does not need application
|
||||||
|
dependencies. This preparation may access the network and may update
|
||||||
|
`go.sum`. The command takes CI values as arguments, so profile settings remain
|
||||||
|
independent of Woodpecker environment variable names. See the
|
||||||
|
[CLI contract](cli.md) for the invocation and exit statuses.
|
||||||
|
|
||||||
|
ReleaseKit's source-only profile is
|
||||||
|
[releasekit.json](../releasekit.json).
|
||||||
|
See the [source-only profile](../examples/releasekit.json) and
|
||||||
|
[binary profile](../examples/releasekit-binary.json). The
|
||||||
|
[CLI contract](cli.md) lists the currently available command.
|
||||||
81
docs/consumers/build.md
Normal file
81
docs/consumers/build.md
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
# Build versioned application binaries
|
||||||
|
|
||||||
|
Use `releasekit.Build` when an application needs binaries for explicit Go
|
||||||
|
operating-system and architecture pairs:
|
||||||
|
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
releasekit "gitea.maximumdirect.net/eric/ReleaseKit"
|
||||||
|
)
|
||||||
|
|
||||||
|
func build(ctx context.Context) error {
|
||||||
|
result, err := releasekit.Build(ctx, releasekit.BuildRequest{
|
||||||
|
RepositoryDir: "/work/project",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Spec: releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/project",
|
||||||
|
BinaryName: "project",
|
||||||
|
Targets: []releasekit.Target{
|
||||||
|
{OS: "linux", Arch: "amd64"},
|
||||||
|
{OS: "linux", Arch: "arm64"},
|
||||||
|
{OS: "darwin", Arch: "arm64"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
OutputDir: "dist",
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err // result retains completed artifacts when a later step fails.
|
||||||
|
}
|
||||||
|
for _, artifact := range result.Artifacts {
|
||||||
|
fmt.Println(artifact.Filename, artifact.SHA256)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`Build` records the repository's current `HEAD`, injects the selected stable
|
||||||
|
version into `buildinfo.Version`, and returns the compiler identity, normalized
|
||||||
|
targets, artifact paths, filenames, and SHA-256 digests. Names follow
|
||||||
|
`<binary>-<version>-<goos>-<goarch>`; Windows targets add `.exe`. A repeated
|
||||||
|
target pair is built once, at its first position. Local builds may use modified
|
||||||
|
source. `SourceVerified` is true only after a complete build observes clean
|
||||||
|
source and the same HEAD before and after compilation; binary delivery requires
|
||||||
|
that fact. This observation is not a source snapshot or attestation guarantee.
|
||||||
|
|
||||||
|
The default output directory is `<repository>/dist`; a relative `OutputDir` is
|
||||||
|
resolved from the repository. Selected artifact filenames are regenerated. Other files in the output
|
||||||
|
directory are left in place. A failed later build or native version check returns the binaries already
|
||||||
|
generated in `BuildResult.Artifacts`.
|
||||||
|
|
||||||
|
Builds use the available compatible Go toolchain selected locally; ReleaseKit
|
||||||
|
does not download a different toolchain automatically. It disables workspace
|
||||||
|
discovery and module network access, uses readonly module mode, sets
|
||||||
|
`CGO_ENABLED=0`, and passes `-trimpath` and `-buildvcs=false`. Effective cache,
|
||||||
|
module-cache, temporary-directory, and tool settings are retained, including
|
||||||
|
values from Go's persistent environment file. Ambient experiment and CPU
|
||||||
|
feature settings are cleared so the selected toolchain uses its baseline for
|
||||||
|
each target. Each selected target is compiled explicitly. ReleaseKit then runs
|
||||||
|
the `version` command on a native binary and requires `<binary> <version>`
|
||||||
|
followed by a newline. If no selected target matches the Go host, it builds a
|
||||||
|
temporary native binary for this check and removes it afterward.
|
||||||
|
Cross-compilation does not promise that a binary runs on another platform.
|
||||||
|
|
||||||
|
An empty target list records the source commit and returns without invoking Go,
|
||||||
|
creating the output directory, or running a version check. It does not require a
|
||||||
|
main package or binary name. This supports source-only operations without
|
||||||
|
silently adding a binary check.
|
||||||
|
|
||||||
|
The [`build` command](../cli.md) reads the same build specification from the
|
||||||
|
profile and writes a private receipt alongside its artifacts. `check` and
|
||||||
|
`publish` run selected builds after the standard suite and any additional
|
||||||
|
checks using temporary output outside the worktree. Candidate checks do not
|
||||||
|
write a receipt or leave build files in the repository.
|
||||||
|
|
||||||
|
For delivery from a tagged checkout, `deliver` builds selected tagged-source
|
||||||
|
targets into temporary storage by default. Use `--assets DIR` to deliver a
|
||||||
|
separate build output; ReleaseKit requires its receipt and verifies the source,
|
||||||
|
build settings, and artifact hashes before the first Gitea write. See the
|
||||||
|
[delivery consumer guide](delivery.md) for page-only delivery and retry states.
|
||||||
57
docs/consumers/check.md
Normal file
57
docs/consumers/check.md
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
# Local candidate check
|
||||||
|
|
||||||
|
Use `releasekit.Check` to verify a candidate against the current local
|
||||||
|
repository state:
|
||||||
|
|
||||||
|
```go
|
||||||
|
result, err := releasekit.Check(ctx, releasekit.ReleaseRequest{
|
||||||
|
RepositoryDir: "/work/project",
|
||||||
|
Product: "Example",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
AdditionalChecks: func(ctx context.Context, candidate releasekit.Candidate) error {
|
||||||
|
return runProjectChecks(ctx, candidate.RepositoryDir)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
fmt.Println(result.Version, result.Commit)
|
||||||
|
```
|
||||||
|
|
||||||
|
The repository must have a clean index and worktree on `main`, and the selected
|
||||||
|
version must be stable `vMAJOR.MINOR.PATCH`. The committed
|
||||||
|
`docs/releases/<version>.md` note must have a first Markdown H1 containing the
|
||||||
|
product name and exact version as complete title elements. No local tag with
|
||||||
|
that version may already exist.
|
||||||
|
|
||||||
|
ReleaseKit always runs `go test -mod=readonly -count=1 ./...` with the available
|
||||||
|
compatible local Go toolchain, then calls `AdditionalChecks` once when supplied.
|
||||||
|
It does not download a different toolchain automatically. The standard suite
|
||||||
|
uses the Go host target, disables workspace and module network access, and
|
||||||
|
ignores ambient `GOFLAGS`, experiment, and CPU feature overrides. Effective
|
||||||
|
cache and native cgo/C-tool settings are preserved, including values from Go's
|
||||||
|
persistent environment file. The check revalidates the branch, commit, and
|
||||||
|
cleanliness after validation.
|
||||||
|
|
||||||
|
A successful check is evidence about the local candidate only. It does not
|
||||||
|
check whether a remote branch or tag is available and does not create a tag.
|
||||||
|
The [`check` command](../cli.md) reads the product and optional additional
|
||||||
|
commands from `releasekit.json`.
|
||||||
|
|
||||||
|
## Publishing the source tag
|
||||||
|
|
||||||
|
`releasekit.Publish` uses the same request and validation order: the standard
|
||||||
|
suite runs first, followed by `AdditionalChecks` when supplied. It then performs
|
||||||
|
authoritative remote checks, annotated-tag creation, and an exact tag push. The
|
||||||
|
selected remote must publish `main` at the captured commit and must not already
|
||||||
|
contain the selected version tag. A successful result includes the endpoint and
|
||||||
|
tag object ID. Publication states distinguish an unattempted push, a tag that
|
||||||
|
was created locally but not pushed, a successful push, a guard conflict, and an
|
||||||
|
unresolved push error. See the [publication guide](publish.md) for the complete
|
||||||
|
workflow.
|
||||||
|
|
||||||
|
When a push reports an error, ReleaseKit makes one bounded query for the
|
||||||
|
authoritative tag. An exact tag object match confirms success. An absent tag is
|
||||||
|
reported as `not_published`, a different object as `conflict`, and an unreadable
|
||||||
|
query as `unknown`. The local annotated tag is retained in every case; an
|
||||||
|
`unknown` result is neither success nor proof that the remote lacks the tag.
|
||||||
195
docs/consumers/delivery.md
Normal file
195
docs/consumers/delivery.md
Normal file
@@ -0,0 +1,195 @@
|
|||||||
|
# Deliver a tagged source release
|
||||||
|
|
||||||
|
Use `releasekit.Deliver` or the `deliver` command after a source tag exists.
|
||||||
|
Delivery status is separate from source publication: a delivery problem does
|
||||||
|
not move or remove the tag, and a retry can use the same immutable version.
|
||||||
|
The operation accepts historical lightweight and annotated tags, including a
|
||||||
|
detached checkout, when the checked-out `HEAD` identifies the selected tag
|
||||||
|
commit. It does not require the old remote `main` to match.
|
||||||
|
|
||||||
|
## CI preparation
|
||||||
|
|
||||||
|
Use `PrepareTaggedCheckout` when a disposable CI checkout must be verified
|
||||||
|
against the commit that triggered the job. It fetches only the selected tag
|
||||||
|
from the chosen remote (default `origin`), compares the peeled tag commit with
|
||||||
|
the expected commit, and checks out that commit detached. Fetch or checkout
|
||||||
|
conflicts are returned so the caller can replace or repair the workspace.
|
||||||
|
Cancellation is returned to the caller; the operation does not publish a tag
|
||||||
|
or hosted content.
|
||||||
|
|
||||||
|
```go
|
||||||
|
err := releasekit.PrepareTaggedCheckout(ctx, releasekit.TaggedCheckoutRequest{
|
||||||
|
RepositoryDir: repositoryDir,
|
||||||
|
Version: version,
|
||||||
|
ExpectedCommit: ciCommit,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
For binary profiles, call `PrepareBuildDependencies(ctx, repositoryDir)` after
|
||||||
|
checkout preparation and before delivery. It runs `go mod download` with
|
||||||
|
workspace discovery disabled and the available compatible local Go toolchain.
|
||||||
|
The operation may use the network and updates the Go module cache while
|
||||||
|
preserving the caller's proxy, private-module, credential, and cache settings.
|
||||||
|
If checksums are missing, Go may update `go.sum`; see the
|
||||||
|
[Go Modules Reference](https://go.dev/ref/mod#go-mod-download). Cancellation
|
||||||
|
and command errors are returned. Page-only profiles do not need dependency
|
||||||
|
preparation.
|
||||||
|
|
||||||
|
## Command line
|
||||||
|
|
||||||
|
Add a Gitea destination to the profile:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"product": "Example",
|
||||||
|
"delivery": {
|
||||||
|
"base_url": "https://gitea.example",
|
||||||
|
"owner": "example",
|
||||||
|
"repository": "example",
|
||||||
|
"token_env": "RELEASEKIT_GITEA_TOKEN"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
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
|
||||||
|
```
|
||||||
|
|
||||||
|
The CLI reads the named token variable only for `deliver`; its default name is
|
||||||
|
`RELEASEKIT_GITEA_TOKEN`. It verifies the local checkout and hosted tag before
|
||||||
|
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.
|
||||||
|
|
||||||
|
With no build targets, delivery is page-only: no builder, version smoke check,
|
||||||
|
receipt, binary asset, or checksum manifest is involved. With selected targets,
|
||||||
|
one `deliver` invocation builds the tagged source through the facade into
|
||||||
|
temporary storage and delivers the result. To retain artifacts for a retry or
|
||||||
|
separate credentials between build and delivery, use two invocations:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
releasekit build --output dist v1.2.3
|
||||||
|
RELEASEKIT_GITEA_TOKEN="$GITEA_TOKEN" releasekit deliver --assets dist v1.2.3
|
||||||
|
```
|
||||||
|
|
||||||
|
The build command does not need delivery credentials. The `--assets DIR`
|
||||||
|
directory must contain the private `.releasekit-build.json` receipt created by
|
||||||
|
`build`. ReleaseKit checks the receipt's repository, commit, version, resolved
|
||||||
|
build settings, and file hashes before making a remote request; caller-owned
|
||||||
|
files remain available for retries. Ordinary `deliver` does not download
|
||||||
|
application dependencies or change the checkout.
|
||||||
|
|
||||||
|
The result reports `complete`, `partial`, `conflict`, `unknown`, or
|
||||||
|
`not_attempted`, along with matching, uploaded, pending, conflicting, and
|
||||||
|
uncertain assets when known. These are disjoint current observations: an asset
|
||||||
|
appears in at most one category, and early failures may leave some declared
|
||||||
|
assets unreported. `Matching` means existing content matches; `Uploaded` means
|
||||||
|
an upload was confirmed during this invocation; `Pending` means known missing
|
||||||
|
work; `Conflicting` means different hosted content was found; `Uncertain` means
|
||||||
|
the remote state could not be resolved.
|
||||||
|
|
||||||
|
Fix local or preflight failures before retrying. For partial delivery, fix the
|
||||||
|
reported cause and retry the same version. Resolve an unknown remote outcome
|
||||||
|
before retrying. Investigate conflicts and use a new version if the source or
|
||||||
|
published content needs correction. If rebuilding could change bytes already
|
||||||
|
on the server, retain the original build output and retry with `--assets DIR`.
|
||||||
|
The command does not run candidate checks or publish tags.
|
||||||
|
|
||||||
|
## Go API
|
||||||
|
|
||||||
|
Pass the Gitea credential explicitly. Set `Build` to a `BuildSpec` to compile
|
||||||
|
selected targets as part of delivery. The facade verifies the local tag, clean
|
||||||
|
checkout, and committed release note before compiling. Managed output is stored
|
||||||
|
outside the checkout and removed when delivery returns. `Output` receives build
|
||||||
|
progress. With no build, or with an empty target set, delivery is page-only.
|
||||||
|
|
||||||
|
To deliver binaries built separately, set `Prebuilt` to the `BuildResult`.
|
||||||
|
ReleaseKit checks that it identifies the selected repository, tagged commit, and
|
||||||
|
version, that its source was verified clean and unchanged during compilation,
|
||||||
|
and that the current files still match their recorded digests. The files remain
|
||||||
|
caller-owned, so callers can retain the original bytes for retries and are
|
||||||
|
responsible for cleanup. With neither artifact source, an empty managed target
|
||||||
|
set, or an empty prebuilt result, delivery is page-only. Do not set both `Build`
|
||||||
|
and `Prebuilt` in one request.
|
||||||
|
|
||||||
|
```go
|
||||||
|
result, err := releasekit.Deliver(ctx, releasekit.DeliveryRequest{
|
||||||
|
RepositoryDir: "/work/example",
|
||||||
|
Product: "Example",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Destination: releasekit.GiteaDestination{
|
||||||
|
BaseURL: "https://gitea.example",
|
||||||
|
Owner: "example",
|
||||||
|
Repository: "example",
|
||||||
|
Token: token,
|
||||||
|
},
|
||||||
|
Build: &releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/example",
|
||||||
|
BinaryName: "example",
|
||||||
|
Targets: []releasekit.Target{{OS: "linux", Arch: "amd64"}},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
// Keep the returned state and any completed asset identities for recovery.
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
fmt.Println(result.State, result.ReleaseURL)
|
||||||
|
```
|
||||||
|
|
||||||
|
See the [CLI contract](../cli.md), [configuration reference](../config.md),
|
||||||
|
and [Gitea integration guide](../integrations/gitea.md) for exact settings,
|
||||||
|
exit codes, and transport behavior.
|
||||||
|
|
||||||
|
## Woodpecker tag workflows
|
||||||
|
|
||||||
|
Use the maintained [tag-delivery workflow](../../examples/woodpecker/tag-delivery.yml)
|
||||||
|
in the consumer repository's `.woodpecker/` directory. Set `GO_IMAGE` to an
|
||||||
|
image with Go 1.25 or newer, Git, and a Go version compatible with the consumer
|
||||||
|
module. Replace `RELEASEKIT_VERSION` with an immutable ReleaseKit revision or
|
||||||
|
published version. The example selects the initial `v0.1.0` baseline; update
|
||||||
|
that pin when adopting a later release. Configure the Woodpecker repository secret
|
||||||
|
`releasekit_gitea_token`; the template maps it to `RELEASEKIT_GITEA_TOKEN` only
|
||||||
|
for the delivery step. The repository needs a `delivery` profile. Page-only and
|
||||||
|
binary behavior both use this template; the profile's build target list selects
|
||||||
|
whether binaries are built and delivered.
|
||||||
|
|
||||||
|
The command runs versioned source directly with `go run`, passing
|
||||||
|
`CI_WORKSPACE`, `CI_COMMIT_SHA`, and `CI_COMMIT_TAG` as command arguments.
|
||||||
|
`ci-deliver` fetches and verifies the event tag against its commit before
|
||||||
|
checking out the commit detached. It then loads the profile from that source,
|
||||||
|
validates the destination and token, and downloads application dependencies
|
||||||
|
only for profiles with build targets. The facade builds and delivers those
|
||||||
|
targets with the note page. Source-only profiles skip dependency downloads and
|
||||||
|
binary work. The workflow does not repeat checkout guards or maintain a
|
||||||
|
separate build/receipt/delivery sequence.
|
||||||
|
|
||||||
|
The normal Go module and build caches are sufficient. Cache mounts may be added
|
||||||
|
as deployment configuration when they help the runner; they are not needed by
|
||||||
|
the template. A locally retained executable can be installed with
|
||||||
|
`go install gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit@PIN`, then run
|
||||||
|
with the same arguments:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
releasekit ci-deliver --repo "$CI_WORKSPACE" --commit "$CI_COMMIT_SHA" "$CI_COMMIT_TAG"
|
||||||
|
```
|
||||||
|
|
||||||
|
Upgrade by changing the selected immutable
|
||||||
|
`RELEASEKIT_VERSION` (or the `@PIN` used by `go install`) and validating the
|
||||||
|
workflow against a tag fixture. The command and profile behavior are documented
|
||||||
|
in the [CLI contract](../cli.md) and [configuration reference](../config.md).
|
||||||
|
|
||||||
|
Woodpecker runs delivery after the tag event, independently from the source
|
||||||
|
publication result. Read its workflow status as delivery status: a delivery
|
||||||
|
failure does not undo source publication. A failed, partial, or uncertain run
|
||||||
|
can be inspected and retried against the same immutable tag and commit; do not
|
||||||
|
move the tag to make a retry pass. See
|
||||||
|
[Woodpecker's environment reference](https://woodpecker-ci.org/docs/usage/environment)
|
||||||
|
for runner-provided tag and commit variables and
|
||||||
|
[workflow syntax](https://woodpecker-ci.org/docs/usage/workflow-syntax) for tag
|
||||||
|
events, sequential steps, and the shared workspace.
|
||||||
41
docs/consumers/publish.md
Normal file
41
docs/consumers/publish.md
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
# Source tag publication
|
||||||
|
|
||||||
|
Use `releasekit.Publish` to validate a committed candidate and push its exact
|
||||||
|
annotated source tag:
|
||||||
|
|
||||||
|
```go
|
||||||
|
result, err := releasekit.Publish(ctx, releasekit.ReleaseRequest{
|
||||||
|
RepositoryDir: "/work/project",
|
||||||
|
Product: "Example",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
AdditionalChecks: func(ctx context.Context, candidate releasekit.Candidate) error {
|
||||||
|
return runProjectChecks(ctx, candidate.RepositoryDir)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
fmt.Println(result.Version, result.CandidateCommit, result.TagObject)
|
||||||
|
```
|
||||||
|
|
||||||
|
Publication captures a clean candidate on `main`, validates its committed
|
||||||
|
release note, and checks the selected remote before running candidate checks.
|
||||||
|
It always runs `go test -mod=readonly -count=1 ./...` with the available
|
||||||
|
compatible local Go toolchain. It then calls `AdditionalChecks` once when
|
||||||
|
supplied. The standard suite cannot be replaced; move product-specific behavior
|
||||||
|
into `AdditionalChecks` and remove repeated standard-suite commands from custom
|
||||||
|
checks. A failed suite or additional check prevents tag creation, and wrapped
|
||||||
|
errors preserve their causes.
|
||||||
|
|
||||||
|
If `Build` selects targets, ReleaseKit verifies them after the standard suite
|
||||||
|
and additional checks, before creating the tag. The operation then rechecks the
|
||||||
|
candidate and remote guards, creates an annotated tag for the captured commit,
|
||||||
|
and pushes only that tag object.
|
||||||
|
|
||||||
|
A successful result means Git confirmed the push or an exact authoritative tag
|
||||||
|
query confirmed it after a push error. The local tag is retained after a failed
|
||||||
|
push. `PublicationState` distinguishes a known failure, conflict, confirmed
|
||||||
|
publication, and unresolved outcome. Resolve an unknown result against the
|
||||||
|
captured endpoint before retrying; see the [maintainer procedure](../release.md)
|
||||||
|
for the recovery steps. The [CLI contract](../cli.md) documents command output
|
||||||
|
and exit statuses.
|
||||||
17
docs/consumers/runtime-version.md
Normal file
17
docs/consumers/runtime-version.md
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
# Runtime version
|
||||||
|
|
||||||
|
Applications can read their embedded version through the public `buildinfo`
|
||||||
|
package:
|
||||||
|
|
||||||
|
```go
|
||||||
|
import "gitea.maximumdirect.net/eric/ReleaseKit/buildinfo"
|
||||||
|
|
||||||
|
version := buildinfo.Version()
|
||||||
|
```
|
||||||
|
|
||||||
|
`Version` returns the identifier injected into the executable when present.
|
||||||
|
Otherwise it returns the executable's main module version when that metadata is
|
||||||
|
available and is not `(devel)`. It returns `dev` when neither source provides a
|
||||||
|
release identifier. Applications should use this accessor for version output;
|
||||||
|
the runtime implementation and [ReleaseKit's build API](build.md) own the
|
||||||
|
injection detail.
|
||||||
79
docs/development.md
Normal file
79
docs/development.md
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
# Developing ReleaseKit
|
||||||
|
|
||||||
|
ReleaseKit contains a Go module with the documented root `releasekit` facade,
|
||||||
|
adopted policies, and design documents. See the [README](../README.md) for
|
||||||
|
orientation and the [product roadmap](roadmap/releasekit.md) for proposed
|
||||||
|
capabilities and implementation sequencing.
|
||||||
|
|
||||||
|
Read the [agent policy](policy/agents.md) and inspect the worktree before editing.
|
||||||
|
Preserve unrelated changes and follow explicit instructions about commits.
|
||||||
|
The [architecture policy](policy/architecture.md) governs development boundaries;
|
||||||
|
[ADR 0001](adr/0001-public-facade.md) records the facade decision. The
|
||||||
|
[documentation policy](policy/documentation.md#canonical-ownership) owns the
|
||||||
|
documentation topic map.
|
||||||
|
|
||||||
|
[ADR 0002](adr/0002-routine-releases.md) records the priorities and non-goals
|
||||||
|
behind ReleaseKit's standard, minimal API for routine releases.
|
||||||
|
|
||||||
|
## Policy Reading Guide
|
||||||
|
|
||||||
|
| Policy | Read before… |
|
||||||
|
| --- | --- |
|
||||||
|
| [Policy set provenance](policy/meta.md) | Adopting policies, checking upstream revisions, or updating the adopted policy set. |
|
||||||
|
| [Agents](policy/agents.md) | Recommending, planning, or implementing repository changes. |
|
||||||
|
| [Architecture](policy/architecture.md) | Planning or changing library or executable code or its structure. |
|
||||||
|
| [Testing](policy/testing.md) | Selecting validation for code changes, or adding, changing, removing, or evaluating tests. |
|
||||||
|
| [Documentation](policy/documentation.md) | Writing, revising, or reorganizing documentation. |
|
||||||
|
| [OSS](policy/oss.md) | Adding or updating dependencies or incorporated third-party material, or changing licensing or attribution. |
|
||||||
|
| [Release](policy/release.md) | Preparing or publishing a release, changing release procedures, or making versioning and compatibility decisions. |
|
||||||
|
|
||||||
|
- Read applicable policies before making decisions they govern; multiple policies
|
||||||
|
may apply.
|
||||||
|
- Select policies using the task triggers above. Follow cross-references to
|
||||||
|
relevant sections when needed to resolve a concrete question.
|
||||||
|
- Reuse policies already available in context; reread when changed or no longer
|
||||||
|
available.
|
||||||
|
- Expand reading when the task's scope expands.
|
||||||
|
- When revising a policy itself, read that policy and any provisions elsewhere
|
||||||
|
affected by the revision.
|
||||||
|
|
||||||
|
## Validation
|
||||||
|
|
||||||
|
Run the offline Go test suite from the repository root with:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go test ./...
|
||||||
|
```
|
||||||
|
|
||||||
|
Run the compiled public API and dependency-boundary checks from the repository
|
||||||
|
root with:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go run ./internal/apicheck
|
||||||
|
```
|
||||||
|
|
||||||
|
See the [candidate check guide](consumers/check.md), [source publication guide](consumers/publish.md),
|
||||||
|
[build consumer guide](consumers/build.md),
|
||||||
|
and [internal package inventory](internal/overview.md) for implemented behavior
|
||||||
|
and capability ownership. The [product roadmap](roadmap/releasekit.md) records
|
||||||
|
remaining adoption and deployment work.
|
||||||
|
|
||||||
|
For prose changes, review the diff and check local links, fragment destinations,
|
||||||
|
provenance, template residue, and consistency with current repository contents.
|
||||||
|
Check prose whitespace with:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
git diff --check -- '*.md' COPYRIGHT
|
||||||
|
git diff --cached --check -- '*.md' COPYRIGHT
|
||||||
|
```
|
||||||
|
|
||||||
|
Verbatim license texts retain their supplied formatting. When changing those
|
||||||
|
texts, compare their bytes with the selected upstream source.
|
||||||
|
|
||||||
|
Run the source publication command from the candidate repository root with
|
||||||
|
`./scripts/release VERSION`. It uses the local Go toolchain and committed
|
||||||
|
`releasekit.json` profile; prepare module dependencies before offline candidate
|
||||||
|
validation. The [maintainer release procedure](release.md) owns preparation,
|
||||||
|
publication, and recovery. Hosted note-page delivery is a separate prepared
|
||||||
|
workflow and does not change the successful-tag-push completion point. ReleaseKit
|
||||||
|
does not declare binary deliverables.
|
||||||
72
docs/integrations/gitea.md
Normal file
72
docs/integrations/gitea.md
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
# Gitea release pages
|
||||||
|
|
||||||
|
ReleaseKit's public `Deliver` operation and `deliver` command verify tagged
|
||||||
|
source, find or create its stable release page, inspect existing assets, and
|
||||||
|
upload missing assets through the internal Gitea client. Page-only and
|
||||||
|
binary-producing profiles use the same delivery path. The
|
||||||
|
[consumer delivery guide](../consumers/delivery.md) covers caller workflows;
|
||||||
|
this guide describes the Gitea protocol and its failure behavior.
|
||||||
|
|
||||||
|
The caller supplies the Gitea base URL, owner, repository name, and token
|
||||||
|
explicitly. The client does not read ambient credentials. The token is sent in
|
||||||
|
the `Authorization: token …` request header and is not included in errors or
|
||||||
|
results. The base URL must use HTTP or HTTPS and cannot contain URL credentials,
|
||||||
|
a query, or a fragment.
|
||||||
|
|
||||||
|
For version `vMAJOR.MINOR.PATCH`, the client first reads
|
||||||
|
`/api/v1/repos/{owner}/{repo}/tags/{tag}` and requires the hosted tag's commit
|
||||||
|
SHA to equal the captured source commit. It then reads
|
||||||
|
`/api/v1/repos/{owner}/{repo}/releases/tags/{tag}`. A matching existing page
|
||||||
|
must have that tag, the complete committed release note as its body, and stable
|
||||||
|
non-draft state. Its existing title is retained. ReleaseKit does not edit a
|
||||||
|
conflicting page.
|
||||||
|
|
||||||
|
If the page is absent, the client posts to `/api/v1/repos/{owner}/{repo}/releases`
|
||||||
|
with the selected tag and commit, the release note's H1 as title, the complete
|
||||||
|
note as body, and draft and prerelease disabled. A create conflict, interrupted
|
||||||
|
response, or malformed create response (including inconsistent decoded fields)
|
||||||
|
triggers one lookup. An exact page found
|
||||||
|
there confirms the existing content; a differing page is a conflict. If that
|
||||||
|
lookup cannot determine the result after a possibly successful write, the
|
||||||
|
client returns an unknown outcome. Other HTTP failures retain their structured
|
||||||
|
failure kind and status code. A recovered create retains its write history;
|
||||||
|
a later asset-inspection failure reports partial page progress.
|
||||||
|
|
||||||
|
For a binary-producing release, the client can build a deterministic
|
||||||
|
`SHA256SUMS` file from the declared artifact names and SHA-256 digests. Entries
|
||||||
|
are sorted by filename and use the standard two-space separator. A source-only
|
||||||
|
release produces no manifest.
|
||||||
|
|
||||||
|
Asset inspection lists the release attachments, streams each declared existing
|
||||||
|
file, and compares its SHA-256 digest. It reports each asset as matching,
|
||||||
|
missing, conflicting, or unverifiable. Same-name attachments with different
|
||||||
|
bytes are conflicts even when their reported size matches. An existing
|
||||||
|
`SHA256SUMS` must exactly match the complete expected manifest; a subset or
|
||||||
|
different manifest is a conflict. An unreadable attachment is unverifiable,
|
||||||
|
not missing. A failed read-only inspection reports `not_attempted`; if this
|
||||||
|
invocation already delivered the page, its outcome retains `partial` progress.
|
||||||
|
Unknown-write outcomes are reserved for unresolved writes. Unrelated attachments are returned separately and are preserved.
|
||||||
|
|
||||||
|
Attachment downloads and redirects carry the Gitea authorization token only
|
||||||
|
when their scheme, host, and port match the configured service. Cross-origin
|
||||||
|
content is downloaded without that token and verified by its digest.
|
||||||
|
|
||||||
|
The upload operation accepts only an inspection result without conflicts or
|
||||||
|
unverifiable assets. It uploads missing binaries in filename order and then the
|
||||||
|
missing `SHA256SUMS`, using multipart field `attachment` and the filename query
|
||||||
|
parameter `name`. Matching attachments are retained; unrelated and existing
|
||||||
|
attachments are never overwritten or deleted. Results use disjoint current
|
||||||
|
observations: matching, uploaded, pending, conflicting, and uncertain. An asset
|
||||||
|
moved from known missing work to another category is removed from `pending`;
|
||||||
|
later known-missing assets can remain pending when an earlier upload stops the
|
||||||
|
operation. Early failures may leave declarations unreported. After an ambiguous
|
||||||
|
upload or an upload name conflict, the client performs one list and content
|
||||||
|
check. It does not repeat the POST when the result is missing or cannot be
|
||||||
|
verified, so a caller can resolve the remote state before retrying.
|
||||||
|
|
||||||
|
Uploads use the configured service origin and the same explicit token header.
|
||||||
|
Source-only page delivery supplies no binary assets and creates no manifest.
|
||||||
|
|
||||||
|
The integration tests use a local HTTP fixture and assert request paths,
|
||||||
|
payloads, authorization, streaming comparisons, manifest handling, and failure
|
||||||
|
handling. They do not contact a live Gitea service or use real credentials.
|
||||||
46
docs/internal/gotool.md
Normal file
46
docs/internal/gotool.md
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
# Go command environments
|
||||||
|
|
||||||
|
`internal/gotool` resolves effective Go settings once for a validation or build
|
||||||
|
operation and applies the shared environment to its Go commands. It uses
|
||||||
|
`internal/process` for cancellation, the working directory, output, and wrapped
|
||||||
|
errors.
|
||||||
|
|
||||||
|
## Configuration discovery
|
||||||
|
|
||||||
|
The owner asks the installed `go` command for `GOHOSTOS` and `GOHOSTARCH`, then
|
||||||
|
queries effective operational settings with that host selected. Both queries
|
||||||
|
use `GOTOOLCHAIN=local` and controlled `GOFLAGS`. Discovery sets
|
||||||
|
`GOEXPERIMENT=none` and clears architecture feature variables so an invalid or
|
||||||
|
nonbaseline tuning value cannot prevent settings from being read. The
|
||||||
|
experiment override is discovery-only.
|
||||||
|
|
||||||
|
The persistent Go environment remains active during discovery. The owner copies
|
||||||
|
the effective cache and module-cache locations, Go root, temporary directory,
|
||||||
|
and native cgo/C-tool configuration into its settings. This captures values
|
||||||
|
supplied by either the process environment or the persistent Go environment
|
||||||
|
file.
|
||||||
|
|
||||||
|
Configuration discovery parses JSON from stdout. Stderr is captured separately
|
||||||
|
and included in command-failure diagnostics, so a successful query can emit
|
||||||
|
warnings while supplying valid configuration.
|
||||||
|
|
||||||
|
## Command environments
|
||||||
|
|
||||||
|
Every Go command receives `GOENV=off`, so removed persistent values cannot
|
||||||
|
return. ReleaseKit owns `GOFLAGS=-mod=readonly`, `GOWORK=off`,
|
||||||
|
`GOTOOLCHAIN=local`, `GOPROXY=off`, `GONOPROXY=none`, and `GOSUMDB=off`.
|
||||||
|
Native commands use `GOHOSTOS` and `GOHOSTARCH` and retain the effective
|
||||||
|
`CGO_ENABLED`, `CC`, `CXX`, `PKG_CONFIG`, and `CGO_CFLAGS`, `CGO_CPPFLAGS`,
|
||||||
|
`CGO_CXXFLAGS`, and `CGO_LDFLAGS`. Static commands use the selected target and
|
||||||
|
`CGO_ENABLED=0`.
|
||||||
|
|
||||||
|
Both modes clear `GOEXPERIMENT` and the Go architecture feature variables
|
||||||
|
`GOAMD64`, `GOARM`, `GOARM64`, `GO386`, `GOMIPS`, `GOMIPS64`, `GOPPC64`,
|
||||||
|
`GORISCV64`, and `GOWASM`. The selected Go toolchain supplies its ordinary
|
||||||
|
baseline values. Effective `GOCACHE`, `GOCACHEPROG`, `GOMODCACHE`, `GOPATH`,
|
||||||
|
`GOROOT`, and `GOTMPDIR` values are retained. Other process variables remain
|
||||||
|
available to child commands.
|
||||||
|
|
||||||
|
Candidate validation uses native mode for the offline `go test` suite. Builds
|
||||||
|
use static mode for selected-target compilation and the native version-check
|
||||||
|
build. The native version executable itself runs as a normal child process.
|
||||||
92
docs/internal/overview.md
Normal file
92
docs/internal/overview.md
Normal file
@@ -0,0 +1,92 @@
|
|||||||
|
# Package and capability inventory
|
||||||
|
|
||||||
|
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
|
||||||
|
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`
|
||||||
|
and `PrepareBuildDependencies` provide explicit local CI preparation.
|
||||||
|
- `buildinfo` is the small runtime facade. `Version` reports the injected
|
||||||
|
application version, the main-module version when available, or `dev`.
|
||||||
|
- `cmd/releasekit` is the executable interface. Its `version`, `check`,
|
||||||
|
`publish`, `build`, `deliver`, and `ci-deliver` commands adapt profiles and
|
||||||
|
command output to the supported library operations.
|
||||||
|
|
||||||
|
See the [CLI contract](../cli.md), [configuration reference](../config.md),
|
||||||
|
[candidate check guide](../consumers/check.md),
|
||||||
|
[source publication guide](../consumers/publish.md),
|
||||||
|
[build guide](../consumers/build.md),
|
||||||
|
[delivery guide](../consumers/delivery.md), and
|
||||||
|
[runtime version guide](../consumers/runtime-version.md) for task-oriented use.
|
||||||
|
Go declarations and GoDoc remain the owners of exact exported contracts.
|
||||||
|
|
||||||
|
## Module and dependencies
|
||||||
|
|
||||||
|
The module is `gitea.maximumdirect.net/eric/ReleaseKit`, with Go language
|
||||||
|
version `1.25.0`. `go.mod` has no required third-party modules; packages use the
|
||||||
|
standard library and first-party ReleaseKit packages. `go list ./...` reports
|
||||||
|
these implemented packages:
|
||||||
|
|
||||||
|
| Package | Responsibility |
|
||||||
|
| --- | --- |
|
||||||
|
| `releasekit` | Public orchestration facade and consumer-owned request/result types. |
|
||||||
|
| `buildinfo` | Public runtime version accessor. |
|
||||||
|
| `cmd/releasekit` | Executable entry point, command routing, output, and exit status. |
|
||||||
|
| `cmd/releasekit/internal/cli` | Command parsing, strict JSON profile loading, configured checks, and private build receipts. |
|
||||||
|
| `internal/apicheck` | Compiled-export and import-boundary checks run during development. |
|
||||||
|
| `internal/artifact` | Shared build-target normalization, artifact declarations, filename rules, and checksum-manifest naming. |
|
||||||
|
| `internal/build` | Candidate-build coordination, selected Go target compilation, version injection, native smoke check, and artifact digests. |
|
||||||
|
| `internal/candidate` | Stable-version, note, repository-state, candidate capture, and post-validation checks. |
|
||||||
|
| `internal/delivery` | Tagged-source and release-note checks, managed builds in disposable storage outside the checkout, prebuilt artifact validation, manifest assembly, and hosted delivery coordination. |
|
||||||
|
| `internal/git` | Git command boundary, push-destination resolution, exact ref inspection, tagged checkout preparation, and tag operations, including captured-endpoint verification during recovery. |
|
||||||
|
| `internal/gitea` | Gitea API transport, hosted release pages, asset inspection, manifests, and uploads. |
|
||||||
|
| `internal/gotool` | Effective Go configuration discovery, shared native-validation and static-build environments, and network-capable dependency preparation; see [Go command environments](gotool.md). |
|
||||||
|
| `internal/tempdir` | Disposable system temporary storage outside source worktrees. |
|
||||||
|
| `internal/process` | Cancellable child-process execution with per-command environment overlays and removals. |
|
||||||
|
| `internal/preparation` | Coordination for expected-commit tag checkout and Go module dependency preparation. |
|
||||||
|
| `internal/publish` | Publication guards, one validation run, annotated tag creation, push, and recovery state. |
|
||||||
|
| `internal/runtimeinfo` | Private version lookup used by the runtime facade. |
|
||||||
|
| `internal/versioncontract` | Shared stable-version rules and linker-symbol identity. |
|
||||||
|
|
||||||
|
The `buildinfo` facade depends only on its small runtime implementation. The
|
||||||
|
root facade forwards to internal implementation packages. The CLI adapter is
|
||||||
|
owned under `cmd/releasekit/internal`; implementation packages do not import
|
||||||
|
either public facade. `internal/apicheck` verifies exported type ownership and
|
||||||
|
dependency direction with `go run ./internal/apicheck`. These constraints are
|
||||||
|
also recorded in [ADR 0001](../adr/0001-public-facade.md) and the
|
||||||
|
[architecture policy](../policy/architecture.md).
|
||||||
|
|
||||||
|
## Capability owners and behavioral evidence
|
||||||
|
|
||||||
|
The following tests are representative evidence from the current offline suite,
|
||||||
|
not a separate release matrix:
|
||||||
|
|
||||||
|
| Capability | Implementation owner | Existing evidence |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Runtime version lookup and injected application version | `buildinfo`, `internal/runtimeinfo`, `internal/versioncontract`, `internal/build` | `TestVersionInConsumerExecutable`, `TestVersion` |
|
||||||
|
| Candidate capture, standard suite, additional checks, and rechecks | `releasekit.Check`, `releasekit.Publish`, `internal/candidate`, `cmd/releasekit/internal/cli` | `TestCheckCapturesCandidateAndCallsAdditionalChecksOnce`, `TestPublishPushesOnlyTheCapturedAnnotatedTag`, `TestPublishFailedStandardSuiteSkipsAdditionalChecksAndTagCreation`, `TestPublishAdditionalCheckFailurePreservesCauseAndPreventsTagCreation`, `TestCheckCommandBindsConfiguredChecksToCapturedCandidate`, `TestPublishCommandPublishesConfiguredCandidate` |
|
||||||
|
| Shared Go settings for validation and builds | `internal/gotool`, `internal/process`, `internal/candidate`, `internal/build` | `TestDefaultValidationDoesNotInheritGOFLAGSRunFilter`, `TestNativeAndStaticCommandsUseOwnedBaseline`, `TestPersistentSettingsPreserveCachesAndNativeCTools`, `TestBuildIgnoresAmbientAndPersistentArchitectureTuning` |
|
||||||
|
| Authoritative endpoint and exact annotated tag publication | `releasekit.Publish`, `internal/publish`, `internal/git` | `TestPublishPushesOnlyTheCapturedAnnotatedTag`, `TestResolveUsesPushURLAndQueriesWithoutMutation` |
|
||||||
|
| Publication partial and uncertain recovery | `internal/publish`, `internal/git` | `TestPublishRejectedPushKeepsLocalTagAndReportsNotPublished`, `TestPublishLostAcknowledgmentConfirmsExactRemoteObject`, `TestPublishLostAcknowledgmentWithChangedEndpointRemainsUnknown`, `TestPublishUnavailableReconciliationRemainsUnknownAndPreservesPushError` |
|
||||||
|
| Cross-builds, version smoke checks, empty target sets, and partial outputs | `releasekit.Build`, `internal/build`, `buildinfo` | `TestBuildCreatesSelectedTargetsAndInjectsVersion`, `TestBuildWithNoTargetsDoesNotInvokeCompiler`, `TestBuildReturnsPartialArtifactsAfterTargetFailure` |
|
||||||
|
| Page-only and managed or prebuilt binary delivery | `releasekit.Deliver`, `internal/delivery`, `internal/gitea`, CLI | `TestDeliverPageOnlySkipsBuildAndHostedAssets`, `TestDeliverManagedBuildUploadsArtifactsAndCleansTemporaryOutput`, `TestDeliverBinaryConsumerWithBuildinfoAndSelectedTargets`, `TestDeliverPrebuiltArtifactsRemainCallerOwned`, `TestDeliverManagedBuildFailureCleansTemporaryOutputBeforeHostedWrites`, `TestDeliverManagedBuildCancellationCleansTemporaryOutput`, `TestDeliverBuildsTaggedArtifactsAndReusesAssets`, `TestDeliverRejectsTamperedAssetsAndStaleReceiptBeforeRemoteWrites` |
|
||||||
|
| Tagged checkout and build dependency preparation | `releasekit.PrepareTaggedCheckout`, `releasekit.PrepareBuildDependencies`, `internal/preparation`, `internal/git`, `internal/gotool` | `TestPrepareTaggedCheckoutFetchesExpectedCommitAndDetaches`, `TestPrepareTaggedCheckoutRejectsWrongCommitBeforeCheckout`, `TestPrepareTaggedCheckoutReportsLocalCheckoutConflict`, `TestPrepareTaggedCheckoutReportsConflictingLocalTag`, `TestPrepareBuildDependenciesPreservesPreparationEnvironment`, `TestPrepareBuildDependenciesPropagatesCommandFailure`, `TestPrepareBuildDependenciesPropagatesCancellation` |
|
||||||
|
| Page, manifest, asset comparison, and additive retry outcomes | `internal/gitea` | `TestEnsureReleaseCreatesMissingPageFromCommittedNote`, `TestInspectAssetsDetectsSameNameAndSizeWithDifferentBytes`, `TestUploadMissingPartialFailureThenRerunOnlyMissingAssets` |
|
||||||
|
| CLI profiles and prepared Woodpecker sequences | `cmd/releasekit`, `cmd/releasekit/internal/cli`, `examples/woodpecker/` | `TestLoadSettingsRejectsInvalidProfiles`, `TestWoodpeckerTagDeliveryTemplate`, `TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout` |
|
||||||
|
|
||||||
|
Run the complete suite with `go test ./...`. The public API and import boundary
|
||||||
|
check is `go run ./internal/apicheck`. Local HTTP and Git fixtures exercise
|
||||||
|
publication and delivery without real credentials or a hosted service.
|
||||||
|
|
||||||
|
## Integration references
|
||||||
|
|
||||||
|
The [Gitea integration guide](../integrations/gitea.md) owns the HTTP contract
|
||||||
|
and hosted response handling. The [Woodpecker examples](../../examples/woodpecker/)
|
||||||
|
are prepared integrations; their YAML is not active in this repository, and no
|
||||||
|
live Woodpecker runner, configured secret, or hosted delivery has been used.
|
||||||
|
A read-only PromptKit and Narratio migration review and projected deletion
|
||||||
|
estimates are recorded in the [product roadmap](../roadmap/releasekit.md);
|
||||||
|
actual consumer migrations and measurement of realized savings remain future
|
||||||
|
adoption work.
|
||||||
16
docs/oss/attribution.md
Normal file
16
docs/oss/attribution.md
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
# Open Source Attribution Notices
|
||||||
|
|
||||||
|
## Standard Repository Policies
|
||||||
|
|
||||||
|
Material: policy documents under `docs/policy/`, the root `AGENTS.md` orientation,
|
||||||
|
and the Policy Reading Guide in `docs/development.md`, adapted for this repository.
|
||||||
|
|
||||||
|
Copyright (C) 2026 Eric Rakestraw
|
||||||
|
|
||||||
|
SPDX-License-Identifier: CC-BY-SA-4.0
|
||||||
|
|
||||||
|
License and notices: [CC BY-SA 4.0](licenses/CC-BY-SA-4.0.txt) |
|
||||||
|
[COPYRIGHT](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/COPYRIGHT) |
|
||||||
|
[LICENSE](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/LICENSE).
|
||||||
|
|
||||||
|
[Source](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843).
|
||||||
170
docs/oss/licenses/CC-BY-SA-4.0.txt
Normal file
170
docs/oss/licenses/CC-BY-SA-4.0.txt
Normal file
@@ -0,0 +1,170 @@
|
|||||||
|
Creative Commons Attribution-ShareAlike 4.0 International
|
||||||
|
|
||||||
|
Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.
|
||||||
|
|
||||||
|
Using Creative Commons Public Licenses
|
||||||
|
|
||||||
|
Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.
|
||||||
|
|
||||||
|
Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. More considerations for licensors.
|
||||||
|
|
||||||
|
Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described.
|
||||||
|
|
||||||
|
Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public.
|
||||||
|
|
||||||
|
Creative Commons Attribution-ShareAlike 4.0 International Public License
|
||||||
|
|
||||||
|
By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
|
||||||
|
|
||||||
|
Section 1 – Definitions.
|
||||||
|
|
||||||
|
a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
|
||||||
|
|
||||||
|
b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
|
||||||
|
|
||||||
|
c. BY-SA Compatible License means a license listed at creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License.
|
||||||
|
|
||||||
|
d. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
|
||||||
|
|
||||||
|
e. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
|
||||||
|
|
||||||
|
f. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
|
||||||
|
|
||||||
|
g. License Elements means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution and ShareAlike.
|
||||||
|
|
||||||
|
h. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
|
||||||
|
|
||||||
|
i. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
|
||||||
|
|
||||||
|
j. Licensor means the individual(s) or entity(ies) granting rights under this Public License.
|
||||||
|
|
||||||
|
k. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
|
||||||
|
|
||||||
|
l. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
|
||||||
|
|
||||||
|
m. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
|
||||||
|
|
||||||
|
Section 2 – Scope.
|
||||||
|
|
||||||
|
a. License grant.
|
||||||
|
|
||||||
|
1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
|
||||||
|
|
||||||
|
A. reproduce and Share the Licensed Material, in whole or in part; and
|
||||||
|
|
||||||
|
B. produce, reproduce, and Share Adapted Material.
|
||||||
|
|
||||||
|
2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
|
||||||
|
|
||||||
|
3. Term. The term of this Public License is specified in Section 6(a).
|
||||||
|
|
||||||
|
4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.
|
||||||
|
|
||||||
|
5. Downstream recipients.
|
||||||
|
|
||||||
|
A. Offer from the Licensor – Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
|
||||||
|
|
||||||
|
B. Additional offer from the Licensor – Adapted Material. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter’s License You apply.
|
||||||
|
|
||||||
|
C. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
|
||||||
|
|
||||||
|
6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
|
||||||
|
|
||||||
|
b. Other rights.
|
||||||
|
|
||||||
|
1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
|
||||||
|
|
||||||
|
2. Patent and trademark rights are not licensed under this Public License.
|
||||||
|
|
||||||
|
3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties.
|
||||||
|
|
||||||
|
Section 3 – License Conditions.
|
||||||
|
|
||||||
|
Your exercise of the Licensed Rights is expressly made subject to the following conditions.
|
||||||
|
|
||||||
|
a. Attribution.
|
||||||
|
|
||||||
|
1. If You Share the Licensed Material (including in modified form), You must:
|
||||||
|
|
||||||
|
A. retain the following if it is supplied by the Licensor with the Licensed Material:
|
||||||
|
|
||||||
|
i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
|
||||||
|
|
||||||
|
ii. a copyright notice;
|
||||||
|
|
||||||
|
iii. a notice that refers to this Public License;
|
||||||
|
|
||||||
|
iv. a notice that refers to the disclaimer of warranties;
|
||||||
|
|
||||||
|
v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
|
||||||
|
|
||||||
|
B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
|
||||||
|
|
||||||
|
C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
|
||||||
|
|
||||||
|
2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.
|
||||||
|
|
||||||
|
3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
|
||||||
|
|
||||||
|
b. ShareAlike.In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply.
|
||||||
|
|
||||||
|
1. The Adapter’s License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-SA Compatible License.
|
||||||
|
|
||||||
|
2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material.
|
||||||
|
|
||||||
|
3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply.
|
||||||
|
|
||||||
|
Section 4 – Sui Generis Database Rights.
|
||||||
|
|
||||||
|
Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
|
||||||
|
|
||||||
|
a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database;
|
||||||
|
|
||||||
|
b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and
|
||||||
|
|
||||||
|
c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
|
||||||
|
For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.
|
||||||
|
|
||||||
|
Section 5 – Disclaimer of Warranties and Limitation of Liability.
|
||||||
|
|
||||||
|
a. Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.
|
||||||
|
|
||||||
|
b. To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.
|
||||||
|
|
||||||
|
c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
|
||||||
|
|
||||||
|
Section 6 – Term and Termination.
|
||||||
|
|
||||||
|
a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
|
||||||
|
|
||||||
|
b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
|
||||||
|
|
||||||
|
1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
|
||||||
|
|
||||||
|
2. upon express reinstatement by the Licensor.
|
||||||
|
|
||||||
|
c. For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
|
||||||
|
|
||||||
|
d. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
|
||||||
|
|
||||||
|
e. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
|
||||||
|
|
||||||
|
Section 7 – Other Terms and Conditions.
|
||||||
|
|
||||||
|
a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
|
||||||
|
|
||||||
|
b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
|
||||||
|
|
||||||
|
Section 8 – Interpretation.
|
||||||
|
|
||||||
|
a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
|
||||||
|
|
||||||
|
b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
|
||||||
|
|
||||||
|
c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
|
||||||
|
|
||||||
|
d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
|
||||||
|
|
||||||
|
Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.
|
||||||
|
|
||||||
|
Creative Commons may be contacted at creativecommons.org.
|
||||||
90
docs/policy/agents.md
Normal file
90
docs/policy/agents.md
Normal file
@@ -0,0 +1,90 @@
|
|||||||
|
# Agent Policy
|
||||||
|
|
||||||
|
**Base Policy Version:** 1.3
|
||||||
|
|
||||||
|
**Last Updated**: 2026-10-05
|
||||||
|
|
||||||
|
**Upstream Source:** [agents.md](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/docs/policy/agents.md)
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
|
||||||
|
Agents must read and follow these rules.
|
||||||
|
|
||||||
|
## Implementation Discipline
|
||||||
|
|
||||||
|
**KEY PRINCIPLES:** Write the simplest idiomatic code that satisfies the user's
|
||||||
|
request. Do not implicitly strengthen requirements, restrictions, or guarantees
|
||||||
|
beyond what the user actually requested.
|
||||||
|
|
||||||
|
**Keep implementation machinery proportionate.** Use straightforward,
|
||||||
|
idiomatic code and introduce only the machinery needed to support the requested
|
||||||
|
behavior and flexibility. Optimize for conceptual simplicity and
|
||||||
|
maintainability, not for the fewest lines, fewest options, or narrowest product
|
||||||
|
surface.
|
||||||
|
|
||||||
|
**Do not invent restrictions.** Do not reject, prohibit, constrain, cap,
|
||||||
|
harden, or otherwise narrow behavior unless required by the user, an explicit
|
||||||
|
repository contract, or an unavoidable correctness constraint. Preserve
|
||||||
|
operator and caller choice where policy has not been established. If an
|
||||||
|
additional restriction appears advisable, present it as a decision rather than
|
||||||
|
silently implementing it.
|
||||||
|
|
||||||
|
A correctness constraint must follow from the requested behavior or an
|
||||||
|
established invariant, not from the convenience of the chosen implementation.
|
||||||
|
Explain the specific failure it prevents and why a less restrictive
|
||||||
|
implementation cannot satisfy the contract.
|
||||||
|
|
||||||
|
**Do not invent guarantees.** Do not strengthen public contracts, guarantees,
|
||||||
|
or invariants beyond those expressly requested by the user.
|
||||||
|
|
||||||
|
**Use the standard library.** For example: in almost every case, the best
|
||||||
|
approach to copying files is to use the standard library. Writing custom code to
|
||||||
|
implement power-loss protection at the application level, or to guard against
|
||||||
|
bad actors with privileged and concurrent access to the host's filesystem,
|
||||||
|
is wasteful, unnecessary, and not idiomatic. Stick to the simple, standard, and
|
||||||
|
idiomatic approach unless another path is expressly requested by the user.
|
||||||
|
|
||||||
|
**An implementation detail is not repository policy.** Tests and documentation
|
||||||
|
must not elevate incidental behavior into a durable guarantee or restriction
|
||||||
|
unless that behavior was expressly selected as part of the contract.
|
||||||
|
|
||||||
|
Existing explicit contracts remain authoritative. Changing one requires a
|
||||||
|
deliberate decision. Agent-authored plans, tests, documentation, and prior
|
||||||
|
implementations do not independently establish additional contracts. Identify
|
||||||
|
the authorizing requirement or decision; when that authority is unclear, surface
|
||||||
|
the ambiguity rather than treating repetition as approval.
|
||||||
|
|
||||||
|
## Git Commit Policy
|
||||||
|
|
||||||
|
By default, commit each completed, nonempty unit of work using a
|
||||||
|
concise, plain-English message describing what changed. This policy is standing
|
||||||
|
authorization to create those local commits; a separate user request is not
|
||||||
|
required. An explicit user instruction to leave work uncommitted takes precedence.
|
||||||
|
|
||||||
|
A unit of work is a focused, reviewable outcome, including its relevant tests and
|
||||||
|
documentation.
|
||||||
|
Complete the appropriate validation before committing. If work is incomplete or
|
||||||
|
validation is blocked, report that state accurately.
|
||||||
|
|
||||||
|
Before committing:
|
||||||
|
|
||||||
|
1. Run `git status --short` and review the relevant diff, including any staged
|
||||||
|
changes. Identify changes that predate the current unit of work.
|
||||||
|
2. Exclude secrets, local environment files, generated junk, and unrelated changes.
|
||||||
|
3. Stage only the files or hunks belonging to the completed unit. Use `git add .`
|
||||||
|
only when every included change belongs to that unit. Preserve unrelated
|
||||||
|
staged and unstaged work.
|
||||||
|
4. Review `git diff --staged` and run appropriate checks for the change. Reuse
|
||||||
|
successful checks for unchanged content.
|
||||||
|
5. Review `git log --oneline -n 10` and use
|
||||||
|
`git commit -m "<concise plain-English commit message>"`.
|
||||||
|
6. Report the commit identifier and any remaining uncommitted work.
|
||||||
|
|
||||||
|
If the unit cannot be safely separated from pre-existing work, leave it uncommitted
|
||||||
|
and explain the overlap rather than silently including that work. If a commit
|
||||||
|
fails, preserve the changes and report the failure; do not bypass hooks.
|
||||||
|
|
||||||
|
Default commit authorization does not authorize pushing, publishing, amending,
|
||||||
|
resetting, reverting, or rewriting history. Those actions require a separate user
|
||||||
|
instruction. Do not use `git commit -a` or `git commit --no-verify` to bypass the
|
||||||
|
staging and validation discipline above.
|
||||||
121
docs/policy/architecture.md
Normal file
121
docs/policy/architecture.md
Normal file
@@ -0,0 +1,121 @@
|
|||||||
|
# Architecture Policy
|
||||||
|
|
||||||
|
**Base Policy Version:** 1.3
|
||||||
|
|
||||||
|
**Last Updated**: 2026-10-06
|
||||||
|
|
||||||
|
**Upstream Source:** [architecture.md](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/docs/policy/architecture.md)
|
||||||
|
|
||||||
|
## Purpose And Ownership
|
||||||
|
|
||||||
|
ReleaseKit is an opinionated Go library and release executable for common
|
||||||
|
publication, builds, version injection, and delivery. This policy owns
|
||||||
|
responsibility boundaries, dependency direction, and adopted constraints for
|
||||||
|
development. The [product roadmap](../roadmap/releasekit.md) owns proposed
|
||||||
|
capabilities, implementation status, and sequencing.
|
||||||
|
|
||||||
|
The [internal documentation](../internal/overview.md) owns concrete package
|
||||||
|
inventory and implementation mechanics. Canonical public contracts own exact
|
||||||
|
behavior; ADRs record decision rationale.
|
||||||
|
|
||||||
|
## Adopted Constraints And Implemented Structure
|
||||||
|
|
||||||
|
Architectural constraints govern current and future development and reflect
|
||||||
|
deliberately selected requirements and decisions. Current architecture describes
|
||||||
|
implemented structure. Roadmaps record proposals, implementation status, and
|
||||||
|
sequencing; ADRs record significant decisions and rationale. Internal
|
||||||
|
implementation choices evolve within these constraints.
|
||||||
|
|
||||||
|
## Success Criteria
|
||||||
|
|
||||||
|
Evaluate ReleaseKit development and adoption against both criteria:
|
||||||
|
|
||||||
|
1. Applications delete substantial release infrastructure while retaining clear
|
||||||
|
ownership of product-specific checks and compatibility decisions.
|
||||||
|
2. Consumers adopt one coherent set of deliberately selected release conventions.
|
||||||
|
|
||||||
|
Consumer implementations supply evidence of needs. ReleaseKit selects a common
|
||||||
|
model and enough flexibility to express genuine product requirements. API
|
||||||
|
designs should demonstrate reduced consumer infrastructure and consistent
|
||||||
|
conventions through representative consumers.
|
||||||
|
|
||||||
|
## Responsibility Boundaries
|
||||||
|
|
||||||
|
ReleaseKit owns the mechanics of selected publication, version injection,
|
||||||
|
cross-build, and delivery conventions. Applications supply product identity,
|
||||||
|
their main package, selected build targets, application-specific candidate
|
||||||
|
checks, and delivery declarations. Applications own their compatibility
|
||||||
|
decisions and adaptation of version output to the supported runtime accessor.
|
||||||
|
|
||||||
|
The release executable invokes the supported orchestration facade and owns
|
||||||
|
argument parsing, output, and exit codes. Library operations return meaningful
|
||||||
|
errors and outcomes, including partial progress and uncertain publication state.
|
||||||
|
Consumers map those values to their own user interfaces.
|
||||||
|
|
||||||
|
ReleaseKit builds and tests independently of consuming repositories. Production
|
||||||
|
dependencies use supported public contracts available independently of consumer
|
||||||
|
checkouts. Committed module and workspace configuration supports independent
|
||||||
|
builds; temporary local development configuration remains local.
|
||||||
|
|
||||||
|
## Public Facades And Dependency Direction
|
||||||
|
|
||||||
|
[ADR 0001](../adr/0001-public-facade.md) records the accepted decision for the root
|
||||||
|
`releasekit` orchestration facade and separate `buildinfo` runtime facade.
|
||||||
|
Both belong to one Go module and share its versioning and compatibility
|
||||||
|
obligations. Each facade exposes a cohesive consumer contract.
|
||||||
|
|
||||||
|
Public named types belong to their facade. Exported signatures, fields,
|
||||||
|
callbacks, and method sets use facade-owned types and deliberately selected
|
||||||
|
public dependencies. Handles retain private implementation state, with explicit
|
||||||
|
forwarding and conversions preserving supported identity, ownership, error
|
||||||
|
semantics, and callback lifetime.
|
||||||
|
|
||||||
|
Implementation packages live under Go's `internal/` boundary. Dependencies run
|
||||||
|
from facades into internal implementation; internal production packages depend
|
||||||
|
on internal contracts. Git operations, Go toolchain execution, Gitea integration,
|
||||||
|
and orchestration bookkeeping belong behind that boundary. Additional public
|
||||||
|
packages and extension interfaces require a deliberate decision grounded in a
|
||||||
|
durable consumer need.
|
||||||
|
|
||||||
|
Go declarations and GoDoc own exact API contracts. Compiled-export checks,
|
||||||
|
dependency checks, and external-package behavioral tests protect the selected
|
||||||
|
facade boundaries.
|
||||||
|
|
||||||
|
## Runtime Version Boundary
|
||||||
|
|
||||||
|
The `buildinfo` public API exposes runtime information justified by
|
||||||
|
consumer needs. Its implementation uses the standard library and a small
|
||||||
|
internal dependency graph independent of release orchestration. Applications
|
||||||
|
read their embedded version through its supported accessor.
|
||||||
|
|
||||||
|
The builder and runtime implementation own the linker symbol and injection
|
||||||
|
mechanism together. Dependency checks protect the runtime boundary;
|
||||||
|
build-and-run integration tests verify that the builder injects the selected
|
||||||
|
version and the public accessor reports it correctly.
|
||||||
|
|
||||||
|
## External Effects
|
||||||
|
|
||||||
|
Keep Git, filesystem, Go toolchain, and Gitea effects behind proportionate
|
||||||
|
internal boundaries and perform them through explicit operations. Select
|
||||||
|
interfaces and package layout for actual responsibilities and testability.
|
||||||
|
The library owns reusable outcomes and failure handling; the executable owns
|
||||||
|
presentation and process exits.
|
||||||
|
|
||||||
|
Source publication and asynchronous delivery have distinct outcomes. The
|
||||||
|
[release policy](release.md) governs releases of ReleaseKit itself. Go
|
||||||
|
declarations and GoDoc define supported consumer API contracts;
|
||||||
|
[consumer guides](../consumers/) explain their use, and
|
||||||
|
[integration guides](../integrations/) define external formats and protocols.
|
||||||
|
The product roadmap records planned capabilities and implementation status.
|
||||||
|
|
||||||
|
## Trust Boundaries And Threat Scope
|
||||||
|
|
||||||
|
Base defenses and guarantees on selected requirements. Candidate validation,
|
||||||
|
remote-state changes, transport failures, and partial delivery receive explicit
|
||||||
|
handling. Additional threat scenarios require a deliberate scope decision under
|
||||||
|
the [agent policy](agents.md).
|
||||||
|
|
||||||
|
Public API, [configuration](../config.md), and integration contracts own
|
||||||
|
credential supply and observable handling. Internal documents own the mechanisms.
|
||||||
|
Tests use local collaborators and controlled failures as specified by the
|
||||||
|
[testing policy](testing.md).
|
||||||
176
docs/policy/documentation.md
Normal file
176
docs/policy/documentation.md
Normal file
@@ -0,0 +1,176 @@
|
|||||||
|
# Documentation Policy
|
||||||
|
|
||||||
|
**Base Policy Version:** 1.11
|
||||||
|
|
||||||
|
**Last Updated**: 2026-10-05
|
||||||
|
|
||||||
|
**Upstream Source:** [documentation.md](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/docs/policy/documentation.md)
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
|
||||||
|
This policy assigns each documentation topic to one canonical owner. Its goal is
|
||||||
|
to keep ReleaseKit's documentation accurate, concise, discoverable, and resistant
|
||||||
|
to drift for consumers, maintainers, developers, and coding agents.
|
||||||
|
|
||||||
|
## Core Rules
|
||||||
|
|
||||||
|
### One Canonical Owner
|
||||||
|
|
||||||
|
Each authoritative fact belongs in one document. A non-owning document may give
|
||||||
|
a short, stable summary for orientation, but it must link to the canonical owner
|
||||||
|
for volatile details.
|
||||||
|
|
||||||
|
Volatile details include commands, flags, configuration fields and defaults,
|
||||||
|
module keys, schemas, file names, paths, status codes, retry behavior, and
|
||||||
|
runtime guarantees. If readers could reasonably treat a statement as a
|
||||||
|
contract, maintain it only in the owning document.
|
||||||
|
|
||||||
|
### Current And Future Behavior
|
||||||
|
|
||||||
|
Outside `docs/roadmap/`, documentation describes implemented behavior only.
|
||||||
|
Partial features may be described only to their implemented boundary.
|
||||||
|
|
||||||
|
Architectural constraints may govern future changes. Describe current structure
|
||||||
|
from implemented behavior.
|
||||||
|
|
||||||
|
ADRs may record an accepted architectural decision before implementation. The
|
||||||
|
roadmap owns implementation status and sequencing until the decision is
|
||||||
|
implemented. Current architecture, user, operator, integration, and internal
|
||||||
|
documentation are updated when the behavior lands.
|
||||||
|
|
||||||
|
### Audience And Detail
|
||||||
|
|
||||||
|
Write for the document's stated audience and include only the detail needed for
|
||||||
|
its owned topic. Keep user and operator docs focused on using and operating the
|
||||||
|
application. Developer docs should link to user-facing and external contracts
|
||||||
|
for their definitions.
|
||||||
|
|
||||||
|
### Examples
|
||||||
|
|
||||||
|
Complete copyable files belong in `examples/`. Documentation may use the
|
||||||
|
smallest illustrative snippet needed to explain its owned topic, but should link
|
||||||
|
to maintained examples for complete copyable files.
|
||||||
|
|
||||||
|
Examples must be valid, secret-free, and tested where practical. Commands and
|
||||||
|
configuration used in documentation should match the application.
|
||||||
|
|
||||||
|
### Security And Privacy
|
||||||
|
|
||||||
|
Documentation and examples must not contain real credentials, private keys,
|
||||||
|
private environment dumps, sensitive source material, or private infrastructure
|
||||||
|
details unless intentionally public. Document secret-handling mechanisms, not
|
||||||
|
secret values.
|
||||||
|
|
||||||
|
## Canonical Ownership
|
||||||
|
|
||||||
|
| Topic | Canonical owner | Owned content | Content owned elsewhere |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| Product orientation and minimal example | `README.md` | Purpose, current status, shortest useful example when implemented, and navigation, including licensing and attribution. | Complete command reference, configuration reference, operational procedures, implementation detail. |
|
||||||
|
| Contributor entry point | `docs/development.md` | Task-oriented reading guide, contributor orientation, baseline validation commands, and canonical links. | Package inventory, architecture rules, subsystem behavior, detailed change recipes. |
|
||||||
|
| ReleaseKit architecture policy | `docs/policy/architecture.md` | System shape, normative ownership, dependency direction, boundaries, invariants, safety properties, and non-goals. | Concrete package inventory, implementation mechanics, contributor procedures, decision history, future work. |
|
||||||
|
| Policy-set provenance and upstream navigation | `docs/policy/meta.md` | Policy-set origin, local authority, adoption baselines, and upstream adoption and update links. | Task-specific reading triggers, detailed adoption procedures, and formal attribution notices. |
|
||||||
|
| Agent policy | `docs/policy/agents.md` | Proportionate, idiomatic implementation; rules against inventing requirements, restrictions, guarantees, or policy. | Application contracts, architecture, testing policy, and contributor procedures. |
|
||||||
|
| Documentation policy | `docs/policy/documentation.md` | Documentation ownership, audience boundaries, maintenance rules, and ADR/document lifecycle. | Application architecture or product behavior. |
|
||||||
|
| Testing policy | `docs/policy/testing.md` | Test philosophy, risk sufficiency, boundaries, doubles, coverage, regressions, and test maintenance. | Subsystem behavior, application contracts, subsystem-specific test inventories, and implementation plans. |
|
||||||
|
| Release policy | `docs/policy/release.md` | Versioning, compatibility, release integrity and immutability, release documentation, proportionate gates, publication controls, completion, and required versus optional checks. | Repository-specific commands, product installation guidance, CLI version semantics, historical release summaries, and CI implementation detail. |
|
||||||
|
| Open source licensing and attribution policy | `docs/policy/oss.md` | License defaults and author choices, COPYRIGHT and attribution formats, license/notice links, discoverability, maintenance, and concrete exceptions. | Component entries, license texts, release commands, and dependency security review. |
|
||||||
|
| Project copyright and license grant | `COPYRIGHT` | Project identity, copyright holders and years, SPDX expression, grant, separately licensed document scope, warranty disclaimer, and third-party statement. | Complete license texts and upstream component attribution. |
|
||||||
|
| Project license texts | `LICENSE` | Complete project and incorporated companion license texts, with required project-specific fields. | General licensing policy and upstream component attribution. |
|
||||||
|
| Upstream component attribution | `docs/oss/attribution.md` | House Format component entries: identity, material scope and modifications where applicable, copyright, license, required notices, and license, notice, and source links. | General attribution policy, exception reasoning, research narratives, compliance commentary, and complete standard license texts. |
|
||||||
|
| Standard license texts | `docs/oss/licenses/` | Complete, verbatim standard license texts shared by applicable entries, including copied documentation. | Project-specific upstream notices, attribution prose, and policy interpretation. |
|
||||||
|
| Repository-specific release procedure | `docs/release.md` | Maintainer prerequisites, candidate preparation, validation and publication commands and automated guards, asynchronous deliverables, delivery status, optional consumer verification, and recovery. | General release requirements, product installation guidance, historical release summaries, and current compatibility contracts. |
|
||||||
|
| CLI contract (if applicable) | `docs/cli.md` | Commands, arguments, flags, invocation semantics, and exit codes. | End-to-end operating procedures, configuration field definitions, runtime filesystem layout, module implementation details. |
|
||||||
|
| Configuration contract (if applicable) | `docs/config.md` | Discovery, precedence, fields, defaults, environment inputs, and validation for implemented configuration. | Complete example files, CLI syntax, runtime state lifecycle, implementation details. |
|
||||||
|
| Exported Go API (when implemented) | Go declarations and GoDoc | Exact symbol contracts, errors, ownership, and lifecycle semantics for each facade. | Consumer walkthroughs, CLI contracts, integration protocols, and internal mechanics. |
|
||||||
|
| Consumer guidance for the public Go API (if applicable) | `docs/consumers/` | Task-oriented public Go API usage, minimal examples, and consumer responsibilities. | HTTP wire semantics, external protocol contracts, internal implementation detail. |
|
||||||
|
| Integration contracts for external components (if applicable) | `docs/integrations/` | External formats and protocols, upstream and downstream contracts, logical output paths and schemas, media types, and compatibility. | Physical runtime placement and lifecycle, internal transformations, CLI syntax, configuration defaults. |
|
||||||
|
| Inventory of implemented internal packages | `docs/internal/overview.md` | Implemented packages and components, responsibilities, and links to focused internal docs. | Normative architecture, contributor reading policy, external contracts. |
|
||||||
|
| Behavior and architecture of internal packages | Other files under `docs/internal/` | Implementation flow, collaborators, state transitions, package-local guarantees and failures, and relevant tests. | Global architecture invariants, configuration definitions and defaults, external schemas, operator procedures. |
|
||||||
|
| Architectural decision records | `docs/adr/` | Significant decisions, context, alternatives, rationale, consequences, and supersession history. | Current behavior reference, implementation status, task sequencing. |
|
||||||
|
| Future work and implementation status | `docs/roadmap/` | Proposed, accepted, deferred, or rejected work; implementation status, sequencing, and task breakdowns. | Implemented behavior reference and architectural decision rationale. |
|
||||||
|
| Release-note history | `docs/releases/` | One checked-in summary per source release under the procedure; the note at its immutable tag is the release record. | Current commands, behavior, contracts, and compatibility definitions. |
|
||||||
|
| Complete copyable artifacts | `examples/` | Maintained configuration, inputs, and other copyable or runnable files. | Field-by-field reference, command reference, prose explanation. |
|
||||||
|
|
||||||
|
Create supporting documents for existing interfaces and responsibilities when
|
||||||
|
substantive content is available. The CLI, configuration, consumer, integration,
|
||||||
|
internal, example, and release-procedure owners become documents as their
|
||||||
|
corresponding implementation lands. Keep implementation status in the roadmap
|
||||||
|
and avoid empty owners.
|
||||||
|
|
||||||
|
## Boundary Rules
|
||||||
|
|
||||||
|
### Orientation
|
||||||
|
|
||||||
|
Link among orientation, architecture, and internal documents; maintain each
|
||||||
|
package or behavior description in its canonical owner.
|
||||||
|
|
||||||
|
### Go API, CLI, And Configuration
|
||||||
|
|
||||||
|
Go declarations and GoDoc own exact exported contracts. Consumer guidance
|
||||||
|
explains tasks and links to those declarations. CLI documentation owns invocation
|
||||||
|
and exit semantics; configuration documentation owns settings. Release procedures
|
||||||
|
own maintainer publication and recovery workflows. Link across those owners
|
||||||
|
when a task spans their boundaries.
|
||||||
|
|
||||||
|
### Releases
|
||||||
|
|
||||||
|
The release policy defines requirements and invariants that every release must
|
||||||
|
satisfy. The repository-specific release procedure defines the commands and
|
||||||
|
workflow maintainers use to satisfy that policy. Release notes record history
|
||||||
|
at immutable tags. Maintain current behavior in its canonical documentation,
|
||||||
|
update it with the corresponding behavior changes, and keep release procedures
|
||||||
|
consistent with adopted policy.
|
||||||
|
|
||||||
|
### Project Licensing And Upstream Attribution
|
||||||
|
|
||||||
|
README and release documents link to the canonical licensing and attribution
|
||||||
|
materials under the [OSS policy](oss.md). The release procedure owns URL
|
||||||
|
construction and publication mechanics.
|
||||||
|
|
||||||
|
### Contracts And Implementation
|
||||||
|
|
||||||
|
GoDoc, CLI, configuration, and integration documents define externally observable
|
||||||
|
shapes and semantics. Internal documents explain how ReleaseKit implements or
|
||||||
|
consumes those contracts. Internal docs may name a field, file, or protocol to
|
||||||
|
identify a dependency, but must link to its canonical contract for the definition.
|
||||||
|
|
||||||
|
### Security Topics
|
||||||
|
|
||||||
|
This policy owns what documentation and examples may contain. Architecture owns
|
||||||
|
selected security invariants. Public API, configuration, and integration
|
||||||
|
contracts own credential supply and observable handling. Internal docs own
|
||||||
|
implementation mechanisms only.
|
||||||
|
|
||||||
|
## Architecture Decision Records
|
||||||
|
|
||||||
|
Use sequentially numbered ADR filenames such as
|
||||||
|
`0001-record-architecture-decisions.md`. Follow the lightweight Nygard format:
|
||||||
|
|
||||||
|
1. title;
|
||||||
|
2. status;
|
||||||
|
3. date;
|
||||||
|
4. context;
|
||||||
|
5. decision;
|
||||||
|
6. alternatives considered;
|
||||||
|
7. consequences.
|
||||||
|
|
||||||
|
Treat the decision content of an accepted ADR as immutable. When a decision
|
||||||
|
changes, create a new ADR and update the earlier ADR's status to superseded.
|
||||||
|
Rejected architectural alternatives belong in the ADR; rejected product ideas
|
||||||
|
belong in the roadmap. Routine choices need no ADR.
|
||||||
|
|
||||||
|
## Maintenance
|
||||||
|
|
||||||
|
When behavior changes, update its canonical owner in the same change. If
|
||||||
|
ownership moves, remove the old definition and replace it with a link where
|
||||||
|
navigation remains useful.
|
||||||
|
|
||||||
|
Before completing documentation work:
|
||||||
|
|
||||||
|
- verify affected behavior and examples;
|
||||||
|
- check commands, flags, fields, defaults, schemas, and paths against their
|
||||||
|
implementation;
|
||||||
|
- keep unimplemented behavior in the roadmap, subject to the ADR exception;
|
||||||
|
- remove stale references and validate links;
|
||||||
|
- confirm that non-owning documents summarize and link rather than redefine;
|
||||||
|
- confirm that no secrets or sensitive private data were added.
|
||||||
27
docs/policy/meta.md
Normal file
27
docs/policy/meta.md
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
# Policy Set Provenance
|
||||||
|
|
||||||
|
**Base Policy Version:** 1.0
|
||||||
|
|
||||||
|
**Last Updated**: 2026-10-05
|
||||||
|
|
||||||
|
**Upstream Source:** [meta.md](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/docs/policy/meta.md)
|
||||||
|
|
||||||
|
## Origin And Local Authority
|
||||||
|
|
||||||
|
This repository's policy set is adapted from
|
||||||
|
[Standard Repository Policies](https://gitea.maximumdirect.net/eric/policy).
|
||||||
|
The adopted local policies govern work in this repository. Upstream revisions
|
||||||
|
become local policy through deliberate adoption, preserving local decisions.
|
||||||
|
Each policy's `Upstream Source` identifies its adopted baseline.
|
||||||
|
|
||||||
|
## Adoption And Updates
|
||||||
|
|
||||||
|
For policy adoption, upstream revision reviews, and updates, consult the
|
||||||
|
[upstream adoption and update guide](https://gitea.maximumdirect.net/eric/policy/src/branch/main/docs/adoption.md).
|
||||||
|
That guide and the reference example collection are maintained upstream and
|
||||||
|
accessed through links. Keep discovery links pointed at the current upstream
|
||||||
|
project and guide; keep adopted-source and example links pinned to commits.
|
||||||
|
|
||||||
|
The local [developer guide](../development.md) routes tasks to applicable
|
||||||
|
policies. Formal credit and licensing notices for the copied policy material
|
||||||
|
belong in the local [attribution document](../oss/attribution.md).
|
||||||
221
docs/policy/oss.md
Normal file
221
docs/policy/oss.md
Normal file
@@ -0,0 +1,221 @@
|
|||||||
|
# Open Source Licensing And Attribution Policy
|
||||||
|
|
||||||
|
**Base Policy Version:** 1.8
|
||||||
|
|
||||||
|
**Last Updated**: 2026-10-07
|
||||||
|
|
||||||
|
**Upstream Source:** [oss.md](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/docs/policy/oss.md)
|
||||||
|
|
||||||
|
## Purpose And Scope
|
||||||
|
|
||||||
|
This policy defines project licensing conventions and a repeatable House Format
|
||||||
|
for upstream attribution and license notices. It covers the project's own code
|
||||||
|
and upstream components incorporated into or distributed with the application
|
||||||
|
or library, including relevant transitive dependencies and copied code,
|
||||||
|
documentation, or assets.
|
||||||
|
Determine treatment from the component's terms and actual use.
|
||||||
|
|
||||||
|
Consulting development guidance or using tooling alone does not require an
|
||||||
|
attribution entry. Copying or adapting documentation for inclusion in the
|
||||||
|
repository is different: preserve its applicable attribution and license terms.
|
||||||
|
A material's role as development guidance does not exempt copied documents.
|
||||||
|
Apply any express permissions for attribution-free reuse of example formatting.
|
||||||
|
|
||||||
|
The baseline is a publicly available source repository with releases published
|
||||||
|
alongside it. The format is independent of language, forge, and build system.
|
||||||
|
It does not require attribution for every development tool, establish license
|
||||||
|
compatibility, or resolve every obligation arising from use or distribution.
|
||||||
|
|
||||||
|
## Canonical Locations
|
||||||
|
|
||||||
|
The [documentation policy](documentation.md) assigns ownership:
|
||||||
|
|
||||||
|
- `COPYRIGHT`: project name, copyright statements, SPDX expression, grant,
|
||||||
|
warranty disclaimer, and third-party statement.
|
||||||
|
- `LICENSE` contains the complete, unmodified project license text, including
|
||||||
|
incorporated companion text. Dependency attribution does not relicense the project.
|
||||||
|
- `docs/oss/attribution.md`: canonical component entries.
|
||||||
|
- `docs/oss/licenses/`: complete, verbatim standard and applicable companion texts.
|
||||||
|
|
||||||
|
Use recognizable license filenames, such as `Apache-2.0.txt` or `LGPL-3.0.txt`.
|
||||||
|
A shared standard text may serve multiple entries. Keep explanations outside
|
||||||
|
license texts and preserve distinct versions and exceptions.
|
||||||
|
|
||||||
|
## Upstream Reference Examples
|
||||||
|
|
||||||
|
Use the commit-pinned upstream examples to create actual project notices.
|
||||||
|
Retain their links and keep the example collection upstream; keep applicable
|
||||||
|
license texts locally as specified above.
|
||||||
|
|
||||||
|
The pinned upstream [standard license reference collection](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/docs/oss/licenses/README.md)
|
||||||
|
provides texts to copy for applicable licenses and their companions.
|
||||||
|
|
||||||
|
## Project Licensing
|
||||||
|
|
||||||
|
ReleaseKit's selected grant is LGPL version 3 or later, recorded in
|
||||||
|
[COPYRIGHT](../../COPYRIGHT). It applies to the library and release
|
||||||
|
executable. Adapted policy documents, agent orientation, and the policy reading
|
||||||
|
guide retain their CC-BY-SA-4.0 scope as identified there and in the
|
||||||
|
[attribution document](../oss/attribution.md).
|
||||||
|
|
||||||
|
Unless the author specifies otherwise, use **GPL version 3 or later**
|
||||||
|
(`GPL-3.0-or-later`) for applications and **LGPL version 3 or later**
|
||||||
|
(`LGPL-3.0-or-later`) for libraries. An author's explicit choice takes precedence:
|
||||||
|
for example, a one-off script may use MIT. Such a choice requires no exception
|
||||||
|
rationale, additional approval, or compensating controls under this policy.
|
||||||
|
|
||||||
|
These defaults guide new license selection. Adopting this policy does not
|
||||||
|
relicense existing code or override third-party terms. Preserve an existing
|
||||||
|
license unless the author deliberately changes it. For mixed-purpose projects,
|
||||||
|
follow the author's selected scope rather than inferring different licenses for
|
||||||
|
individual packages.
|
||||||
|
|
||||||
|
Use the upstream [application COPYRIGHT example](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/examples/licensing/application/COPYRIGHT)
|
||||||
|
or [library COPYRIGHT example](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/examples/licensing/library/COPYRIGHT)
|
||||||
|
to create the project’s root `COPYRIGHT` file.
|
||||||
|
Use verified project names, contribution years, and copyright holders.
|
||||||
|
For another selected license, adapt the grant, SPDX expression, disclaimer, and
|
||||||
|
text references together to reflect the author's selected grant.
|
||||||
|
|
||||||
|
For GPLv3 projects, copy the complete GPLv3 text into `LICENSE`. For LGPLv3
|
||||||
|
projects, place the complete LGPLv3 text followed by the complete GPLv3 text in
|
||||||
|
`LICENSE`; the LGPL incorporates the GPL terms. Keep the texts unmodified and
|
||||||
|
place project-specific statements in `COPYRIGHT`. For the default grants, the
|
||||||
|
grant and SPDX expression in `COPYRIGHT` must expressly identify `or-later`;
|
||||||
|
follow the author’s choice if a different grant is selected.
|
||||||
|
|
||||||
|
For other licenses, provide their complete text and any required project-specific
|
||||||
|
fields; the standard reference collection remains unchanged. Keep `COPYRIGHT`,
|
||||||
|
`LICENSE`, SPDX expressions, and README descriptions consistent with the actual
|
||||||
|
grant. This convention introduces no blanket requirement for per-file headers;
|
||||||
|
preserve notices or add them where the applicable terms require them.
|
||||||
|
|
||||||
|
Identify separately licensed documentation or assets in the project grant, with
|
||||||
|
links to their attribution and license information. An application's default
|
||||||
|
code license does not override the terms of incorporated documentation.
|
||||||
|
|
||||||
|
## Upstream Attribution House Format
|
||||||
|
|
||||||
|
Begin `docs/oss/attribution.md` with `# Open Source Attribution Notices`,
|
||||||
|
followed directly by component entries. These comprise the complete document.
|
||||||
|
|
||||||
|
Each entry presents these five fields in order, with blank lines between them:
|
||||||
|
|
||||||
|
1. **Project name** as a level-two heading. An optional identification paragraph
|
||||||
|
may follow, such as `Selected module: MODULE at VERSION.` with the module and
|
||||||
|
version in backticks. For copied documentation, a concise `Material:` sentence
|
||||||
|
may identify the affected files and whether they were adapted or copied
|
||||||
|
without modification. A factual qualifier such as `(transitive dependency)`
|
||||||
|
is permitted. Limit optional identification prose to factual component and
|
||||||
|
material scope.
|
||||||
|
2. **Upstream copyright statement or statements**, preserving their wording.
|
||||||
|
Put multiple statements in separate paragraphs. Include this field when the
|
||||||
|
selected upstream source supplies an applicable statement; otherwise, omit it.
|
||||||
|
3. **SPDX license identifier or expression**, when applicable, using
|
||||||
|
`SPDX-License-Identifier: EXPRESSION`.
|
||||||
|
4. **License and notice links**, beginning `License and notices:`, separated
|
||||||
|
by ` | `, and ending with a period. Label local standard texts by license
|
||||||
|
name, such as `MIT` or `Apache 2.0`. Label upstream files by their actual
|
||||||
|
filenames, such as `COPYRIGHT`, `LICENSE`, `NOTICE`, or `PATENTS`.
|
||||||
|
5. **Source repository link**, rendered exactly as `[Source](COMMIT_URL).`.
|
||||||
|
|
||||||
|
Use the upstream [attribution example](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/examples/licensing/attribution.md)
|
||||||
|
to create the project’s `docs/oss/attribution.md`.
|
||||||
|
The example illustrates omitted fields and multiple copyrights and licenses.
|
||||||
|
Replace the uppercase placeholders and illustrative URLs with actual component
|
||||||
|
information. Local license links are relative to the destination
|
||||||
|
`docs/oss/attribution.md`; copy the applicable texts into its `licenses/`
|
||||||
|
directory. Do not copy example entries for components the project does not use.
|
||||||
|
|
||||||
|
These are five fields, not a line limit. Omit the SPDX field when no applicable
|
||||||
|
identifier exists; identify nonstandard terms through the linked text. Preserve
|
||||||
|
licensing alternatives and exceptions, and record a selected option when
|
||||||
|
relevant through the factual license identification. Do not invent an identifier
|
||||||
|
or silently resolve an unsettled licensing choice.
|
||||||
|
|
||||||
|
Keep entries factual. Do not add agent-authored explanations of license
|
||||||
|
expressions, file-level license scope, research performed, retained source
|
||||||
|
notices, or compliance conclusions. Avoid filler such as "none is invented
|
||||||
|
here" and embellished link labels such as "upstream LICENSE", "additional
|
||||||
|
patent grant", or "at the imported commit". Preserve actual required upstream
|
||||||
|
content; this rule excludes editorial additions, not required notices. Policy
|
||||||
|
interpretation and exception reasoning belong in the adopted OSS policy or an
|
||||||
|
appropriate decision record, not the attribution document.
|
||||||
|
|
||||||
|
## License Texts And Upstream Links
|
||||||
|
|
||||||
|
Link standard license texts to their local copies. Link project-specific
|
||||||
|
notices to their upstream copies. Every upstream repository or notice link must
|
||||||
|
identify the exact commit corresponding to the
|
||||||
|
imported version, including the selected source revision for copied material.
|
||||||
|
|
||||||
|
Classify material according to its contents. An upstream `LICENSE`,
|
||||||
|
`COPYING`, or similar file may contain project-specific notices or exceptions
|
||||||
|
in addition to standard wording. Link both the local standard text and the
|
||||||
|
commit-specific upstream file when needed. Make companion license texts directly
|
||||||
|
reachable from the entry.
|
||||||
|
|
||||||
|
For project-specific license and attribution material, this policy accepts
|
||||||
|
direct links to the applicable upstream texts as satisfying reproduction,
|
||||||
|
inclusion, or copy requirements. This is the adopted house interpretation.
|
||||||
|
Agents must apply it without adding local-copy requirements or seeking repeated
|
||||||
|
approval solely because a license uses those terms.
|
||||||
|
|
||||||
|
This interpretation concerns notice reproduction. Concrete obligations such as
|
||||||
|
marking modified files or supplying corresponding source receive their own
|
||||||
|
applicable treatment. Preserve required notices already present in incorporated
|
||||||
|
source files; the central attribution entry does not authorize stripping them.
|
||||||
|
|
||||||
|
## Discoverability
|
||||||
|
|
||||||
|
End the project's README with two friendly statements linking to its actual
|
||||||
|
grant in `COPYRIGHT` and the attribution document. For example, for a project
|
||||||
|
with the stated license:
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
ReleaseKit is licensed under the [LGPL v3.0 or later](COPYRIGHT).
|
||||||
|
|
||||||
|
[Open Source attribution notices](docs/oss/attribution.md) are available.
|
||||||
|
```
|
||||||
|
|
||||||
|
Each new checked-in release document and its hosted download page must end
|
||||||
|
with links whose visible text is `COPYRIGHT | LICENSE | ATTRIBUTION`. Use absolute
|
||||||
|
URLs to those files at the release's immutable tag or corresponding immutable source
|
||||||
|
revision so the links work in both locations. This release navigation is distinct
|
||||||
|
from upstream component links, which must use the imported commit.
|
||||||
|
|
||||||
|
Reuse the checked-in release document as the hosted release body where supported.
|
||||||
|
The release procedure owns concrete URLs and publication mechanics for delivering
|
||||||
|
the links through the selected channel. Do not maintain duplicate notice lists.
|
||||||
|
These conventions do not by themselves require separate downloadable license
|
||||||
|
assets, source bundles, or a different binary package format.
|
||||||
|
|
||||||
|
## Maintenance And Exceptions
|
||||||
|
|
||||||
|
Update project licensing statements together when the author changes the grant
|
||||||
|
or its scope. Update upstream notices in the change that adds, removes, upgrades,
|
||||||
|
copies, or changes the distribution of a relevant component. Check the selected source's license
|
||||||
|
and notices rather than assuming they are unchanged. Update affected entries,
|
||||||
|
commit links, and texts; retain historical versions through Git.
|
||||||
|
|
||||||
|
Check affected statements, faithful standard-text copies, and link destinations
|
||||||
|
as part of ordinary change review. For a future release tag, check intended file
|
||||||
|
paths against the candidate source; the tag need not resolve remotely before
|
||||||
|
publication. Do not add publication-time network checks, CI polling, recurring
|
||||||
|
legal sign-offs, mandatory scanners, or a full software bill of materials merely
|
||||||
|
to implement this policy.
|
||||||
|
|
||||||
|
Use the House Format routinely. Raise an exception only for a concrete obligation
|
||||||
|
or unresolved rights question it does not address, including any arising from a
|
||||||
|
particular distribution channel. Record the issue and selected treatment in the
|
||||||
|
adopted OSS policy or an appropriate decision record. Attribution entries
|
||||||
|
contain the resulting factual identification and required material, without
|
||||||
|
repeating that reasoning. Resolve the issue before the affected use or
|
||||||
|
distribution without reopening settled choices.
|
||||||
|
Common ownership of projects is neither required nor a blanket exception.
|
||||||
|
|
||||||
|
Apply the formatting convention prospectively. Do not rewrite published tags,
|
||||||
|
notes, binaries, or checksums to retrofit it. Address actual omissions deliberately
|
||||||
|
under the applicable terms and the [release correction policy](release.md#immutability-and-failure-recovery).
|
||||||
|
Ordinary attribution maintenance and release links are preparation work, not new
|
||||||
|
release approval gates.
|
||||||
215
docs/policy/release.md
Normal file
215
docs/policy/release.md
Normal file
@@ -0,0 +1,215 @@
|
|||||||
|
# Release Policy
|
||||||
|
|
||||||
|
**Base Policy Version:** 1.4
|
||||||
|
|
||||||
|
**Last Updated**: 2026-10-07
|
||||||
|
|
||||||
|
**Upstream Source:** [release.md](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/docs/policy/release.md)
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
|
||||||
|
This policy defines a proportionate workflow for validating and publishing an
|
||||||
|
intended source revision under a fresh version. Releases should require little
|
||||||
|
routine intervention, avoid repeated work, and preserve published contents.
|
||||||
|
|
||||||
|
The repository-specific commands belong in `docs/release.md`. Historical release
|
||||||
|
summaries belong in `docs/releases/`. The procedure must agree with the adopted
|
||||||
|
policy and link to it rather than introduce additional release requirements.
|
||||||
|
|
||||||
|
This policy governs releases of ReleaseKit itself. Go declarations and GoDoc
|
||||||
|
own supported consumer API contracts; the [product roadmap](../roadmap/releasekit.md)
|
||||||
|
records planned adoption and deployment work. The maintainer runbook describes
|
||||||
|
ReleaseKit's implemented source publication and hosted-page delivery procedure.
|
||||||
|
|
||||||
|
## Release Model And Completion
|
||||||
|
|
||||||
|
A source release identifies one exact committed source revision through an
|
||||||
|
immutable version tag and a version-matched, checked-in release note. The
|
||||||
|
primary release branch is `main`.
|
||||||
|
The procedure must name the authoritative publication remote.
|
||||||
|
|
||||||
|
A successful push of the intended annotated tag, with its source commit already
|
||||||
|
published on authoritative `main`, completes the release. The remote branch must
|
||||||
|
identify the validated candidate before the command publishes only the exact
|
||||||
|
intended tag object. The [maintainer runbook](../release.md) identifies the
|
||||||
|
authoritative endpoint and command.
|
||||||
|
|
||||||
|
Release commands must finish at successful publication. They must not wait for
|
||||||
|
or poll CI, require successful CI status, inspect downloadable artifacts, or
|
||||||
|
check consumer installation or Go module availability as completion gates.
|
||||||
|
A failed or ambiguous push requires resolving the authoritative remote state
|
||||||
|
before declaring success or retrying; successful pushes do not require a
|
||||||
|
separate remote read-back gate.
|
||||||
|
|
||||||
|
ReleaseKit's deliverables are its immutable source tag and a hosted Gitea
|
||||||
|
release page whose body is the complete checked-in release note. A prepared
|
||||||
|
Woodpecker workflow builds the local release tool from that tagged source and
|
||||||
|
delivers the note page. This adds no executable download or binary manifest.
|
||||||
|
Any later distribution of executable builds requires a deliberate update
|
||||||
|
identifying the deliverables, selected targets, and automation responsibilities.
|
||||||
|
Supporting cross-builds for consumers does not declare ReleaseKit binaries.
|
||||||
|
Additional declared deliverables may be published asynchronously from the
|
||||||
|
tagged source, must be traceable to that source, and must identify the same
|
||||||
|
version.
|
||||||
|
|
||||||
|
Track source-release completion and artifact delivery separately. Report delivery
|
||||||
|
failures and optional investigations under artifact-delivery status.
|
||||||
|
|
||||||
|
## Versioning And Compatibility
|
||||||
|
|
||||||
|
Stable releases use Semantic Versioning in the form `vMAJOR.MINOR.PATCH`, with
|
||||||
|
no leading zeroes. Prereleases require an explicit adopted policy defining
|
||||||
|
their format and use.
|
||||||
|
|
||||||
|
The selected version must be unused locally and on the authoritative remote.
|
||||||
|
Do not require queries to every configured remote or publication service.
|
||||||
|
A version known to have already been published must not be reused, even if the
|
||||||
|
normal guards do not inspect that channel. Adding a distribution channel
|
||||||
|
requires a deliberate update to the policy and procedure where needed.
|
||||||
|
|
||||||
|
For releases at or after `v1.0.0`:
|
||||||
|
|
||||||
|
- a major release may make intentional incompatible changes;
|
||||||
|
- a minor release may add backward-compatible behavior; and
|
||||||
|
- a patch release may make backward-compatible fixes.
|
||||||
|
|
||||||
|
Before `v1.0.0`, a minor release may change a documented public, operational,
|
||||||
|
configuration, data, integration, or compatibility contract when the release
|
||||||
|
note explains the impact and required consumer action. A patch release must
|
||||||
|
not intentionally break those contracts within its minor line.
|
||||||
|
|
||||||
|
Additional compatibility promises and deliberate exceptions belong in the
|
||||||
|
adopted policy or canonical contract documentation. Release notes explain
|
||||||
|
changes; they do not redefine current compatibility contracts.
|
||||||
|
|
||||||
|
## Release Documentation And Preparation
|
||||||
|
|
||||||
|
Every new release must include `docs/releases/<version>.md` in the tagged
|
||||||
|
source tree. Use the complete version tag as the filename and begin with a
|
||||||
|
title containing the product name and that exact version.
|
||||||
|
|
||||||
|
Include a short summary and any relevant compatibility impact or upgrade
|
||||||
|
instructions. Choose sections suited to the release and keep the note
|
||||||
|
proportionate to the change.
|
||||||
|
|
||||||
|
Keep exact current contracts in their canonical documents and update affected
|
||||||
|
documentation with the behavior change. Link to those documents from the note
|
||||||
|
where useful. Derive the annotated tag's message from the checked-in note.
|
||||||
|
|
||||||
|
Include the release footer defined by the [OSS policy](oss.md#discoverability)
|
||||||
|
in each new release document and preserve it on the hosted download page. The
|
||||||
|
release procedure defines the concrete URLs and publication mechanics. Prepare
|
||||||
|
these links with the release note; they do not add a network check or approval
|
||||||
|
gate.
|
||||||
|
|
||||||
|
Handle version selection, release-note content, and retirement of completed
|
||||||
|
roadmaps during preparation. Preserve planned and deferred work and repair
|
||||||
|
affected links when retiring roadmaps. Reuse ordinary change review for
|
||||||
|
unintended files, credentials, and private data. Scope release-content review
|
||||||
|
to the tagged source.
|
||||||
|
|
||||||
|
## Candidate Validation
|
||||||
|
|
||||||
|
Provide one publication command that validates the final committed candidate,
|
||||||
|
checks publication state, and publishes the intended refs. A validation-only
|
||||||
|
mode or command may be provided for diagnosis, but must not be a required step
|
||||||
|
before publication repeats the same checks.
|
||||||
|
|
||||||
|
Run the complete deterministic, offline default test suite once for the final
|
||||||
|
candidate, following the [testing policy](testing.md). For repositories that
|
||||||
|
publish builds, verify the required build targets. Select those targets for
|
||||||
|
the project's actual support commitments; native testing on each platform
|
||||||
|
and access to particular hardware are not default release prerequisites.
|
||||||
|
|
||||||
|
The publication command runs the standard offline Go test suite, followed by
|
||||||
|
any additional product checks. The [maintainer runbook](../release.md) owns its
|
||||||
|
invocation. ReleaseKit's source-only deliverable adds no binary target matrix.
|
||||||
|
|
||||||
|
Additional gates must address a concrete risk that the existing checks do not
|
||||||
|
adequately cover. Do not automatically require linting, race testing, module
|
||||||
|
hygiene audits, documentation audits, credential scans, example validation, or
|
||||||
|
expanded platform matrices solely because they are possible. Retain such
|
||||||
|
checks when their distinct protection justifies their cost. A one-time migration
|
||||||
|
check must not silently become a permanent release requirement.
|
||||||
|
|
||||||
|
Release tests must not require real credentials, mutable application services,
|
||||||
|
paid APIs, or live service probes. The procedure may describe dependency
|
||||||
|
preparation separately from offline validation.
|
||||||
|
|
||||||
|
Avoid duplicate validation across release phases. Successful checks for the
|
||||||
|
same final candidate need not be repeated solely to satisfy another phase;
|
||||||
|
any reuse must clearly apply to that exact candidate. Persistent validation
|
||||||
|
caches are not required. If the candidate changes, validate the new candidate.
|
||||||
|
Cheap publication-state checks may be repeated immediately before pushing
|
||||||
|
because local or remote state may have changed during validation.
|
||||||
|
|
||||||
|
Automate mechanical guards. Human review gates are strongly disfavored: add one
|
||||||
|
only through an explicit project-specific policy decision explaining the
|
||||||
|
concrete risk and why ordinary change review or automation is insufficient.
|
||||||
|
Do not add routine confirmations for checks the command can perform itself.
|
||||||
|
|
||||||
|
## Publication Guards
|
||||||
|
|
||||||
|
Automate the checks needed to publish the intended source under a fresh version:
|
||||||
|
|
||||||
|
- the version has the adopted format and is unused locally and on the
|
||||||
|
authoritative remote;
|
||||||
|
- the worktree and index are clean on the primary release branch;
|
||||||
|
- the source being published is the exact candidate that passed validation,
|
||||||
|
including its matching release note;
|
||||||
|
- authoritative `main` already identifies that candidate; and
|
||||||
|
- the annotated tag identifies the validated candidate and only its exact object
|
||||||
|
is published through an explicit tag ref.
|
||||||
|
|
||||||
|
Fetch the authoritative branch and tag state as needed for these checks.
|
||||||
|
Do not force branch or tag updates to bypass a failed guard. Publish explicit
|
||||||
|
refs rather than all local tags. Do not require CI success, publication-service
|
||||||
|
availability checks, or a separate manual confirmation for each guard.
|
||||||
|
|
||||||
|
## Immutability And Failure Recovery
|
||||||
|
|
||||||
|
Published version tags and published contents are immutable. Do not move,
|
||||||
|
overwrite, recreate, or delete a published tag, or replace a published artifact,
|
||||||
|
checksum, signature, provenance statement, or release note under that version.
|
||||||
|
The checked-in note at the immutable tag is that release's historical record.
|
||||||
|
|
||||||
|
If validation fails before publication, correct and commit the candidate and
|
||||||
|
rerun the publication command. If a push fails or its outcome is ambiguous,
|
||||||
|
query the authoritative tag ref once. Confirm success only when it identifies
|
||||||
|
the exact intended tag object on the validated commit; otherwise report failed
|
||||||
|
or unknown status and retain the local tag. Resolve that authoritative state
|
||||||
|
before retrying. Remove an unpublished local tag only after confirming it was
|
||||||
|
never published or used by a release channel.
|
||||||
|
An unavailable remote leaves publication status unknown; do not overwrite a tag
|
||||||
|
to resolve uncertainty.
|
||||||
|
|
||||||
|
Transient network, authentication, CI, or consumer-availability failures do not
|
||||||
|
by themselves require a new version. Asynchronous delivery may be retried from
|
||||||
|
the same immutable tag. Missing artifacts may be published later, provided
|
||||||
|
existing published contents are not replaced and the additions remain consistent
|
||||||
|
with the tagged source and any already-published checksum manifest. If that
|
||||||
|
cannot be achieved, publish a new version.
|
||||||
|
|
||||||
|
A defect requiring changes to published source or contents requires a corrected
|
||||||
|
commit, a new semantically appropriate version, a matching release note, and
|
||||||
|
the release procedure again. Leave the original release intact. A channel's
|
||||||
|
yank, deprecation, or advisory mechanism may warn consumers away from a defective
|
||||||
|
release without replacing its contents or reusing its version.
|
||||||
|
|
||||||
|
## Repository Release Procedure
|
||||||
|
|
||||||
|
Create and maintain `docs/release.md` with the first working publication command
|
||||||
|
as a short, executable maintainer runbook. It must identify:
|
||||||
|
|
||||||
|
1. prerequisites, primary branch, and authoritative remote;
|
||||||
|
2. version and release-note preparation;
|
||||||
|
3. one publication command with its selected local checks and automated guards;
|
||||||
|
4. declared deliverables, required build targets, and automation responsibilities;
|
||||||
|
5. the successful-push completion point and separately reported delivery status;
|
||||||
|
and
|
||||||
|
6. failure handling, ambiguous-push recovery, and asynchronous delivery retries.
|
||||||
|
|
||||||
|
Use copyable commands where practical. Keep optional diagnostics and consumer
|
||||||
|
verification clearly optional. The procedure must not turn preparation work,
|
||||||
|
ordinary change review, or post-publication investigation into additional
|
||||||
|
release gates.
|
||||||
285
docs/policy/testing.md
Normal file
285
docs/policy/testing.md
Normal file
@@ -0,0 +1,285 @@
|
|||||||
|
# Testing Policy
|
||||||
|
|
||||||
|
**Base Policy Version:** 1.3
|
||||||
|
|
||||||
|
**Last Updated**: 2026-10-05
|
||||||
|
|
||||||
|
**Upstream Source:** [testing.md](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/docs/policy/testing.md)
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
|
||||||
|
Our tests exist to make **incorrect changes expensive and correct changes cheap**.
|
||||||
|
|
||||||
|
We optimize for sufficient confidence in important behavior while minimizing friction on future development.
|
||||||
|
|
||||||
|
## Every test has a cost
|
||||||
|
|
||||||
|
Every test has an immediate and continuing cost: writing, review, execution,
|
||||||
|
diagnosis, fixture maintenance, and updates when legitimate behavior changes.
|
||||||
|
Tests can also constrain refactoring, duplicate policy, and add failure noise.
|
||||||
|
|
||||||
|
A test is warranted only when the confidence it provides justifies these costs.
|
||||||
|
Evaluate that tradeoff at two levels:
|
||||||
|
|
||||||
|
1. **Per test:** What realistic defect does this test detect, how consequential would that defect be, and is that protection worth the test's lifetime cost?
|
||||||
|
2. **Across the suite:** Does this collection provide materially more confidence than a smaller, simpler suite would?
|
||||||
|
|
||||||
|
Some friction is intentional. Tests should make dangerous changes—such as breaking compatibility, corrupting data, violating security boundaries, or reintroducing subtle bugs—require deliberate review. Keep ordinary internal changes inexpensive.
|
||||||
|
|
||||||
|
Evaluate maintenance cost against the specific failure being protected. When omitting a plausible test, be able to state why the protected failure is low-risk, already covered, obvious, reversible, or cheaper to detect elsewhere. For consequential, subtle, or difficult-to-observe behavior, the presumption should favor testing.
|
||||||
|
|
||||||
|
## Default testing style
|
||||||
|
|
||||||
|
Use a **classical/Detroit-style** approach:
|
||||||
|
|
||||||
|
- Test observable behavior, resulting state, contracts, and invariants.
|
||||||
|
- Use real internal collaborators when they are fast and deterministic.
|
||||||
|
- Use fakes, stubs, or mocks primarily at expensive, nondeterministic, destructive, or external boundaries.
|
||||||
|
- Prefer package-level behavioral tests over tests coupled to private helpers or internal call sequences.
|
||||||
|
- Treat exact collaborator interactions as testable behavior only when the interaction itself is a requirement.
|
||||||
|
|
||||||
|
Examples of appropriate seams include clocks, randomness, subprocesses, remote APIs, object storage, email, and paid LLM calls.
|
||||||
|
|
||||||
|
## Test execution requirements
|
||||||
|
|
||||||
|
Tests in the default suite must be deterministic, offline, and independent of real credentials. They must not invoke paid APIs or depend on mutable external services. Tests that require live infrastructure must be explicitly opt-in and clearly separated from the default suite.
|
||||||
|
|
||||||
|
Control clocks, randomness, environment variables, and other process-global or machine-specific state when they affect behavior. Tests should be safe to run repeatedly and alongside other tests without depending on execution order or state left by an earlier test.
|
||||||
|
|
||||||
|
## ReleaseKit Priorities
|
||||||
|
|
||||||
|
As the corresponding features are implemented, prioritize:
|
||||||
|
|
||||||
|
- publication of the exact validated candidate and tag object, using temporary
|
||||||
|
local Git repositories and remotes;
|
||||||
|
- remote advancement, rejected pushes, lost acknowledgments, and unavailable
|
||||||
|
remotes, with accurate failed, successful, and unknown outcomes;
|
||||||
|
- preservation of published content and consistent retries after partial asset
|
||||||
|
delivery, using a local HTTP server for Gitea interactions;
|
||||||
|
- cross-build target selection and version injection, including a host-runnable
|
||||||
|
application whose public `buildinfo` accessor reports the selected version;
|
||||||
|
- public type ownership, exported signatures and method sets, error identity,
|
||||||
|
and dependency direction across both facades; and
|
||||||
|
- a `buildinfo` dependency graph restricted to the standard library and small
|
||||||
|
internal runtime implementation, independent of orchestration.
|
||||||
|
|
||||||
|
These priorities guide risk-based tests as features land. Compilation of a
|
||||||
|
cross-built binary establishes build compatibility; execution requires a
|
||||||
|
compatible host. The developer guide owns actual test commands.
|
||||||
|
|
||||||
|
## What deserves tests
|
||||||
|
|
||||||
|
To the extent the following features are present in the application, prioritize tests for:
|
||||||
|
|
||||||
|
1. Public and package-level contracts.
|
||||||
|
2. Domain rules and important invariants.
|
||||||
|
3. Boundary conditions and malformed input.
|
||||||
|
4. Failure handling, cancellation, retries, recovery, and partial success.
|
||||||
|
5. Serialization, schemas, compatibility, and round trips.
|
||||||
|
6. Previously observed or plausible regressions.
|
||||||
|
7. Representative integration and end-to-end workflows.
|
||||||
|
|
||||||
|
A package-level contract comprises behavior relied upon by another package or major collaborator.
|
||||||
|
|
||||||
|
Choose tests for requested behavior and established contracts. Tests must not
|
||||||
|
introduce new restrictions, guarantees, or threat scenarios merely because they
|
||||||
|
could be asserted. Follow the [agent policy](agents.md) when deciding whether a
|
||||||
|
behavior belongs to the contract; current implementation behavior alone is not
|
||||||
|
sufficient authority.
|
||||||
|
|
||||||
|
For established behavior involving **data integrity, destructive operations,
|
||||||
|
compatibility, security, concurrency, idempotency, or recovery**, favor durable
|
||||||
|
tests for realistic failures whose consequences warrant protection. Identify
|
||||||
|
the failure and the existing contract it would violate. These categories call
|
||||||
|
for attention, not an automatic test inventory or permission to strengthen the
|
||||||
|
application's guarantees. Account for protection already provided at other layers.
|
||||||
|
|
||||||
|
Do not add tests merely because a function, branch, or line exists. Do not add a test when the same meaningful risk is already adequately protected elsewhere.
|
||||||
|
|
||||||
|
## Choose the right test boundary
|
||||||
|
|
||||||
|
Choose the narrowest stable boundary that expresses the behavior clearly and
|
||||||
|
provides durable confidence with minimal incidental coupling.
|
||||||
|
|
||||||
|
This is often the package API, but it may instead be:
|
||||||
|
|
||||||
|
- a smaller pure function when dense domain logic is most clearly isolated there;
|
||||||
|
- a package-level operation when several internal collaborators jointly produce the behavior; or
|
||||||
|
- a larger integration boundary when correctness emerges from interaction with a real dependency.
|
||||||
|
|
||||||
|
## Test behavior, not implementation
|
||||||
|
|
||||||
|
A test should protect a selected decision, contract, or invariant.
|
||||||
|
|
||||||
|
A test is suspect when it primarily detects changes to private constants or
|
||||||
|
helpers, equivalent operation ordering, incidental formatting, equivalent
|
||||||
|
algorithms, or internal structure that preserves behavior.
|
||||||
|
|
||||||
|
Behavioral tests should normally remain stable through internal refactoring that preserves the contract.
|
||||||
|
|
||||||
|
## Expected effects of different changes
|
||||||
|
|
||||||
|
Use the following expectations when evaluating test failures and test maintenance:
|
||||||
|
|
||||||
|
| Change | Expected effect on tests |
|
||||||
|
|---|---|
|
||||||
|
| Internal refactor that preserves behavior | Existing tests should normally remain unchanged and continue to pass. |
|
||||||
|
| Change to an internal default with no contractual significance | Behavioral tests should normally remain unchanged; tests should derive expectations from configuration or relationships rather than duplicate the old value. |
|
||||||
|
| Intentional change to public behavior, policy, schema, or compatibility guarantees | The relevant tests should be reviewed and changed deliberately. |
|
||||||
|
| Accidental violation of a contract or invariant | Tests should fail; fix the production code rather than rewriting the tests to accept the defect. |
|
||||||
|
|
||||||
|
A test failing is not the same as a test needing to be edited. Many tests may correctly fail because of one production defect. The maintenance smell is a correct internal change that requires unrelated expectation updates throughout the suite.
|
||||||
|
|
||||||
|
## Separate mechanism from policy
|
||||||
|
|
||||||
|
Derive expectations from test-controlled configuration and relationships.
|
||||||
|
|
||||||
|
For this example, assume the selected contract rejects a request to start more
|
||||||
|
processes than a configured limit. Do not encode its production default indirectly:
|
||||||
|
|
||||||
|
```go
|
||||||
|
// Production default:
|
||||||
|
const maxConcurrency = 4
|
||||||
|
|
||||||
|
// Brittle test:
|
||||||
|
err := startProcesses(5)
|
||||||
|
require.Error(t, err)
|
||||||
|
```
|
||||||
|
|
||||||
|
Instead, test the mechanism relationally:
|
||||||
|
|
||||||
|
```go
|
||||||
|
const limit = 2
|
||||||
|
runner := NewRunner(limit)
|
||||||
|
|
||||||
|
require.NoError(t, runner.Start(limit))
|
||||||
|
require.ErrorIs(t, runner.Start(limit+1), ErrTooMuchConcurrency)
|
||||||
|
```
|
||||||
|
|
||||||
|
For this selected contract, the test should prove:
|
||||||
|
|
||||||
|
- the configured limit is accepted; and
|
||||||
|
- one beyond the configured limit is rejected.
|
||||||
|
|
||||||
|
Rejection is not a general requirement for concurrency control. If the selected
|
||||||
|
contract queues excess work or limits active workers while accepting larger
|
||||||
|
batches, test that behavior instead. Do not add rejection or a configurable
|
||||||
|
limit solely to reproduce this example.
|
||||||
|
|
||||||
|
The production default should be tested exactly only when its literal value is itself a public, operational, safety, protocol, or compatibility requirement.
|
||||||
|
|
||||||
|
Apply the same rule to limits, timeouts, capacities, retry counts, and ranges: test relationships and behavior.
|
||||||
|
|
||||||
|
For established concurrency limits, distinguish these behaviors where the contract requires them:
|
||||||
|
|
||||||
|
1. **Configuration handling:** values are accepted or rejected according to the selected contract.
|
||||||
|
2. **Runtime enforcement:** observed peak concurrency never exceeds the configured limit.
|
||||||
|
|
||||||
|
Use a test-controlled limit and measure the behavior relative to that limit.
|
||||||
|
|
||||||
|
## Assign each behavior a test owner
|
||||||
|
|
||||||
|
Where these layers exist, assign ownership as follows:
|
||||||
|
|
||||||
|
- Parser tests own parsing cases.
|
||||||
|
- Validator tests own validation rules.
|
||||||
|
- Domain tests own transformations and invariants.
|
||||||
|
- Adapter tests own external integration behavior.
|
||||||
|
- Orchestrator tests own coordination and failure propagation.
|
||||||
|
- CLI tests own argument and configuration mapping.
|
||||||
|
- End-to-end tests prove that representative assembled workflows work.
|
||||||
|
|
||||||
|
Give each layer its distinct responsibility and keep expectation updates localized to the contract being changed.
|
||||||
|
|
||||||
|
## Use test doubles deliberately
|
||||||
|
|
||||||
|
Choose the least elaborate test double that provides the required control or observation.
|
||||||
|
|
||||||
|
As a default:
|
||||||
|
|
||||||
|
1. Prefer real collaborators when they are fast and deterministic.
|
||||||
|
2. Use small in-memory fakes when realistic stateful behavior is helpful.
|
||||||
|
3. Use stubs when a dependency only needs to provide controlled responses.
|
||||||
|
4. Use mocks when the interaction itself is contractual.
|
||||||
|
|
||||||
|
Mocks are appropriate when the contract includes facts such as:
|
||||||
|
|
||||||
|
- a notification is sent exactly once;
|
||||||
|
- a transaction is committed only after successful writes;
|
||||||
|
- cancellation reaches a subprocess;
|
||||||
|
- an expensive API is called no more than once; or
|
||||||
|
- a security audit event is emitted.
|
||||||
|
|
||||||
|
## Go-specific guidance
|
||||||
|
|
||||||
|
Select techniques by behavior and risk:
|
||||||
|
|
||||||
|
- table-driven tests for meaningful behavioral categories and boundaries;
|
||||||
|
- `t.TempDir()` for real filesystem behavior;
|
||||||
|
- `httptest.Server` for realistic HTTP interactions;
|
||||||
|
- fuzz tests when exploring broad input spaces, such as parsers or path handling, adds useful protection beyond representative cases;
|
||||||
|
- golden files only when the complete output is intentionally stable;
|
||||||
|
- integration tests where correctness depends on component interaction; and
|
||||||
|
- a small number of representative end-to-end tests when assembled workflows expose meaningful risks not adequately covered at narrower boundaries.
|
||||||
|
|
||||||
|
Prefer `errors.Is`, `errors.As`, typed errors, or structured error fields. Use exact error-wording assertions only when the wording is contractual.
|
||||||
|
|
||||||
|
At CLI boundaries, prefer exit classifications, structured output, and the smallest stable semantic fragment needed to identify the error. Use complete diagnostic snapshots only when the wording is contractual.
|
||||||
|
|
||||||
|
Golden-file updates must require an explicit local flag. CI must not update golden files automatically, and reviewers must inspect the semantic diff before accepting an update.
|
||||||
|
|
||||||
|
Keep tests readable and direct. Size test helpers and fixture frameworks to the maintenance benefit they provide.
|
||||||
|
|
||||||
|
## Coverage
|
||||||
|
|
||||||
|
Use coverage to locate untested critical branches and unexpectedly weak packages. Evaluate test quality through meaningful behavioral protection and choose coverage according to risk.
|
||||||
|
|
||||||
|
Pure domain logic will often warrant higher coverage than CLI wiring or external adapters. Uneven coverage is acceptable when it reflects risk.
|
||||||
|
|
||||||
|
## Regression tests
|
||||||
|
|
||||||
|
A bug fix should normally include a regression test that fails before the fix and passes afterward.
|
||||||
|
|
||||||
|
Retain the test when the defect could realistically recur and its consequences justify the ongoing cost. Prefer the narrowest durable test of the violated contract or invariant.
|
||||||
|
|
||||||
|
Remove or consolidate a test when the underlying design has made recurrence impossible, its protection is redundant, or a stronger invariant test subsumes it.
|
||||||
|
|
||||||
|
## Deleting or rewriting tests
|
||||||
|
|
||||||
|
Delete or rewrite tests when maintenance cost exceeds their continuing
|
||||||
|
protective value.
|
||||||
|
|
||||||
|
Strong candidates include tests that:
|
||||||
|
|
||||||
|
- require updates after harmless internal changes;
|
||||||
|
- assert incidental private constants or snapshot large amounts of incidental output;
|
||||||
|
- verify mock choreography rather than outcomes;
|
||||||
|
- duplicate policy across layers, retest trivial helpers covered by package
|
||||||
|
behavior, or protect risks covered more effectively elsewhere;
|
||||||
|
- are flaky, misleading, obsolete, or disproportionately expensive to diagnose; or
|
||||||
|
- no longer correspond to a plausible failure mode.
|
||||||
|
|
||||||
|
Several brittle tests may encode one genuine requirement. Consolidate them into one durable behavior-level or invariant test.
|
||||||
|
|
||||||
|
## Reviewing a proposed test
|
||||||
|
|
||||||
|
Use the following questions when a proposed test needs closer evaluation. Significant test additions should be reviewable against them; written answers are optional for routine tests.
|
||||||
|
|
||||||
|
1. Which requested behavior or established contract does it protect, and what realistic defect would violate it?
|
||||||
|
2. How likely and consequential is that defect, and is it already protected elsewhere?
|
||||||
|
3. What is the narrowest stable boundary that can test it clearly?
|
||||||
|
4. Would a correct internal refactor or a change to an incidental default require test edits?
|
||||||
|
5. Does its confidence justify its maintenance, execution, and diagnostic cost, or would a smaller test suffice?
|
||||||
|
|
||||||
|
## Definition of sufficient
|
||||||
|
|
||||||
|
A test suite is sufficient when:
|
||||||
|
|
||||||
|
- important requested behavior and established contracts are protected against realistic, consequential failures;
|
||||||
|
- boundaries and component interactions have coverage where they introduce meaningful risks not protected elsewhere;
|
||||||
|
- failures provide useful, distinct signals;
|
||||||
|
- tests usually remain stable through legitimate internal changes; and
|
||||||
|
- additional tests would mostly repeat existing protection or preserve inconsequential implementation details.
|
||||||
|
|
||||||
|
Reassess sufficiency as the application, its users, and the consequences of
|
||||||
|
failure evolve.
|
||||||
134
docs/release.md
Normal file
134
docs/release.md
Normal file
@@ -0,0 +1,134 @@
|
|||||||
|
# ReleaseKit release procedure
|
||||||
|
|
||||||
|
ReleaseKit's deliverables are its source tag and a hosted Gitea page containing
|
||||||
|
the complete checked-in release note. The page is delivered asynchronously by
|
||||||
|
the prepared [Woodpecker workflow](../examples/woodpecker/releasekit-source-delivery.yml);
|
||||||
|
it is not a source-release completion check and carries no binary assets. The
|
||||||
|
authoritative repository is `origin` at
|
||||||
|
`https://gitea.maximumdirect.net/eric/ReleaseKit.git`, and the release branch
|
||||||
|
is `main`. A release completes when the intended annotated tag is successfully
|
||||||
|
pushed, or when one exact-object recovery query confirms that the push
|
||||||
|
succeeded. CI and consumer installation are not completion checks.
|
||||||
|
|
||||||
|
## Prepare a candidate
|
||||||
|
|
||||||
|
Use a local Go 1.25 toolchain and a clean clone. Start on `main`, choose an
|
||||||
|
unused stable `vMAJOR.MINOR.PATCH` version, and add
|
||||||
|
`docs/releases/<version>.md` with a first heading containing `ReleaseKit` and
|
||||||
|
the exact version. Summarize the change and any compatibility or upgrade impact.
|
||||||
|
End the note with the three license links at the immutable source tag:
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
[COPYRIGHT](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/vX.Y.Z/COPYRIGHT) |
|
||||||
|
[LICENSE](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/vX.Y.Z/LICENSE) |
|
||||||
|
[ATTRIBUTION](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/vX.Y.Z/docs/oss/attribution.md)
|
||||||
|
```
|
||||||
|
|
||||||
|
Replace every `vX.Y.Z` with the selected version. These are links to the same
|
||||||
|
release note's immutable source tree and also work when the note is used as a
|
||||||
|
hosted release body.
|
||||||
|
|
||||||
|
Commit the note and all candidate changes on `main`, then publish that commit
|
||||||
|
to `origin/main`:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
git push origin main
|
||||||
|
```
|
||||||
|
|
||||||
|
ReleaseKit checks that the worktree is clean, the candidate is on `main`, the
|
||||||
|
authoritative branch identifies that commit, and the version is unused locally
|
||||||
|
and on `origin`.
|
||||||
|
|
||||||
|
## Prepare dependencies, then publish
|
||||||
|
|
||||||
|
Dependency preparation is separate from the offline candidate validation. Run
|
||||||
|
it from the captured candidate source before the release command:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
GOTOOLCHAIN=local go mod download
|
||||||
|
```
|
||||||
|
|
||||||
|
Then run the single publication command from the repository root:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
./scripts/release vX.Y.Z
|
||||||
|
```
|
||||||
|
|
||||||
|
The command always runs the offline default test suite,
|
||||||
|
`go test -mod=readonly -count=1 ./...`, with toolchain and module network
|
||||||
|
access disabled. Any profile `checks` run afterward as additional product
|
||||||
|
checks; they should not repeat the standard suite. The command checks the
|
||||||
|
authoritative remote state, creates a local annotated tag from the captured
|
||||||
|
candidate and checked-in note, rechecks the tag and remote guards, and pushes
|
||||||
|
only that tag object. It prints the published version, commit, and tag object
|
||||||
|
on success. Exit status 0 means publication is confirmed; status 1 means a
|
||||||
|
known failure or conflict; status 2 means invalid input or profile; status 3
|
||||||
|
means the push outcome remains unknown and requires resolution.
|
||||||
|
|
||||||
|
The wrapper builds the native CLI into ignored `.releasekit/bin`, then invokes
|
||||||
|
it directly to preserve its exit status. The CLI comes from the source tree
|
||||||
|
being published, so this command also works
|
||||||
|
for ReleaseKit's first release before any released ReleaseKit executable
|
||||||
|
exists. It uses the local Go toolchain. Preparation must finish before the
|
||||||
|
offline validation begins.
|
||||||
|
|
||||||
|
## Resolve failures
|
||||||
|
|
||||||
|
A failed push triggers a URL-resolution check against the captured endpoint,
|
||||||
|
then at most one exact authoritative tag query. If the endpoint no longer
|
||||||
|
resolves to itself, recovery reports `unknown` without querying the rewritten
|
||||||
|
destination. An exact tag-object match confirms publication even when Git
|
||||||
|
reported an error. A proven absent tag is `not_published`; a different object
|
||||||
|
is a conflict; an unreadable query is `unknown`. The command retains its local
|
||||||
|
tag and reports the state, phase,
|
||||||
|
candidate commit, tag object, and captured publication endpoint when available.
|
||||||
|
Do not retry an unknown result until you resolve the authoritative ref at that
|
||||||
|
exact endpoint. Copy the reported endpoint value into the variable below using
|
||||||
|
normal shell quoting; retain the version and tag object from the same result.
|
||||||
|
The command checks that Git URL rewriting still resolves this value to itself;
|
||||||
|
the manual check below applies the same rule before querying:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
releasekit_endpoint='COPY_CAPTURED_ENDPOINT'
|
||||||
|
releasekit_version='vX.Y.Z'
|
||||||
|
test "$(git ls-remote --get-url -- "$releasekit_endpoint")" = "$releasekit_endpoint" &&
|
||||||
|
git ls-remote --refs -- "$releasekit_endpoint" "refs/tags/$releasekit_version"
|
||||||
|
```
|
||||||
|
|
||||||
|
A failed URL-equality check or remote query leaves the outcome unresolved.
|
||||||
|
Correct transport configuration before continuing. The reported endpoint may
|
||||||
|
be different from `origin`'s fetch URL or its current push URL; querying either
|
||||||
|
of those does not establish absence at the captured endpoint.
|
||||||
|
|
||||||
|
Compare the returned object ID with the tag object reported by the command.
|
||||||
|
An exact match confirms publication. If the ref is absent, the version was not
|
||||||
|
published; only then may you deliberately remove the unpublished local tag
|
||||||
|
with `git tag -d vX.Y.Z` before correcting the candidate or retrying. Do not
|
||||||
|
move, overwrite, or delete a tag that exists remotely. If a different object
|
||||||
|
uses the version, choose a new version after resolving the conflict.
|
||||||
|
|
||||||
|
If validation or a guard fails before this invocation pushes, correct and
|
||||||
|
commit the candidate, publish `main`, and run the command again. A retained
|
||||||
|
local tag still requires the authoritative-state check above before removal;
|
||||||
|
a concurrent publisher may already have published the version. The prepared
|
||||||
|
Woodpecker workflow builds the CLI from the tagged checkout, then uses
|
||||||
|
`ci-deliver` for page-only delivery. To activate it after configuring the
|
||||||
|
destination and secret, copy it to `.woodpecker/releasekit-source-delivery.yml`
|
||||||
|
and add the Woodpecker repository secret `releasekit_gitea_token`. If page
|
||||||
|
delivery fails or is uncertain, inspect the hosted release and retry the same
|
||||||
|
immutable version from its tag:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
git fetch origin "refs/tags/vX.Y.Z:refs/tags/vX.Y.Z"
|
||||||
|
git checkout --detach "vX.Y.Z"
|
||||||
|
mkdir -p .releasekit/bin
|
||||||
|
GOTOOLCHAIN=local GOPROXY=off GOSUMDB=off go build -o .releasekit/bin/releasekit ./cmd/releasekit
|
||||||
|
RELEASEKIT_GITEA_TOKEN="$GITEA_TOKEN" .releasekit/bin/releasekit deliver "vX.Y.Z"
|
||||||
|
```
|
||||||
|
|
||||||
|
The root ignore file excludes `.releasekit/`. Delivery uses the committed note
|
||||||
|
and does not build consumer binaries, create a checksum manifest, or require a
|
||||||
|
previously released ReleaseKit executable. Keep source publication and hosted
|
||||||
|
page delivery status separate; retry only after resolving an uncertain remote
|
||||||
|
write. The workflow secret is named `releasekit_gitea_token` and is mapped to
|
||||||
|
`RELEASEKIT_GITEA_TOKEN` only in the delivery step.
|
||||||
64
docs/releases/v0.1.0.md
Normal file
64
docs/releases/v0.1.0.md
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
# ReleaseKit v0.1.0
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
ReleaseKit's initial release provides an opinionated Go library and executable
|
||||||
|
for candidate validation, annotated source-tag publication, version injection,
|
||||||
|
selected-target builds, and Gitea release delivery.
|
||||||
|
|
||||||
|
The root `releasekit` facade owns release orchestration. The separate `buildinfo`
|
||||||
|
facade supplies lightweight runtime version access. Both belong to one Go module
|
||||||
|
with a Go 1.25.0 minimum language version.
|
||||||
|
|
||||||
|
## Capabilities
|
||||||
|
|
||||||
|
- Run the standard offline Go test suite once, followed by optional
|
||||||
|
product-specific checks and selected-target build verification.
|
||||||
|
- Publish the exact annotated tag for a validated candidate already on
|
||||||
|
authoritative `main`, with bounded recovery after failed or ambiguous pushes.
|
||||||
|
- Cross-build selected Go targets with shared version injection, artifact names,
|
||||||
|
digests, and a native version smoke check. Source-only projects select no
|
||||||
|
binary targets.
|
||||||
|
- Deliver committed release notes and declared assets to Gitea, preserving
|
||||||
|
existing content and reporting partial, conflicting, and uncertain outcomes.
|
||||||
|
- Use one managed build-and-deliver operation or supply retained prebuilt
|
||||||
|
artifacts for retries and separate build/delivery environments.
|
||||||
|
- Prepare tagged CI checkouts and dependencies through the shared `ci-deliver`
|
||||||
|
command and maintained Woodpecker workflow.
|
||||||
|
|
||||||
|
See the [CLI contract](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.1.0/docs/cli.md),
|
||||||
|
[configuration reference](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.1.0/docs/config.md),
|
||||||
|
[consumer delivery guide](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.1.0/docs/consumers/delivery.md),
|
||||||
|
and [runtime version guide](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.1.0/docs/consumers/runtime-version.md)
|
||||||
|
for supported behavior.
|
||||||
|
|
||||||
|
## Adoption and compatibility
|
||||||
|
|
||||||
|
Consumers can select this initial baseline with:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go get gitea.maximumdirect.net/eric/ReleaseKit@v0.1.0
|
||||||
|
go install gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit@v0.1.0
|
||||||
|
```
|
||||||
|
|
||||||
|
Profiles declare product identity, additional checks, selected binaries and
|
||||||
|
targets, and a Gitea destination. Applications obtain their embedded version
|
||||||
|
through `buildinfo.Version()`.
|
||||||
|
|
||||||
|
For consumers experimenting with earlier development revisions, rename the
|
||||||
|
`ReleaseRequest.Validate` callback to `AdditionalChecks` and remove repeated
|
||||||
|
standard-suite commands from profile `checks`. `DeliveryRequest.Build` now
|
||||||
|
accepts a `*BuildSpec` for managed builds; use `Prebuilt` for an existing
|
||||||
|
`BuildResult`.
|
||||||
|
|
||||||
|
Compatibility follows the [release policy](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.1.0/docs/policy/release.md): before
|
||||||
|
v1.0.0, minor releases may change documented contracts with migration guidance;
|
||||||
|
patch releases preserve contracts within their minor line.
|
||||||
|
|
||||||
|
ReleaseKit's deliverables are this immutable source tag and the hosted page
|
||||||
|
containing this complete note. Consumer migration and live Woodpecker deployment
|
||||||
|
remain adoption work tracked in the [product roadmap](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.1.0/docs/roadmap/releasekit.md).
|
||||||
|
|
||||||
|
[COPYRIGHT](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.1.0/COPYRIGHT) |
|
||||||
|
[LICENSE](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.1.0/LICENSE) |
|
||||||
|
[ATTRIBUTION](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.1.0/docs/oss/attribution.md)
|
||||||
261
docs/roadmap/releasekit.md
Normal file
261
docs/roadmap/releasekit.md
Normal file
@@ -0,0 +1,261 @@
|
|||||||
|
# ReleaseKit: shared release process
|
||||||
|
|
||||||
|
Status: Initial implementation, policy adoption, and architecture remediation
|
||||||
|
are complete. Consumer adoption and live CI integration work remain.
|
||||||
|
|
||||||
|
This roadmap records the shared release-process opportunity identified in
|
||||||
|
PromptKit, ConfigKit, Audita, Notarius, Narratio, and Scriptorium on 2026-09-29,
|
||||||
|
and the remaining adoption goals. The [internal package inventory](../internal/overview.md)
|
||||||
|
records implemented capability owners and behavioral evidence. The
|
||||||
|
[architecture policy](../policy/architecture.md) and
|
||||||
|
[ADR 0001](../adr/0001-public-facade.md) own the facade boundaries and rationale.
|
||||||
|
The completed implementation, policy adoption, and remediation plans are
|
||||||
|
preserved in Git history.
|
||||||
|
|
||||||
|
## Opportunity
|
||||||
|
|
||||||
|
All six repositories follow the same base release policy. Their release scripts
|
||||||
|
repeat stable-version parsing, candidate and release-note checks, local and
|
||||||
|
remote tag checks, validation of one captured commit, explicit Git publication,
|
||||||
|
and recovery guidance for uncertain pushes. They differ in publication approach,
|
||||||
|
tag type, validation commands, and artifact delivery. The mechanics of embedding
|
||||||
|
a release version and cross-building an application are further candidates for
|
||||||
|
standardization.
|
||||||
|
|
||||||
|
If the projects deliberately standardize publication approach and tag type,
|
||||||
|
ReleaseKit can own most of the repeated release-process code. The current six
|
||||||
|
repositories contain 942 lines of release shell scripts and 742 lines of
|
||||||
|
dedicated release tests, or 1,684 lines total. A directional estimate is that
|
||||||
|
roughly 1,000–1,250 lines could leave those repositories: about 450–500 lines
|
||||||
|
of publication scripts, 150–250 lines of checks and builders, and 400–500 lines
|
||||||
|
of repeated publication tests. ReleaseKit would gain its own implementation and
|
||||||
|
tests, so this is a reduction in local code, not a net line-count saving.
|
||||||
|
|
||||||
|
## Selected publication standard
|
||||||
|
|
||||||
|
1. Prepare and commit a version-matched note at `docs/releases/<version>.md`.
|
||||||
|
2. Publish the candidate commit to authoritative `main` before invoking the
|
||||||
|
release command.
|
||||||
|
3. Run one command that checks the candidate and unused stable version, runs
|
||||||
|
that repository's offline candidate validation once, and rechecks mutable
|
||||||
|
state.
|
||||||
|
4. Create an annotated tag at the validated commit with a message derived from
|
||||||
|
the checked-in note. Push only that exact tag object to the authoritative
|
||||||
|
endpoint. A successful tag push completes the source release.
|
||||||
|
5. Treat hosted release pages and binary assets as asynchronous delivery with
|
||||||
|
their own status. Do not poll CI or require artifact availability to declare
|
||||||
|
the source release complete.
|
||||||
|
|
||||||
|
This would replace Audita's atomic branch-and-tag push, ConfigKit's and
|
||||||
|
Notarius's branch push during the release command, and Audita's, Notarius's,
|
||||||
|
and Narratio's lightweight tags. Those changes require updates to each
|
||||||
|
repository's adopted release policy and procedure; they are not merely code
|
||||||
|
cleanup.
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
[ADR 0001](../adr/0001-public-facade.md) owns the accepted facade decision.
|
||||||
|
The [architecture policy](../policy/architecture.md) owns the adopted
|
||||||
|
responsibility and dependency rules, including the runtime version boundary.
|
||||||
|
The root `releasekit` package provides the public facade for candidate
|
||||||
|
validation, source publication, selected-target builds, and tagged-source
|
||||||
|
delivery. The Gitea page and asset-delivery client is integrated through that
|
||||||
|
facade and the CLI. The separate public `buildinfo` package provides lightweight
|
||||||
|
runtime version access.
|
||||||
|
|
||||||
|
Each facade owns its public named types and documented contracts. Public
|
||||||
|
operations, inputs, outcomes, errors, and callbacks express deliberately
|
||||||
|
selected consumer needs. Handles retain private implementation state; explicit
|
||||||
|
forwarding and conversions connect the public contracts to internal
|
||||||
|
representations.
|
||||||
|
|
||||||
|
Git operations, Go toolchain execution, Gitea integration, and orchestration
|
||||||
|
bookkeeping belong under Go's `internal/` boundary. Dependency direction runs
|
||||||
|
from the facades into internal implementation, with internal collaborators using
|
||||||
|
contracts defined inside that boundary. Implementation packages can evolve
|
||||||
|
while the supported public contracts retain their compatibility obligations.
|
||||||
|
|
||||||
|
The `buildinfo` facade keeps runtime version access lightweight. Applications
|
||||||
|
read their embedded version through its supported accessor. ReleaseKit's builder
|
||||||
|
and runtime implementation own the linker symbol and injection mechanism
|
||||||
|
together.
|
||||||
|
|
||||||
|
The `buildinfo` facade follows three constraints:
|
||||||
|
|
||||||
|
- Its public API exposes only runtime information justified by consumer needs.
|
||||||
|
- Its implementation uses the standard library and a small internal dependency
|
||||||
|
graph independent of release orchestration.
|
||||||
|
- Dependency checks protect that boundary, and build-and-run integration tests
|
||||||
|
verify that the builder injects the selected version and the public accessor
|
||||||
|
reports it correctly.
|
||||||
|
|
||||||
|
The release executable calls the orchestration facade and handles command
|
||||||
|
parsing, output, and exit codes. Library errors and outcomes report meaningful
|
||||||
|
publication state, including partial progress and uncertainty. Go declarations
|
||||||
|
and GoDoc own exact public API contracts; additional public packages and
|
||||||
|
extension interfaces require a deliberate decision grounded in durable consumer
|
||||||
|
needs.
|
||||||
|
|
||||||
|
Compiled-export and dependency checks protect facade ownership.
|
||||||
|
External-package behavioral tests protect error identity, value ownership,
|
||||||
|
callback lifetime, and observable outcomes across forwarding and conversions.
|
||||||
|
|
||||||
|
## Shared tool boundary
|
||||||
|
|
||||||
|
Provide a versioned ReleaseKit executable backed by a Go library. Existing
|
||||||
|
shell entry points can become short invocations of that executable. A library
|
||||||
|
alone would still require a caller in every shell-driven repository.
|
||||||
|
|
||||||
|
ReleaseKit should own:
|
||||||
|
|
||||||
|
- stable-version parsing and committed-note identity checks;
|
||||||
|
- authoritative Git endpoint resolution, candidate capture, clean `main` and
|
||||||
|
remote-branch agreement checks, and unused local/remote tag checks;
|
||||||
|
- one validation invocation bound to the captured candidate, followed by cheap
|
||||||
|
rechecks before publication;
|
||||||
|
- annotated-tag creation and verification, explicit tag-object push, and one
|
||||||
|
bounded authoritative-ref check after a failed or ambiguous push;
|
||||||
|
- a standard version accessor in the public `buildinfo` facade, backed by
|
||||||
|
release-build injection of the selected tag;
|
||||||
|
- a cross-build API that accepts the application's main package and selected
|
||||||
|
targets, initially Linux amd64, Linux arm64, and macOS arm64 (Go's
|
||||||
|
`darwin/arm64`), including an empty set for source-only projects;
|
||||||
|
- consistent release build flags and asset naming, plus a host-runnable build
|
||||||
|
that checks the executable's reported version; and
|
||||||
|
- Git publication tests using temporary local remotes, including remote
|
||||||
|
advancement, rejected pushes, lost acknowledgments, and unavailable remotes.
|
||||||
|
|
||||||
|
Each repository should retain its product name, compatibility decisions,
|
||||||
|
candidate-specific checks, main package, selected build targets, delivery
|
||||||
|
declaration, and a small test of its ReleaseKit wiring. For example, PromptKit
|
||||||
|
exercises its consumer examples. Applications would adapt their existing
|
||||||
|
version output to use the `buildinfo` accessor; one agreed version command
|
||||||
|
or flag would let ReleaseKit smoke-test a host-runnable build the same way.
|
||||||
|
Cross-built binaries would use the same injection mechanism, but compilation
|
||||||
|
alone would not establish that they run correctly on another platform.
|
||||||
|
ReleaseKit should run the selected checks and builds without silently adding
|
||||||
|
binary gates to source-only projects.
|
||||||
|
|
||||||
|
The build API should own the mechanics rather than require each application to
|
||||||
|
provide a custom linker symbol or shell loop. The initial target list reflects
|
||||||
|
the current projects, not a permanent limit on future platforms. It should
|
||||||
|
support both candidate cross-build checks and artifact builds from the tagged
|
||||||
|
source, using the same version and target selection.
|
||||||
|
|
||||||
|
## Woodpecker and Gitea delivery
|
||||||
|
|
||||||
|
A common tag-triggered Woodpecker workflow can run ReleaseKit against the
|
||||||
|
tagged source. Repository-local YAML should declare the pinned tool image and
|
||||||
|
credentials; each repository's ReleaseKit configuration should declare its
|
||||||
|
delivery destination and any binary main package and target set. ReleaseKit can
|
||||||
|
own version injection, cross-builds, checksum generation, and delivery. All
|
||||||
|
projects should receive hosted Gitea
|
||||||
|
release pages. Source-only repositories declare zero binary assets and deliver
|
||||||
|
the committed release note without a binary build or checksum manifest.
|
||||||
|
|
||||||
|
The shared delivery command should create or find the release for the tag,
|
||||||
|
use the checked-in note, and add declared binary assets and their checksum
|
||||||
|
manifest where applicable. A retry should inspect existing assets, verify
|
||||||
|
matching content, add only missing items, and stop on a conflict.
|
||||||
|
An existing checksum manifest must remain consistent with any later addition.
|
||||||
|
The release and its attachments are separate remote operations, so partial
|
||||||
|
delivery must be expected and reported clearly.
|
||||||
|
|
||||||
|
Audita, Narratio, and Scriptorium currently use the Woodpecker release plugin
|
||||||
|
with `file-exists: skip` and `overwrite: false`. Those settings avoid deliberate
|
||||||
|
replacement by filename, but they do not prove that a rebuilt file has the
|
||||||
|
same bytes as a previously published file. Content comparison would be a
|
||||||
|
reason to implement a shared Gitea delivery client rather than rely solely on
|
||||||
|
the plugin's skip behavior.
|
||||||
|
|
||||||
|
Hosted pages are selected for source-only projects, including PromptKit,
|
||||||
|
ConfigKit, Notarius, and ReleaseKit. Adoption adds a page deliverable and delivery
|
||||||
|
credentials to their procedures while preserving successful tag publication as
|
||||||
|
source completion. The initial implementation should support both page-only and
|
||||||
|
binary delivery through the same facade and command.
|
||||||
|
|
||||||
|
## Failure states
|
||||||
|
|
||||||
|
ReleaseKit should report source publication and artifact delivery separately:
|
||||||
|
|
||||||
|
| Event | Result |
|
||||||
|
| --- | --- |
|
||||||
|
| Candidate validation or a pre-push guard fails | No release was published; correct and validate the candidate again. |
|
||||||
|
| Tag push reports success | Source release is complete; delivery may still be pending. |
|
||||||
|
| Tag push fails or its acknowledgment is lost | Query the authoritative ref once. Confirm success only if the exact intended tag object is present on the intended commit; otherwise report failed or unknown status and retain the local tag. |
|
||||||
|
| Woodpecker or Gitea delivery fails after tag publication | Keep the source release successful. Retry missing delivery from the immutable tag after checking existing content. |
|
||||||
|
| Published source or content needs correction | Publish a new version; never replace content under the published version. |
|
||||||
|
|
||||||
|
## Consumer adoption target
|
||||||
|
|
||||||
|
All six projects should use the same selected publication, runtime version,
|
||||||
|
build, and delivery conventions where those responsibilities apply. Repository
|
||||||
|
entry points should contain only tool invocation and product-specific settings
|
||||||
|
or checks. Shared mechanics and their repeated tests belong in ReleaseKit.
|
||||||
|
|
||||||
|
Application runtime code should obtain version information through `buildinfo`.
|
||||||
|
Source-only libraries need no runtime import or automatic binary deliverable.
|
||||||
|
Projects declaring binaries should use the common target selection and version
|
||||||
|
injection; hosted delivery should use content-aware retries for both page-only
|
||||||
|
and binary releases.
|
||||||
|
Existing published tags, notes, pages, and assets retain their historical contents.
|
||||||
|
|
||||||
|
Consumer policy and procedure changes should describe the deliberately adopted
|
||||||
|
standard and its compatibility impact. Adoption should demonstrate reduced local
|
||||||
|
infrastructure and one coherent release model.
|
||||||
|
|
||||||
|
## Representative migration review
|
||||||
|
|
||||||
|
Read-only reviews of the available PromptKit and Narratio checkouts were
|
||||||
|
verified on 2026-10-06 at `4b8169d` and `8afb49c`; both worktrees were clean.
|
||||||
|
These are migration assessments, not changes to either consumer.
|
||||||
|
|
||||||
|
| Consumer | Retain in its profile and product checks | Adaptation and procedure changes |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| PromptKit, source-only | Product identity; its `Summary`, `Compatibility`, `Upgrade`, and `Changes` release-note sections; checks that exercise the three maintained Go examples and their product outputs. No runtime `buildinfo` import or binary targets are needed. | Its current release scripts total 209 lines. The projected deletion is about 120–160 lines of shared publication and generic validation machinery; retain the note-content rule and product-example checks as a configured additional check plus a small wiring test. PromptKit already pushes `main` before publication and creates annotated tags. Its release policy and procedure still need to add the hosted note page, delivery credentials, versioned CI invocation, and separate delivery status and recovery. |
|
||||||
|
| Narratio, binary | Product/module identity, the `./cmd/narratio` main package, `narratio` executable name, Linux amd64, Linux arm64, and macOS arm64 targets, and the `narratio <version>` command. Keep the module-graph check (`go mod tidy -diff`) if it remains useful as a product-specific candidate check. | Its release, check, asset-builder, and helper scripts total 304 lines; two dedicated release test files total 741 lines. Projected deletions are about 220–280 shell lines and 450–650 repeated test lines, leaving a small consumer wiring test and any retained module/note checks. Replace the private linker-version variable with `buildinfo.Version()` while preserving the current command output. Its policy and procedure need to change lightweight tags to annotated tags, state that a successful tag push completes source publication, and move plugin-based page/assets delivery to the shared versioned CI command with content-aware retries and separately provisioned delivery credentials. |
|
||||||
|
|
||||||
|
The deletion figures are estimates from the reviewed files, not measured
|
||||||
|
migration results or a promise that each line will disappear. Product checks,
|
||||||
|
version output, target choices, and at least one ReleaseKit integration check
|
||||||
|
remain with each consumer. The existing cross-project estimate of 1,000–1,250
|
||||||
|
potentially removable lines remains directional until migrations are completed.
|
||||||
|
The self-contained ReleaseKit fixtures exercise a meaningful source-only
|
||||||
|
compatibility check through local Git publication, and a `buildinfo` binary
|
||||||
|
consumer with selected targets through local HTTP delivery. These are separate
|
||||||
|
publication and delivery operations.
|
||||||
|
|
||||||
|
## Remaining work
|
||||||
|
|
||||||
|
- Use the [v0.1.0 baseline](../releases/v0.1.0.md) for initial consumer integration
|
||||||
|
under the [maintainer procedure](../release.md).
|
||||||
|
- Choose the broader consumer integration test plan and migration sequence.
|
||||||
|
Evaluate API clarity, product-specific checks, and the infrastructure removed
|
||||||
|
from each consuming repository.
|
||||||
|
- Provision delivery credentials and activate consumer Woodpecker workflows
|
||||||
|
using the maintained example's `v0.1.0` pin or a later selected immutable
|
||||||
|
version as part of deployment.
|
||||||
|
- Verify live Gitea delivery and Woodpecker execution. Existing verification uses
|
||||||
|
local Git and HTTP fixtures; no live deployment has been verified.
|
||||||
|
- Keep ReleaseKit executable binary distribution deferred until deliverables
|
||||||
|
are deliberately selected. Selecting binaries would require delivery
|
||||||
|
declarations, target checks, automation responsibilities, and corresponding
|
||||||
|
release policy and procedure updates.
|
||||||
|
- Evaluate a maintained ReleaseKit CI image or specialized validation/build
|
||||||
|
settings when a demonstrated consumer need justifies their maintenance cost
|
||||||
|
under [ADR 0002](../adr/0002-routine-releases.md).
|
||||||
|
|
||||||
|
## Reviewed implementations
|
||||||
|
|
||||||
|
- [PromptKit release script](../../../promptkit/scripts/release.sh),
|
||||||
|
[checker](../../../promptkit/scripts/release-check.sh)
|
||||||
|
- [ConfigKit release script](../../../ConfigKit/scripts/release.sh),
|
||||||
|
[checker](../../../ConfigKit/scripts/release-check.sh)
|
||||||
|
- [Audita release script](../../../audita/scripts/release.sh),
|
||||||
|
[Woodpecker job](../../../audita/.woodpecker/release.yml)
|
||||||
|
- [Notarius release script](../../../notarius/scripts/release.sh),
|
||||||
|
[checker](../../../notarius/scripts/check-release-source.sh)
|
||||||
|
- [Narratio release script](../../../narratio/scripts/release.sh),
|
||||||
|
[Woodpecker job](../../../narratio/.woodpecker/release.yml)
|
||||||
|
- [Scriptorium release script](../../../scriptorium/scripts/release.sh),
|
||||||
|
[Woodpecker job](../../../scriptorium/.woodpecker/release.yml)
|
||||||
15
examples/releasekit-binary.json
Normal file
15
examples/releasekit-binary.json
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"product": "Example",
|
||||||
|
"remote": "origin",
|
||||||
|
"build": {
|
||||||
|
"main_package": "./cmd/example",
|
||||||
|
"binary_name": "example",
|
||||||
|
"targets": ["linux/amd64", "linux/arm64", "darwin/arm64"]
|
||||||
|
},
|
||||||
|
"delivery": {
|
||||||
|
"base_url": "https://gitea.example",
|
||||||
|
"owner": "example",
|
||||||
|
"repository": "example",
|
||||||
|
"token_env": "RELEASEKIT_GITEA_TOKEN"
|
||||||
|
}
|
||||||
|
}
|
||||||
10
examples/releasekit.json
Normal file
10
examples/releasekit.json
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
{
|
||||||
|
"product": "Example",
|
||||||
|
"remote": "origin",
|
||||||
|
"delivery": {
|
||||||
|
"base_url": "https://gitea.example",
|
||||||
|
"owner": "example",
|
||||||
|
"repository": "example",
|
||||||
|
"token_env": "RELEASEKIT_GITEA_TOKEN"
|
||||||
|
}
|
||||||
|
}
|
||||||
29
examples/woodpecker/releasekit-source-delivery.yml
Normal file
29
examples/woodpecker/releasekit-source-delivery.yml
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
when:
|
||||||
|
- event: tag
|
||||||
|
ref: refs/tags/v*
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: build-tool
|
||||||
|
image: golang:1.25.0-bookworm
|
||||||
|
commands:
|
||||||
|
- |
|
||||||
|
test -n "$${CI_COMMIT_TAG}"
|
||||||
|
test -n "$${CI_COMMIT_SHA}"
|
||||||
|
git fetch origin "refs/tags/$${CI_COMMIT_TAG}:refs/tags/$${CI_COMMIT_TAG}"
|
||||||
|
test "$(git rev-parse "refs/tags/$${CI_COMMIT_TAG}^{commit}")" = "$${CI_COMMIT_SHA}"
|
||||||
|
git checkout --detach "$${CI_COMMIT_SHA}"
|
||||||
|
test "$(git rev-parse HEAD)" = "$${CI_COMMIT_SHA}"
|
||||||
|
mkdir -p "$${CI_WORKSPACE}/.releasekit/bin"
|
||||||
|
GOTOOLCHAIN=local GOPROXY=off GOSUMDB=off go build -o "$${CI_WORKSPACE}/.releasekit/bin/releasekit" ./cmd/releasekit
|
||||||
|
|
||||||
|
- name: deliver-page
|
||||||
|
image: golang:1.25.0-bookworm
|
||||||
|
environment:
|
||||||
|
RELEASEKIT_GITEA_TOKEN:
|
||||||
|
from_secret: releasekit_gitea_token
|
||||||
|
commands:
|
||||||
|
- |
|
||||||
|
"$${CI_WORKSPACE}/.releasekit/bin/releasekit" ci-deliver \
|
||||||
|
--repo "$${CI_WORKSPACE}" \
|
||||||
|
--commit "$${CI_COMMIT_SHA}" \
|
||||||
|
"$${CI_COMMIT_TAG}"
|
||||||
21
examples/woodpecker/tag-delivery.yml
Normal file
21
examples/woodpecker/tag-delivery.yml
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
- GO_IMAGE: golang:1.25.0-bookworm
|
||||||
|
RELEASEKIT_VERSION: v0.1.0
|
||||||
|
|
||||||
|
when:
|
||||||
|
- event: tag
|
||||||
|
ref: refs/tags/v*
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: deliver
|
||||||
|
image: ${GO_IMAGE}
|
||||||
|
environment:
|
||||||
|
RELEASEKIT_GITEA_TOKEN:
|
||||||
|
from_secret: releasekit_gitea_token
|
||||||
|
commands:
|
||||||
|
- |
|
||||||
|
go run gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit@${RELEASEKIT_VERSION} ci-deliver \
|
||||||
|
--repo "$${CI_WORKSPACE}" \
|
||||||
|
--commit "$${CI_COMMIT_SHA}" \
|
||||||
|
"$${CI_COMMIT_TAG}"
|
||||||
3
go.mod
Normal file
3
go.mod
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
module gitea.maximumdirect.net/eric/ReleaseKit
|
||||||
|
|
||||||
|
go 1.25.0
|
||||||
4
ideas.md
Normal file
4
ideas.md
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
# ReleaseKit ideas
|
||||||
|
|
||||||
|
The [product roadmap](docs/roadmap/releasekit.md) records shared release-process
|
||||||
|
adoption goals and remaining release and deployment work.
|
||||||
355
internal/apicheck/main.go
Normal file
355
internal/apicheck/main.go
Normal file
@@ -0,0 +1,355 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"go/importer"
|
||||||
|
"go/token"
|
||||||
|
"go/types"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
const modulePath = "gitea.maximumdirect.net/eric/ReleaseKit"
|
||||||
|
|
||||||
|
var facades = []string{modulePath, modulePath + "/buildinfo"}
|
||||||
|
|
||||||
|
type listedPackage struct {
|
||||||
|
ImportPath string
|
||||||
|
Export string
|
||||||
|
Standard bool
|
||||||
|
Imports []string
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
os.Exit(run(context.Background(), ".", os.Stdout, os.Stderr))
|
||||||
|
}
|
||||||
|
|
||||||
|
func run(ctx context.Context, dir string, stdout, stderr io.Writer) int {
|
||||||
|
if err := checkRepository(ctx, dir); err != nil {
|
||||||
|
fmt.Fprintln(stderr, err)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
fmt.Fprintln(stdout, "public API and dependency boundaries pass")
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkRepository(ctx context.Context, dir string) error {
|
||||||
|
packages, err := listPackages(ctx, dir)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := checkImportDirections(packages); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
lookup := make(map[string]string, len(packages))
|
||||||
|
for _, pkg := range packages {
|
||||||
|
if pkg.Export != "" {
|
||||||
|
lookup[pkg.ImportPath] = pkg.Export
|
||||||
|
}
|
||||||
|
}
|
||||||
|
apiImporter := importer.ForCompiler(token.NewFileSet(), "gc", func(path string) (io.ReadCloser, error) {
|
||||||
|
export, ok := lookup[path]
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("no compiled export data for %q", path)
|
||||||
|
}
|
||||||
|
return os.Open(export)
|
||||||
|
})
|
||||||
|
|
||||||
|
for _, path := range facades {
|
||||||
|
pkg, err := apiImporter.Import(path)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("load facade %s: %w", path, err)
|
||||||
|
}
|
||||||
|
if violations := checkExports(pkg); len(violations) != 0 {
|
||||||
|
return fmt.Errorf("facade %s has invalid public contracts:\n %s", path, strings.Join(violations, "\n "))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func listPackages(ctx context.Context, dir string) ([]listedPackage, error) {
|
||||||
|
cmd := exec.CommandContext(ctx, "go", "list", "-deps", "-export", "-json", "./...")
|
||||||
|
cmd.Dir = dir
|
||||||
|
output, err := cmd.Output()
|
||||||
|
if err != nil {
|
||||||
|
var exitErr *exec.ExitError
|
||||||
|
if errors.As(err, &exitErr) {
|
||||||
|
return nil, fmt.Errorf("go list -deps -export failed: %s", strings.TrimSpace(string(exitErr.Stderr)))
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("go list -deps -export: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
decoder := json.NewDecoder(strings.NewReader(string(output)))
|
||||||
|
var packages []listedPackage
|
||||||
|
for {
|
||||||
|
var pkg listedPackage
|
||||||
|
if err := decoder.Decode(&pkg); errors.Is(err, io.EOF) {
|
||||||
|
break
|
||||||
|
} else if err != nil {
|
||||||
|
return nil, fmt.Errorf("decode go list output: %w", err)
|
||||||
|
}
|
||||||
|
packages = append(packages, pkg)
|
||||||
|
}
|
||||||
|
return packages, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkImportDirections(packages []listedPackage) error {
|
||||||
|
byPath := make(map[string]listedPackage, len(packages))
|
||||||
|
for _, pkg := range packages {
|
||||||
|
byPath[pkg.ImportPath] = pkg
|
||||||
|
}
|
||||||
|
var violations []string
|
||||||
|
|
||||||
|
for _, pkg := range packages {
|
||||||
|
if !isInternalPackage(pkg.ImportPath) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, imported := range pkg.Imports {
|
||||||
|
commandDependency := strings.HasPrefix(imported, modulePath+"/cmd/")
|
||||||
|
owner := commandInternalRoot(pkg.ImportPath)
|
||||||
|
ownHelper := owner != "" && strings.HasPrefix(imported+"/", owner)
|
||||||
|
if imported == modulePath || imported == modulePath+"/buildinfo" || commandDependency && !ownHelper {
|
||||||
|
violations = append(violations, fmt.Sprintf("internal package %s imports public or command package %s", pkg.ImportPath, imported))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
seen := make(map[string]bool)
|
||||||
|
var visit func(string)
|
||||||
|
visit = func(path string) {
|
||||||
|
if seen[path] {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
seen[path] = true
|
||||||
|
pkg, ok := byPath[path]
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if path != modulePath+"/buildinfo" && !pkg.Standard {
|
||||||
|
if !strings.HasPrefix(path, modulePath+"/internal/") {
|
||||||
|
violations = append(violations, fmt.Sprintf("buildinfo depends on non-runtime package %s", path))
|
||||||
|
} else if forbiddenRuntimeDependency(path) {
|
||||||
|
violations = append(violations, fmt.Sprintf("buildinfo depends on excluded implementation package %s", path))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, imported := range pkg.Imports {
|
||||||
|
visit(imported)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
visit(modulePath + "/buildinfo")
|
||||||
|
|
||||||
|
if len(violations) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
sort.Strings(violations)
|
||||||
|
return errors.New(strings.Join(violations, "\n"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func isInternalPackage(path string) bool {
|
||||||
|
return strings.HasPrefix(path, modulePath+"/") &&
|
||||||
|
(strings.Contains(strings.TrimPrefix(path, modulePath), "/internal/") || strings.HasSuffix(path, "/internal"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// commandInternalRoot identifies the helper subtree owned by one executable.
|
||||||
|
func commandInternalRoot(path string) string {
|
||||||
|
if !strings.HasPrefix(path, modulePath+"/cmd/") {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
relative := strings.TrimPrefix(path, modulePath+"/cmd/")
|
||||||
|
owner, _, ok := strings.Cut(relative+"/", "/internal/")
|
||||||
|
if !ok {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return modulePath + "/cmd/" + owner + "/internal/"
|
||||||
|
}
|
||||||
|
|
||||||
|
func forbiddenRuntimeDependency(path string) bool {
|
||||||
|
for _, part := range strings.Split(strings.ToLower(path), "/") {
|
||||||
|
switch part {
|
||||||
|
case "orchestration", "orchestrator", "engine", "release", "process", "build", "builder", "gitea", "delivery", "cli":
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
var allowedExternalTypes = map[string]bool{
|
||||||
|
"context.Context": true,
|
||||||
|
"io.Reader": true,
|
||||||
|
"io.Writer": true,
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkExports(pkg *types.Package) []string {
|
||||||
|
checker := contractChecker{
|
||||||
|
packagePath: pkg.Path(),
|
||||||
|
checkedTypes: make(map[types.Type]bool),
|
||||||
|
allowedNamed: allowedExternalTypes,
|
||||||
|
violationsSet: make(map[string]bool),
|
||||||
|
}
|
||||||
|
for _, name := range pkg.Scope().Names() {
|
||||||
|
if !token.IsExported(name) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
object := pkg.Scope().Lookup(name)
|
||||||
|
switch obj := object.(type) {
|
||||||
|
case *types.TypeName:
|
||||||
|
checker.checkType(obj.Type(), name)
|
||||||
|
case *types.Func:
|
||||||
|
checker.checkType(obj.Type(), name)
|
||||||
|
case *types.Var:
|
||||||
|
checker.checkType(obj.Type(), name)
|
||||||
|
case *types.Const:
|
||||||
|
checker.checkType(obj.Type(), name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return checker.violations()
|
||||||
|
}
|
||||||
|
|
||||||
|
type contractChecker struct {
|
||||||
|
packagePath string
|
||||||
|
checkedTypes map[types.Type]bool
|
||||||
|
allowedNamed map[string]bool
|
||||||
|
violationsSet map[string]bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *contractChecker) violations() []string {
|
||||||
|
violations := make([]string, 0, len(c.violationsSet))
|
||||||
|
for violation := range c.violationsSet {
|
||||||
|
violations = append(violations, violation)
|
||||||
|
}
|
||||||
|
sort.Strings(violations)
|
||||||
|
return violations
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *contractChecker) violation(message string) {
|
||||||
|
c.violationsSet[message] = true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *contractChecker) checkType(typ types.Type, path string) {
|
||||||
|
if typ == nil || c.checkedTypes[typ] {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.checkedTypes[typ] = true
|
||||||
|
|
||||||
|
switch typ := typ.(type) {
|
||||||
|
case *types.Basic:
|
||||||
|
case *types.Alias:
|
||||||
|
if params := typ.TypeParams(); params != nil {
|
||||||
|
for i := 0; i < params.Len(); i++ {
|
||||||
|
c.checkType(params.At(i), path+" type parameter")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if args := typ.TypeArgs(); args != nil {
|
||||||
|
for i := 0; i < args.Len(); i++ {
|
||||||
|
c.checkType(args.At(i), path+" type argument")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c.checkType(types.Unalias(typ), path)
|
||||||
|
case *types.Named:
|
||||||
|
object := typ.Obj()
|
||||||
|
if object.Pkg() != nil && object.Pkg().Path() != c.packagePath {
|
||||||
|
key := object.Pkg().Path() + "." + object.Name()
|
||||||
|
if !c.allowedNamed[key] {
|
||||||
|
c.violation(fmt.Sprintf("%s exposes named type %s", path, key))
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if params := typ.TypeParams(); params != nil {
|
||||||
|
for i := 0; i < params.Len(); i++ {
|
||||||
|
c.checkType(params.At(i), path+" type parameter")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if args := typ.TypeArgs(); args != nil {
|
||||||
|
for i := 0; i < args.Len(); i++ {
|
||||||
|
c.checkType(args.At(i), path+" type argument")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c.checkType(typ.Underlying(), path)
|
||||||
|
for _, receiver := range []types.Type{typ, types.NewPointer(typ)} {
|
||||||
|
methodSet := types.NewMethodSet(receiver)
|
||||||
|
for i := 0; i < methodSet.Len(); i++ {
|
||||||
|
method := methodSet.At(i).Obj()
|
||||||
|
if !method.Exported() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
function, _ := method.(*types.Func)
|
||||||
|
if method.Pkg() != nil && method.Pkg().Path() != c.packagePath && !c.allowedMethod(function) {
|
||||||
|
c.violation(fmt.Sprintf("%s promotes method %s from %s", path, method.Name(), method.Pkg().Path()))
|
||||||
|
}
|
||||||
|
c.checkType(method.Type(), path+" method "+method.Name())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case *types.Pointer:
|
||||||
|
c.checkType(typ.Elem(), path)
|
||||||
|
case *types.Array:
|
||||||
|
c.checkType(typ.Elem(), path)
|
||||||
|
case *types.Slice:
|
||||||
|
c.checkType(typ.Elem(), path)
|
||||||
|
case *types.Map:
|
||||||
|
c.checkType(typ.Key(), path)
|
||||||
|
c.checkType(typ.Elem(), path)
|
||||||
|
case *types.Chan:
|
||||||
|
c.checkType(typ.Elem(), path)
|
||||||
|
case *types.Struct:
|
||||||
|
for i := 0; i < typ.NumFields(); i++ {
|
||||||
|
field := typ.Field(i)
|
||||||
|
if field.Exported() || field.Embedded() {
|
||||||
|
c.checkType(field.Type(), path+" field "+field.Name())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case *types.Interface:
|
||||||
|
typ.Complete()
|
||||||
|
for i := 0; i < typ.NumMethods(); i++ {
|
||||||
|
method := typ.Method(i)
|
||||||
|
if method.Pkg() != nil && method.Pkg().Path() != c.packagePath && !c.allowedMethod(method) {
|
||||||
|
c.violation(fmt.Sprintf("%s exposes method %s from %s", path, method.Name(), method.Pkg().Path()))
|
||||||
|
}
|
||||||
|
c.checkType(method.Type(), path+" method "+method.Name())
|
||||||
|
}
|
||||||
|
for i := 0; i < typ.NumEmbeddeds(); i++ {
|
||||||
|
c.checkType(typ.EmbeddedType(i), path+" embedded interface")
|
||||||
|
}
|
||||||
|
case *types.Signature:
|
||||||
|
if params := typ.TypeParams(); params != nil {
|
||||||
|
for i := 0; i < params.Len(); i++ {
|
||||||
|
c.checkType(params.At(i), path+" type parameter")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c.checkType(typ.Params(), path+" parameter")
|
||||||
|
c.checkType(typ.Results(), path+" result")
|
||||||
|
if typ.Variadic() && typ.Params().Len() != 0 {
|
||||||
|
c.checkType(typ.Params().At(typ.Params().Len()-1).Type(), path+" variadic parameter")
|
||||||
|
}
|
||||||
|
case *types.Tuple:
|
||||||
|
for i := 0; i < typ.Len(); i++ {
|
||||||
|
c.checkType(typ.At(i).Type(), path)
|
||||||
|
}
|
||||||
|
case *types.TypeParam:
|
||||||
|
c.checkType(typ.Constraint(), path+" constraint")
|
||||||
|
case *types.Union:
|
||||||
|
for i := 0; i < typ.Len(); i++ {
|
||||||
|
c.checkType(typ.Term(i).Type(), path+" constraint term")
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
c.violation(fmt.Sprintf("%s has uninspected type %T", path, typ))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *contractChecker) allowedMethod(method *types.Func) bool {
|
||||||
|
if method.Pkg() == nil {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
for typeName := range c.allowedNamed {
|
||||||
|
if strings.HasPrefix(typeName, method.Pkg().Path()+".") {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
208
internal/apicheck/main_test.go
Normal file
208
internal/apicheck/main_test.go
Normal file
@@ -0,0 +1,208 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"go/ast"
|
||||||
|
"go/importer"
|
||||||
|
"go/parser"
|
||||||
|
"go/token"
|
||||||
|
"go/types"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestExportedContractBoundaries(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
source string
|
||||||
|
wantError string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "leaked implementation type",
|
||||||
|
source: `package facade
|
||||||
|
import "example.com/implementation"
|
||||||
|
func New() *implementation.State { return nil }
|
||||||
|
`,
|
||||||
|
wantError: "exposes named type example.com/implementation.State",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "alias to implementation type",
|
||||||
|
source: `package facade
|
||||||
|
import "example.com/implementation"
|
||||||
|
type Alias = implementation.State
|
||||||
|
`,
|
||||||
|
wantError: "exposes named type example.com/implementation.State",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "callback leaks implementation type",
|
||||||
|
source: `package facade
|
||||||
|
import "example.com/implementation"
|
||||||
|
type Callback func() *implementation.State
|
||||||
|
`,
|
||||||
|
wantError: "exposes named type example.com/implementation.State",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "generic constraint leaks implementation type",
|
||||||
|
source: `package facade
|
||||||
|
import "example.com/implementation"
|
||||||
|
type Box[T interface{ Value() *implementation.State }] struct { value T }
|
||||||
|
`,
|
||||||
|
wantError: "exposes named type example.com/implementation.State",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "generic instantiation leaks implementation type",
|
||||||
|
source: `package facade
|
||||||
|
import "example.com/implementation"
|
||||||
|
type Box[T any] struct { value T }
|
||||||
|
func New() Box[implementation.State] { return Box[implementation.State]{} }
|
||||||
|
`,
|
||||||
|
wantError: "exposes named type example.com/implementation.State",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "promoted implementation method",
|
||||||
|
source: `package facade
|
||||||
|
import "example.com/implementation"
|
||||||
|
type state = implementation.State
|
||||||
|
type Handle struct { state }
|
||||||
|
`,
|
||||||
|
wantError: "promotes method Promoted from example.com/implementation",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "promoted pointer implementation method",
|
||||||
|
source: `package facade
|
||||||
|
import "example.com/implementation"
|
||||||
|
type state = implementation.State
|
||||||
|
type Handle struct { state }
|
||||||
|
`,
|
||||||
|
wantError: "promotes method PointerPromoted from example.com/implementation",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, test := range tests {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
violations := checkFixture(t, test.source)
|
||||||
|
if !strings.Contains(strings.Join(violations, "\n"), test.wantError) {
|
||||||
|
t.Fatalf("checkExports() = %v, want an error containing %q", violations, test.wantError)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPrivateImplementationFieldAndSelectedStandardTypes(t *testing.T) {
|
||||||
|
source := `package facade
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"example.com/implementation"
|
||||||
|
)
|
||||||
|
type Handle struct { state *implementation.State }
|
||||||
|
func Open(context.Context) *Handle { return nil }
|
||||||
|
`
|
||||||
|
if violations := checkFixture(t, source); len(violations) != 0 {
|
||||||
|
t.Fatalf("private implementation field and selected standard type were rejected: %v", violations)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestActualRepositoryBoundaries(t *testing.T) {
|
||||||
|
if err := checkRepository(t.Context(), "../.."); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInternalPackagesCannotImportPublicFacades(t *testing.T) {
|
||||||
|
packages := []listedPackage{
|
||||||
|
{ImportPath: modulePath + "/internal/operations", Imports: []string{modulePath}},
|
||||||
|
{ImportPath: modulePath + "/cmd/releasekit/internal/cli", Imports: []string{modulePath + "/buildinfo"}},
|
||||||
|
{ImportPath: modulePath},
|
||||||
|
{ImportPath: modulePath + "/buildinfo"},
|
||||||
|
}
|
||||||
|
err := checkImportDirections(packages)
|
||||||
|
if err == nil ||
|
||||||
|
!strings.Contains(err.Error(), "internal package "+modulePath+"/internal/operations imports public or command package "+modulePath) ||
|
||||||
|
!strings.Contains(err.Error(), "internal package "+modulePath+"/cmd/releasekit/internal/cli imports public or command package "+modulePath+"/buildinfo") {
|
||||||
|
t.Fatalf("checkImportDirections() error = %v, want internal-to-facade violation", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRuntimeFacadeCannotDependOnExternalPackages(t *testing.T) {
|
||||||
|
packages := []listedPackage{
|
||||||
|
{ImportPath: modulePath + "/buildinfo", Imports: []string{"example.com/runtime"}},
|
||||||
|
{ImportPath: "example.com/runtime"},
|
||||||
|
}
|
||||||
|
err := checkImportDirections(packages)
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "buildinfo depends on non-runtime package example.com/runtime") {
|
||||||
|
t.Fatalf("checkImportDirections() error = %v, want runtime dependency violation", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkFixture(t *testing.T, facadeSource string) []string {
|
||||||
|
t.Helper()
|
||||||
|
fset := token.NewFileSet()
|
||||||
|
implementation := typecheck(t, fset, "example.com/implementation", `package implementation
|
||||||
|
type State struct{}
|
||||||
|
func (State) Promoted() {}
|
||||||
|
func (*State) PointerPromoted() {}
|
||||||
|
`)
|
||||||
|
fixtureImporter := singlePackageImporter{path: "example.com/implementation", pkg: implementation}
|
||||||
|
facade := typecheckWithImporter(t, fset, "example.com/facade", facadeSource, fixtureImporter)
|
||||||
|
return checkExports(facade)
|
||||||
|
}
|
||||||
|
|
||||||
|
type singlePackageImporter struct {
|
||||||
|
path string
|
||||||
|
pkg *types.Package
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i singlePackageImporter) Import(path string) (*types.Package, error) {
|
||||||
|
if path == i.path {
|
||||||
|
return i.pkg, nil
|
||||||
|
}
|
||||||
|
return importer.Default().Import(path)
|
||||||
|
}
|
||||||
|
|
||||||
|
func typecheck(t *testing.T, fset *token.FileSet, path, source string) *types.Package {
|
||||||
|
t.Helper()
|
||||||
|
return typecheckWithImporter(t, fset, path, source, importer.Default())
|
||||||
|
}
|
||||||
|
|
||||||
|
func typecheckWithImporter(t *testing.T, fset *token.FileSet, path, source string, imports types.Importer) *types.Package {
|
||||||
|
t.Helper()
|
||||||
|
file, err := parser.ParseFile(fset, path+".go", source, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var errors []error
|
||||||
|
config := types.Config{
|
||||||
|
Importer: imports,
|
||||||
|
Error: func(err error) {
|
||||||
|
errors = append(errors, err)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
pkg, err := config.Check(path, fset, []*ast.File{file}, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("typecheck %s: %v (%v)", path, err, errors)
|
||||||
|
}
|
||||||
|
return pkg
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCommandInternalCompositionPreservesLibraryBoundaries(t *testing.T) {
|
||||||
|
for _, test := range []struct {
|
||||||
|
name, from, to string
|
||||||
|
reject bool
|
||||||
|
}{
|
||||||
|
{"command helpers", "/cmd/releasekit/internal/cli/parser", "/cmd/releasekit/internal/cli/settings", false},
|
||||||
|
{"other executable helpers", "/cmd/future/internal/parser", "/cmd/future/internal/settings", false},
|
||||||
|
{"helper root", "/cmd/releasekit/internal", "/cmd/releasekit/internal/cli", false},
|
||||||
|
{"controller uses facade", "/cmd/releasekit", "", false},
|
||||||
|
{"library imports controller", "/internal/build", "/cmd/releasekit", true},
|
||||||
|
{"library imports helper", "/internal/build", "/cmd/releasekit/internal/cli", true},
|
||||||
|
{"helper imports facade", "/cmd/releasekit/internal/cli", "", true},
|
||||||
|
{"helper imports runtime facade", "/cmd/releasekit/internal/cli", "/buildinfo", true},
|
||||||
|
{"helper imports controller", "/cmd/releasekit/internal/cli", "/cmd/releasekit", true},
|
||||||
|
} {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
err := checkImportDirections([]listedPackage{{ImportPath: modulePath + test.from, Imports: []string{modulePath + test.to}}})
|
||||||
|
if (err != nil) != test.reject {
|
||||||
|
t.Fatalf("dependency %s -> %s: %v", test.from, test.to, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
62
internal/artifact/artifact.go
Normal file
62
internal/artifact/artifact.go
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
// Package artifact owns shared build artifact identity rules.
|
||||||
|
package artifact
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
const ManifestFilename = "SHA256SUMS"
|
||||||
|
|
||||||
|
type Target struct {
|
||||||
|
OS string
|
||||||
|
Arch string
|
||||||
|
}
|
||||||
|
|
||||||
|
type Declaration struct {
|
||||||
|
Target Target
|
||||||
|
Filename string
|
||||||
|
}
|
||||||
|
|
||||||
|
// NormalizeTargets removes duplicate targets while preserving their first
|
||||||
|
// occurrence.
|
||||||
|
func NormalizeTargets(targets []Target) []Target {
|
||||||
|
seen := make(map[Target]struct{}, len(targets))
|
||||||
|
result := make([]Target, 0, len(targets))
|
||||||
|
for _, target := range targets {
|
||||||
|
if _, ok := seen[target]; ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[target] = struct{}{}
|
||||||
|
result = append(result, target)
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidComponent reports whether value is a nonempty filename component under
|
||||||
|
// the build and receipt contracts.
|
||||||
|
func ValidComponent(value string) bool {
|
||||||
|
return value != "" && !strings.ContainsAny(value, "/\\\r\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Filename returns the declared binary filename for one target.
|
||||||
|
func Filename(binaryName, version string, target Target) string {
|
||||||
|
filename := fmt.Sprintf("%s-%s-%s-%s", binaryName, version, target.OS, target.Arch)
|
||||||
|
if target.OS == "windows" {
|
||||||
|
filename += ".exe"
|
||||||
|
}
|
||||||
|
return filename
|
||||||
|
}
|
||||||
|
|
||||||
|
// ExpectedBuild returns artifact declarations in target order. Callers retain
|
||||||
|
// responsibility for validating their boundary-specific build identity.
|
||||||
|
func ExpectedBuild(binaryName, version string, targets []Target) []Declaration {
|
||||||
|
declarations := make([]Declaration, 0, len(targets))
|
||||||
|
for _, target := range targets {
|
||||||
|
declarations = append(declarations, Declaration{
|
||||||
|
Target: target,
|
||||||
|
Filename: Filename(binaryName, version, target),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return declarations
|
||||||
|
}
|
||||||
42
internal/artifact/artifact_test.go
Normal file
42
internal/artifact/artifact_test.go
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
package artifact
|
||||||
|
|
||||||
|
import (
|
||||||
|
"reflect"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestNormalizeTargetsPreservesOrderAndFirstOccurrence(t *testing.T) {
|
||||||
|
targets := []Target{
|
||||||
|
{OS: "linux", Arch: "amd64"},
|
||||||
|
{OS: "windows", Arch: "arm64"},
|
||||||
|
{OS: "linux", Arch: "amd64"},
|
||||||
|
}
|
||||||
|
want := []Target{{OS: "linux", Arch: "amd64"}, {OS: "windows", Arch: "arm64"}}
|
||||||
|
if got := NormalizeTargets(targets); !reflect.DeepEqual(got, want) {
|
||||||
|
t.Fatalf("NormalizeTargets() = %#v, want %#v", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExpectedBuildUsesSharedNamesInTargetOrder(t *testing.T) {
|
||||||
|
targets := []Target{{OS: "windows", Arch: "arm64"}, {OS: "linux", Arch: "amd64"}}
|
||||||
|
want := []Declaration{
|
||||||
|
{Target: targets[0], Filename: "app-v1.2.3-windows-arm64.exe"},
|
||||||
|
{Target: targets[1], Filename: "app-v1.2.3-linux-amd64"},
|
||||||
|
}
|
||||||
|
if got := ExpectedBuild("app", "v1.2.3", targets); !reflect.DeepEqual(got, want) {
|
||||||
|
t.Fatalf("ExpectedBuild() = %#v, want %#v", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidComponentPreservesBuildAndReceiptRules(t *testing.T) {
|
||||||
|
for _, value := range []string{"", "path/name", `path\name`, "line\nbreak", "line\rbreak"} {
|
||||||
|
if ValidComponent(value) {
|
||||||
|
t.Errorf("ValidComponent(%q) = true, want false", value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, value := range []string{"app", "..", "nul\x00byte"} {
|
||||||
|
if !ValidComponent(value) {
|
||||||
|
t.Errorf("ValidComponent(%q) = false, want true", value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
259
internal/build/build.go
Normal file
259
internal/build/build.go
Normal file
@@ -0,0 +1,259 @@
|
|||||||
|
// Package build compiles versioned application binaries for explicit targets.
|
||||||
|
package build
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/artifact"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/candidate"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/gotool"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/versioncontract"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Target = artifact.Target
|
||||||
|
|
||||||
|
type Spec struct {
|
||||||
|
MainPackage string
|
||||||
|
BinaryName string
|
||||||
|
Targets []Target
|
||||||
|
}
|
||||||
|
|
||||||
|
type Request struct {
|
||||||
|
RepositoryDir string
|
||||||
|
Version string
|
||||||
|
Spec Spec
|
||||||
|
OutputDir string
|
||||||
|
Output io.Writer
|
||||||
|
}
|
||||||
|
|
||||||
|
type Artifact struct {
|
||||||
|
Path string
|
||||||
|
Filename string
|
||||||
|
Target Target
|
||||||
|
SHA256 string
|
||||||
|
}
|
||||||
|
|
||||||
|
type Result struct {
|
||||||
|
RepositoryDir string
|
||||||
|
CandidateCommit string
|
||||||
|
SourceVerified bool
|
||||||
|
Version string
|
||||||
|
MainPackage string
|
||||||
|
BinaryName string
|
||||||
|
OutputDir string
|
||||||
|
Targets []Target
|
||||||
|
Artifacts []Artifact
|
||||||
|
Compiler string
|
||||||
|
}
|
||||||
|
|
||||||
|
func Build(ctx context.Context, request Request) (Result, error) {
|
||||||
|
result := Result{
|
||||||
|
Version: request.Version,
|
||||||
|
MainPackage: request.Spec.MainPackage,
|
||||||
|
BinaryName: request.Spec.BinaryName,
|
||||||
|
Targets: artifact.NormalizeTargets(request.Spec.Targets),
|
||||||
|
}
|
||||||
|
if !versioncontract.ValidStableVersion(request.Version) {
|
||||||
|
return result, fmt.Errorf("%w: %q", candidate.ErrInvalidVersion, request.Version)
|
||||||
|
}
|
||||||
|
if request.RepositoryDir == "" {
|
||||||
|
return result, errors.New("build requires a repository directory")
|
||||||
|
}
|
||||||
|
if len(result.Targets) != 0 {
|
||||||
|
if request.Spec.MainPackage == "" {
|
||||||
|
return result, errors.New("build requires a main package when targets are selected")
|
||||||
|
}
|
||||||
|
if !artifact.ValidComponent(request.Spec.BinaryName) {
|
||||||
|
return result, fmt.Errorf("unsafe binary name %q", request.Spec.BinaryName)
|
||||||
|
}
|
||||||
|
for _, target := range result.Targets {
|
||||||
|
if !artifact.ValidComponent(target.OS) || !artifact.ValidComponent(target.Arch) {
|
||||||
|
return result, fmt.Errorf("unsafe target %q/%q", target.OS, target.Arch)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return result, fmt.Errorf("build canceled: %w", err)
|
||||||
|
}
|
||||||
|
repositoryDir, err := filepath.Abs(request.RepositoryDir)
|
||||||
|
if err != nil {
|
||||||
|
return result, fmt.Errorf("resolve repository directory: %w", err)
|
||||||
|
}
|
||||||
|
result.RepositoryDir = repositoryDir
|
||||||
|
commit, err := gitCommit(ctx, repositoryDir)
|
||||||
|
if err != nil {
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
result.CandidateCommit = commit
|
||||||
|
cleanBefore, err := cleanSource(ctx, repositoryDir)
|
||||||
|
if err != nil {
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(result.Targets) == 0 {
|
||||||
|
result.OutputDir = resolvedOutputDir(repositoryDir, request.OutputDir)
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
result.OutputDir = resolvedOutputDir(repositoryDir, request.OutputDir)
|
||||||
|
declarations := artifact.ExpectedBuild(request.Spec.BinaryName, request.Version, result.Targets)
|
||||||
|
filenames := make([]string, len(declarations))
|
||||||
|
for i, declaration := range declarations {
|
||||||
|
filenames[i] = declaration.Filename
|
||||||
|
}
|
||||||
|
if err := os.MkdirAll(result.OutputDir, 0o755); err != nil {
|
||||||
|
return result, fmt.Errorf("create build output directory %q: %w", result.OutputDir, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
goTool, err := gotool.New(ctx, repositoryDir)
|
||||||
|
if err != nil {
|
||||||
|
return result, fmt.Errorf("prepare Go toolchain: %w", err)
|
||||||
|
}
|
||||||
|
compiler, err := goTool.Run(ctx, repositoryDir, gotool.Native, gotool.Target{}, nil, "version")
|
||||||
|
if err != nil {
|
||||||
|
return result, fmt.Errorf("identify Go compiler: %w", err)
|
||||||
|
}
|
||||||
|
result.Compiler = strings.TrimSpace(string(compiler))
|
||||||
|
goHost := goTool.HostTarget()
|
||||||
|
host := Target{OS: goHost.OS, Arch: goHost.Arch}
|
||||||
|
|
||||||
|
for index, target := range result.Targets {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return result, fmt.Errorf("build canceled: %w", err)
|
||||||
|
}
|
||||||
|
filename := filenames[index]
|
||||||
|
path := filepath.Join(result.OutputDir, filename)
|
||||||
|
if request.Output != nil {
|
||||||
|
fmt.Fprintf(request.Output, "building %s/%s as %s\n", target.OS, target.Arch, filename)
|
||||||
|
}
|
||||||
|
if err := buildTarget(ctx, goTool, repositoryDir, request.Spec.MainPackage, path, request.Version, target); err != nil {
|
||||||
|
return result, fmt.Errorf("build target %s/%s: %w", target.OS, target.Arch, err)
|
||||||
|
}
|
||||||
|
artifact := Artifact{Path: path, Filename: filename, Target: target}
|
||||||
|
result.Artifacts = append(result.Artifacts, artifact)
|
||||||
|
if err := hashArtifact(&result.Artifacts[len(result.Artifacts)-1]); err != nil {
|
||||||
|
return result, fmt.Errorf("hash build output %q: %w", path, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var smokePath string
|
||||||
|
for _, artifact := range result.Artifacts {
|
||||||
|
if artifact.Target == host {
|
||||||
|
smokePath = artifact.Path
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if smokePath == "" {
|
||||||
|
temporaryDir, err := os.MkdirTemp("", "releasekit-native-smoke-")
|
||||||
|
if err != nil {
|
||||||
|
return result, fmt.Errorf("create native smoke directory: %w", err)
|
||||||
|
}
|
||||||
|
defer os.RemoveAll(temporaryDir)
|
||||||
|
smokePath = filepath.Join(temporaryDir, request.Spec.BinaryName)
|
||||||
|
if host.OS == "windows" {
|
||||||
|
smokePath += ".exe"
|
||||||
|
}
|
||||||
|
if request.Output != nil {
|
||||||
|
fmt.Fprintf(request.Output, "building temporary version check for %s/%s\n", host.OS, host.Arch)
|
||||||
|
}
|
||||||
|
if err := buildTarget(ctx, goTool, repositoryDir, request.Spec.MainPackage, smokePath, request.Version, host); err != nil {
|
||||||
|
return result, fmt.Errorf("build native version check: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if request.Output != nil {
|
||||||
|
fmt.Fprintf(request.Output, "checking %s version output\n", request.Spec.BinaryName)
|
||||||
|
}
|
||||||
|
if err := checkVersion(ctx, smokePath, request.Spec.BinaryName, request.Version); err != nil {
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
commitAfter, err := gitCommit(ctx, repositoryDir)
|
||||||
|
if err != nil {
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
cleanAfter, err := cleanSource(ctx, repositoryDir)
|
||||||
|
if err != nil {
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
result.SourceVerified = cleanBefore && cleanAfter && commitAfter == commit
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func resolvedOutputDir(repositoryDir, outputDir string) string {
|
||||||
|
if outputDir == "" {
|
||||||
|
outputDir = filepath.Join(repositoryDir, "dist")
|
||||||
|
} else if !filepath.IsAbs(outputDir) {
|
||||||
|
outputDir = filepath.Join(repositoryDir, outputDir)
|
||||||
|
}
|
||||||
|
resolved, err := filepath.Abs(outputDir)
|
||||||
|
if err != nil {
|
||||||
|
return filepath.Clean(outputDir)
|
||||||
|
}
|
||||||
|
return resolved
|
||||||
|
}
|
||||||
|
|
||||||
|
func gitCommit(ctx context.Context, repositoryDir string) (string, error) {
|
||||||
|
command := exec.CommandContext(ctx, "git", "-C", repositoryDir, "rev-parse", "--verify", "HEAD^{commit}")
|
||||||
|
output, err := command.Output()
|
||||||
|
if err != nil {
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return "", fmt.Errorf("read source commit: %w", ctx.Err())
|
||||||
|
}
|
||||||
|
return "", fmt.Errorf("read source commit: %w", err)
|
||||||
|
}
|
||||||
|
return strings.TrimSpace(string(output)), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildTarget(ctx context.Context, goTool *gotool.Tool, repositoryDir, mainPackage, outputPath, version string, target Target) error {
|
||||||
|
ldflags := "-s -w -X " + versioncontract.InjectedVersionLinkerSymbol + "=" + version
|
||||||
|
_, err := goTool.Run(ctx, repositoryDir, gotool.Static, gotool.Target{OS: target.OS, Arch: target.Arch}, nil,
|
||||||
|
"build", "-o", outputPath, "-mod=readonly", "-trimpath", "-buildvcs=false", "-ldflags", ldflags, mainPackage)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func hashArtifact(artifact *Artifact) error {
|
||||||
|
file, err := os.Open(artifact.Path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
hash := sha256.New()
|
||||||
|
if _, err := io.Copy(hash, file); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
artifact.SHA256 = hex.EncodeToString(hash.Sum(nil))
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkVersion(ctx context.Context, binaryPath, binaryName, version string) error {
|
||||||
|
command := exec.CommandContext(ctx, binaryPath, "version")
|
||||||
|
output, err := command.CombinedOutput()
|
||||||
|
if err != nil {
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return fmt.Errorf("run native version check: %w", ctx.Err())
|
||||||
|
}
|
||||||
|
return fmt.Errorf("run native version check: %w: %s", err, strings.TrimSpace(string(output)))
|
||||||
|
}
|
||||||
|
want := binaryName + " " + version + "\n"
|
||||||
|
if string(output) != want {
|
||||||
|
return fmt.Errorf("native version output = %q, want %q", output, want)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func cleanSource(ctx context.Context, repositoryDir string) (bool, error) {
|
||||||
|
command := exec.CommandContext(ctx, "git", "-C", repositoryDir, "status", "--porcelain", "--untracked-files=all")
|
||||||
|
output, err := command.Output()
|
||||||
|
if err != nil {
|
||||||
|
return false, fmt.Errorf("inspect build source: %w", err)
|
||||||
|
}
|
||||||
|
return len(output) == 0, nil
|
||||||
|
}
|
||||||
37
internal/build/candidate.go
Normal file
37
internal/build/candidate.go
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
package build
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/candidate"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/tempdir"
|
||||||
|
)
|
||||||
|
|
||||||
|
func CandidateCallback(spec *Spec, output io.Writer) func(context.Context, candidate.Candidate) error {
|
||||||
|
if spec == nil || len(spec.Targets) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
selected := *spec
|
||||||
|
selected.Targets = append([]Target(nil), spec.Targets...)
|
||||||
|
return func(ctx context.Context, captured candidate.Candidate) error {
|
||||||
|
temporaryDir, err := tempdir.Outside(captured.RepositoryDir, "releasekit-candidate-build-")
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("create temporary candidate build output: %w", err)
|
||||||
|
}
|
||||||
|
defer os.RemoveAll(temporaryDir)
|
||||||
|
_, err = Build(ctx, Request{
|
||||||
|
RepositoryDir: captured.RepositoryDir,
|
||||||
|
Version: captured.Version,
|
||||||
|
Spec: selected,
|
||||||
|
OutputDir: temporaryDir,
|
||||||
|
Output: output,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("build candidate: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
270
internal/candidate/check.go
Normal file
270
internal/candidate/check.go
Normal file
@@ -0,0 +1,270 @@
|
|||||||
|
// Package candidate captures and validates a committed local release candidate.
|
||||||
|
package candidate
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/gotool"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/process"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/versioncontract"
|
||||||
|
)
|
||||||
|
|
||||||
|
var ErrInvalidVersion = errors.New("invalid stable version")
|
||||||
|
|
||||||
|
type Candidate struct {
|
||||||
|
RepositoryDir string
|
||||||
|
Commit string
|
||||||
|
Version string
|
||||||
|
Note string
|
||||||
|
}
|
||||||
|
|
||||||
|
type Request struct {
|
||||||
|
RepositoryDir string
|
||||||
|
Product string
|
||||||
|
Version string
|
||||||
|
AdditionalChecks func(context.Context, Candidate) error
|
||||||
|
AfterValidate func(context.Context, Candidate) error
|
||||||
|
Output io.Writer
|
||||||
|
}
|
||||||
|
|
||||||
|
func Check(ctx context.Context, request Request) (Candidate, error) {
|
||||||
|
captured, err := Capture(ctx, request)
|
||||||
|
if err != nil {
|
||||||
|
return Candidate{}, err
|
||||||
|
}
|
||||||
|
if err := Validate(ctx, request, captured); err != nil {
|
||||||
|
return Candidate{}, err
|
||||||
|
}
|
||||||
|
if request.AfterValidate != nil {
|
||||||
|
if err := request.AfterValidate(ctx, captured); err != nil {
|
||||||
|
return Candidate{}, fmt.Errorf("after candidate validation: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := Recheck(ctx, captured, ""); err != nil {
|
||||||
|
return Candidate{}, err
|
||||||
|
}
|
||||||
|
return captured, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Capture validates request identity and records one clean local candidate,
|
||||||
|
// including the note bytes from the captured commit. It does not run checks.
|
||||||
|
func Capture(ctx context.Context, request Request) (Candidate, error) {
|
||||||
|
if !validStableVersion(request.Version) {
|
||||||
|
return Candidate{}, fmt.Errorf("%w: %q", ErrInvalidVersion, request.Version)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(request.Product) == "" {
|
||||||
|
return Candidate{}, errors.New("product is required")
|
||||||
|
}
|
||||||
|
|
||||||
|
repositoryDir, err := filepath.Abs(request.RepositoryDir)
|
||||||
|
if err != nil {
|
||||||
|
return Candidate{}, fmt.Errorf("resolve repository directory: %w", err)
|
||||||
|
}
|
||||||
|
state, err := inspectLocalState(ctx, repositoryDir)
|
||||||
|
if err != nil {
|
||||||
|
return Candidate{}, err
|
||||||
|
}
|
||||||
|
if state.branch != "main" {
|
||||||
|
return Candidate{}, fmt.Errorf("release candidate must be on main; current branch is %q", state.branch)
|
||||||
|
}
|
||||||
|
if state.status != "" {
|
||||||
|
return Candidate{}, fmt.Errorf("release candidate worktree and index must be clean:\n%s", state.status)
|
||||||
|
}
|
||||||
|
|
||||||
|
path := "docs/releases/" + request.Version + ".md"
|
||||||
|
note, err := gitOutput(ctx, repositoryDir, "show", state.commit+":"+path)
|
||||||
|
if err != nil {
|
||||||
|
return Candidate{}, fmt.Errorf("read committed release note %q: %w", path, err)
|
||||||
|
}
|
||||||
|
if err := validateNote(note, request.Product, request.Version); err != nil {
|
||||||
|
return Candidate{}, fmt.Errorf("release note %q: %w", path, err)
|
||||||
|
}
|
||||||
|
if exists, err := hasLocalTag(ctx, repositoryDir, request.Version); err != nil {
|
||||||
|
return Candidate{}, fmt.Errorf("inspect local tag %q: %w", request.Version, err)
|
||||||
|
} else if exists {
|
||||||
|
return Candidate{}, fmt.Errorf("local tag %q already exists", request.Version)
|
||||||
|
}
|
||||||
|
|
||||||
|
return Candidate{RepositoryDir: repositoryDir, Commit: state.commit, Version: request.Version, Note: string(note)}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate runs the standard offline Go suite, followed by AdditionalChecks
|
||||||
|
// when supplied, for the captured candidate.
|
||||||
|
func Validate(ctx context.Context, request Request, captured Candidate) error {
|
||||||
|
if err := runDefaultValidation(ctx, captured.RepositoryDir, request.Output); err != nil {
|
||||||
|
return fmt.Errorf("validate candidate %s: %w", captured.Commit, err)
|
||||||
|
}
|
||||||
|
if request.AdditionalChecks != nil {
|
||||||
|
if err := request.AdditionalChecks(ctx, captured); err != nil {
|
||||||
|
return fmt.Errorf("validate candidate %s: %w", captured.Commit, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Recheck verifies that the captured local source is unchanged. When
|
||||||
|
// expectedTagObject is empty, the selected local version tag must still be
|
||||||
|
// absent; otherwise the existing annotated tag must still have that object ID.
|
||||||
|
func Recheck(ctx context.Context, captured Candidate, expectedTagObject string) error {
|
||||||
|
current, err := inspectLocalState(ctx, captured.RepositoryDir)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("recheck local candidate state: %w", err)
|
||||||
|
}
|
||||||
|
if current.branch != "main" {
|
||||||
|
return fmt.Errorf("release candidate branch changed to %q", current.branch)
|
||||||
|
}
|
||||||
|
if current.commit != captured.Commit {
|
||||||
|
return fmt.Errorf("HEAD changed from %s to %s", captured.Commit, current.commit)
|
||||||
|
}
|
||||||
|
if current.status != "" {
|
||||||
|
return fmt.Errorf("worktree or index changed:\n%s", current.status)
|
||||||
|
}
|
||||||
|
if expectedTagObject == "" {
|
||||||
|
if exists, err := hasLocalTag(ctx, captured.RepositoryDir, captured.Version); err != nil {
|
||||||
|
return fmt.Errorf("recheck local tag %q: %w", captured.Version, err)
|
||||||
|
} else if exists {
|
||||||
|
return fmt.Errorf("local tag %q appeared during validation", captured.Version)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
object, err := gitOutput(ctx, captured.RepositoryDir, "rev-parse", "--verify", "refs/tags/"+captured.Version)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("read local tag %q: %w", captured.Version, err)
|
||||||
|
}
|
||||||
|
tagType, err := gitOutput(ctx, captured.RepositoryDir, "cat-file", "-t", "refs/tags/"+captured.Version)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("inspect local tag %q: %w", captured.Version, err)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(string(object)) != expectedTagObject || strings.TrimSpace(string(tagType)) != "tag" {
|
||||||
|
return fmt.Errorf("local tag %q no longer identifies annotated tag object %s", captured.Version, expectedTagObject)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type localState struct {
|
||||||
|
branch string
|
||||||
|
commit string
|
||||||
|
status string
|
||||||
|
}
|
||||||
|
|
||||||
|
func inspectLocalState(ctx context.Context, repositoryDir string) (localState, error) {
|
||||||
|
branchOutput, err := gitOutput(ctx, repositoryDir, "branch", "--show-current")
|
||||||
|
if err != nil {
|
||||||
|
return localState{}, fmt.Errorf("inspect current branch: %w", err)
|
||||||
|
}
|
||||||
|
commitOutput, err := gitOutput(ctx, repositoryDir, "rev-parse", "--verify", "HEAD^{commit}")
|
||||||
|
if err != nil {
|
||||||
|
return localState{}, fmt.Errorf("capture HEAD commit: %w", err)
|
||||||
|
}
|
||||||
|
statusOutput, err := gitOutput(ctx, repositoryDir, "status", "--porcelain=v1", "--untracked-files=all")
|
||||||
|
if err != nil {
|
||||||
|
return localState{}, fmt.Errorf("inspect worktree and index: %w", err)
|
||||||
|
}
|
||||||
|
return localState{
|
||||||
|
branch: strings.TrimSpace(string(branchOutput)),
|
||||||
|
commit: strings.TrimSpace(string(commitOutput)),
|
||||||
|
status: strings.TrimSpace(string(statusOutput)),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func gitOutput(ctx context.Context, repositoryDir string, args ...string) ([]byte, error) {
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
commandArgs := append([]string{"git"}, args...)
|
||||||
|
err := process.Run(ctx, process.Invocation{
|
||||||
|
Args: commandArgs,
|
||||||
|
Dir: repositoryDir,
|
||||||
|
Stdout: &stdout,
|
||||||
|
Stderr: &stderr,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
message := strings.TrimSpace(stderr.String())
|
||||||
|
if message != "" {
|
||||||
|
return nil, fmt.Errorf("git %s: %s: %w", strings.Join(args, " "), message, err)
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("git %s: %w", strings.Join(args, " "), err)
|
||||||
|
}
|
||||||
|
return stdout.Bytes(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func hasLocalTag(ctx context.Context, repositoryDir, version string) (bool, error) {
|
||||||
|
var stderr bytes.Buffer
|
||||||
|
err := process.Run(ctx, process.Invocation{
|
||||||
|
Args: []string{"git", "show-ref", "--verify", "--quiet", "refs/tags/" + version},
|
||||||
|
Dir: repositoryDir,
|
||||||
|
Stderr: &stderr,
|
||||||
|
})
|
||||||
|
if err == nil {
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
var exitErr *exec.ExitError
|
||||||
|
if errors.As(err, &exitErr) && exitErr.ExitCode() == 1 {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
message := strings.TrimSpace(stderr.String())
|
||||||
|
if message != "" {
|
||||||
|
return false, fmt.Errorf("%s: %w", message, err)
|
||||||
|
}
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func runDefaultValidation(ctx context.Context, repositoryDir string, output io.Writer) error {
|
||||||
|
tool, err := gotool.New(ctx, repositoryDir)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("prepare Go toolchain: %w", err)
|
||||||
|
}
|
||||||
|
_, err = tool.Run(ctx, repositoryDir, gotool.Native, gotool.Target{}, output,
|
||||||
|
"test", "-mod=readonly", "-count=1", "./...")
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func validStableVersion(version string) bool {
|
||||||
|
return versioncontract.ValidStableVersion(version)
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateNote(note []byte, product, version string) error {
|
||||||
|
line := string(note)
|
||||||
|
if firstLine, _, ok := strings.Cut(line, "\n"); ok {
|
||||||
|
line = firstLine
|
||||||
|
}
|
||||||
|
line = strings.TrimSuffix(line, "\r")
|
||||||
|
if !strings.HasPrefix(line, "# ") {
|
||||||
|
return errors.New("first line must be a level-one Markdown heading")
|
||||||
|
}
|
||||||
|
elements := strings.Fields(strings.TrimPrefix(line, "# "))
|
||||||
|
productElements := strings.Fields(product)
|
||||||
|
if !containsSequence(elements, productElements) || !containsSequence(elements, []string{version}) {
|
||||||
|
return fmt.Errorf("first heading must contain product %q and exact version %q as title elements", product, version)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidateReleaseNote checks the title contract for a committed release note.
|
||||||
|
func ValidateReleaseNote(note []byte, product, version string) error {
|
||||||
|
return validateNote(note, product, version)
|
||||||
|
}
|
||||||
|
|
||||||
|
func containsSequence(elements, sequence []string) bool {
|
||||||
|
if len(sequence) == 0 || len(sequence) > len(elements) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for start := 0; start+len(sequence) <= len(elements); start++ {
|
||||||
|
match := true
|
||||||
|
for i, element := range sequence {
|
||||||
|
if elements[start+i] != element {
|
||||||
|
match = false
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if match {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
375
internal/candidate/check_test.go
Normal file
375
internal/candidate/check_test.go
Normal file
@@ -0,0 +1,375 @@
|
|||||||
|
package candidate
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
const testVersion = "v1.2.3"
|
||||||
|
|
||||||
|
func TestValidStableVersion(t *testing.T) {
|
||||||
|
for _, version := range []string{
|
||||||
|
"v0.0.0",
|
||||||
|
"v1.2.3",
|
||||||
|
"v123456789012345678901234567890.0.9",
|
||||||
|
} {
|
||||||
|
if !validStableVersion(version) {
|
||||||
|
t.Errorf("validStableVersion(%q) = false", version)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, version := range []string{
|
||||||
|
"",
|
||||||
|
"1.2.3",
|
||||||
|
"V1.2.3",
|
||||||
|
"v01.2.3",
|
||||||
|
"v1.02.3",
|
||||||
|
"v1.2.03",
|
||||||
|
"v1.2",
|
||||||
|
"v1.2.3-alpha",
|
||||||
|
"v1..3",
|
||||||
|
"v+1.2.3",
|
||||||
|
} {
|
||||||
|
if validStableVersion(version) {
|
||||||
|
t.Errorf("validStableVersion(%q) = true", version)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckCapturesCandidateAndCallsAdditionalChecksOnce(t *testing.T) {
|
||||||
|
repository := newRepository(t, "# Example Product v1.2.3\n\nRelease note.\n")
|
||||||
|
calls := 0
|
||||||
|
var seen Candidate
|
||||||
|
candidate, err := Check(context.Background(), Request{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Example Product",
|
||||||
|
Version: testVersion,
|
||||||
|
AdditionalChecks: func(_ context.Context, captured Candidate) error {
|
||||||
|
calls++
|
||||||
|
seen = captured
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
commit := gitOutputForTest(t, repository, "rev-parse", "HEAD")
|
||||||
|
if calls != 1 {
|
||||||
|
t.Fatalf("validation callback called %d times, want 1", calls)
|
||||||
|
}
|
||||||
|
if seen != candidate {
|
||||||
|
t.Fatalf("callback candidate = %#v, returned candidate = %#v", seen, candidate)
|
||||||
|
}
|
||||||
|
if candidate.RepositoryDir != repository || candidate.Commit != commit || candidate.Version != testVersion {
|
||||||
|
t.Fatalf("Check() candidate = %#v", candidate)
|
||||||
|
}
|
||||||
|
if tags := gitOutputForTest(t, repository, "tag", "--list"); tags != "" {
|
||||||
|
t.Fatalf("Check created local tags: %q", tags)
|
||||||
|
}
|
||||||
|
if refs := gitOutputForTest(t, repository, "for-each-ref", "--format=%(refname)", "refs/remotes"); refs != "" {
|
||||||
|
t.Fatalf("Check created remote-tracking refs: %q", refs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckRunsDefaultOfflineGoValidation(t *testing.T) {
|
||||||
|
repository := newRepository(t, "# Example Product v1.2.3\n\nRelease note.\n")
|
||||||
|
var output bytes.Buffer
|
||||||
|
_, err := Check(context.Background(), Request{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Example Product",
|
||||||
|
Version: testVersion,
|
||||||
|
Output: &output,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Check() with default validation: %v\n%s", err, output.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDefaultValidationDoesNotInheritGOFLAGSRunFilter(t *testing.T) {
|
||||||
|
repository := newRepository(t, "# Example Product v1.2.3\n\nRelease note.\n")
|
||||||
|
writeTestFile(t, repository, "failure_test.go", "package candidate\nimport \"testing\"\nfunc TestExpectedFailure(t *testing.T) { t.Fatal(\"expected fixture failure\") }\n")
|
||||||
|
gitRun(t, repository, "add", "failure_test.go")
|
||||||
|
gitRun(t, repository, "commit", "-m", "add failing validation fixture")
|
||||||
|
|
||||||
|
for _, source := range []string{"process environment", "Go environment file"} {
|
||||||
|
t.Run(source, func(t *testing.T) {
|
||||||
|
unsetCandidateEnv(t, "GOFLAGS", "GOOS", "GOARCH")
|
||||||
|
goEnv := filepath.Join(t.TempDir(), "go-env")
|
||||||
|
if source == "Go environment file" {
|
||||||
|
if err := os.WriteFile(goEnv, []byte("GOFLAGS=-run=^$\nGOOS=windows\nGOARCH=arm64\n"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if err := os.WriteFile(goEnv, nil, 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Setenv("GOFLAGS", "-run=^$")
|
||||||
|
t.Setenv("GOOS", "windows")
|
||||||
|
t.Setenv("GOARCH", "arm64")
|
||||||
|
}
|
||||||
|
t.Setenv("GOENV", goEnv)
|
||||||
|
var output bytes.Buffer
|
||||||
|
_, err := Check(context.Background(), Request{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Example Product",
|
||||||
|
Version: testVersion,
|
||||||
|
Output: &output,
|
||||||
|
})
|
||||||
|
if err == nil || !strings.Contains(output.String(), "TestExpectedFailure") {
|
||||||
|
t.Fatalf("Check() error = %v, output = %q; wanted the failing standard test to run", err, output.String())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func unsetCandidateEnv(t *testing.T, keys ...string) {
|
||||||
|
t.Helper()
|
||||||
|
for _, key := range keys {
|
||||||
|
value, exists := os.LookupEnv(key)
|
||||||
|
if err := os.Unsetenv(key); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() {
|
||||||
|
if exists {
|
||||||
|
_ = os.Setenv(key, value)
|
||||||
|
} else {
|
||||||
|
_ = os.Unsetenv(key)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckRejectsInvalidVersionsBeforeGitAccess(t *testing.T) {
|
||||||
|
for _, version := range []string{"v01.2.3", "v1.2.3-alpha", "1.2.3"} {
|
||||||
|
t.Run(version, func(t *testing.T) {
|
||||||
|
_, err := Check(context.Background(), Request{Version: version})
|
||||||
|
if !errors.Is(err, ErrInvalidVersion) {
|
||||||
|
t.Fatalf("Check() error = %v, want ErrInvalidVersion", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckRequiresMatchingCommittedNote(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
note string
|
||||||
|
}{
|
||||||
|
{name: "missing note"},
|
||||||
|
{name: "wrong product", note: "# Other Product v1.2.3\n"},
|
||||||
|
{name: "wrong version", note: "# Example Product v1.2.4\n"},
|
||||||
|
{name: "embedded product text", note: "# Example Products v1.2.3\n"},
|
||||||
|
{name: "not a level one heading", note: "## Example Product v1.2.3\n"},
|
||||||
|
}
|
||||||
|
for _, test := range tests {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
repository := newRepository(t, test.note)
|
||||||
|
called := false
|
||||||
|
_, err := Check(context.Background(), Request{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Example Product",
|
||||||
|
Version: testVersion,
|
||||||
|
AdditionalChecks: func(context.Context, Candidate) error {
|
||||||
|
called = true
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("Check() succeeded with an invalid committed note")
|
||||||
|
}
|
||||||
|
if called {
|
||||||
|
t.Fatal("validation ran before the committed note passed")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckRejectsDirtyTrackedAndUntrackedState(t *testing.T) {
|
||||||
|
for _, test := range []struct {
|
||||||
|
name string
|
||||||
|
path string
|
||||||
|
value string
|
||||||
|
}{
|
||||||
|
{name: "tracked", path: "tracked.txt", value: "changed\n"},
|
||||||
|
{name: "untracked", path: "new file.txt", value: "untracked\n"},
|
||||||
|
} {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
repository := newRepository(t, "# Example Product v1.2.3\n")
|
||||||
|
if err := os.WriteFile(filepath.Join(repository, test.path), []byte(test.value), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_, err := Check(context.Background(), validRequest(repository))
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "must be clean") {
|
||||||
|
t.Fatalf("Check() error = %v, want dirty state error", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckRequiresMainBranchAndUnusedTag(t *testing.T) {
|
||||||
|
t.Run("detached HEAD", func(t *testing.T) {
|
||||||
|
repository := newRepository(t, "# Example Product v1.2.3\n")
|
||||||
|
gitRun(t, repository, "checkout", "--detach", "HEAD")
|
||||||
|
_, err := Check(context.Background(), validRequest(repository))
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "must be on main") {
|
||||||
|
t.Fatalf("Check() error = %v, want branch error", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
t.Run("existing local tag", func(t *testing.T) {
|
||||||
|
repository := newRepository(t, "# Example Product v1.2.3\n")
|
||||||
|
gitRun(t, repository, "tag", testVersion)
|
||||||
|
_, err := Check(context.Background(), validRequest(repository))
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "already exists") {
|
||||||
|
t.Fatalf("Check() error = %v, want existing-tag error", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckStopsOnAdditionalCheckFailure(t *testing.T) {
|
||||||
|
repository := newRepository(t, "# Example Product v1.2.3\n")
|
||||||
|
want := errors.New("selected check failed")
|
||||||
|
calls := 0
|
||||||
|
_, err := Check(context.Background(), Request{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Example Product",
|
||||||
|
Version: testVersion,
|
||||||
|
AdditionalChecks: func(context.Context, Candidate) error {
|
||||||
|
calls++
|
||||||
|
return want
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if !errors.Is(err, want) {
|
||||||
|
t.Fatalf("Check() error = %v, want wrapped callback error", err)
|
||||||
|
}
|
||||||
|
if calls != 1 {
|
||||||
|
t.Fatalf("validation callback called %d times, want 1", calls)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckRechecksHeadAndWorktreeAfterCallback(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
validate func(*testing.T, string)
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "HEAD changes",
|
||||||
|
validate: func(t *testing.T, repository string) {
|
||||||
|
t.Helper()
|
||||||
|
if err := os.WriteFile(filepath.Join(repository, "later.txt"), []byte("later\n"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
gitRun(t, repository, "add", "later.txt")
|
||||||
|
gitRun(t, repository, "-c", "commit.gpgsign=false", "commit", "-m", "advance HEAD")
|
||||||
|
},
|
||||||
|
want: "HEAD changed from",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "worktree changes",
|
||||||
|
validate: func(t *testing.T, repository string) {
|
||||||
|
t.Helper()
|
||||||
|
if err := os.WriteFile(filepath.Join(repository, "later.txt"), []byte("later\n"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
want: "worktree or index changed",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, test := range tests {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
repository := newRepository(t, "# Example Product v1.2.3\n")
|
||||||
|
_, err := Check(context.Background(), Request{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Example Product",
|
||||||
|
Version: testVersion,
|
||||||
|
AdditionalChecks: func(context.Context, Candidate) error {
|
||||||
|
test.validate(t, repository)
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err == nil || !strings.Contains(err.Error(), test.want) {
|
||||||
|
t.Fatalf("Check() error = %v, want text %q", err, test.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckRechecksLocalTagAfterCallback(t *testing.T) {
|
||||||
|
repository := newRepository(t, "# Example Product v1.2.3\n")
|
||||||
|
_, err := Check(context.Background(), Request{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Example Product",
|
||||||
|
Version: testVersion,
|
||||||
|
AdditionalChecks: func(context.Context, Candidate) error {
|
||||||
|
gitRun(t, repository, "tag", testVersion)
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "appeared during validation") {
|
||||||
|
t.Fatalf("Check() error = %v, want tag recheck error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func validRequest(repository string) Request {
|
||||||
|
return Request{RepositoryDir: repository, Product: "Example Product", Version: testVersion, AdditionalChecks: func(context.Context, Candidate) error { return nil }}
|
||||||
|
}
|
||||||
|
|
||||||
|
func newRepository(t *testing.T, note string) string {
|
||||||
|
t.Helper()
|
||||||
|
repository := filepath.Join(t.TempDir(), "repository with spaces")
|
||||||
|
if err := os.Mkdir(repository, 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
gitRun(t, repository, "init", "--initial-branch=main")
|
||||||
|
gitRun(t, repository, "config", "user.name", "ReleaseKit Test")
|
||||||
|
gitRun(t, repository, "config", "user.email", "releasekit@example.test")
|
||||||
|
gitRun(t, repository, "config", "commit.gpgsign", "false")
|
||||||
|
writeTestFile(t, repository, "go.mod", "module example.com/candidate\n\ngo 1.25.0\n")
|
||||||
|
writeTestFile(t, repository, "candidate_test.go", "package candidate\nimport \"testing\"\nfunc TestFixture(t *testing.T) {}\n")
|
||||||
|
writeTestFile(t, repository, "tracked.txt", "tracked\n")
|
||||||
|
if note != "" {
|
||||||
|
writeTestFile(t, repository, "docs/releases/"+testVersion+".md", note)
|
||||||
|
}
|
||||||
|
gitRun(t, repository, "add", "--all")
|
||||||
|
gitRun(t, repository, "commit", "-m", "candidate")
|
||||||
|
return repository
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeTestFile(t *testing.T, repository, name, contents string) {
|
||||||
|
t.Helper()
|
||||||
|
path := filepath.Join(repository, filepath.FromSlash(name))
|
||||||
|
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func gitRun(t *testing.T, repository string, args ...string) {
|
||||||
|
t.Helper()
|
||||||
|
commandArgs := append([]string{"git"}, args...)
|
||||||
|
command := exec.Command(commandArgs[0], commandArgs[1:]...)
|
||||||
|
command.Dir = repository
|
||||||
|
output, err := command.CombinedOutput()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("%v: %v\n%s", commandArgs, err, output)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func gitOutputForTest(t *testing.T, repository string, args ...string) string {
|
||||||
|
t.Helper()
|
||||||
|
commandArgs := append([]string{"git"}, args...)
|
||||||
|
command := exec.Command(commandArgs[0], commandArgs[1:]...)
|
||||||
|
command.Dir = repository
|
||||||
|
output, err := command.Output()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("%v: %v", commandArgs, err)
|
||||||
|
}
|
||||||
|
return strings.TrimSpace(string(output))
|
||||||
|
}
|
||||||
87
internal/delivery/assets.go
Normal file
87
internal/delivery/assets.go
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
package delivery
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/artifact"
|
||||||
|
internalbuild "gitea.maximumdirect.net/eric/ReleaseKit/internal/build"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/gitea"
|
||||||
|
)
|
||||||
|
|
||||||
|
func declaredBuildAssets(result internalbuild.Result) ([]gitea.ExpectedAsset, error) {
|
||||||
|
if len(result.Targets) == 0 {
|
||||||
|
if len(result.Artifacts) != 0 {
|
||||||
|
return nil, fmt.Errorf("source-only build result contains artifacts")
|
||||||
|
}
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
if len(result.Artifacts) != len(result.Targets) {
|
||||||
|
return nil, fmt.Errorf("build result must contain one artifact for each selected target")
|
||||||
|
}
|
||||||
|
declarations := artifact.ExpectedBuild(result.BinaryName, result.Version, result.Targets)
|
||||||
|
wantByTarget := make(map[artifact.Target]string, len(declarations))
|
||||||
|
for _, declaration := range declarations {
|
||||||
|
target := declaration.Target
|
||||||
|
if !artifact.ValidComponent(target.OS) || !artifact.ValidComponent(target.Arch) {
|
||||||
|
return nil, fmt.Errorf("build result contains an invalid target")
|
||||||
|
}
|
||||||
|
if _, exists := wantByTarget[target]; exists {
|
||||||
|
return nil, fmt.Errorf("build result repeats target %q", target.OS+"/"+target.Arch)
|
||||||
|
}
|
||||||
|
wantByTarget[target] = declaration.Filename
|
||||||
|
}
|
||||||
|
assets := make([]gitea.ExpectedAsset, 0, len(result.Artifacts)+1)
|
||||||
|
seenTargets := make(map[artifact.Target]bool, len(result.Artifacts))
|
||||||
|
for _, artifact := range result.Artifacts {
|
||||||
|
wantName, ok := wantByTarget[artifact.Target]
|
||||||
|
if !ok || seenTargets[artifact.Target] || artifact.Filename != wantName {
|
||||||
|
return nil, fmt.Errorf("build artifact %q does not match a selected target and its declared name", artifact.Filename)
|
||||||
|
}
|
||||||
|
seenTargets[artifact.Target] = true
|
||||||
|
if filepath.Base(artifact.Path) != artifact.Filename {
|
||||||
|
return nil, fmt.Errorf("build artifact path %q does not end with filename %q", artifact.Path, artifact.Filename)
|
||||||
|
}
|
||||||
|
info, err := os.Stat(artifact.Path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("inspect build artifact %q: %w", artifact.Filename, err)
|
||||||
|
}
|
||||||
|
if !info.Mode().IsRegular() {
|
||||||
|
return nil, fmt.Errorf("build artifact %q is not a regular file", artifact.Filename)
|
||||||
|
}
|
||||||
|
file, err := os.Open(artifact.Path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("open build artifact %q: %w", artifact.Filename, err)
|
||||||
|
}
|
||||||
|
hash := sha256.New()
|
||||||
|
_, copyErr := io.Copy(hash, file)
|
||||||
|
closeErr := file.Close()
|
||||||
|
if copyErr != nil {
|
||||||
|
return nil, fmt.Errorf("hash build artifact %q: %w", artifact.Filename, copyErr)
|
||||||
|
}
|
||||||
|
if closeErr != nil {
|
||||||
|
return nil, fmt.Errorf("close build artifact %q: %w", artifact.Filename, closeErr)
|
||||||
|
}
|
||||||
|
if artifact.SHA256 != hex.EncodeToString(hash.Sum(nil)) {
|
||||||
|
return nil, fmt.Errorf("build artifact %q does not match its declared SHA-256 digest", artifact.Filename)
|
||||||
|
}
|
||||||
|
assets = append(assets, gitea.ExpectedAsset{
|
||||||
|
Filename: artifact.Filename,
|
||||||
|
SHA256: artifact.SHA256,
|
||||||
|
Size: info.Size(),
|
||||||
|
Path: artifact.Path,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
manifest, err := gitea.BuildManifest(assets)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("build checksum manifest: %w", err)
|
||||||
|
}
|
||||||
|
if manifest.Filename != "" {
|
||||||
|
assets = append(assets, manifest)
|
||||||
|
}
|
||||||
|
return assets, nil
|
||||||
|
}
|
||||||
91
internal/delivery/assets_test.go
Normal file
91
internal/delivery/assets_test.go
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
package delivery
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
internalbuild "gitea.maximumdirect.net/eric/ReleaseKit/internal/build"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/gitea"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestDeclaredBuildAssetsGenerateManifestFromBuildResult(t *testing.T) {
|
||||||
|
output := t.TempDir()
|
||||||
|
first := []byte("first artifact")
|
||||||
|
second := []byte("second artifact")
|
||||||
|
firstPath := filepath.Join(output, "app-v1.2.3-linux-amd64")
|
||||||
|
secondPath := filepath.Join(output, "app-v1.2.3-darwin-arm64")
|
||||||
|
if err := os.WriteFile(firstPath, first, 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(secondPath, second, 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
result, err := declaredBuildAssets(internalbuild.Result{
|
||||||
|
Version: "v1.2.3", BinaryName: "app",
|
||||||
|
Targets: []internalbuild.Target{{OS: "linux", Arch: "amd64"}, {OS: "darwin", Arch: "arm64"}},
|
||||||
|
Artifacts: []internalbuild.Artifact{
|
||||||
|
{Path: firstPath, Filename: filepath.Base(firstPath), Target: internalbuild.Target{OS: "linux", Arch: "amd64"}, SHA256: assetDigest(first)},
|
||||||
|
{Path: secondPath, Filename: filepath.Base(secondPath), Target: internalbuild.Target{OS: "darwin", Arch: "arm64"}, SHA256: assetDigest(second)},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(result) != 3 || result[0].Filename != filepath.Base(firstPath) || result[1].Filename != filepath.Base(secondPath) || result[2].Filename != gitea.ManifestFilename {
|
||||||
|
t.Fatalf("assets = %#v", result)
|
||||||
|
}
|
||||||
|
want := assetDigest(second) + " app-v1.2.3-darwin-arm64\n" + assetDigest(first) + " app-v1.2.3-linux-amd64\n"
|
||||||
|
if string(result[2].Content) != want {
|
||||||
|
t.Fatalf("manifest = %q, want %q", result[2].Content, want)
|
||||||
|
}
|
||||||
|
if result[0].Size != int64(len(first)) || result[1].Size != int64(len(second)) {
|
||||||
|
t.Fatalf("sizes = %d, %d", result[0].Size, result[1].Size)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeclaredBuildAssetsRejectsTamperedArtifact(t *testing.T) {
|
||||||
|
path := filepath.Join(t.TempDir(), "app-v1.2.3-linux-amd64")
|
||||||
|
if err := os.WriteFile(path, []byte("changed bytes"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_, err := declaredBuildAssets(internalbuild.Result{
|
||||||
|
Version: "v1.2.3", BinaryName: "app", Targets: []internalbuild.Target{{OS: "linux", Arch: "amd64"}},
|
||||||
|
Artifacts: []internalbuild.Artifact{{Path: path, Filename: filepath.Base(path), Target: internalbuild.Target{OS: "linux", Arch: "amd64"}, SHA256: assetDigest([]byte("original bytes"))}},
|
||||||
|
})
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "SHA-256") {
|
||||||
|
t.Fatalf("declaredBuildAssets() error = %v, want digest mismatch", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeclaredBuildAssetsRejectsArtifactDeclarationMismatch(t *testing.T) {
|
||||||
|
path := filepath.Join(t.TempDir(), "app-v1.2.3-linux-arm64")
|
||||||
|
contents := []byte("built application")
|
||||||
|
if err := os.WriteFile(path, contents, 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_, err := declaredBuildAssets(internalbuild.Result{
|
||||||
|
Version: "v1.2.3", BinaryName: "app", Targets: []internalbuild.Target{{OS: "linux", Arch: "amd64"}},
|
||||||
|
Artifacts: []internalbuild.Artifact{{
|
||||||
|
Path: path, Filename: filepath.Base(path), Target: internalbuild.Target{OS: "linux", Arch: "amd64"}, SHA256: assetDigest(contents),
|
||||||
|
}},
|
||||||
|
})
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "does not match a selected target") {
|
||||||
|
t.Fatalf("declaredBuildAssets() error = %v, want declaration mismatch", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeclaredBuildAssetsKeepsSourceOnlyBuildManifestFree(t *testing.T) {
|
||||||
|
assets, err := declaredBuildAssets(internalbuild.Result{})
|
||||||
|
if err != nil || len(assets) != 0 {
|
||||||
|
t.Fatalf("assets = %#v, error = %v", assets, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func assetDigest(content []byte) string {
|
||||||
|
sum := sha256.Sum256(content)
|
||||||
|
return hex.EncodeToString(sum[:])
|
||||||
|
}
|
||||||
221
internal/delivery/delivery.go
Normal file
221
internal/delivery/delivery.go
Normal file
@@ -0,0 +1,221 @@
|
|||||||
|
package delivery
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
internalbuild "gitea.maximumdirect.net/eric/ReleaseKit/internal/build"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/candidate"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/git"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/gitea"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/tempdir"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/versioncontract"
|
||||||
|
)
|
||||||
|
|
||||||
|
type State string
|
||||||
|
|
||||||
|
const (
|
||||||
|
NotAttempted State = "not_attempted"
|
||||||
|
Complete State = "complete"
|
||||||
|
Partial State = "partial"
|
||||||
|
Conflict State = "conflict"
|
||||||
|
Unknown State = "unknown"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Request struct {
|
||||||
|
RepositoryDir string
|
||||||
|
Product string
|
||||||
|
Version string
|
||||||
|
Destination gitea.Destination
|
||||||
|
Build *internalbuild.Spec
|
||||||
|
Prebuilt *internalbuild.Result
|
||||||
|
Output io.Writer
|
||||||
|
}
|
||||||
|
|
||||||
|
type Result struct {
|
||||||
|
CandidateCommit string
|
||||||
|
ReleaseURL string
|
||||||
|
State State
|
||||||
|
Matching []gitea.AssetIdentity
|
||||||
|
Uploaded []gitea.AssetIdentity
|
||||||
|
Pending []gitea.AssetIdentity
|
||||||
|
Conflicting []gitea.AssetIdentity
|
||||||
|
Uncertain []gitea.AssetIdentity
|
||||||
|
}
|
||||||
|
|
||||||
|
func Deliver(ctx context.Context, request Request) (Result, error) {
|
||||||
|
result := Result{State: NotAttempted}
|
||||||
|
if !versioncontract.ValidStableVersion(request.Version) {
|
||||||
|
return result, candidate.ErrInvalidVersion
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(request.Product) == "" {
|
||||||
|
return result, errors.New("product is required")
|
||||||
|
}
|
||||||
|
if request.Build != nil && request.Prebuilt != nil {
|
||||||
|
return result, errors.New("delivery cannot use both a managed build and prebuilt artifacts")
|
||||||
|
}
|
||||||
|
repositoryDir, err := filepath.Abs(request.RepositoryDir)
|
||||||
|
if err != nil {
|
||||||
|
return result, fmt.Errorf("resolve repository directory: %w", err)
|
||||||
|
}
|
||||||
|
source, err := git.InspectTaggedSource(ctx, repositoryDir, request.Version)
|
||||||
|
if err != nil {
|
||||||
|
return result, fmt.Errorf("inspect tagged source: %w", err)
|
||||||
|
}
|
||||||
|
result.CandidateCommit = source.TagCommit
|
||||||
|
if source.Status != "" {
|
||||||
|
return result, fmt.Errorf("tagged checkout must be clean:\n%s", source.Status)
|
||||||
|
}
|
||||||
|
if source.Head != source.TagCommit {
|
||||||
|
return result, fmt.Errorf("checkout HEAD %s does not match tag %s commit %s", source.Head, request.Version, source.TagCommit)
|
||||||
|
}
|
||||||
|
notePath := "docs/releases/" + request.Version + ".md"
|
||||||
|
note, err := git.ReadCommitFile(ctx, repositoryDir, source.TagCommit, notePath)
|
||||||
|
if err != nil {
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
if err := candidate.ValidateReleaseNote(note, request.Product, request.Version); err != nil {
|
||||||
|
return result, fmt.Errorf("release note %q: %w", notePath, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
build := request.Prebuilt
|
||||||
|
if request.Build != nil && len(request.Build.Targets) != 0 {
|
||||||
|
temporaryDir, err := tempdir.Outside(repositoryDir, "releasekit-delivery-build-*")
|
||||||
|
if err != nil {
|
||||||
|
return result, fmt.Errorf("create temporary delivery build directory: %w", err)
|
||||||
|
}
|
||||||
|
defer os.RemoveAll(temporaryDir)
|
||||||
|
built, err := internalbuild.Build(ctx, internalbuild.Request{
|
||||||
|
RepositoryDir: repositoryDir,
|
||||||
|
Version: request.Version,
|
||||||
|
Spec: *request.Build,
|
||||||
|
OutputDir: filepath.Join(temporaryDir, "assets"),
|
||||||
|
Output: request.Output,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return result, fmt.Errorf("build delivery assets: %w", err)
|
||||||
|
}
|
||||||
|
build = &built
|
||||||
|
}
|
||||||
|
var assets []gitea.ExpectedAsset
|
||||||
|
if build != nil {
|
||||||
|
assets, err = declaredBuildAssets(*build)
|
||||||
|
if err != nil {
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := validateBuild(repositoryDir, source.TagCommit, request.Version, build, assets); err != nil {
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
if len(assets) > 0 {
|
||||||
|
if err := gitea.VerifyLocalAssets(assets); err != nil {
|
||||||
|
return result, fmt.Errorf("verify build assets: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if build != nil && len(build.Targets) != 0 {
|
||||||
|
current, err := git.InspectTaggedSource(ctx, repositoryDir, request.Version)
|
||||||
|
if err != nil {
|
||||||
|
return result, fmt.Errorf("recheck tagged source after build: %w", err)
|
||||||
|
}
|
||||||
|
if current.Status != "" {
|
||||||
|
return result, fmt.Errorf("tagged checkout changed during build:\n%s", current.Status)
|
||||||
|
}
|
||||||
|
if current.Head != source.TagCommit || current.TagCommit != source.TagCommit {
|
||||||
|
return result, errors.New("tagged source changed during build")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
releaseResult, err := (gitea.Client{}).EnsureRelease(ctx, gitea.Request{
|
||||||
|
Destination: request.Destination,
|
||||||
|
Version: request.Version,
|
||||||
|
Commit: source.TagCommit,
|
||||||
|
Note: string(note),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
result.State = stateForError(err, false)
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
result.ReleaseURL = releaseResult.Release.URL
|
||||||
|
if len(assets) == 0 {
|
||||||
|
result.State = Complete
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
inspection, err := (gitea.Client{}).InspectAssets(ctx, request.Destination, releaseResult.Release.ID, assets)
|
||||||
|
if err != nil {
|
||||||
|
result.State = NotAttempted
|
||||||
|
if releaseResult.WriteAttempted {
|
||||||
|
result.State = Partial
|
||||||
|
}
|
||||||
|
result.Uncertain = assetIdentities(assets)
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
uploadResult, uploadErr := (gitea.Client{}).UploadMissing(ctx, request.Destination, releaseResult.Release.ID, inspection)
|
||||||
|
result.Matching = uploadResult.Matching
|
||||||
|
result.Uploaded = uploadResult.Uploaded
|
||||||
|
result.Pending = uploadResult.Pending
|
||||||
|
result.Conflicting = uploadResult.Conflicting
|
||||||
|
result.Uncertain = uploadResult.Uncertain
|
||||||
|
result.State = State(uploadResult.State)
|
||||||
|
if result.State == NotAttempted && releaseResult.WriteAttempted {
|
||||||
|
result.State = Partial
|
||||||
|
}
|
||||||
|
return result, uploadErr
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateBuild(repositoryDir, commit, version string, build *internalbuild.Result, assets []gitea.ExpectedAsset) error {
|
||||||
|
if build == nil {
|
||||||
|
if len(assets) != 0 {
|
||||||
|
return errors.New("assets require a build identity")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if len(build.Targets) == 0 {
|
||||||
|
if len(assets) != 0 {
|
||||||
|
return errors.New("page-only delivery cannot include binary assets")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if !build.SourceVerified {
|
||||||
|
return errors.New("build source was not verified as clean and unchanged during compilation")
|
||||||
|
}
|
||||||
|
buildRepository, err := filepath.Abs(build.RepositoryDir)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("resolve build repository: %w", err)
|
||||||
|
}
|
||||||
|
if buildRepository != repositoryDir || build.CandidateCommit != commit || build.Version != version {
|
||||||
|
return errors.New("build result does not identify the selected tagged source")
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(build.MainPackage) == "" || strings.TrimSpace(build.BinaryName) == "" || len(assets) != len(build.Targets)+1 || assets[len(assets)-1].Filename != gitea.ManifestFilename {
|
||||||
|
return errors.New("build result does not contain the selected artifacts and complete checksum manifest")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func stateForError(err error, pageCreated bool) State {
|
||||||
|
var failure *gitea.Failure
|
||||||
|
if errors.As(err, &failure) {
|
||||||
|
switch failure.Kind {
|
||||||
|
case gitea.FailureConflict:
|
||||||
|
return Conflict
|
||||||
|
case gitea.FailureUnknown:
|
||||||
|
return Unknown
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if pageCreated {
|
||||||
|
return Partial
|
||||||
|
}
|
||||||
|
return NotAttempted
|
||||||
|
}
|
||||||
|
|
||||||
|
func assetIdentities(assets []gitea.ExpectedAsset) []gitea.AssetIdentity {
|
||||||
|
result := make([]gitea.AssetIdentity, 0, len(assets))
|
||||||
|
for _, asset := range assets {
|
||||||
|
result = append(result, gitea.AssetIdentity{Filename: asset.Filename, SHA256: asset.SHA256})
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
37
internal/git/prepare.go
Normal file
37
internal/git/prepare.go
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
package git
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// PrepareTaggedCheckout fetches one explicit tag ref, checks its peeled commit
|
||||||
|
// against expectedCommit, and checks out that commit detached.
|
||||||
|
func PrepareTaggedCheckout(ctx context.Context, repositoryDir, version, remote, expectedCommit string) error {
|
||||||
|
if !validVersionRef(version) || !validObjectID(expectedCommit) {
|
||||||
|
return fmt.Errorf("invalid tagged checkout identity %q at %q", expectedCommit, version)
|
||||||
|
}
|
||||||
|
ref := "refs/tags/" + version
|
||||||
|
if _, err := run(ctx, repositoryDir, nil, "fetch", "--no-tags", remote, ref+":"+ref); err != nil {
|
||||||
|
return fmt.Errorf("fetch tag %s from remote %s: %w", version, remote, err)
|
||||||
|
}
|
||||||
|
source, err := InspectTaggedSource(ctx, repositoryDir, version)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !strings.EqualFold(source.TagCommit, expectedCommit) {
|
||||||
|
return fmt.Errorf("tag %s resolves to commit %s, expected %s", version, source.TagCommit, expectedCommit)
|
||||||
|
}
|
||||||
|
if _, err := run(ctx, repositoryDir, nil, "checkout", "--detach", source.TagCommit); err != nil {
|
||||||
|
return fmt.Errorf("check out tag %s at %s: %w", version, source.TagCommit, err)
|
||||||
|
}
|
||||||
|
head, err := run(ctx, repositoryDir, nil, "rev-parse", "--verify", "HEAD^{commit}")
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("verify prepared checkout HEAD: %w", err)
|
||||||
|
}
|
||||||
|
if !strings.EqualFold(strings.TrimSpace(head), expectedCommit) {
|
||||||
|
return fmt.Errorf("prepared checkout HEAD is %s, expected %s", strings.TrimSpace(head), expectedCommit)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
328
internal/git/remote.go
Normal file
328
internal/git/remote.go
Normal file
@@ -0,0 +1,328 @@
|
|||||||
|
// Package git resolves and inspects a repository's authoritative Git remote.
|
||||||
|
package git
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/rand"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/process"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrInvalidRemote = errors.New("invalid Git remote")
|
||||||
|
ErrMultiplePushURLs = errors.New("Git remote has multiple push URLs")
|
||||||
|
ErrEndpointChanged = errors.New("Git publication endpoint changed")
|
||||||
|
ErrRemoteMainMissing = errors.New("authoritative remote has no main branch")
|
||||||
|
ErrRemoteMainConflict = errors.New("authoritative main does not identify the candidate commit")
|
||||||
|
ErrRemoteTagConflict = errors.New("version tag already exists on the authoritative remote")
|
||||||
|
ErrRemoteStateUnreadable = errors.New("authoritative remote state is unreadable")
|
||||||
|
)
|
||||||
|
|
||||||
|
// Endpoint identifies the single effective publication destination captured
|
||||||
|
// from a selected remote. ScopedName is a transient remote name used with
|
||||||
|
// command-scoped configuration; it is never written to the repository.
|
||||||
|
type Endpoint struct {
|
||||||
|
RemoteName string
|
||||||
|
PushURL string
|
||||||
|
ScopedName string
|
||||||
|
transport []string
|
||||||
|
}
|
||||||
|
|
||||||
|
// RefState records whether an exact remote ref was found by a successful query.
|
||||||
|
type RefState uint8
|
||||||
|
|
||||||
|
const (
|
||||||
|
RefUnreadable RefState = iota
|
||||||
|
RefAbsent
|
||||||
|
RefPresent
|
||||||
|
RefConflict
|
||||||
|
)
|
||||||
|
|
||||||
|
// RemoteRef holds an exact ref's object and optional peeled commit. State is
|
||||||
|
// RefConflict only when more than one exact result or malformed data is found.
|
||||||
|
type RemoteRef struct {
|
||||||
|
State RefState
|
||||||
|
Object string
|
||||||
|
Peeled string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Snapshot is the result of querying refs/heads/main and one exact version tag.
|
||||||
|
type Snapshot struct {
|
||||||
|
Main RemoteRef
|
||||||
|
Tag RemoteRef
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resolve captures the selected remote's effective push URL and establishes a
|
||||||
|
// command-scoped remote whose read and push URLs resolve to that same endpoint.
|
||||||
|
func Resolve(ctx context.Context, repositoryDir, remoteName string) (Endpoint, error) {
|
||||||
|
if strings.TrimSpace(remoteName) == "" || strings.HasPrefix(remoteName, "-") {
|
||||||
|
return Endpoint{}, fmt.Errorf("%w: %q", ErrInvalidRemote, remoteName)
|
||||||
|
}
|
||||||
|
urls, err := pushURLs(ctx, repositoryDir, remoteName)
|
||||||
|
if err != nil {
|
||||||
|
return Endpoint{}, err
|
||||||
|
}
|
||||||
|
if len(urls) != 1 {
|
||||||
|
return Endpoint{}, fmt.Errorf("%w: %s resolves to %d distinct destinations", ErrMultiplePushURLs, remoteName, len(urls))
|
||||||
|
}
|
||||||
|
scopedName, err := newScopedName()
|
||||||
|
if err != nil {
|
||||||
|
return Endpoint{}, fmt.Errorf("create command-scoped remote name: %w", err)
|
||||||
|
}
|
||||||
|
endpoint := Endpoint{RemoteName: remoteName, PushURL: urls[0], ScopedName: scopedName}
|
||||||
|
endpoint.transport, err = transportConfig(ctx, repositoryDir, remoteName, scopedName)
|
||||||
|
if err != nil {
|
||||||
|
return Endpoint{}, err
|
||||||
|
}
|
||||||
|
if err := endpoint.verifyScopedURLs(ctx, repositoryDir); err != nil {
|
||||||
|
return Endpoint{}, err
|
||||||
|
}
|
||||||
|
return endpoint, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Recheck confirms both the selected remote's effective push destination and
|
||||||
|
// the scoped remote's effective read and push URLs still identify this endpoint.
|
||||||
|
func (endpoint Endpoint) Recheck(ctx context.Context, repositoryDir string) error {
|
||||||
|
urls, err := pushURLs(ctx, repositoryDir, endpoint.RemoteName)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("re-resolve remote %q: %w", endpoint.RemoteName, err)
|
||||||
|
}
|
||||||
|
if len(urls) != 1 || urls[0] != endpoint.PushURL {
|
||||||
|
return fmt.Errorf("%w: remote %q now resolves to %q", ErrEndpointChanged, endpoint.RemoteName, strings.Join(urls, ", "))
|
||||||
|
}
|
||||||
|
return endpoint.verifyScopedURLs(ctx, repositoryDir)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Query reads exact main and version-tag refs. A command failure is unreadable,
|
||||||
|
// never evidence that a ref is absent.
|
||||||
|
func (endpoint Endpoint) Query(ctx context.Context, repositoryDir, version string) (Snapshot, error) {
|
||||||
|
if !validVersionRef(version) {
|
||||||
|
return Snapshot{}, fmt.Errorf("invalid version tag name %q", version)
|
||||||
|
}
|
||||||
|
mainRef := "refs/heads/main"
|
||||||
|
tagRef := "refs/tags/" + version
|
||||||
|
peeledRef := tagRef + "^{}"
|
||||||
|
output, err := run(ctx, repositoryDir, endpoint.scopedConfig(), "ls-remote", endpoint.ScopedName, mainRef, tagRef, peeledRef)
|
||||||
|
if err != nil {
|
||||||
|
snapshot := Snapshot{Main: RemoteRef{State: RefUnreadable}, Tag: RemoteRef{State: RefUnreadable}}
|
||||||
|
return snapshot, fmt.Errorf("%w: query authoritative refs at %s: %w", ErrRemoteStateUnreadable, endpoint.PushURL, err)
|
||||||
|
}
|
||||||
|
main := RemoteRef{State: RefAbsent}
|
||||||
|
tag := 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 Snapshot{Main: RemoteRef{State: RefUnreadable}, Tag: RemoteRef{State: RefUnreadable}}, fmt.Errorf("%w: malformed ls-remote output %q", ErrRemoteStateUnreadable, line)
|
||||||
|
}
|
||||||
|
switch name {
|
||||||
|
case mainRef:
|
||||||
|
main = mergeRef(main, object, false)
|
||||||
|
case tagRef:
|
||||||
|
tag = mergeRef(tag, object, false)
|
||||||
|
case peeledRef:
|
||||||
|
tag = mergeRef(tag, object, true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Snapshot{Main: main, Tag: tag}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// RequireCandidate requires exact main equality and an absent remote version
|
||||||
|
// tag. It deliberately does not accept a main branch that merely contains the
|
||||||
|
// candidate as an ancestor.
|
||||||
|
func (endpoint Endpoint) RequireCandidate(ctx context.Context, repositoryDir, version, commit string) (Snapshot, error) {
|
||||||
|
snapshot, err := endpoint.Query(ctx, repositoryDir, version)
|
||||||
|
if err != nil {
|
||||||
|
return snapshot, err
|
||||||
|
}
|
||||||
|
if snapshot.Main.State == RefAbsent {
|
||||||
|
return snapshot, ErrRemoteMainMissing
|
||||||
|
}
|
||||||
|
if snapshot.Main.State != RefPresent || snapshot.Main.Object != commit {
|
||||||
|
snapshot.Main.State = RefConflict
|
||||||
|
return snapshot, fmt.Errorf("%w: candidate %s, remote main %s", ErrRemoteMainConflict, commit, snapshot.Main.Object)
|
||||||
|
}
|
||||||
|
if snapshot.Tag.State != RefAbsent {
|
||||||
|
if snapshot.Tag.State == RefUnreadable {
|
||||||
|
return snapshot, ErrRemoteStateUnreadable
|
||||||
|
}
|
||||||
|
snapshot.Tag.State = RefConflict
|
||||||
|
return snapshot, fmt.Errorf("%w: %s", ErrRemoteTagConflict, snapshot.Tag.Object)
|
||||||
|
}
|
||||||
|
return snapshot, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (endpoint Endpoint) verifyScopedURLs(ctx context.Context, repositoryDir string) error {
|
||||||
|
readURL, err := run(ctx, repositoryDir, endpoint.scopedConfig(), "ls-remote", "--get-url", endpoint.ScopedName)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("resolve scoped read URL: %w", err)
|
||||||
|
}
|
||||||
|
resolved := outputLines(readURL)
|
||||||
|
if len(resolved) != 1 || resolved[0] != endpoint.PushURL {
|
||||||
|
return fmt.Errorf("%w: scoped URL resolves to %q, expected %q", ErrEndpointChanged, resolved, endpoint.PushURL)
|
||||||
|
}
|
||||||
|
// The scoped remote sets its push URL explicitly to the same captured value.
|
||||||
|
// Git applies the same insteadOf rules to both explicit URLs; pushInsteadOf
|
||||||
|
// applies only when no push URL exists and therefore cannot change this one.
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (endpoint Endpoint) scopedConfig() []string {
|
||||||
|
config := []string{
|
||||||
|
"remote." + endpoint.ScopedName + ".url=" + endpoint.PushURL,
|
||||||
|
"remote." + endpoint.ScopedName + ".pushurl=" + endpoint.PushURL,
|
||||||
|
"remote." + endpoint.ScopedName + ".mirror=false",
|
||||||
|
}
|
||||||
|
// These options affect Git transport behavior and are carried into the
|
||||||
|
// scoped remote without copying refspecs, mirror mode, or push destinations.
|
||||||
|
config = append(config, endpoint.transport...)
|
||||||
|
return config
|
||||||
|
}
|
||||||
|
|
||||||
|
// transportConfig evaluates Git's normal configuration, including includes,
|
||||||
|
// then copies transport settings under the transient remote's name.
|
||||||
|
func transportConfig(ctx context.Context, repositoryDir, remoteName, scopedName string) ([]string, error) {
|
||||||
|
var config []string
|
||||||
|
for _, key := range []string{"proxy", "uploadpack", "receivepack", "vcs", "serveroption"} {
|
||||||
|
output, err := run(ctx, repositoryDir, nil, "config", "--get-all", "remote."+remoteName+"."+key)
|
||||||
|
if err != nil {
|
||||||
|
// git config exits 1 when the key is absent; that is expected.
|
||||||
|
var exitErr interface{ ExitCode() int }
|
||||||
|
if errors.As(err, &exitErr) && exitErr.ExitCode() == 1 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("read transport setting remote.%s.%s: %w", remoteName, key, err)
|
||||||
|
}
|
||||||
|
for _, value := range outputLines(output) {
|
||||||
|
config = append(config, "remote."+scopedName+"."+key+"="+value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return config, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func pushURLs(ctx context.Context, repositoryDir, remoteName string) ([]string, error) {
|
||||||
|
output, err := run(ctx, repositoryDir, nil, "remote", "get-url", "--push", "--all", remoteName)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("resolve push URL for remote %q: %w", remoteName, err)
|
||||||
|
}
|
||||||
|
values := outputLines(output)
|
||||||
|
unique := make([]string, 0, len(values))
|
||||||
|
seen := make(map[string]struct{}, len(values))
|
||||||
|
for _, value := range values {
|
||||||
|
if _, ok := seen[value]; ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[value] = struct{}{}
|
||||||
|
unique = append(unique, value)
|
||||||
|
}
|
||||||
|
return unique, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func run(ctx context.Context, dir string, config []string, args ...string) (string, error) {
|
||||||
|
commandArgs := make([]string, 0, len(config)*2+len(args))
|
||||||
|
for _, value := range config {
|
||||||
|
commandArgs = append(commandArgs, "-c", value)
|
||||||
|
}
|
||||||
|
commandArgs = append(commandArgs, args...)
|
||||||
|
var stdout, stderr strings.Builder
|
||||||
|
err := process.Run(ctx, process.Invocation{
|
||||||
|
Args: append([]string{"git"}, commandArgs...),
|
||||||
|
Dir: dir,
|
||||||
|
Stdout: &stdout,
|
||||||
|
Stderr: &stderr,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
message := strings.TrimSpace(stderr.String())
|
||||||
|
if message != "" {
|
||||||
|
return stdout.String(), fmt.Errorf("%w: %s", err, message)
|
||||||
|
}
|
||||||
|
return stdout.String(), err
|
||||||
|
}
|
||||||
|
return stdout.String(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func newScopedName() (string, error) {
|
||||||
|
var bytes [12]byte
|
||||||
|
if _, err := rand.Read(bytes[:]); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return "releasekit-" + hex.EncodeToString(bytes[:]), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func outputLines(output string) []string {
|
||||||
|
output = strings.TrimSuffix(output, "\n")
|
||||||
|
if output == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
lines := strings.Split(output, "\n")
|
||||||
|
for i := range lines {
|
||||||
|
lines[i] = strings.TrimSuffix(lines[i], "\r")
|
||||||
|
}
|
||||||
|
return lines
|
||||||
|
}
|
||||||
|
|
||||||
|
func mergeRef(ref RemoteRef, object string, peeled bool) RemoteRef {
|
||||||
|
if ref.State == RefConflict {
|
||||||
|
return ref
|
||||||
|
}
|
||||||
|
if peeled {
|
||||||
|
if ref.State == RefAbsent {
|
||||||
|
ref.State = RefPresent
|
||||||
|
ref.Peeled = object
|
||||||
|
return ref
|
||||||
|
}
|
||||||
|
if ref.Peeled != "" {
|
||||||
|
return RemoteRef{State: RefConflict, Object: ref.Object}
|
||||||
|
}
|
||||||
|
ref.Peeled = object
|
||||||
|
return ref
|
||||||
|
}
|
||||||
|
if ref.State == RefAbsent {
|
||||||
|
ref.State, ref.Object = RefPresent, object
|
||||||
|
return ref
|
||||||
|
}
|
||||||
|
if ref.Object != "" {
|
||||||
|
return RemoteRef{State: RefConflict, Object: ref.Object}
|
||||||
|
}
|
||||||
|
ref.Object = object
|
||||||
|
return ref
|
||||||
|
}
|
||||||
|
|
||||||
|
func validVersionRef(version string) bool {
|
||||||
|
if len(version) < 6 || !strings.HasPrefix(version, "v") {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
parts := strings.Split(version[1:], ".")
|
||||||
|
if len(parts) != 3 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, part := range parts {
|
||||||
|
if part == "" || (len(part) > 1 && part[0] == '0') {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, char := range part {
|
||||||
|
if char < '0' || char > '9' {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func validObjectID(object string) bool {
|
||||||
|
if len(object) != 40 && len(object) != 64 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, char := range object {
|
||||||
|
if (char < '0' || char > '9') && (char < 'a' || char > 'f') && (char < 'A' || char > 'F') {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
223
internal/git/remote_test.go
Normal file
223
internal/git/remote_test.go
Normal file
@@ -0,0 +1,223 @@
|
|||||||
|
package git
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
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")
|
||||||
|
refsBefore := gitText(t, repo.bare, "show-ref", "--heads", "--tags")
|
||||||
|
|
||||||
|
endpoint, err := Resolve(context.Background(), repo.work, "origin")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if endpoint.PushURL != repo.bare {
|
||||||
|
t.Fatalf("push URL = %q, want %q", endpoint.PushURL, repo.bare)
|
||||||
|
}
|
||||||
|
if err := endpoint.Recheck(context.Background(), repo.work); err != nil {
|
||||||
|
t.Fatalf("Recheck() error = %v", err)
|
||||||
|
}
|
||||||
|
snapshot, err := endpoint.RequireCandidate(context.Background(), repo.work, "v1.2.3", repo.commit)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("RequireCandidate() error = %v", err)
|
||||||
|
}
|
||||||
|
if snapshot.Main.State != RefPresent || snapshot.Main.Object != repo.commit || snapshot.Tag.State != RefAbsent {
|
||||||
|
t.Fatalf("snapshot = %#v", snapshot)
|
||||||
|
}
|
||||||
|
configAfter := gitText(t, repo.work, "config", "--get-all", "remote.origin.url") + "\x00" + gitText(t, repo.work, "config", "--get-all", "remote.origin.pushurl")
|
||||||
|
refsAfter := gitText(t, repo.bare, "show-ref", "--heads", "--tags")
|
||||||
|
if configAfter != configBefore {
|
||||||
|
t.Fatalf("persistent remote config changed: before %q, after %q", configBefore, configAfter)
|
||||||
|
}
|
||||||
|
if refsAfter != refsBefore {
|
||||||
|
t.Fatalf("remote refs changed: before %q, after %q", refsBefore, refsAfter)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestResolveAppliesGitURLRewrites(t *testing.T) {
|
||||||
|
for _, kind := range []string{"insteadOf", "pushInsteadOf"} {
|
||||||
|
t.Run(kind, func(t *testing.T) {
|
||||||
|
repo := newRemoteFixture(t)
|
||||||
|
alias := "releasekit-test:"
|
||||||
|
if kind == "insteadOf" {
|
||||||
|
gitRun(t, repo.work, "config", "url."+repo.bare+".insteadOf", alias)
|
||||||
|
gitRun(t, repo.work, "remote", "set-url", "origin", alias)
|
||||||
|
gitRun(t, repo.work, "config", "--unset-all", "remote.origin.pushurl")
|
||||||
|
} else {
|
||||||
|
gitRun(t, repo.work, "config", "url."+repo.bare+".pushInsteadOf", alias)
|
||||||
|
gitRun(t, repo.work, "remote", "set-url", "origin", alias)
|
||||||
|
gitRun(t, repo.work, "config", "--unset-all", "remote.origin.pushurl")
|
||||||
|
}
|
||||||
|
endpoint, err := Resolve(context.Background(), repo.work, "origin")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if endpoint.PushURL != repo.bare {
|
||||||
|
t.Fatalf("effective push URL = %q, want %q", endpoint.PushURL, repo.bare)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestResolveRejectsMultipleDistinctPushDestinations(t *testing.T) {
|
||||||
|
repo := newRemoteFixture(t)
|
||||||
|
second := filepath.Join(t.TempDir(), "second.git")
|
||||||
|
gitRun(t, t.TempDir(), "init", "--bare", second)
|
||||||
|
gitRun(t, repo.work, "config", "--add", "remote.origin.pushurl", second)
|
||||||
|
_, err := Resolve(context.Background(), repo.work, "origin")
|
||||||
|
if !errors.Is(err, ErrMultiplePushURLs) {
|
||||||
|
t.Fatalf("Resolve() error = %v, want ErrMultiplePushURLs", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRequireCandidateDistinguishesMissingMainTagConflictAndMainMismatch(t *testing.T) {
|
||||||
|
t.Run("missing main", func(t *testing.T) {
|
||||||
|
repo := newRemoteFixture(t)
|
||||||
|
gitRun(t, repo.bare, "update-ref", "-d", "refs/heads/main")
|
||||||
|
endpoint := resolveFixture(t, repo)
|
||||||
|
snapshot, err := endpoint.RequireCandidate(context.Background(), repo.work, "v1.2.3", repo.commit)
|
||||||
|
if !errors.Is(err, ErrRemoteMainMissing) || snapshot.Main.State != RefAbsent {
|
||||||
|
t.Fatalf("snapshot = %#v, error = %v", snapshot, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("existing tag", func(t *testing.T) {
|
||||||
|
repo := newRemoteFixture(t)
|
||||||
|
gitRun(t, repo.work, "tag", "v1.2.3", repo.commit)
|
||||||
|
gitRun(t, repo.work, "push", repo.bare, "refs/tags/v1.2.3:refs/tags/v1.2.3")
|
||||||
|
endpoint := resolveFixture(t, repo)
|
||||||
|
snapshot, err := endpoint.RequireCandidate(context.Background(), repo.work, "v1.2.3", repo.commit)
|
||||||
|
if !errors.Is(err, ErrRemoteTagConflict) || snapshot.Tag.State != RefConflict {
|
||||||
|
t.Fatalf("snapshot = %#v, error = %v", snapshot, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
for _, relation := range []string{"ahead", "behind"} {
|
||||||
|
t.Run("main "+relation, func(t *testing.T) {
|
||||||
|
repo := newRemoteFixture(t)
|
||||||
|
candidate := repo.commit
|
||||||
|
remoteMain := repo.commit
|
||||||
|
if relation == "ahead" {
|
||||||
|
writeRepoFile(t, repo.work, "ahead.txt", "ahead")
|
||||||
|
gitRun(t, repo.work, "add", "ahead.txt")
|
||||||
|
gitRun(t, repo.work, "commit", "-m", "Advance main")
|
||||||
|
remoteMain = gitText(t, repo.work, "rev-parse", "HEAD")
|
||||||
|
gitRun(t, repo.work, "push", repo.bare, "HEAD:refs/heads/main")
|
||||||
|
} else {
|
||||||
|
writeRepoFile(t, repo.work, "behind.txt", "candidate is ahead")
|
||||||
|
gitRun(t, repo.work, "add", "behind.txt")
|
||||||
|
gitRun(t, repo.work, "commit", "-m", "Candidate ahead of main")
|
||||||
|
candidate = gitText(t, repo.work, "rev-parse", "HEAD")
|
||||||
|
}
|
||||||
|
if relation == "behind" {
|
||||||
|
gitRun(t, repo.bare, "update-ref", "refs/heads/main", remoteMain)
|
||||||
|
}
|
||||||
|
endpoint := resolveFixture(t, repo)
|
||||||
|
snapshot, err := endpoint.RequireCandidate(context.Background(), repo.work, "v1.2.3", candidate)
|
||||||
|
if !errors.Is(err, ErrRemoteMainConflict) || snapshot.Main.State != RefConflict {
|
||||||
|
t.Fatalf("snapshot = %#v, error = %v", snapshot, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestQueryFailureIsUnreadableAndEndpointChangesAreDetected(t *testing.T) {
|
||||||
|
repo := newRemoteFixture(t)
|
||||||
|
endpoint := resolveFixture(t, repo)
|
||||||
|
missing := filepath.Join(t.TempDir(), "missing.git")
|
||||||
|
gitRun(t, repo.work, "remote", "set-url", "--push", "origin", missing)
|
||||||
|
if err := endpoint.Recheck(context.Background(), repo.work); !errors.Is(err, ErrEndpointChanged) {
|
||||||
|
t.Fatalf("Recheck() error = %v, want ErrEndpointChanged", err)
|
||||||
|
}
|
||||||
|
gitRun(t, repo.work, "remote", "set-url", "--push", "origin", missing)
|
||||||
|
broken, err := Resolve(context.Background(), repo.work, "origin")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Resolve(missing bare path) error = %v", err)
|
||||||
|
}
|
||||||
|
snapshot, err := broken.Query(context.Background(), repo.work, "v1.2.3")
|
||||||
|
if !errors.Is(err, ErrRemoteStateUnreadable) || snapshot.Main.State != RefUnreadable || snapshot.Tag.State != RefUnreadable {
|
||||||
|
t.Fatalf("snapshot = %#v, error = %v", snapshot, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMergeRefMarksDuplicateExactResultsConflicting(t *testing.T) {
|
||||||
|
first := strings.Repeat("a", 40)
|
||||||
|
second := strings.Repeat("b", 40)
|
||||||
|
ref := mergeRef(RemoteRef{State: RefAbsent}, first, false)
|
||||||
|
ref = mergeRef(ref, second, false)
|
||||||
|
if ref.State != RefConflict {
|
||||||
|
t.Fatalf("state = %v, want RefConflict", ref.State)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type remoteFixture struct {
|
||||||
|
work string
|
||||||
|
bare string
|
||||||
|
commit string
|
||||||
|
}
|
||||||
|
|
||||||
|
func newRemoteFixture(t *testing.T) remoteFixture {
|
||||||
|
t.Helper()
|
||||||
|
base := t.TempDir()
|
||||||
|
work := filepath.Join(base, "work")
|
||||||
|
bare := filepath.Join(base, "authoritative.git")
|
||||||
|
decoy := filepath.Join(base, "fetch-only.git")
|
||||||
|
gitRun(t, base, "init", "-b", "main", work)
|
||||||
|
gitRun(t, work, "config", "user.name", "ReleaseKit Test")
|
||||||
|
gitRun(t, work, "config", "user.email", "releasekit@example.invalid")
|
||||||
|
gitRun(t, work, "init", "--bare", bare)
|
||||||
|
gitRun(t, work, "init", "--bare", decoy)
|
||||||
|
writeRepoFile(t, work, "source.txt", "candidate")
|
||||||
|
gitRun(t, work, "add", "source.txt")
|
||||||
|
gitRun(t, work, "commit", "-m", "Candidate")
|
||||||
|
commit := gitText(t, work, "rev-parse", "HEAD")
|
||||||
|
gitRun(t, work, "remote", "add", "origin", decoy)
|
||||||
|
gitRun(t, work, "config", "--add", "remote.origin.pushurl", bare)
|
||||||
|
gitRun(t, work, "push", bare, "HEAD:refs/heads/main")
|
||||||
|
return remoteFixture{work: work, bare: bare, commit: commit}
|
||||||
|
}
|
||||||
|
|
||||||
|
func resolveFixture(t *testing.T, repo remoteFixture) Endpoint {
|
||||||
|
t.Helper()
|
||||||
|
endpoint, err := Resolve(context.Background(), repo.work, "origin")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return endpoint
|
||||||
|
}
|
||||||
|
|
||||||
|
func gitRun(t *testing.T, dir string, args ...string) {
|
||||||
|
t.Helper()
|
||||||
|
cmd := exec.Command("git", args...)
|
||||||
|
cmd.Dir = dir
|
||||||
|
if output, err := cmd.CombinedOutput(); err != nil {
|
||||||
|
t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, output)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func gitText(t *testing.T, dir string, args ...string) string {
|
||||||
|
t.Helper()
|
||||||
|
cmd := exec.Command("git", args...)
|
||||||
|
cmd.Dir = dir
|
||||||
|
outputBytes, err := cmd.CombinedOutput()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, outputBytes)
|
||||||
|
}
|
||||||
|
return strings.TrimSuffix(string(outputBytes), "\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeRepoFile(t *testing.T, repoDir, name, contents string) {
|
||||||
|
t.Helper()
|
||||||
|
path := filepath.Join(repoDir, name)
|
||||||
|
if err := os.WriteFile(path, []byte(contents), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
76
internal/git/source.go
Normal file
76
internal/git/source.go
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
package git
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"path"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
type TaggedSource struct {
|
||||||
|
Head string
|
||||||
|
Status string
|
||||||
|
TagObject string
|
||||||
|
TagCommit string
|
||||||
|
TagObjectType string
|
||||||
|
}
|
||||||
|
|
||||||
|
// InspectTaggedSource reads the local HEAD, worktree state, and selected tag.
|
||||||
|
// Both lightweight historical tags and annotated tags are supported.
|
||||||
|
func InspectTaggedSource(ctx context.Context, repositoryDir, version string) (TaggedSource, error) {
|
||||||
|
if !validVersionRef(version) {
|
||||||
|
return TaggedSource{}, fmt.Errorf("invalid tag version %q", version)
|
||||||
|
}
|
||||||
|
var source TaggedSource
|
||||||
|
head, err := run(ctx, repositoryDir, nil, "rev-parse", "--verify", "HEAD^{commit}")
|
||||||
|
if err != nil {
|
||||||
|
return TaggedSource{}, fmt.Errorf("read checkout HEAD: %w", err)
|
||||||
|
}
|
||||||
|
source.Head = strings.TrimSpace(head)
|
||||||
|
if !validObjectID(source.Head) {
|
||||||
|
return TaggedSource{}, fmt.Errorf("Git returned an invalid checkout commit %q", source.Head)
|
||||||
|
}
|
||||||
|
status, err := run(ctx, repositoryDir, nil, "status", "--porcelain", "--untracked-files=all")
|
||||||
|
if err != nil {
|
||||||
|
return TaggedSource{}, fmt.Errorf("inspect tagged checkout state: %w", err)
|
||||||
|
}
|
||||||
|
source.Status = strings.TrimSpace(status)
|
||||||
|
ref := "refs/tags/" + version
|
||||||
|
object, err := run(ctx, repositoryDir, nil, "rev-parse", "--verify", ref)
|
||||||
|
if err != nil {
|
||||||
|
return TaggedSource{}, fmt.Errorf("read local tag %s: %w", version, err)
|
||||||
|
}
|
||||||
|
source.TagObject = strings.TrimSpace(object)
|
||||||
|
if !validObjectID(source.TagObject) {
|
||||||
|
return TaggedSource{}, fmt.Errorf("Git returned an invalid tag object %q", source.TagObject)
|
||||||
|
}
|
||||||
|
peeled, err := run(ctx, repositoryDir, nil, "rev-parse", "--verify", ref+"^{commit}")
|
||||||
|
if err != nil {
|
||||||
|
return TaggedSource{}, fmt.Errorf("resolve local tag %s to a commit: %w", version, err)
|
||||||
|
}
|
||||||
|
source.TagCommit = strings.TrimSpace(peeled)
|
||||||
|
if !validObjectID(source.TagCommit) {
|
||||||
|
return TaggedSource{}, fmt.Errorf("Git returned an invalid tagged commit %q", source.TagCommit)
|
||||||
|
}
|
||||||
|
tagType, err := run(ctx, repositoryDir, nil, "cat-file", "-t", ref)
|
||||||
|
if err != nil {
|
||||||
|
return TaggedSource{}, fmt.Errorf("inspect local tag %s: %w", version, err)
|
||||||
|
}
|
||||||
|
source.TagObjectType = strings.TrimSpace(tagType)
|
||||||
|
if source.TagObjectType != "tag" && source.TagObjectType != "commit" {
|
||||||
|
return TaggedSource{}, fmt.Errorf("local tag %s has unsupported object type %q", version, source.TagObjectType)
|
||||||
|
}
|
||||||
|
return source, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReadCommitFile reads a repository-relative file from a specific commit.
|
||||||
|
func ReadCommitFile(ctx context.Context, repositoryDir, commit, name string) ([]byte, error) {
|
||||||
|
if !validObjectID(commit) || name == "" || path.IsAbs(name) || path.Clean(name) != name || strings.HasPrefix(name, "../") || name == ".." || strings.Contains(name, "\\") {
|
||||||
|
return nil, fmt.Errorf("invalid committed file identity %q at %q", name, commit)
|
||||||
|
}
|
||||||
|
content, err := run(ctx, repositoryDir, nil, "show", commit+":"+name)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("read committed file %q: %w", name, err)
|
||||||
|
}
|
||||||
|
return []byte(content), nil
|
||||||
|
}
|
||||||
46
internal/git/source_test.go
Normal file
46
internal/git/source_test.go
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
package git
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestInspectTaggedSourceSupportsLightweightAndAnnotatedTags(t *testing.T) {
|
||||||
|
fixture := newRemoteFixture(t)
|
||||||
|
gitRun(t, fixture.work, "tag", "v1.2.3")
|
||||||
|
gitRun(t, fixture.work, "checkout", "--detach", "HEAD")
|
||||||
|
lightweight, err := InspectTaggedSource(context.Background(), fixture.work, "v1.2.3")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if lightweight.Head != fixture.commit || lightweight.TagCommit != fixture.commit || lightweight.TagObject != fixture.commit || lightweight.TagObjectType != "commit" || lightweight.Status != "" {
|
||||||
|
t.Fatalf("lightweight source = %#v", lightweight)
|
||||||
|
}
|
||||||
|
gitRun(t, fixture.work, "tag", "-d", "v1.2.3")
|
||||||
|
gitRun(t, fixture.work, "tag", "-a", "v1.2.3", "-m", "Historical release")
|
||||||
|
annotated, err := InspectTaggedSource(context.Background(), fixture.work, "v1.2.3")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if annotated.Head != fixture.commit || annotated.TagCommit != fixture.commit || annotated.TagObject == fixture.commit || annotated.TagObjectType != "tag" || annotated.Status != "" {
|
||||||
|
t.Fatalf("annotated source = %#v", annotated)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInspectTaggedSourceReportsDirtyCheckoutAndReadCommitFile(t *testing.T) {
|
||||||
|
fixture := newRemoteFixture(t)
|
||||||
|
gitRun(t, fixture.work, "tag", "v1.2.3")
|
||||||
|
content, err := ReadCommitFile(context.Background(), fixture.work, fixture.commit, "source.txt")
|
||||||
|
if err != nil || string(content) != "candidate" {
|
||||||
|
t.Fatalf("committed content = %q, error = %v", content, err)
|
||||||
|
}
|
||||||
|
writeRepoFile(t, fixture.work, "untracked.txt", "dirty")
|
||||||
|
source, err := InspectTaggedSource(context.Background(), fixture.work, "v1.2.3")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(source.Status, "untracked.txt") {
|
||||||
|
t.Fatalf("dirty status = %q", source.Status)
|
||||||
|
}
|
||||||
|
}
|
||||||
137
internal/git/tag.go
Normal file
137
internal/git/tag.go
Normal file
@@ -0,0 +1,137 @@
|
|||||||
|
package git
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CreateAnnotatedTag records the captured note as an unsigned annotated tag
|
||||||
|
// on the captured commit and returns the tag object's ID.
|
||||||
|
func CreateAnnotatedTag(ctx context.Context, repositoryDir, version, commit string, note []byte) (string, error) {
|
||||||
|
if !validVersionRef(version) {
|
||||||
|
return "", fmt.Errorf("invalid version tag name %q", version)
|
||||||
|
}
|
||||||
|
if !validObjectID(commit) {
|
||||||
|
return "", fmt.Errorf("invalid candidate commit object ID %q", commit)
|
||||||
|
}
|
||||||
|
message, err := os.CreateTemp("", "releasekit-tag-message-*")
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("create temporary release note: %w", err)
|
||||||
|
}
|
||||||
|
messagePath := message.Name()
|
||||||
|
defer os.Remove(messagePath)
|
||||||
|
if _, err := message.Write(note); err != nil {
|
||||||
|
_ = message.Close()
|
||||||
|
return "", fmt.Errorf("write temporary release note: %w", err)
|
||||||
|
}
|
||||||
|
if err := message.Close(); err != nil {
|
||||||
|
return "", fmt.Errorf("close temporary release note: %w", err)
|
||||||
|
}
|
||||||
|
if _, err := run(ctx, repositoryDir, []string{"tag.gpgSign=false"}, "tag", "--annotate", "--cleanup=verbatim", "--file", messagePath, version, commit); err != nil {
|
||||||
|
return "", fmt.Errorf("create annotated tag %s: %w", version, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
ref := "refs/tags/" + version
|
||||||
|
tagType, err := run(ctx, repositoryDir, nil, "cat-file", "-t", ref)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("inspect created tag %s: %w", version, err)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(tagType) != "tag" {
|
||||||
|
return "", fmt.Errorf("created tag %s has object type %q, want tag", version, strings.TrimSpace(tagType))
|
||||||
|
}
|
||||||
|
tagObject, err := run(ctx, repositoryDir, nil, "rev-parse", "--verify", ref)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("read created tag object %s: %w", version, err)
|
||||||
|
}
|
||||||
|
tagObject = strings.TrimSpace(tagObject)
|
||||||
|
if !validObjectID(tagObject) {
|
||||||
|
return "", fmt.Errorf("created tag %s has invalid object ID %q", version, tagObject)
|
||||||
|
}
|
||||||
|
peeled, err := run(ctx, repositoryDir, nil, "rev-parse", "--verify", ref+"^{}")
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("read peeled commit for tag %s: %w", version, err)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(peeled) != commit {
|
||||||
|
return "", fmt.Errorf("created tag %s peels to %s, want candidate %s", version, strings.TrimSpace(peeled), commit)
|
||||||
|
}
|
||||||
|
tagContents, err := run(ctx, repositoryDir, nil, "cat-file", "tag", ref)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("read annotated tag %s: %w", version, err)
|
||||||
|
}
|
||||||
|
separator := bytes.Index([]byte(tagContents), []byte("\n\n"))
|
||||||
|
if separator < 0 || !bytes.Equal([]byte(tagContents[separator+2:]), note) {
|
||||||
|
return "", fmt.Errorf("annotated tag %s message does not match the captured release note", version)
|
||||||
|
}
|
||||||
|
return tagObject, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// InspectLocalTag confirms the selected tag still points to the exact
|
||||||
|
// annotated tag object captured before publication.
|
||||||
|
func InspectLocalTag(ctx context.Context, repositoryDir, version, expectedObject string) error {
|
||||||
|
if !validVersionRef(version) || !validObjectID(expectedObject) {
|
||||||
|
return fmt.Errorf("invalid expected tag identity %q at %q", expectedObject, version)
|
||||||
|
}
|
||||||
|
ref := "refs/tags/" + version
|
||||||
|
tagType, err := run(ctx, repositoryDir, nil, "cat-file", "-t", ref)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("inspect local tag %s: %w", version, err)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(tagType) != "tag" {
|
||||||
|
return fmt.Errorf("local tag %s has type %q, want annotated tag", version, strings.TrimSpace(tagType))
|
||||||
|
}
|
||||||
|
object, err := run(ctx, repositoryDir, nil, "rev-parse", "--verify", ref)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("read local tag %s: %w", version, err)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(object) != expectedObject {
|
||||||
|
return fmt.Errorf("local tag %s identifies %s, want %s", version, strings.TrimSpace(object), expectedObject)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// QueryTag verifies the captured endpoint still resolves to itself, then reads
|
||||||
|
// one exact authoritative version tag and its peeled commit. Failed
|
||||||
|
// verification or reads are unreadable and never interpreted as absence.
|
||||||
|
func (endpoint Endpoint) QueryTag(ctx context.Context, repositoryDir, version string) (RemoteRef, error) {
|
||||||
|
if !validVersionRef(version) {
|
||||||
|
return RemoteRef{}, fmt.Errorf("invalid version tag name %q", version)
|
||||||
|
}
|
||||||
|
if err := endpoint.verifyScopedURLs(ctx, repositoryDir); err != nil {
|
||||||
|
return RemoteRef{State: RefUnreadable}, fmt.Errorf("%w: verify authoritative endpoint before tag query: %w", ErrRemoteStateUnreadable, err)
|
||||||
|
}
|
||||||
|
ref := "refs/tags/" + version
|
||||||
|
peeledRef := ref + "^{}"
|
||||||
|
output, err := run(ctx, repositoryDir, endpoint.scopedConfig(), "ls-remote", endpoint.ScopedName, ref, peeledRef)
|
||||||
|
if err != nil {
|
||||||
|
return RemoteRef{State: RefUnreadable}, fmt.Errorf("%w: query authoritative tag %s at %s: %w", ErrRemoteStateUnreadable, version, endpoint.PushURL, err)
|
||||||
|
}
|
||||||
|
remoteTag := RemoteRef{State: RefAbsent}
|
||||||
|
for _, line := range outputLines(output) {
|
||||||
|
object, name, ok := strings.Cut(line, "\t")
|
||||||
|
if !ok || !validObjectID(object) {
|
||||||
|
return RemoteRef{State: RefUnreadable}, fmt.Errorf("%w: malformed ls-remote output %q", ErrRemoteStateUnreadable, line)
|
||||||
|
}
|
||||||
|
switch name {
|
||||||
|
case ref:
|
||||||
|
remoteTag = mergeRef(remoteTag, object, false)
|
||||||
|
case peeledRef:
|
||||||
|
remoteTag = mergeRef(remoteTag, object, true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return remoteTag, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// PushTag publishes only the captured tag object to its exact tag ref.
|
||||||
|
func (endpoint Endpoint) PushTag(ctx context.Context, repositoryDir, version, tagObject string) error {
|
||||||
|
if !validVersionRef(version) || !validObjectID(tagObject) {
|
||||||
|
return fmt.Errorf("invalid tag publication identity %q at %q", tagObject, version)
|
||||||
|
}
|
||||||
|
refspec := tagObject + ":refs/tags/" + version
|
||||||
|
if _, err := run(ctx, repositoryDir, endpoint.scopedConfig(), "push", "--no-follow-tags", "--porcelain", endpoint.ScopedName, refspec); err != nil {
|
||||||
|
return fmt.Errorf("push annotated tag %s to %s: %w", version, endpoint.PushURL, err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
270
internal/gitea/assets.go
Normal file
270
internal/gitea/assets.go
Normal file
@@ -0,0 +1,270 @@
|
|||||||
|
package gitea
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"path"
|
||||||
|
"sort"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/artifact"
|
||||||
|
)
|
||||||
|
|
||||||
|
const ManifestFilename = artifact.ManifestFilename
|
||||||
|
|
||||||
|
type AssetState string
|
||||||
|
|
||||||
|
const (
|
||||||
|
AssetMatching AssetState = "matching"
|
||||||
|
AssetMissing AssetState = "missing"
|
||||||
|
AssetConflicting AssetState = "conflicting"
|
||||||
|
AssetUnverifiable AssetState = "unverifiable"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ExpectedAsset describes one declared file. Content is populated for the
|
||||||
|
// generated checksum manifest; Path identifies local binary content for later
|
||||||
|
// upload operations.
|
||||||
|
type ExpectedAsset struct {
|
||||||
|
Filename string
|
||||||
|
SHA256 string
|
||||||
|
Size int64
|
||||||
|
Path string
|
||||||
|
Content []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
type RemoteAsset struct {
|
||||||
|
ID int64
|
||||||
|
Filename string
|
||||||
|
Size int64
|
||||||
|
DownloadURL string
|
||||||
|
}
|
||||||
|
|
||||||
|
type AssetInspection struct {
|
||||||
|
Expected ExpectedAsset
|
||||||
|
State AssetState
|
||||||
|
Existing []RemoteAsset
|
||||||
|
Err error
|
||||||
|
}
|
||||||
|
|
||||||
|
type Inspection struct {
|
||||||
|
Assets []AssetInspection
|
||||||
|
Unrelated []RemoteAsset
|
||||||
|
}
|
||||||
|
|
||||||
|
type assetResponse struct {
|
||||||
|
ID int64 `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Size int64 `json:"size"`
|
||||||
|
BrowserDownloadURL string `json:"browser_download_url"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// BuildManifest creates the deterministic checksum file for the declared
|
||||||
|
// binaries. An empty binary set produces no manifest.
|
||||||
|
func BuildManifest(binaries []ExpectedAsset) (ExpectedAsset, error) {
|
||||||
|
if len(binaries) == 0 {
|
||||||
|
return ExpectedAsset{}, nil
|
||||||
|
}
|
||||||
|
ordered := append([]ExpectedAsset(nil), binaries...)
|
||||||
|
sort.Slice(ordered, func(i, j int) bool { return ordered[i].Filename < ordered[j].Filename })
|
||||||
|
var body strings.Builder
|
||||||
|
seen := make(map[string]struct{}, len(ordered))
|
||||||
|
for _, binary := range ordered {
|
||||||
|
if !validAssetName(binary.Filename) || binary.Filename == ManifestFilename || !validSHA256(binary.SHA256) {
|
||||||
|
return ExpectedAsset{}, failure(FailureInvalid, "build checksum manifest", 0, fmt.Errorf("invalid binary identity for %q", binary.Filename))
|
||||||
|
}
|
||||||
|
if _, exists := seen[binary.Filename]; exists {
|
||||||
|
return ExpectedAsset{}, failure(FailureInvalid, "build checksum manifest", 0, fmt.Errorf("duplicate binary filename %q", binary.Filename))
|
||||||
|
}
|
||||||
|
seen[binary.Filename] = struct{}{}
|
||||||
|
fmt.Fprintf(&body, "%s %s\n", binary.SHA256, binary.Filename)
|
||||||
|
}
|
||||||
|
content := []byte(body.String())
|
||||||
|
return ExpectedAsset{Filename: ManifestFilename, SHA256: digest(content), Size: int64(len(content)), Content: content}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// InspectAssets lists the release's attachments and compares every declared
|
||||||
|
// asset by streamed SHA-256 content. It does not create or modify remote data.
|
||||||
|
func (c Client) InspectAssets(ctx context.Context, destination Destination, releaseID int64, expected []ExpectedAsset) (Inspection, error) {
|
||||||
|
if releaseID <= 0 {
|
||||||
|
return Inspection{}, failure(FailureInvalid, "inspect release assets", 0, errors.New("release ID must be positive"))
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(destination.Token) == "" {
|
||||||
|
return Inspection{}, failure(FailureInvalid, "inspect release assets", 0, errors.New("Gitea token is required"))
|
||||||
|
}
|
||||||
|
base, err := parseBaseURL(destination.BaseURL)
|
||||||
|
if err != nil {
|
||||||
|
return Inspection{}, failure(FailureInvalid, "validate destination", 0, err)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(destination.Owner) == "" || strings.ContainsAny(destination.Owner, "/\\") || strings.TrimSpace(destination.Repository) == "" || strings.ContainsAny(destination.Repository, "/\\") {
|
||||||
|
return Inspection{}, failure(FailureInvalid, "inspect release assets", 0, errors.New("Gitea owner and repository must be path segments"))
|
||||||
|
}
|
||||||
|
if err := validateExpectedAssets(expected); err != nil {
|
||||||
|
return Inspection{}, err
|
||||||
|
}
|
||||||
|
apiRoot := strings.TrimRight(base.String(), "/") + "/api/v1/repos/" + url.PathEscape(destination.Owner) + "/" + url.PathEscape(destination.Repository)
|
||||||
|
assetsURL := apiRoot + "/releases/" + strconv.FormatInt(releaseID, 10) + "/assets"
|
||||||
|
var listed []assetResponse
|
||||||
|
if err := c.getJSON(ctx, c.httpClient(), destination.Token, "list release assets", assetsURL, &listed); err != nil {
|
||||||
|
return Inspection{}, err
|
||||||
|
}
|
||||||
|
if listed == nil {
|
||||||
|
return Inspection{}, failure(FailureMalformed, "decode release assets", http.StatusOK, errors.New("attachment response must be a JSON array"))
|
||||||
|
}
|
||||||
|
|
||||||
|
remoteByName := make(map[string][]RemoteAsset, len(listed))
|
||||||
|
for _, item := range listed {
|
||||||
|
if item.ID <= 0 || item.Name == "" || item.Size < 0 {
|
||||||
|
return Inspection{}, failure(FailureMalformed, "decode release assets", http.StatusOK, errors.New("attachment entry is missing its ID, name, or size"))
|
||||||
|
}
|
||||||
|
remote := RemoteAsset{ID: item.ID, Filename: item.Name, Size: item.Size, DownloadURL: item.BrowserDownloadURL}
|
||||||
|
remoteByName[item.Name] = append(remoteByName[item.Name], remote)
|
||||||
|
}
|
||||||
|
inspection := Inspection{Assets: make([]AssetInspection, 0, len(expected))}
|
||||||
|
declared := make(map[string]struct{}, len(expected))
|
||||||
|
for _, item := range expected {
|
||||||
|
declared[item.Filename] = struct{}{}
|
||||||
|
matches := remoteByName[item.Filename]
|
||||||
|
observation := AssetInspection{Expected: item, Existing: matches}
|
||||||
|
switch len(matches) {
|
||||||
|
case 0:
|
||||||
|
observation.State = AssetMissing
|
||||||
|
case 1:
|
||||||
|
remoteHash, _, err := c.downloadHash(ctx, c.httpClient(), base, destination.Token, matches[0].DownloadURL)
|
||||||
|
if err != nil {
|
||||||
|
observation.State = AssetUnverifiable
|
||||||
|
observation.Err = err
|
||||||
|
} else if remoteHash == item.SHA256 {
|
||||||
|
observation.State = AssetMatching
|
||||||
|
} else {
|
||||||
|
observation.State = AssetConflicting
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
observation.State = AssetConflicting
|
||||||
|
}
|
||||||
|
inspection.Assets = append(inspection.Assets, observation)
|
||||||
|
}
|
||||||
|
for _, item := range listed {
|
||||||
|
if _, expected := declared[item.Name]; !expected {
|
||||||
|
inspection.Unrelated = append(inspection.Unrelated, RemoteAsset{ID: item.ID, Filename: item.Name, Size: item.Size, DownloadURL: item.BrowserDownloadURL})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return inspection, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c Client) downloadHash(ctx context.Context, client *http.Client, base *url.URL, token, rawURL string) (string, int64, error) {
|
||||||
|
if strings.TrimSpace(rawURL) == "" {
|
||||||
|
return "", 0, failure(FailureUnverifiable, "download release asset", 0, errors.New("attachment has no download URL"))
|
||||||
|
}
|
||||||
|
assetURL, err := base.Parse(rawURL)
|
||||||
|
if err != nil || assetURL.User != nil {
|
||||||
|
return "", 0, failure(FailureUnverifiable, "download release asset", 0, errors.New("invalid attachment URL"))
|
||||||
|
}
|
||||||
|
assetURL.Fragment = ""
|
||||||
|
visited := make(map[string]struct{})
|
||||||
|
for {
|
||||||
|
key := assetURL.String()
|
||||||
|
if _, exists := visited[key]; exists {
|
||||||
|
return "", 0, failure(FailureUnverifiable, "download release asset", 0, errors.New("asset redirect loop"))
|
||||||
|
}
|
||||||
|
visited[key] = struct{}{}
|
||||||
|
request, err := http.NewRequestWithContext(ctx, http.MethodGet, key, nil)
|
||||||
|
if err != nil {
|
||||||
|
return "", 0, failure(FailureUnverifiable, "download release asset", 0, err)
|
||||||
|
}
|
||||||
|
if sameOrigin(base, assetURL) {
|
||||||
|
request.Header.Set("Authorization", "token "+token)
|
||||||
|
}
|
||||||
|
request.Header.Set("Accept", "application/octet-stream")
|
||||||
|
response, err := client.Do(request)
|
||||||
|
if err != nil {
|
||||||
|
return "", 0, failure(FailureUnverifiable, "download release asset", 0, err)
|
||||||
|
}
|
||||||
|
if isRedirect(response.StatusCode) {
|
||||||
|
location, locationErr := response.Location()
|
||||||
|
_ = response.Body.Close()
|
||||||
|
if locationErr != nil || location.User != nil {
|
||||||
|
return "", 0, failure(FailureUnverifiable, "redirect release asset", response.StatusCode, errors.New("invalid attachment redirect"))
|
||||||
|
}
|
||||||
|
location.Fragment = ""
|
||||||
|
assetURL = location
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
defer response.Body.Close()
|
||||||
|
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
||||||
|
return "", 0, responseFailure("download release asset", response.StatusCode)
|
||||||
|
}
|
||||||
|
hasher := sha256.New()
|
||||||
|
size, err := io.Copy(hasher, response.Body)
|
||||||
|
if err != nil {
|
||||||
|
return "", size, failure(FailureUnverifiable, "read release asset", response.StatusCode, err)
|
||||||
|
}
|
||||||
|
return hex.EncodeToString(hasher.Sum(nil)), size, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateExpectedAssets(expected []ExpectedAsset) error {
|
||||||
|
seen := make(map[string]struct{}, len(expected))
|
||||||
|
for _, item := range expected {
|
||||||
|
if !validAssetName(item.Filename) || !validSHA256(item.SHA256) || item.Size < 0 {
|
||||||
|
return failure(FailureInvalid, "inspect release assets", 0, fmt.Errorf("invalid expected asset %q", item.Filename))
|
||||||
|
}
|
||||||
|
if _, duplicate := seen[item.Filename]; duplicate {
|
||||||
|
return failure(FailureInvalid, "inspect release assets", 0, fmt.Errorf("duplicate expected asset %q", item.Filename))
|
||||||
|
}
|
||||||
|
seen[item.Filename] = struct{}{}
|
||||||
|
if len(item.Content) > 0 && (int64(len(item.Content)) != item.Size || digest(item.Content) != item.SHA256) {
|
||||||
|
return failure(FailureInvalid, "inspect release assets", 0, fmt.Errorf("expected content does not match identity for %q", item.Filename))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func validAssetName(name string) bool {
|
||||||
|
return name != "" && name != "." && name != ".." && path.Base(name) == name && !strings.ContainsAny(name, "\\\r\n\x00")
|
||||||
|
}
|
||||||
|
|
||||||
|
func validSHA256(value string) bool {
|
||||||
|
if len(value) != sha256.Size*2 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
_, err := hex.DecodeString(value)
|
||||||
|
return err == nil && strings.ToLower(value) == value
|
||||||
|
}
|
||||||
|
|
||||||
|
func digest(content []byte) string {
|
||||||
|
sum := sha256.Sum256(content)
|
||||||
|
return hex.EncodeToString(sum[:])
|
||||||
|
}
|
||||||
|
|
||||||
|
func sameOrigin(base, target *url.URL) bool {
|
||||||
|
if target == nil || target.User != nil || target.Host == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return strings.EqualFold(base.Scheme, target.Scheme) && strings.EqualFold(base.Hostname(), target.Hostname()) && effectivePort(base) == effectivePort(target)
|
||||||
|
}
|
||||||
|
|
||||||
|
func effectivePort(parsed *url.URL) string {
|
||||||
|
if port := parsed.Port(); port != "" {
|
||||||
|
return port
|
||||||
|
}
|
||||||
|
if strings.EqualFold(parsed.Scheme, "https") {
|
||||||
|
return "443"
|
||||||
|
}
|
||||||
|
return "80"
|
||||||
|
}
|
||||||
|
|
||||||
|
func isRedirect(status int) bool {
|
||||||
|
switch status {
|
||||||
|
case http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect, http.StatusPermanentRedirect:
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
325
internal/gitea/assets_test.go
Normal file
325
internal/gitea/assets_test.go
Normal file
@@ -0,0 +1,325 @@
|
|||||||
|
package gitea
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"sync/atomic"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
const assetListPath = "/api/v1/repos/owner/project/releases/10/assets"
|
||||||
|
|
||||||
|
func TestBuildManifestSortsNamesAndOmitsEmptySourceOnlyManifest(t *testing.T) {
|
||||||
|
manifest, err := BuildManifest([]ExpectedAsset{
|
||||||
|
assetFor("zeta.bin", []byte("zeta")),
|
||||||
|
assetFor("alpha.bin", []byte("alpha")),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
want := fmt.Sprintf("%s alpha.bin\n%s zeta.bin\n", digest([]byte("alpha")), digest([]byte("zeta")))
|
||||||
|
if string(manifest.Content) != want || manifest.Filename != ManifestFilename || manifest.SHA256 != digest([]byte(want)) || manifest.Size != int64(len(want)) {
|
||||||
|
t.Fatalf("manifest = %#v, content %q", manifest, manifest.Content)
|
||||||
|
}
|
||||||
|
empty, err := BuildManifest(nil)
|
||||||
|
if err != nil || empty.Filename != "" || len(empty.Content) != 0 {
|
||||||
|
t.Fatalf("empty manifest = %#v, error = %v", empty, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInspectAssetsAcceptsMatchingContentAndPreservesUnrelatedFiles(t *testing.T) {
|
||||||
|
content := []byte("selected binary")
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
assertAssetGET(t, r, "")
|
||||||
|
switch r.URL.Path {
|
||||||
|
case assetListPath:
|
||||||
|
writeAssetList(t, w, []assetResponse{
|
||||||
|
{ID: 4, Name: "app-v1.2.3-linux-amd64", Size: int64(len(content)), BrowserDownloadURL: "/files/app"},
|
||||||
|
{ID: 8, Name: "notes.txt", Size: 9, BrowserDownloadURL: "/files/notes"},
|
||||||
|
})
|
||||||
|
case "/files/app":
|
||||||
|
_, _ = w.Write(content)
|
||||||
|
case "/files/notes":
|
||||||
|
_, _ = w.Write([]byte("unrelated"))
|
||||||
|
default:
|
||||||
|
t.Fatalf("unexpected path %s", r.URL.Path)
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
|
||||||
|
inspection, err := testClient(server).InspectAssets(context.Background(), testDestination(server.URL), 10, []ExpectedAsset{assetFor("app-v1.2.3-linux-amd64", content)})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(inspection.Assets) != 1 || inspection.Assets[0].State != AssetMatching {
|
||||||
|
t.Fatalf("inspection = %#v", inspection)
|
||||||
|
}
|
||||||
|
if len(inspection.Unrelated) != 1 || inspection.Unrelated[0].Filename != "notes.txt" {
|
||||||
|
t.Fatalf("unrelated = %#v", inspection.Unrelated)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInspectAssetsDetectsSameNameAndSizeWithDifferentBytes(t *testing.T) {
|
||||||
|
expected := []ExpectedAsset{assetFor("app.bin", []byte("alpha")), assetFor("other.bin", []byte("beta"))}
|
||||||
|
var appDownloads, otherDownloads atomic.Int32
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
assertAssetGET(t, r, "")
|
||||||
|
if r.URL.Path == assetListPath {
|
||||||
|
writeAssetList(t, w, []assetResponse{
|
||||||
|
{ID: 2, Name: expected[0].Filename, Size: 5, BrowserDownloadURL: "/files/app"},
|
||||||
|
{ID: 3, Name: expected[1].Filename, Size: 4, BrowserDownloadURL: "/files/other"},
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.URL.Path == "/files/app" {
|
||||||
|
appDownloads.Add(1)
|
||||||
|
_, _ = w.Write([]byte("bravo"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
otherDownloads.Add(1)
|
||||||
|
_, _ = w.Write([]byte("beta"))
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
inspection, err := testClient(server).InspectAssets(context.Background(), testDestination(server.URL), 10, expected)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if inspection.Assets[0].State != AssetConflicting || inspection.Assets[1].State != AssetMatching || appDownloads.Load() != 1 || otherDownloads.Load() != 1 {
|
||||||
|
t.Fatalf("inspection = %#v, downloads = %d and %d", inspection, appDownloads.Load(), otherDownloads.Load())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInspectAssetsAcceptsFullManifestWhenBinariesAreMissing(t *testing.T) {
|
||||||
|
binaries := []ExpectedAsset{assetFor("alpha.bin", []byte("alpha")), assetFor("beta.bin", []byte("beta"))}
|
||||||
|
manifest, err := BuildManifest(binaries)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
assertAssetGET(t, r, "")
|
||||||
|
if r.URL.Path == assetListPath {
|
||||||
|
writeAssetList(t, w, []assetResponse{{ID: 3, Name: manifest.Filename, Size: manifest.Size, BrowserDownloadURL: "/files/manifest"}})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.URL.Path != "/files/manifest" {
|
||||||
|
t.Fatalf("unexpected path %s", r.URL.Path)
|
||||||
|
}
|
||||||
|
_, _ = w.Write(manifest.Content)
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
inspection, err := testClient(server).InspectAssets(context.Background(), testDestination(server.URL), 10, append(binaries, manifest))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(inspection.Assets) != 3 || inspection.Assets[0].State != AssetMissing || inspection.Assets[1].State != AssetMissing || inspection.Assets[2].State != AssetMatching {
|
||||||
|
t.Fatalf("inspection = %#v", inspection)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInspectAssetsRejectsSubsetManifest(t *testing.T) {
|
||||||
|
binaries := []ExpectedAsset{assetFor("alpha.bin", []byte("alpha")), assetFor("beta.bin", []byte("beta"))}
|
||||||
|
full, err := BuildManifest(binaries)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
subset, err := BuildManifest(binaries[:1])
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
assertAssetGET(t, r, "")
|
||||||
|
if r.URL.Path == assetListPath {
|
||||||
|
writeAssetList(t, w, []assetResponse{{ID: 3, Name: ManifestFilename, Size: subset.Size, BrowserDownloadURL: "/files/manifest"}})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_, _ = w.Write(subset.Content)
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
inspection, err := testClient(server).InspectAssets(context.Background(), testDestination(server.URL), 10, []ExpectedAsset{full})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if inspection.Assets[0].State != AssetConflicting {
|
||||||
|
t.Fatalf("inspection = %#v", inspection)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInspectAssetsRejectsDifferentManifest(t *testing.T) {
|
||||||
|
expected, err := BuildManifest([]ExpectedAsset{assetFor("alpha.bin", []byte("alpha"))})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
different := []byte("not the declared checksum list\n")
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
assertAssetGET(t, r, "")
|
||||||
|
if r.URL.Path == assetListPath {
|
||||||
|
writeAssetList(t, w, []assetResponse{{ID: 3, Name: ManifestFilename, Size: int64(len(different)), BrowserDownloadURL: "/files/manifest"}})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_, _ = w.Write(different)
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
inspection, err := testClient(server).InspectAssets(context.Background(), testDestination(server.URL), 10, []ExpectedAsset{expected})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if inspection.Assets[0].State != AssetConflicting {
|
||||||
|
t.Fatalf("inspection = %#v", inspection)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInspectAssetsMarksUnreadableContentUnverifiable(t *testing.T) {
|
||||||
|
expected := assetFor("app.bin", []byte("alpha"))
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
assertAssetGET(t, r, "")
|
||||||
|
if r.URL.Path == assetListPath {
|
||||||
|
writeAssetList(t, w, []assetResponse{{ID: 2, Name: expected.Filename, Size: expected.Size, BrowserDownloadURL: "/files/app"}})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
http.Error(w, "forbidden", http.StatusForbidden)
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
inspection, err := testClient(server).InspectAssets(context.Background(), testDestination(server.URL), 10, []ExpectedAsset{expected})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if inspection.Assets[0].State != AssetUnverifiable || inspection.Assets[0].Err == nil {
|
||||||
|
t.Fatalf("inspection = %#v", inspection)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInspectAssetsRejectsMalformedAttachmentList(t *testing.T) {
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
assertAssetGET(t, r, assetListPath)
|
||||||
|
_, _ = w.Write([]byte("null"))
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
_, err := testClient(server).InspectAssets(context.Background(), testDestination(server.URL), 10, []ExpectedAsset{assetFor("app.bin", []byte("alpha"))})
|
||||||
|
if failureKind(t, err) != FailureMalformed {
|
||||||
|
t.Fatalf("error = %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInspectAssetsSourceOnlyDoesNotDeclareManifest(t *testing.T) {
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
assertAssetGET(t, r, assetListPath)
|
||||||
|
writeAssetList(t, w, []assetResponse{{ID: 7, Name: "historical.txt", Size: 3}})
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
inspection, err := testClient(server).InspectAssets(context.Background(), testDestination(server.URL), 10, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(inspection.Assets) != 0 || len(inspection.Unrelated) != 1 || inspection.Unrelated[0].Filename != "historical.txt" {
|
||||||
|
t.Fatalf("inspection = %#v", inspection)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInspectAssetsFollowsSameOriginRedirectWithAuthorization(t *testing.T) {
|
||||||
|
content := []byte("alpha")
|
||||||
|
expected := assetFor("app.bin", content)
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
assertAssetGET(t, r, "")
|
||||||
|
if r.URL.Path == assetListPath {
|
||||||
|
writeAssetList(t, w, []assetResponse{{ID: 1, Name: expected.Filename, Size: expected.Size, BrowserDownloadURL: "/files/redirect"}})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.URL.Path == "/files/redirect" {
|
||||||
|
http.Redirect(w, r, "/files/content", http.StatusFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.URL.Path == "/files/content" {
|
||||||
|
_, _ = w.Write(content)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
t.Fatalf("unexpected path %s", r.URL.Path)
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
inspection, err := testClient(server).InspectAssets(context.Background(), testDestination(server.URL), 10, []ExpectedAsset{expected})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if inspection.Assets[0].State != AssetMatching {
|
||||||
|
t.Fatalf("inspection = %#v", inspection)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInspectAssetsVerifiesExternalContentWithoutGiteaToken(t *testing.T) {
|
||||||
|
for _, mode := range []string{"direct", "redirect", "conflicting"} {
|
||||||
|
t.Run(mode, func(t *testing.T) {
|
||||||
|
expected := assetFor("app.bin", []byte("matching bytes"))
|
||||||
|
externalGets := 0
|
||||||
|
external := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
externalGets++
|
||||||
|
if r.Header.Get("Authorization") != "" {
|
||||||
|
t.Error("Gitea token reached external host")
|
||||||
|
}
|
||||||
|
content := []byte("matching bytes")
|
||||||
|
if mode == "conflicting" {
|
||||||
|
content = []byte("different bytes")
|
||||||
|
}
|
||||||
|
w.Write(content)
|
||||||
|
}))
|
||||||
|
defer external.Close()
|
||||||
|
origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
assertAssetGET(t, r, "")
|
||||||
|
if r.URL.Path == assetListPath {
|
||||||
|
download := external.URL + "/content"
|
||||||
|
if mode == "redirect" {
|
||||||
|
download = "/redirect"
|
||||||
|
}
|
||||||
|
writeAssetList(t, w, []assetResponse{{ID: 1, Name: expected.Filename, Size: expected.Size, BrowserDownloadURL: download}})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
http.Redirect(w, r, external.URL+"/content", http.StatusFound)
|
||||||
|
}))
|
||||||
|
defer origin.Close()
|
||||||
|
inspection, err := testClient(origin).InspectAssets(context.Background(), testDestination(origin.URL), 10, []ExpectedAsset{expected})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
want := AssetMatching
|
||||||
|
if mode == "conflicting" {
|
||||||
|
want = AssetConflicting
|
||||||
|
}
|
||||||
|
if inspection.Assets[0].State != want || externalGets != 1 {
|
||||||
|
t.Fatalf("inspection=%#v downloads=%d", inspection, externalGets)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func assetFor(filename string, content []byte) ExpectedAsset {
|
||||||
|
sum := sha256.Sum256(content)
|
||||||
|
return ExpectedAsset{Filename: filename, SHA256: hex.EncodeToString(sum[:]), Size: int64(len(content)), Content: append([]byte(nil), content...)}
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeAssetList(t *testing.T, w http.ResponseWriter, assets []assetResponse) {
|
||||||
|
t.Helper()
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
if err := json.NewEncoder(w).Encode(assets); err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func assertAssetGET(t *testing.T, r *http.Request, expectedPath string) {
|
||||||
|
t.Helper()
|
||||||
|
if r.Method != http.MethodGet {
|
||||||
|
t.Errorf("method = %q, want GET", r.Method)
|
||||||
|
}
|
||||||
|
if expectedPath != "" && r.URL.Path != expectedPath {
|
||||||
|
t.Errorf("path = %q, want %q", r.URL.Path, expectedPath)
|
||||||
|
}
|
||||||
|
if got := r.Header.Get("Authorization"); got != "token "+testToken {
|
||||||
|
t.Errorf("Authorization = %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func testDestination(base string) Destination {
|
||||||
|
return Destination{BaseURL: base, Owner: "owner", Repository: "project", Token: testToken}
|
||||||
|
}
|
||||||
375
internal/gitea/release.go
Normal file
375
internal/gitea/release.go
Normal file
@@ -0,0 +1,375 @@
|
|||||||
|
// Package gitea implements the internal Gitea REST operations used by delivery.
|
||||||
|
package gitea
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/versioncontract"
|
||||||
|
)
|
||||||
|
|
||||||
|
type FailureKind string
|
||||||
|
|
||||||
|
const (
|
||||||
|
FailureInvalid FailureKind = "invalid_request"
|
||||||
|
FailureNotFound FailureKind = "not_found"
|
||||||
|
FailureUnauthorized FailureKind = "unauthorized"
|
||||||
|
FailureConflict FailureKind = "conflict"
|
||||||
|
FailureMalformed FailureKind = "malformed_response"
|
||||||
|
FailureUnverifiable FailureKind = "unverifiable"
|
||||||
|
FailureTransport FailureKind = "transport"
|
||||||
|
FailureRejected FailureKind = "rejected"
|
||||||
|
FailureUnknown FailureKind = "unknown"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Failure describes how a Gitea operation failed. StatusCode is zero when no
|
||||||
|
// HTTP response was received.
|
||||||
|
type Failure struct {
|
||||||
|
Kind FailureKind
|
||||||
|
Operation string
|
||||||
|
StatusCode int
|
||||||
|
Err error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Failure) Error() string {
|
||||||
|
if f.StatusCode != 0 {
|
||||||
|
return fmt.Sprintf("gitea %s: %s (HTTP %d)", f.Operation, f.Kind, f.StatusCode)
|
||||||
|
}
|
||||||
|
if f.Err != nil {
|
||||||
|
return fmt.Sprintf("gitea %s: %s: %v", f.Operation, f.Kind, f.Err)
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("gitea %s: %s", f.Operation, f.Kind)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Failure) Unwrap() error { return f.Err }
|
||||||
|
|
||||||
|
type Destination struct {
|
||||||
|
BaseURL string
|
||||||
|
Owner string
|
||||||
|
Repository string
|
||||||
|
Token string
|
||||||
|
}
|
||||||
|
|
||||||
|
type Request struct {
|
||||||
|
Destination Destination
|
||||||
|
Version string
|
||||||
|
Commit string
|
||||||
|
Note string
|
||||||
|
}
|
||||||
|
|
||||||
|
type Release struct {
|
||||||
|
ID int64
|
||||||
|
URL string
|
||||||
|
TagName string
|
||||||
|
Title string
|
||||||
|
Body string
|
||||||
|
Draft bool
|
||||||
|
Prerelease bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type Result struct {
|
||||||
|
Release Release
|
||||||
|
Created bool
|
||||||
|
WriteAttempted bool // a create request was issued, including reconciled creates.
|
||||||
|
}
|
||||||
|
|
||||||
|
type Client struct {
|
||||||
|
HTTPClient *http.Client
|
||||||
|
}
|
||||||
|
|
||||||
|
type tagResponse struct {
|
||||||
|
Commit struct {
|
||||||
|
SHA string `json:"sha"`
|
||||||
|
} `json:"commit"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type releaseResponse struct {
|
||||||
|
ID int64 `json:"id"`
|
||||||
|
HTMLURL string `json:"html_url"`
|
||||||
|
TagName string `json:"tag_name"`
|
||||||
|
TargetCommitish string `json:"target_commitish"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Body string `json:"body"`
|
||||||
|
Draft bool `json:"draft"`
|
||||||
|
Prerelease bool `json:"prerelease"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type createReleaseRequest struct {
|
||||||
|
TagName string `json:"tag_name"`
|
||||||
|
TargetCommitish string `json:"target_commitish"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Body string `json:"body"`
|
||||||
|
Draft bool `json:"draft"`
|
||||||
|
Prerelease bool `json:"prerelease"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// EnsureRelease verifies the hosted tag and finds or creates its stable release
|
||||||
|
// page. It never edits a release that already exists.
|
||||||
|
func (c Client) EnsureRelease(ctx context.Context, request Request) (Result, error) {
|
||||||
|
if err := validateRequest(request); err != nil {
|
||||||
|
return Result{}, err
|
||||||
|
}
|
||||||
|
base, err := parseBaseURL(request.Destination.BaseURL)
|
||||||
|
if err != nil {
|
||||||
|
return Result{}, failure(FailureInvalid, "validate destination", 0, err)
|
||||||
|
}
|
||||||
|
client := c.httpClient()
|
||||||
|
apiRoot := strings.TrimRight(base.String(), "/") + "/api/v1/repos/" + url.PathEscape(request.Destination.Owner) + "/" + url.PathEscape(request.Destination.Repository)
|
||||||
|
tagURL := apiRoot + "/tags/" + url.PathEscape(request.Version)
|
||||||
|
|
||||||
|
var tag tagResponse
|
||||||
|
if err := c.getJSON(ctx, client, request.Destination.Token, "get hosted tag", tagURL, &tag); err != nil {
|
||||||
|
return Result{}, err
|
||||||
|
}
|
||||||
|
if tag.Commit.SHA != request.Commit {
|
||||||
|
return Result{}, failure(FailureConflict, "verify hosted tag", 0, fmt.Errorf("tag %q targets %q, want %q", request.Version, tag.Commit.SHA, request.Commit))
|
||||||
|
}
|
||||||
|
|
||||||
|
releaseURL := apiRoot + "/releases/tags/" + url.PathEscape(request.Version)
|
||||||
|
existing, status, err := c.getRelease(ctx, client, request.Destination.Token, releaseURL)
|
||||||
|
if err == nil {
|
||||||
|
return acceptExisting(existing, request)
|
||||||
|
}
|
||||||
|
if status != http.StatusNotFound {
|
||||||
|
return Result{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
title := noteTitle(request.Note)
|
||||||
|
body, err := json.Marshal(createReleaseRequest{
|
||||||
|
TagName: request.Version, TargetCommitish: request.Commit,
|
||||||
|
Name: title, Body: request.Note,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return Result{}, failure(FailureInvalid, "encode release", 0, err)
|
||||||
|
}
|
||||||
|
created, postStatus, postErr := c.postRelease(ctx, client, request.Destination.Token, apiRoot+"/releases", body)
|
||||||
|
if postErr == nil {
|
||||||
|
result, verifyErr := acceptCreated(created, request)
|
||||||
|
if verifyErr == nil {
|
||||||
|
result.WriteAttempted = true
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
postErr = verifyErr
|
||||||
|
}
|
||||||
|
if !shouldReconcileWrite(postStatus, postErr) {
|
||||||
|
return Result{}, postErr
|
||||||
|
}
|
||||||
|
|
||||||
|
// A conflict or interrupted server response may have followed a successful
|
||||||
|
// create. One lookup resolves only a page with the exact selected content.
|
||||||
|
retry, retryStatus, retryErr := c.getRelease(ctx, client, request.Destination.Token, releaseURL)
|
||||||
|
if retryErr == nil {
|
||||||
|
result, matchErr := acceptExisting(retry, request)
|
||||||
|
if matchErr == nil {
|
||||||
|
result.WriteAttempted = true
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
return Result{}, failure(FailureConflict, "resolve release creation", postStatus, matchErr)
|
||||||
|
}
|
||||||
|
if retryStatus == http.StatusNotFound {
|
||||||
|
if postStatus == http.StatusConflict {
|
||||||
|
return Result{}, failure(FailureConflict, "create release", postStatus, postErr)
|
||||||
|
}
|
||||||
|
return Result{}, failure(FailureUnknown, "resolve release creation", postStatus, postErr)
|
||||||
|
}
|
||||||
|
return Result{}, failure(FailureUnknown, "resolve release creation", postStatus, errors.Join(postErr, retryErr))
|
||||||
|
}
|
||||||
|
|
||||||
|
func shouldReconcileWrite(status int, err error) bool {
|
||||||
|
if status == http.StatusConflict || status >= 500 || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
var failure *Failure
|
||||||
|
return errors.As(err, &failure) && (failure.Kind == FailureTransport || failure.Kind == FailureMalformed)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c Client) getRelease(ctx context.Context, client *http.Client, token, endpoint string) (Release, int, error) {
|
||||||
|
request, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
|
||||||
|
if err != nil {
|
||||||
|
return Release{}, 0, failure(FailureInvalid, "find release", 0, err)
|
||||||
|
}
|
||||||
|
request.Header.Set("Authorization", "token "+token)
|
||||||
|
request.Header.Set("Accept", "application/json")
|
||||||
|
response, err := client.Do(request)
|
||||||
|
if err != nil {
|
||||||
|
return Release{}, 0, failure(FailureTransport, "find release", 0, err)
|
||||||
|
}
|
||||||
|
defer response.Body.Close()
|
||||||
|
if response.StatusCode == http.StatusNotFound {
|
||||||
|
return Release{}, response.StatusCode, failure(FailureNotFound, "find release", response.StatusCode, nil)
|
||||||
|
}
|
||||||
|
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
||||||
|
return Release{}, response.StatusCode, responseFailure("find release", response.StatusCode)
|
||||||
|
}
|
||||||
|
var decoded releaseResponse
|
||||||
|
if err := decodeJSON(response.Body, &decoded); err != nil {
|
||||||
|
return Release{}, response.StatusCode, failure(FailureMalformed, "decode release", response.StatusCode, err)
|
||||||
|
}
|
||||||
|
return decoded.Release(), response.StatusCode, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c Client) getJSON(ctx context.Context, client *http.Client, token, operation, endpoint string, destination any) error {
|
||||||
|
request, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
|
||||||
|
if err != nil {
|
||||||
|
return failure(FailureInvalid, operation, 0, err)
|
||||||
|
}
|
||||||
|
request.Header.Set("Authorization", "token "+token)
|
||||||
|
request.Header.Set("Accept", "application/json")
|
||||||
|
response, err := client.Do(request)
|
||||||
|
if err != nil {
|
||||||
|
return failure(FailureTransport, operation, 0, err)
|
||||||
|
}
|
||||||
|
defer response.Body.Close()
|
||||||
|
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
||||||
|
return responseFailure(operation, response.StatusCode)
|
||||||
|
}
|
||||||
|
if err := decodeJSON(response.Body, destination); err != nil {
|
||||||
|
return failure(FailureMalformed, operation, response.StatusCode, err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c Client) postRelease(ctx context.Context, client *http.Client, token, endpoint string, body []byte) (Release, int, error) {
|
||||||
|
request, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
|
||||||
|
if err != nil {
|
||||||
|
return Release{}, 0, failure(FailureInvalid, "create release", 0, err)
|
||||||
|
}
|
||||||
|
request.Header.Set("Authorization", "token "+token)
|
||||||
|
request.Header.Set("Accept", "application/json")
|
||||||
|
request.Header.Set("Content-Type", "application/json")
|
||||||
|
response, err := client.Do(request)
|
||||||
|
if err != nil {
|
||||||
|
return Release{}, 0, failure(FailureTransport, "create release", 0, err)
|
||||||
|
}
|
||||||
|
defer response.Body.Close()
|
||||||
|
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
||||||
|
return Release{}, response.StatusCode, responseFailure("create release", response.StatusCode)
|
||||||
|
}
|
||||||
|
var decoded releaseResponse
|
||||||
|
if err := decodeJSON(response.Body, &decoded); err != nil {
|
||||||
|
return Release{}, response.StatusCode, failure(FailureMalformed, "decode created release", response.StatusCode, err)
|
||||||
|
}
|
||||||
|
return decoded.Release(), response.StatusCode, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c Client) httpClient() *http.Client {
|
||||||
|
client := http.DefaultClient
|
||||||
|
if c.HTTPClient != nil {
|
||||||
|
clientCopy := *c.HTTPClient
|
||||||
|
clientCopy.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
|
||||||
|
return &clientCopy
|
||||||
|
}
|
||||||
|
clientCopy := *client
|
||||||
|
clientCopy.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
|
||||||
|
return &clientCopy
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateRequest(request Request) error {
|
||||||
|
if !versioncontract.ValidStableVersion(request.Version) {
|
||||||
|
return failure(FailureInvalid, "validate request", 0, errors.New("stable version is required"))
|
||||||
|
}
|
||||||
|
if !validObjectID(request.Commit) {
|
||||||
|
return failure(FailureInvalid, "validate request", 0, errors.New("source commit must be a lowercase Git object ID"))
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(request.Destination.Owner) == "" || strings.ContainsAny(request.Destination.Owner, "/\\") {
|
||||||
|
return failure(FailureInvalid, "validate request", 0, errors.New("Gitea owner is required as one path segment"))
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(request.Destination.Repository) == "" || strings.ContainsAny(request.Destination.Repository, "/\\") {
|
||||||
|
return failure(FailureInvalid, "validate request", 0, errors.New("Gitea repository is required as one path segment"))
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(request.Destination.Token) == "" {
|
||||||
|
return failure(FailureInvalid, "validate request", 0, errors.New("Gitea token is required"))
|
||||||
|
}
|
||||||
|
if noteTitle(request.Note) == "" {
|
||||||
|
return failure(FailureInvalid, "validate request", 0, errors.New("release note must begin with a level-one heading"))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseBaseURL(raw string) (*url.URL, error) {
|
||||||
|
parsed, err := url.Parse(raw)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" || parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" {
|
||||||
|
return nil, errors.New("base URL must be an absolute HTTP(S) origin or path without credentials, query, or fragment")
|
||||||
|
}
|
||||||
|
return parsed, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func acceptExisting(release Release, request Request) (Result, error) {
|
||||||
|
if release.TagName != request.Version || release.Body != request.Note || release.Draft || release.Prerelease {
|
||||||
|
return Result{}, failure(FailureConflict, "verify existing release", 0, errors.New("existing release does not match the committed note and stable tag"))
|
||||||
|
}
|
||||||
|
return Result{Release: release}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func acceptCreated(release Release, request Request) (Result, error) {
|
||||||
|
if release.ID <= 0 || release.TagName != request.Version || release.Body != request.Note || release.Title != noteTitle(request.Note) || release.Draft || release.Prerelease {
|
||||||
|
return Result{}, failure(FailureMalformed, "verify created release", 0, errors.New("created release response does not match the requested stable release"))
|
||||||
|
}
|
||||||
|
return Result{Release: release, Created: true}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (response releaseResponse) Release() Release {
|
||||||
|
return Release{ID: response.ID, URL: response.HTMLURL, TagName: response.TagName, Title: response.Name, Body: response.Body, Draft: response.Draft, Prerelease: response.Prerelease}
|
||||||
|
}
|
||||||
|
|
||||||
|
func noteTitle(note string) string {
|
||||||
|
first := strings.SplitN(note, "\n", 2)[0]
|
||||||
|
if !strings.HasPrefix(first, "# ") {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return strings.TrimSpace(strings.TrimPrefix(first, "# "))
|
||||||
|
}
|
||||||
|
|
||||||
|
func validObjectID(value string) bool {
|
||||||
|
if len(value) != 40 && len(value) != 64 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, r := range value {
|
||||||
|
if !(r >= '0' && r <= '9') && !(r >= 'a' && r <= 'f') {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func responseFailure(operation string, status int) error {
|
||||||
|
kind := FailureRejected
|
||||||
|
switch status {
|
||||||
|
case http.StatusUnauthorized, http.StatusForbidden:
|
||||||
|
kind = FailureUnauthorized
|
||||||
|
case http.StatusConflict:
|
||||||
|
kind = FailureConflict
|
||||||
|
case http.StatusNotFound:
|
||||||
|
kind = FailureNotFound
|
||||||
|
}
|
||||||
|
return failure(kind, operation, status, nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
func failure(kind FailureKind, operation string, status int, err error) error {
|
||||||
|
return &Failure{Kind: kind, Operation: operation, StatusCode: status, Err: err}
|
||||||
|
}
|
||||||
|
|
||||||
|
func decodeJSON(reader io.Reader, destination any) error {
|
||||||
|
decoder := json.NewDecoder(reader)
|
||||||
|
if err := decoder.Decode(destination); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var trailing any
|
||||||
|
if err := decoder.Decode(&trailing); !errors.Is(err, io.EOF) {
|
||||||
|
if err == nil {
|
||||||
|
return errors.New("response contains multiple JSON values")
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
395
internal/gitea/release_test.go
Normal file
395
internal/gitea/release_test.go
Normal file
@@ -0,0 +1,395 @@
|
|||||||
|
package gitea
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
const testCommit = "0123456789012345678901234567890123456789"
|
||||||
|
const testNote = "# Example v1.2.3\n\nRelease details.\n"
|
||||||
|
const testToken = "fixture-secret-token"
|
||||||
|
|
||||||
|
func TestEnsureReleaseFindsMatchingReleaseAndPreservesTitle(t *testing.T) {
|
||||||
|
server, _ := newReleaseServer(t, releaseFixture{title: "Historical title"}, false)
|
||||||
|
result, err := testClient(server).EnsureRelease(context.Background(), testRequest(server.URL))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if result.Created || result.Release.Title != "Historical title" {
|
||||||
|
t.Fatalf("result = %#v", result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEnsureReleaseCreatesMissingPageFromCommittedNote(t *testing.T) {
|
||||||
|
server, _ := newReleaseServer(t, releaseFixture{}, true)
|
||||||
|
result, err := testClient(server).EnsureRelease(context.Background(), testRequest(server.URL))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !result.Created || result.Release.Title != "Example v1.2.3" || result.Release.Body != testNote {
|
||||||
|
t.Fatalf("result = %#v", result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEnsureReleaseConflictDoesNotEditExistingPage(t *testing.T) {
|
||||||
|
server, state := newReleaseServer(t, releaseFixture{title: "Keep this title", body: "Different body"}, false)
|
||||||
|
_, err := testClient(server).EnsureRelease(context.Background(), testRequest(server.URL))
|
||||||
|
if failureKind(t, err) != FailureConflict {
|
||||||
|
t.Fatalf("error = %v", err)
|
||||||
|
}
|
||||||
|
if got := state.posts; got != 0 {
|
||||||
|
t.Fatalf("release creates = %d, want 0", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEnsureReleaseUnauthorizedIsStructuredAndHidesToken(t *testing.T) {
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
assertRequest(t, r, http.MethodGet, "/api/v1/repos/owner/project/tags/v1.2.3")
|
||||||
|
w.WriteHeader(http.StatusUnauthorized)
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
_, err := testClient(server).EnsureRelease(context.Background(), testRequest(server.URL))
|
||||||
|
if failureKind(t, err) != FailureUnauthorized {
|
||||||
|
t.Fatalf("error = %v", err)
|
||||||
|
}
|
||||||
|
if fmt.Sprint(err) == "" || contains(fmt.Sprint(err), testToken) {
|
||||||
|
t.Fatalf("error exposes unexpected content: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEnsureReleaseMalformedTagResponseStopsBeforeCreate(t *testing.T) {
|
||||||
|
posts := 0
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method == http.MethodPost {
|
||||||
|
posts++
|
||||||
|
}
|
||||||
|
assertRequest(t, r, http.MethodGet, "/api/v1/repos/owner/project/tags/v1.2.3")
|
||||||
|
_, _ = w.Write([]byte("{"))
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
_, err := testClient(server).EnsureRelease(context.Background(), testRequest(server.URL))
|
||||||
|
if failureKind(t, err) != FailureMalformed || posts != 0 {
|
||||||
|
t.Fatalf("error = %v, posts = %d", err, posts)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEnsureReleaseWrongHostedTagStopsBeforeCreate(t *testing.T) {
|
||||||
|
posts := 0
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
assertRequest(t, r, http.MethodGet, "/api/v1/repos/owner/project/tags/v1.2.3")
|
||||||
|
if r.Method == http.MethodPost {
|
||||||
|
posts++
|
||||||
|
}
|
||||||
|
_, _ = fmt.Fprintf(w, `{"commit":{"sha":"%040d"}}`, 7)
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
_, err := testClient(server).EnsureRelease(context.Background(), testRequest(server.URL))
|
||||||
|
if failureKind(t, err) != FailureConflict || posts != 0 {
|
||||||
|
t.Fatalf("error = %v, posts = %d", err, posts)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEnsureReleaseMissingHostedTagStopsBeforeCreate(t *testing.T) {
|
||||||
|
posts := 0
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
assertRequest(t, r, http.MethodGet, "/api/v1/repos/owner/project/tags/v1.2.3")
|
||||||
|
if r.Method == http.MethodPost {
|
||||||
|
posts++
|
||||||
|
}
|
||||||
|
http.NotFound(w, r)
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
_, err := testClient(server).EnsureRelease(context.Background(), testRequest(server.URL))
|
||||||
|
if failureKind(t, err) != FailureNotFound || posts != 0 {
|
||||||
|
t.Fatalf("error = %v, posts = %d", err, posts)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEnsureReleaseHonorsContextCancellation(t *testing.T) {
|
||||||
|
called := false
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { called = true }))
|
||||||
|
defer server.Close()
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
cancel()
|
||||||
|
_, err := testClient(server).EnsureRelease(ctx, testRequest(server.URL))
|
||||||
|
if !errors.Is(err, context.Canceled) || called {
|
||||||
|
t.Fatalf("error = %v, server called = %t", err, called)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEnsureReleaseResolvesLostCreateAcknowledgmentWithOneLookup(t *testing.T) {
|
||||||
|
created := false
|
||||||
|
lookups := 0
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
assertAuth(t, r)
|
||||||
|
switch r.URL.Path {
|
||||||
|
case "/api/v1/repos/owner/project/tags/v1.2.3":
|
||||||
|
assertRequest(t, r, http.MethodGet, r.URL.Path)
|
||||||
|
writeTag(t, w, testCommit)
|
||||||
|
case "/api/v1/repos/owner/project/releases/tags/v1.2.3":
|
||||||
|
assertRequest(t, r, http.MethodGet, r.URL.Path)
|
||||||
|
lookups++
|
||||||
|
if !created {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeRelease(t, w, releaseFixture{title: "Example v1.2.3"})
|
||||||
|
case "/api/v1/repos/owner/project/releases":
|
||||||
|
assertRequest(t, r, http.MethodPost, r.URL.Path)
|
||||||
|
var payload createReleaseRequest
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if payload.TagName != "v1.2.3" || payload.TargetCommitish != testCommit || payload.Name != "Example v1.2.3" || payload.Body != testNote || payload.Draft || payload.Prerelease {
|
||||||
|
t.Fatalf("create payload = %#v", payload)
|
||||||
|
}
|
||||||
|
created = true
|
||||||
|
hijacker, ok := w.(http.Hijacker)
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("HTTP writer does not support hijacking")
|
||||||
|
}
|
||||||
|
connection, _, err := hijacker.Hijack()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_ = connection.Close()
|
||||||
|
default:
|
||||||
|
t.Fatalf("unexpected request %s %s", r.Method, r.URL.Path)
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
result, err := testClient(server).EnsureRelease(context.Background(), testRequest(server.URL))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if result.Created || lookups != 2 {
|
||||||
|
t.Fatalf("result = %#v, release lookups = %d", result, lookups)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEnsureReleaseResolvesCreateConflictWithOneLookup(t *testing.T) {
|
||||||
|
lookups := 0
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
assertAuth(t, r)
|
||||||
|
switch r.URL.Path {
|
||||||
|
case "/api/v1/repos/owner/project/tags/v1.2.3":
|
||||||
|
assertRequest(t, r, http.MethodGet, r.URL.Path)
|
||||||
|
writeTag(t, w, testCommit)
|
||||||
|
case "/api/v1/repos/owner/project/releases/tags/v1.2.3":
|
||||||
|
assertRequest(t, r, http.MethodGet, r.URL.Path)
|
||||||
|
lookups++
|
||||||
|
if lookups == 1 {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeRelease(t, w, releaseFixture{title: "Created by another request"})
|
||||||
|
case "/api/v1/repos/owner/project/releases":
|
||||||
|
assertRequest(t, r, http.MethodPost, r.URL.Path)
|
||||||
|
w.WriteHeader(http.StatusConflict)
|
||||||
|
default:
|
||||||
|
t.Fatalf("unexpected request %s %s", r.Method, r.URL.Path)
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
result, err := testClient(server).EnsureRelease(context.Background(), testRequest(server.URL))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if result.Created || result.Release.Title != "Created by another request" || lookups != 2 {
|
||||||
|
t.Fatalf("result = %#v, release lookups = %d", result, lookups)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEnsureReleaseReportsUnknownWhenAmbiguousCreateCannotBeInspected(t *testing.T) {
|
||||||
|
lookups := 0
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
assertAuth(t, r)
|
||||||
|
switch r.URL.Path {
|
||||||
|
case "/api/v1/repos/owner/project/tags/v1.2.3":
|
||||||
|
assertRequest(t, r, http.MethodGet, r.URL.Path)
|
||||||
|
writeTag(t, w, testCommit)
|
||||||
|
case "/api/v1/repos/owner/project/releases/tags/v1.2.3":
|
||||||
|
assertRequest(t, r, http.MethodGet, r.URL.Path)
|
||||||
|
lookups++
|
||||||
|
if lookups == 1 {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
http.Error(w, "temporarily unavailable", http.StatusServiceUnavailable)
|
||||||
|
case "/api/v1/repos/owner/project/releases":
|
||||||
|
assertRequest(t, r, http.MethodPost, r.URL.Path)
|
||||||
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
|
default:
|
||||||
|
t.Fatalf("unexpected request %s %s", r.Method, r.URL.Path)
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
_, err := testClient(server).EnsureRelease(context.Background(), testRequest(server.URL))
|
||||||
|
if failureKind(t, err) != FailureUnknown || lookups != 2 {
|
||||||
|
t.Fatalf("error = %v, release lookups = %d", err, lookups)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type releaseFixture struct {
|
||||||
|
title string
|
||||||
|
body string
|
||||||
|
draft bool
|
||||||
|
pre bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type fixtureState struct{ posts int }
|
||||||
|
|
||||||
|
func newReleaseServer(t *testing.T, existing releaseFixture, createMissing bool) (*httptest.Server, *fixtureState) {
|
||||||
|
t.Helper()
|
||||||
|
state := &fixtureState{}
|
||||||
|
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
assertAuth(t, r)
|
||||||
|
switch r.URL.Path {
|
||||||
|
case "/api/v1/repos/owner/project/tags/v1.2.3":
|
||||||
|
assertRequest(t, r, http.MethodGet, r.URL.Path)
|
||||||
|
writeTag(t, w, testCommit)
|
||||||
|
case "/api/v1/repos/owner/project/releases/tags/v1.2.3":
|
||||||
|
assertRequest(t, r, http.MethodGet, r.URL.Path)
|
||||||
|
if existing.title == "" && existing.body == "" {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeRelease(t, w, existing)
|
||||||
|
case "/api/v1/repos/owner/project/releases":
|
||||||
|
assertRequest(t, r, http.MethodPost, r.URL.Path)
|
||||||
|
state.posts++
|
||||||
|
var payload createReleaseRequest
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if payload.TagName != "v1.2.3" || payload.TargetCommitish != testCommit || payload.Name != "Example v1.2.3" || payload.Body != testNote || payload.Draft || payload.Prerelease {
|
||||||
|
t.Fatalf("create payload = %#v", payload)
|
||||||
|
}
|
||||||
|
if !createMissing {
|
||||||
|
w.WriteHeader(http.StatusConflict)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeRelease(t, w, releaseFixture{title: payload.Name})
|
||||||
|
default:
|
||||||
|
t.Fatalf("unexpected request %s %s", r.Method, r.URL.Path)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
server := httptest.NewServer(handler)
|
||||||
|
return server, state
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeTag(t *testing.T, w http.ResponseWriter, commit string) {
|
||||||
|
t.Helper()
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
_, _ = fmt.Fprintf(w, `{"name":"v1.2.3","commit":{"sha":%q}}`, commit)
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeRelease(t *testing.T, w http.ResponseWriter, fixture releaseFixture) {
|
||||||
|
t.Helper()
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
_ = json.NewEncoder(w).Encode(releaseResponse{ID: 10, HTMLURL: "https://gitea.example/releases/10", TagName: "v1.2.3", Name: fixture.title, Body: fixture.bodyOrDefault(), Draft: fixture.draft, Prerelease: fixture.pre})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (fixture releaseFixture) bodyOrDefault() string {
|
||||||
|
if fixture.body == "" {
|
||||||
|
return testNote
|
||||||
|
}
|
||||||
|
return fixture.body
|
||||||
|
}
|
||||||
|
|
||||||
|
func assertRequest(t *testing.T, request *http.Request, method, path string) {
|
||||||
|
t.Helper()
|
||||||
|
if request.Method != method || request.URL.Path != path {
|
||||||
|
t.Fatalf("request = %s %s, want %s %s", request.Method, request.URL.Path, method, path)
|
||||||
|
}
|
||||||
|
assertAuth(t, request)
|
||||||
|
}
|
||||||
|
|
||||||
|
func assertAuth(t *testing.T, request *http.Request) {
|
||||||
|
t.Helper()
|
||||||
|
if got := request.Header.Get("Authorization"); got != "token "+testToken {
|
||||||
|
t.Fatalf("Authorization = %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func testClient(server *httptest.Server) Client {
|
||||||
|
return Client{HTTPClient: server.Client()}
|
||||||
|
}
|
||||||
|
|
||||||
|
func testRequest(baseURL string) Request {
|
||||||
|
return Request{Destination: Destination{BaseURL: baseURL, Owner: "owner", Repository: "project", Token: testToken}, Version: "v1.2.3", Commit: testCommit, Note: testNote}
|
||||||
|
}
|
||||||
|
|
||||||
|
func failureKind(t *testing.T, err error) FailureKind {
|
||||||
|
t.Helper()
|
||||||
|
var failure *Failure
|
||||||
|
if !errors.As(err, &failure) {
|
||||||
|
t.Fatalf("error type = %T (%v), want *Failure", err, err)
|
||||||
|
}
|
||||||
|
return failure.Kind
|
||||||
|
}
|
||||||
|
|
||||||
|
func contains(value, substring string) bool {
|
||||||
|
return len(substring) > 0 && len(value) >= len(substring) && strings.Contains(value, substring)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEnsureReleaseReconcilesInconsistentSuccessfulCreate(t *testing.T) {
|
||||||
|
for _, mode := range []string{"matching", "conflicting", "unavailable"} {
|
||||||
|
t.Run(mode, func(t *testing.T) {
|
||||||
|
posts, lookups := 0, 0
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
switch {
|
||||||
|
case strings.Contains(r.URL.Path, "/tags/") && !strings.Contains(r.URL.Path, "/releases/"):
|
||||||
|
writeTag(t, w, testCommit)
|
||||||
|
case strings.Contains(r.URL.Path, "/releases/tags/"):
|
||||||
|
lookups++
|
||||||
|
if posts == 0 {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if mode == "unavailable" {
|
||||||
|
http.Error(w, "unavailable", 503)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
body := testNote
|
||||||
|
if mode == "conflicting" {
|
||||||
|
body = "other content"
|
||||||
|
}
|
||||||
|
writeRelease(t, w, releaseFixture{title: "Example v1.2.3", body: body})
|
||||||
|
case r.Method == http.MethodPost:
|
||||||
|
posts++
|
||||||
|
w.WriteHeader(http.StatusCreated)
|
||||||
|
json.NewEncoder(w).Encode(releaseResponse{ID: 10, TagName: "v1.2.3", Name: "inconsistent title", Body: testNote})
|
||||||
|
default:
|
||||||
|
t.Errorf("unexpected request %s", r.URL.Path)
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
result, err := testClient(server).EnsureRelease(context.Background(), testRequest(server.URL))
|
||||||
|
if posts != 1 || lookups != 2 {
|
||||||
|
t.Fatalf("posts=%d lookups=%d", posts, lookups)
|
||||||
|
}
|
||||||
|
switch mode {
|
||||||
|
case "matching":
|
||||||
|
if err != nil || !result.WriteAttempted {
|
||||||
|
t.Fatalf("result=%#v err=%v", result, err)
|
||||||
|
}
|
||||||
|
case "conflicting":
|
||||||
|
if failureKind(t, err) != FailureConflict {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
case "unavailable":
|
||||||
|
if failureKind(t, err) != FailureUnknown {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
330
internal/gitea/upload.go
Normal file
330
internal/gitea/upload.go
Normal file
@@ -0,0 +1,330 @@
|
|||||||
|
package gitea
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"mime/multipart"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"sort"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
type DeliveryState string
|
||||||
|
|
||||||
|
const (
|
||||||
|
DeliveryNotAttempted DeliveryState = "not_attempted"
|
||||||
|
DeliveryComplete DeliveryState = "complete"
|
||||||
|
DeliveryPartial DeliveryState = "partial"
|
||||||
|
DeliveryConflict DeliveryState = "conflict"
|
||||||
|
DeliveryUnknown DeliveryState = "unknown"
|
||||||
|
)
|
||||||
|
|
||||||
|
type AssetIdentity struct {
|
||||||
|
Filename string
|
||||||
|
SHA256 string
|
||||||
|
}
|
||||||
|
|
||||||
|
// UploadResult reports the current asset observations from one upload attempt.
|
||||||
|
// Each identity appears in at most one category; early failures can leave some
|
||||||
|
// declared assets unreported.
|
||||||
|
type UploadResult struct {
|
||||||
|
State DeliveryState
|
||||||
|
// Matching contains existing attachments with the declared content.
|
||||||
|
Matching []AssetIdentity
|
||||||
|
// Uploaded contains assets whose upload was confirmed during this invocation.
|
||||||
|
Uploaded []AssetIdentity
|
||||||
|
// Pending contains assets known to be missing.
|
||||||
|
Pending []AssetIdentity
|
||||||
|
// Conflicting contains assets with detected content conflicts.
|
||||||
|
Conflicting []AssetIdentity
|
||||||
|
// Uncertain contains assets whose remote state could not be resolved.
|
||||||
|
Uncertain []AssetIdentity
|
||||||
|
}
|
||||||
|
|
||||||
|
// VerifyLocalAssets checks that every expected file still matches its declared
|
||||||
|
// size and digest before delivery begins.
|
||||||
|
func VerifyLocalAssets(assets []ExpectedAsset) error {
|
||||||
|
if err := validateExpectedAssets(assets); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for _, asset := range assets {
|
||||||
|
if err := verifyLocalAsset(asset); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// UploadMissing uploads assets classified missing by InspectAssets. It stops
|
||||||
|
// before the first write if any declared existing asset conflicts or cannot be
|
||||||
|
// verified, and never replaces an existing attachment.
|
||||||
|
func (c Client) UploadMissing(ctx context.Context, destination Destination, releaseID int64, inspection Inspection) (UploadResult, error) {
|
||||||
|
if releaseID <= 0 {
|
||||||
|
return UploadResult{State: DeliveryPartial}, failure(FailureInvalid, "upload release assets", 0, errors.New("release ID must be positive"))
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(destination.Token) == "" {
|
||||||
|
return UploadResult{State: DeliveryPartial}, failure(FailureInvalid, "upload release assets", 0, errors.New("Gitea token is required"))
|
||||||
|
}
|
||||||
|
base, err := parseBaseURL(destination.BaseURL)
|
||||||
|
if err != nil {
|
||||||
|
return UploadResult{State: DeliveryPartial}, failure(FailureInvalid, "validate destination", 0, err)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(destination.Owner) == "" || strings.ContainsAny(destination.Owner, "/\\") || strings.TrimSpace(destination.Repository) == "" || strings.ContainsAny(destination.Repository, "/\\") {
|
||||||
|
return UploadResult{State: DeliveryPartial}, failure(FailureInvalid, "upload release assets", 0, errors.New("Gitea owner and repository must be path segments"))
|
||||||
|
}
|
||||||
|
expected := orderedExpected(inspection.Assets)
|
||||||
|
if err := validateExpectedAssets(expected); err != nil {
|
||||||
|
return UploadResult{State: DeliveryPartial}, err
|
||||||
|
}
|
||||||
|
result := UploadResult{State: DeliveryPartial}
|
||||||
|
preflightConflict := false
|
||||||
|
preflightUnknown := false
|
||||||
|
for _, observation := range inspection.Assets {
|
||||||
|
switch observation.State {
|
||||||
|
case AssetMatching:
|
||||||
|
result.Matching = append(result.Matching, identity(observation.Expected))
|
||||||
|
case AssetMissing:
|
||||||
|
result.Pending = append(result.Pending, identity(observation.Expected))
|
||||||
|
case AssetConflicting:
|
||||||
|
preflightConflict = true
|
||||||
|
result.Conflicting = append(result.Conflicting, identity(observation.Expected))
|
||||||
|
case AssetUnverifiable:
|
||||||
|
preflightUnknown = true
|
||||||
|
result.Uncertain = append(result.Uncertain, identity(observation.Expected))
|
||||||
|
default:
|
||||||
|
return result, failure(FailureInvalid, "preflight release assets", 0, fmt.Errorf("asset %q has no inspection result", observation.Expected.Filename))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if preflightConflict {
|
||||||
|
result.State = DeliveryConflict
|
||||||
|
return result, failure(FailureConflict, "preflight release assets", 0, errors.New("one or more existing attachments conflict"))
|
||||||
|
}
|
||||||
|
if preflightUnknown {
|
||||||
|
result.State = DeliveryNotAttempted
|
||||||
|
return result, failure(FailureUnverifiable, "preflight release assets", 0, errors.New("one or more existing attachments could not be verified"))
|
||||||
|
}
|
||||||
|
if len(expected) == 0 {
|
||||||
|
result.State = DeliveryComplete
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
if len(result.Pending) == 0 {
|
||||||
|
result.State = DeliveryComplete
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
missing := make(map[string]ExpectedAsset, len(result.Pending))
|
||||||
|
for _, observation := range inspection.Assets {
|
||||||
|
if observation.State == AssetMissing {
|
||||||
|
missing[observation.Expected.Filename] = observation.Expected
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, item := range expected {
|
||||||
|
if _, needsUpload := missing[item.Filename]; !needsUpload {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err := verifyLocalAsset(item); err != nil {
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
baseAPI := strings.TrimRight(base.String(), "/") + "/api/v1/repos/" + url.PathEscape(destination.Owner) + "/" + url.PathEscape(destination.Repository)
|
||||||
|
client := c.httpClient()
|
||||||
|
for _, item := range expected {
|
||||||
|
if _, needsUpload := missing[item.Filename]; !needsUpload {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
status, uploadErr := c.uploadAsset(ctx, client, destination.Token, baseAPI, releaseID, item)
|
||||||
|
if uploadErr == nil {
|
||||||
|
result.Uploaded = append(result.Uploaded, identity(item))
|
||||||
|
result.Pending = removeIdentity(result.Pending, item.Filename)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !shouldReconcileWrite(status, uploadErr) {
|
||||||
|
return result, uploadErr
|
||||||
|
}
|
||||||
|
inspection, inspectErr := c.InspectAssets(ctx, destination, releaseID, []ExpectedAsset{item})
|
||||||
|
if inspectErr != nil || len(inspection.Assets) != 1 {
|
||||||
|
result.State = DeliveryUnknown
|
||||||
|
result.Pending = removeIdentity(result.Pending, item.Filename)
|
||||||
|
result.Uncertain = append(result.Uncertain, identity(item))
|
||||||
|
return result, failure(FailureUnknown, "resolve asset upload", status, errors.Join(uploadErr, inspectErr))
|
||||||
|
}
|
||||||
|
observation := inspection.Assets[0]
|
||||||
|
switch observation.State {
|
||||||
|
case AssetMatching:
|
||||||
|
result.Matching = append(result.Matching, identity(item))
|
||||||
|
result.Pending = removeIdentity(result.Pending, item.Filename)
|
||||||
|
case AssetConflicting:
|
||||||
|
result.State = DeliveryConflict
|
||||||
|
result.Pending = removeIdentity(result.Pending, item.Filename)
|
||||||
|
result.Conflicting = append(result.Conflicting, identity(item))
|
||||||
|
return result, failure(FailureConflict, "resolve asset upload", status, uploadErr)
|
||||||
|
case AssetMissing:
|
||||||
|
if status == http.StatusConflict {
|
||||||
|
result.State = DeliveryConflict
|
||||||
|
result.Pending = removeIdentity(result.Pending, item.Filename)
|
||||||
|
result.Conflicting = append(result.Conflicting, identity(item))
|
||||||
|
return result, failure(FailureConflict, "resolve asset upload", status, uploadErr)
|
||||||
|
}
|
||||||
|
result.State = DeliveryUnknown
|
||||||
|
result.Pending = removeIdentity(result.Pending, item.Filename)
|
||||||
|
result.Uncertain = append(result.Uncertain, identity(item))
|
||||||
|
return result, failure(FailureUnknown, "resolve asset upload", status, uploadErr)
|
||||||
|
default:
|
||||||
|
result.State = DeliveryUnknown
|
||||||
|
result.Pending = removeIdentity(result.Pending, item.Filename)
|
||||||
|
result.Uncertain = append(result.Uncertain, identity(item))
|
||||||
|
return result, failure(FailureUnknown, "resolve asset upload", status, errors.Join(uploadErr, observation.Err))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(result.Pending) == 0 {
|
||||||
|
result.State = DeliveryComplete
|
||||||
|
} else {
|
||||||
|
result.State = DeliveryPartial
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c Client) uploadAsset(ctx context.Context, client *http.Client, token, apiRoot string, releaseID int64, asset ExpectedAsset) (int, error) {
|
||||||
|
uploadURL := apiRoot + "/releases/" + strconv.FormatInt(releaseID, 10) + "/assets"
|
||||||
|
parsed, err := url.Parse(uploadURL)
|
||||||
|
if err != nil {
|
||||||
|
return 0, failure(FailureInvalid, "prepare asset upload", 0, err)
|
||||||
|
}
|
||||||
|
query := parsed.Query()
|
||||||
|
query.Set("name", asset.Filename)
|
||||||
|
parsed.RawQuery = query.Encode()
|
||||||
|
reader, writer := io.Pipe()
|
||||||
|
multipartWriter := multipart.NewWriter(writer)
|
||||||
|
writeDone := make(chan error, 1)
|
||||||
|
go func() {
|
||||||
|
part, partErr := multipartWriter.CreateFormFile("attachment", asset.Filename)
|
||||||
|
if partErr == nil {
|
||||||
|
var source io.Reader
|
||||||
|
if len(asset.Content) > 0 {
|
||||||
|
source = bytes.NewReader(asset.Content)
|
||||||
|
} else {
|
||||||
|
file, openErr := os.Open(asset.Path)
|
||||||
|
if openErr != nil {
|
||||||
|
partErr = openErr
|
||||||
|
} else {
|
||||||
|
defer file.Close()
|
||||||
|
source = file
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if partErr == nil {
|
||||||
|
_, partErr = io.Copy(part, source)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
closeErr := multipartWriter.Close()
|
||||||
|
if partErr == nil {
|
||||||
|
partErr = closeErr
|
||||||
|
}
|
||||||
|
_ = writer.CloseWithError(partErr)
|
||||||
|
writeDone <- partErr
|
||||||
|
}()
|
||||||
|
|
||||||
|
request, err := http.NewRequestWithContext(ctx, http.MethodPost, parsed.String(), reader)
|
||||||
|
if err != nil {
|
||||||
|
_ = reader.CloseWithError(err)
|
||||||
|
<-writeDone
|
||||||
|
return 0, failure(FailureInvalid, "upload release asset", 0, err)
|
||||||
|
}
|
||||||
|
request.Header.Set("Authorization", "token "+token)
|
||||||
|
request.Header.Set("Accept", "application/json")
|
||||||
|
request.Header.Set("Content-Type", multipartWriter.FormDataContentType())
|
||||||
|
response, requestErr := client.Do(request)
|
||||||
|
if requestErr != nil {
|
||||||
|
_ = reader.CloseWithError(requestErr)
|
||||||
|
<-writeDone
|
||||||
|
return 0, failure(FailureTransport, "upload release asset", 0, requestErr)
|
||||||
|
}
|
||||||
|
defer response.Body.Close()
|
||||||
|
writeErr := <-writeDone
|
||||||
|
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
||||||
|
return response.StatusCode, responseFailure("upload release asset", response.StatusCode)
|
||||||
|
}
|
||||||
|
var uploaded assetResponse
|
||||||
|
if err := decodeJSON(response.Body, &uploaded); err != nil {
|
||||||
|
return response.StatusCode, failure(FailureMalformed, "decode uploaded asset", response.StatusCode, err)
|
||||||
|
}
|
||||||
|
if uploaded.ID <= 0 || uploaded.Name != asset.Filename {
|
||||||
|
return response.StatusCode, failure(FailureMalformed, "verify uploaded asset", response.StatusCode, errors.New("upload response does not identify the selected asset"))
|
||||||
|
}
|
||||||
|
if writeErr != nil {
|
||||||
|
return response.StatusCode, failure(FailureMalformed, "stream uploaded asset", response.StatusCode, writeErr)
|
||||||
|
}
|
||||||
|
return response.StatusCode, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func verifyLocalAsset(asset ExpectedAsset) error {
|
||||||
|
if len(asset.Content) > 0 {
|
||||||
|
if int64(len(asset.Content)) != asset.Size || digest(asset.Content) != asset.SHA256 {
|
||||||
|
return failure(FailureConflict, "verify local asset", 0, fmt.Errorf("local content does not match declared asset %q", asset.Filename))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if asset.Path == "" || filepath.Base(asset.Path) != asset.Filename {
|
||||||
|
return failure(FailureInvalid, "verify local asset", 0, fmt.Errorf("local path for %q does not match its filename", asset.Filename))
|
||||||
|
}
|
||||||
|
file, err := os.Open(asset.Path)
|
||||||
|
if err != nil {
|
||||||
|
return failure(FailureInvalid, "verify local asset", 0, fmt.Errorf("open %q: %w", asset.Filename, err))
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
info, err := file.Stat()
|
||||||
|
if err != nil {
|
||||||
|
return failure(FailureInvalid, "verify local asset", 0, fmt.Errorf("stat %q: %w", asset.Filename, err))
|
||||||
|
}
|
||||||
|
if !info.Mode().IsRegular() || info.Size() != asset.Size {
|
||||||
|
return failure(FailureConflict, "verify local asset", 0, fmt.Errorf("local file does not match declared size for %q", asset.Filename))
|
||||||
|
}
|
||||||
|
hasher := sha256.New()
|
||||||
|
size, err := io.Copy(hasher, file)
|
||||||
|
if err != nil {
|
||||||
|
return failure(FailureInvalid, "verify local asset", 0, fmt.Errorf("read %q: %w", asset.Filename, err))
|
||||||
|
}
|
||||||
|
if size != asset.Size || hex.EncodeToString(hasher.Sum(nil)) != asset.SHA256 {
|
||||||
|
return failure(FailureConflict, "verify local asset", 0, fmt.Errorf("local content does not match declared asset %q", asset.Filename))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func orderedExpected(observations []AssetInspection) []ExpectedAsset {
|
||||||
|
result := make([]ExpectedAsset, 0, len(observations))
|
||||||
|
for _, observation := range observations {
|
||||||
|
result = append(result, observation.Expected)
|
||||||
|
}
|
||||||
|
sort.Slice(result, func(i, j int) bool {
|
||||||
|
if result[i].Filename == ManifestFilename {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if result[j].Filename == ManifestFilename {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return result[i].Filename < result[j].Filename
|
||||||
|
})
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func identity(asset ExpectedAsset) AssetIdentity {
|
||||||
|
return AssetIdentity{Filename: asset.Filename, SHA256: asset.SHA256}
|
||||||
|
}
|
||||||
|
|
||||||
|
func removeIdentity(identities []AssetIdentity, filename string) []AssetIdentity {
|
||||||
|
for index, item := range identities {
|
||||||
|
if item.Filename == filename {
|
||||||
|
return append(identities[:index], identities[index+1:]...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return identities
|
||||||
|
}
|
||||||
457
internal/gitea/upload_test.go
Normal file
457
internal/gitea/upload_test.go
Normal file
@@ -0,0 +1,457 @@
|
|||||||
|
package gitea
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestUploadMissingPartialFailureThenRerunOnlyMissingAssets(t *testing.T) {
|
||||||
|
fixture := &uploadFixture{files: make(map[string][]byte), failName: "beta.bin"}
|
||||||
|
server := httptest.NewServer(fixture)
|
||||||
|
defer server.Close()
|
||||||
|
client := testClient(server)
|
||||||
|
destination := testDestination(server.URL)
|
||||||
|
assets := localAssets(t, []string{"zeta.bin", "alpha.bin", "beta.bin"})
|
||||||
|
manifest, err := BuildManifest(assets)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
assets = append(assets, manifest)
|
||||||
|
|
||||||
|
initial, err := client.InspectAssets(context.Background(), destination, 10, assets)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
first, err := client.UploadMissing(context.Background(), destination, 10, initial)
|
||||||
|
if err == nil || first.State != DeliveryPartial {
|
||||||
|
t.Fatalf("first upload result = %#v, error = %v", first, err)
|
||||||
|
}
|
||||||
|
if got, want := names(first.Uploaded), []string{"alpha.bin"}; !reflect.DeepEqual(got, want) {
|
||||||
|
t.Fatalf("uploaded = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
if got, want := names(first.Pending), []string{"zeta.bin", "beta.bin", "SHA256SUMS"}; !reflect.DeepEqual(got, want) {
|
||||||
|
t.Fatalf("pending = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
assertAssetCategoriesDisjoint(t, first)
|
||||||
|
|
||||||
|
secondInspection, err := client.InspectAssets(context.Background(), destination, 10, assets)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
second, err := client.UploadMissing(context.Background(), destination, 10, secondInspection)
|
||||||
|
if err != nil || second.State != DeliveryComplete {
|
||||||
|
t.Fatalf("second upload result = %#v, error = %v", second, err)
|
||||||
|
}
|
||||||
|
if got, want := names(second.Uploaded), []string{"beta.bin", "zeta.bin", "SHA256SUMS"}; !reflect.DeepEqual(got, want) {
|
||||||
|
t.Fatalf("second uploaded = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
if got, want := fixture.postNames(), []string{"alpha.bin", "beta.bin", "beta.bin", "zeta.bin", "SHA256SUMS"}; !reflect.DeepEqual(got, want) {
|
||||||
|
t.Fatalf("POST order = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUploadMissingAcceptsConcurrentMatchingAttachmentWithoutReplacement(t *testing.T) {
|
||||||
|
fixture := &uploadFixture{files: make(map[string][]byte), conflictName: "app.bin"}
|
||||||
|
server := httptest.NewServer(fixture)
|
||||||
|
defer server.Close()
|
||||||
|
client := testClient(server)
|
||||||
|
destination := testDestination(server.URL)
|
||||||
|
assets := localAssets(t, []string{"app.bin"})
|
||||||
|
initial, err := client.InspectAssets(context.Background(), destination, 10, assets)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
result, err := client.UploadMissing(context.Background(), destination, 10, initial)
|
||||||
|
if err != nil || result.State != DeliveryComplete {
|
||||||
|
t.Fatalf("result = %#v, error = %v", result, err)
|
||||||
|
}
|
||||||
|
if got, want := names(result.Matching), []string{"app.bin"}; !reflect.DeepEqual(got, want) {
|
||||||
|
t.Fatalf("matching = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
if len(result.Uploaded) != 0 || len(fixture.postNames()) != 1 {
|
||||||
|
t.Fatalf("result = %#v, POST names = %v", result, fixture.postNames())
|
||||||
|
}
|
||||||
|
assertAssetCategoriesDisjoint(t, result)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUploadMissingReconcilesLostManifestAcknowledgment(t *testing.T) {
|
||||||
|
assets := localAssets(t, []string{"app.bin"})
|
||||||
|
manifest, err := BuildManifest(assets)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
fixture := &uploadFixture{files: make(map[string][]byte), dropAckName: ManifestFilename}
|
||||||
|
// The local binary is represented by its file path; the server starts with
|
||||||
|
// that exact content so only the checksum manifest needs uploading.
|
||||||
|
fixture.files["app.bin"] = readExpectedFile(t, assets[0])
|
||||||
|
server := httptest.NewServer(fixture)
|
||||||
|
defer server.Close()
|
||||||
|
client := testClient(server)
|
||||||
|
destination := testDestination(server.URL)
|
||||||
|
expected := append(assets, manifest)
|
||||||
|
initial, err := client.InspectAssets(context.Background(), destination, 10, expected)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
result, err := client.UploadMissing(context.Background(), destination, 10, initial)
|
||||||
|
if err != nil || result.State != DeliveryComplete {
|
||||||
|
t.Fatalf("result = %#v, error = %v", result, err)
|
||||||
|
}
|
||||||
|
if got, want := names(result.Matching), []string{"app.bin", ManifestFilename}; !reflect.DeepEqual(got, want) {
|
||||||
|
t.Fatalf("matching = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
if len(result.Uploaded) != 0 || !reflect.DeepEqual(fixture.postNames(), []string{ManifestFilename}) {
|
||||||
|
t.Fatalf("result = %#v, POST names = %v", result, fixture.postNames())
|
||||||
|
}
|
||||||
|
assertAssetCategoriesDisjoint(t, result)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUploadMissingReportsUnknownWhenReconciliationReadFails(t *testing.T) {
|
||||||
|
fixture := &uploadFixture{files: make(map[string][]byte), dropAckName: "app.bin", failListAfter: 1}
|
||||||
|
server := httptest.NewServer(fixture)
|
||||||
|
defer server.Close()
|
||||||
|
client := testClient(server)
|
||||||
|
destination := testDestination(server.URL)
|
||||||
|
assets := localAssets(t, []string{"app.bin", "later.bin"})
|
||||||
|
initial, err := client.InspectAssets(context.Background(), destination, 10, assets)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
result, err := client.UploadMissing(context.Background(), destination, 10, initial)
|
||||||
|
if err == nil || result.State != DeliveryUnknown {
|
||||||
|
t.Fatalf("result = %#v, error = %v", result, err)
|
||||||
|
}
|
||||||
|
if got, want := names(result.Pending), []string{"later.bin"}; !reflect.DeepEqual(got, want) {
|
||||||
|
t.Fatalf("pending = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
if got, want := names(result.Uncertain), []string{"app.bin"}; !reflect.DeepEqual(got, want) {
|
||||||
|
t.Fatalf("uncertain = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
assertAssetCategoriesDisjoint(t, result)
|
||||||
|
if got := fixture.postNames(); !reflect.DeepEqual(got, []string{"app.bin"}) {
|
||||||
|
t.Fatalf("POST names = %v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUploadMissingPreflightConflictPreventsEveryWrite(t *testing.T) {
|
||||||
|
fixture := &uploadFixture{files: map[string][]byte{"app.bin": []byte("different bytes")}}
|
||||||
|
server := httptest.NewServer(fixture)
|
||||||
|
defer server.Close()
|
||||||
|
client := testClient(server)
|
||||||
|
destination := testDestination(server.URL)
|
||||||
|
assets := localAssets(t, []string{"app.bin", "other.bin"})
|
||||||
|
inspection, err := client.InspectAssets(context.Background(), destination, 10, assets)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
result, err := client.UploadMissing(context.Background(), destination, 10, inspection)
|
||||||
|
if err == nil || result.State != DeliveryConflict {
|
||||||
|
t.Fatalf("result = %#v, error = %v", result, err)
|
||||||
|
}
|
||||||
|
if len(fixture.postNames()) != 0 {
|
||||||
|
t.Fatalf("uploads happened before conflict review: %v", fixture.postNames())
|
||||||
|
}
|
||||||
|
if got, want := names(result.Conflicting), []string{"app.bin"}; !reflect.DeepEqual(got, want) {
|
||||||
|
t.Fatalf("conflicting = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
if got, want := names(result.Pending), []string{"other.bin"}; !reflect.DeepEqual(got, want) {
|
||||||
|
t.Fatalf("pending = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
assertAssetCategoriesDisjoint(t, result)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUploadMissingKeepsLaterPendingAfterAmbiguousMissingUpload(t *testing.T) {
|
||||||
|
fixture := &uploadFixture{files: make(map[string][]byte), dropAckMissingName: "alpha.bin"}
|
||||||
|
server := httptest.NewServer(fixture)
|
||||||
|
defer server.Close()
|
||||||
|
client := testClient(server)
|
||||||
|
destination := testDestination(server.URL)
|
||||||
|
assets := localAssets(t, []string{"alpha.bin", "zeta.bin"})
|
||||||
|
initial, err := client.InspectAssets(context.Background(), destination, 10, assets)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
result, err := client.UploadMissing(context.Background(), destination, 10, initial)
|
||||||
|
if err == nil || result.State != DeliveryUnknown {
|
||||||
|
t.Fatalf("result = %#v, error = %v", result, err)
|
||||||
|
}
|
||||||
|
if got, want := names(result.Uncertain), []string{"alpha.bin"}; !reflect.DeepEqual(got, want) {
|
||||||
|
t.Fatalf("uncertain = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
if got, want := names(result.Pending), []string{"zeta.bin"}; !reflect.DeepEqual(got, want) {
|
||||||
|
t.Fatalf("pending = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
assertAssetCategoriesDisjoint(t, result)
|
||||||
|
if got, want := fixture.postNames(), []string{"alpha.bin"}; !reflect.DeepEqual(got, want) {
|
||||||
|
t.Fatalf("POST names = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUploadMissingMovesReconciledConflictOutOfPending(t *testing.T) {
|
||||||
|
fixture := &uploadFixture{
|
||||||
|
files: make(map[string][]byte),
|
||||||
|
conflictName: "alpha.bin",
|
||||||
|
conflictDifferentContent: true,
|
||||||
|
}
|
||||||
|
server := httptest.NewServer(fixture)
|
||||||
|
defer server.Close()
|
||||||
|
client := testClient(server)
|
||||||
|
destination := testDestination(server.URL)
|
||||||
|
assets := localAssets(t, []string{"alpha.bin", "zeta.bin"})
|
||||||
|
initial, err := client.InspectAssets(context.Background(), destination, 10, assets)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
result, err := client.UploadMissing(context.Background(), destination, 10, initial)
|
||||||
|
if err == nil || result.State != DeliveryConflict {
|
||||||
|
t.Fatalf("result = %#v, error = %v", result, err)
|
||||||
|
}
|
||||||
|
if got, want := names(result.Conflicting), []string{"alpha.bin"}; !reflect.DeepEqual(got, want) {
|
||||||
|
t.Fatalf("conflicting = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
if got, want := names(result.Pending), []string{"zeta.bin"}; !reflect.DeepEqual(got, want) {
|
||||||
|
t.Fatalf("pending = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
assertAssetCategoriesDisjoint(t, result)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUploadMissingTreatsUnresolvedNameConflictAsConflict(t *testing.T) {
|
||||||
|
fixture := &uploadFixture{files: make(map[string][]byte), conflictMissingName: "alpha.bin"}
|
||||||
|
server := httptest.NewServer(fixture)
|
||||||
|
defer server.Close()
|
||||||
|
client := testClient(server)
|
||||||
|
destination := testDestination(server.URL)
|
||||||
|
assets := localAssets(t, []string{"alpha.bin", "zeta.bin"})
|
||||||
|
initial, err := client.InspectAssets(context.Background(), destination, 10, assets)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
result, err := client.UploadMissing(context.Background(), destination, 10, initial)
|
||||||
|
if err == nil || result.State != DeliveryConflict {
|
||||||
|
t.Fatalf("result = %#v, error = %v", result, err)
|
||||||
|
}
|
||||||
|
if got, want := names(result.Conflicting), []string{"alpha.bin"}; !reflect.DeepEqual(got, want) {
|
||||||
|
t.Fatalf("conflicting = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
if got, want := names(result.Pending), []string{"zeta.bin"}; !reflect.DeepEqual(got, want) {
|
||||||
|
t.Fatalf("pending = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
assertAssetCategoriesDisjoint(t, result)
|
||||||
|
}
|
||||||
|
|
||||||
|
type uploadFixture struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
files map[string][]byte
|
||||||
|
posts []string
|
||||||
|
failName string
|
||||||
|
conflictName string
|
||||||
|
conflictDifferentContent bool
|
||||||
|
conflictMissingName string
|
||||||
|
dropAckName string
|
||||||
|
dropAckMissingName string
|
||||||
|
failListAfter int
|
||||||
|
listCount int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (fixture *uploadFixture) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Header.Get("Authorization") != "token "+testToken {
|
||||||
|
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.Method == http.MethodGet && r.URL.Path == assetListPath {
|
||||||
|
fixture.mu.Lock()
|
||||||
|
fixture.listCount++
|
||||||
|
if fixture.failListAfter > 0 && fixture.listCount > fixture.failListAfter {
|
||||||
|
fixture.mu.Unlock()
|
||||||
|
http.Error(w, "read failed", http.StatusServiceUnavailable)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
assets := make([]assetResponse, 0, len(fixture.files))
|
||||||
|
for name, content := range fixture.files {
|
||||||
|
assets = append(assets, assetResponse{ID: int64(len(assets) + 1), Name: name, Size: int64(len(content)), BrowserDownloadURL: "/files/" + urlPathEscape(name)})
|
||||||
|
}
|
||||||
|
fixture.mu.Unlock()
|
||||||
|
_ = json.NewEncoder(w).Encode(assets)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/files/") {
|
||||||
|
name := strings.TrimPrefix(r.URL.Path, "/files/")
|
||||||
|
fixture.mu.Lock()
|
||||||
|
content, ok := fixture.files[name]
|
||||||
|
fixture.mu.Unlock()
|
||||||
|
if !ok {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_, _ = w.Write(content)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.Method == http.MethodPost && r.URL.Path == assetListPath {
|
||||||
|
fixture.receiveUpload(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
http.Error(w, "unexpected request", http.StatusMethodNotAllowed)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (fixture *uploadFixture) receiveUpload(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if !strings.HasPrefix(r.Header.Get("Content-Type"), "multipart/form-data; boundary=") {
|
||||||
|
http.Error(w, "multipart required", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := r.ParseMultipartForm(1 << 20); err != nil {
|
||||||
|
http.Error(w, "invalid multipart body", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
file, header, err := r.FormFile("attachment")
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "missing attachment field", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
content, err := io.ReadAll(file)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "read multipart file", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if header.Filename != r.URL.Query().Get("name") {
|
||||||
|
http.Error(w, "filename query mismatch", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
name := header.Filename
|
||||||
|
fixture.mu.Lock()
|
||||||
|
fixture.posts = append(fixture.posts, name)
|
||||||
|
attempts := 0
|
||||||
|
for _, posted := range fixture.posts {
|
||||||
|
if posted == name {
|
||||||
|
attempts++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if name == fixture.failName && attempts == 1 {
|
||||||
|
fixture.mu.Unlock()
|
||||||
|
http.Error(w, "write failed", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if name == fixture.dropAckMissingName {
|
||||||
|
fixture.mu.Unlock()
|
||||||
|
hijacker, ok := w.(http.Hijacker)
|
||||||
|
if !ok {
|
||||||
|
http.Error(w, "hijacking unavailable", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
connection, _, err := hijacker.Hijack()
|
||||||
|
if err == nil {
|
||||||
|
_ = connection.Close()
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if name == fixture.conflictMissingName {
|
||||||
|
fixture.mu.Unlock()
|
||||||
|
w.WriteHeader(http.StatusConflict)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if name == fixture.conflictName && fixture.conflictDifferentContent {
|
||||||
|
fixture.files[name] = []byte("conflicting bytes")
|
||||||
|
fixture.mu.Unlock()
|
||||||
|
w.WriteHeader(http.StatusConflict)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
fixture.files[name] = append([]byte(nil), content...)
|
||||||
|
fixture.mu.Unlock()
|
||||||
|
if name == fixture.conflictName {
|
||||||
|
w.WriteHeader(http.StatusConflict)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if name == fixture.dropAckName {
|
||||||
|
hijacker, ok := w.(http.Hijacker)
|
||||||
|
if !ok {
|
||||||
|
http.Error(w, "hijacking unavailable", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
connection, _, err := hijacker.Hijack()
|
||||||
|
if err == nil {
|
||||||
|
_ = connection.Close()
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.WriteHeader(http.StatusCreated)
|
||||||
|
_ = json.NewEncoder(w).Encode(assetResponse{ID: 50, Name: name, Size: int64(len(content))})
|
||||||
|
}
|
||||||
|
|
||||||
|
func localAssets(t *testing.T, names []string) []ExpectedAsset {
|
||||||
|
t.Helper()
|
||||||
|
output := t.TempDir()
|
||||||
|
assets := make([]ExpectedAsset, 0, len(names))
|
||||||
|
for _, name := range names {
|
||||||
|
content := []byte("binary-" + name)
|
||||||
|
path := filepath.Join(output, name)
|
||||||
|
if err := os.WriteFile(path, content, 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
sum := assetFor(name, content)
|
||||||
|
sum.Content = nil
|
||||||
|
sum.Path = path
|
||||||
|
assets = append(assets, sum)
|
||||||
|
}
|
||||||
|
return assets
|
||||||
|
}
|
||||||
|
|
||||||
|
func readExpectedFile(t *testing.T, asset ExpectedAsset) []byte {
|
||||||
|
t.Helper()
|
||||||
|
content, err := os.ReadFile(asset.Path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return content
|
||||||
|
}
|
||||||
|
|
||||||
|
func (fixture *uploadFixture) postNames() []string {
|
||||||
|
fixture.mu.Lock()
|
||||||
|
defer fixture.mu.Unlock()
|
||||||
|
return append([]string(nil), fixture.posts...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func names(identities []AssetIdentity) []string {
|
||||||
|
result := make([]string, 0, len(identities))
|
||||||
|
for _, identity := range identities {
|
||||||
|
result = append(result, identity.Filename)
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func assertAssetCategoriesDisjoint(t *testing.T, result UploadResult) {
|
||||||
|
t.Helper()
|
||||||
|
groups := []struct {
|
||||||
|
name string
|
||||||
|
identities []AssetIdentity
|
||||||
|
}{
|
||||||
|
{name: "matching", identities: result.Matching},
|
||||||
|
{name: "uploaded", identities: result.Uploaded},
|
||||||
|
{name: "pending", identities: result.Pending},
|
||||||
|
{name: "conflicting", identities: result.Conflicting},
|
||||||
|
{name: "uncertain", identities: result.Uncertain},
|
||||||
|
}
|
||||||
|
seen := make(map[string]string)
|
||||||
|
for _, group := range groups {
|
||||||
|
for _, item := range group.identities {
|
||||||
|
if previous, ok := seen[item.Filename]; ok {
|
||||||
|
t.Errorf("asset %q appears in both %s and %s", item.Filename, previous, group.name)
|
||||||
|
}
|
||||||
|
seen[item.Filename] = group.name
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func urlPathEscape(value string) string {
|
||||||
|
return (&url.URL{Path: value}).EscapedPath()
|
||||||
|
}
|
||||||
227
internal/gotool/gotool.go
Normal file
227
internal/gotool/gotool.go
Normal file
@@ -0,0 +1,227 @@
|
|||||||
|
// Package gotool owns Go configuration discovery and ReleaseKit's Go command
|
||||||
|
// environments.
|
||||||
|
package gotool
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/process"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Mode selects the target environment for a Go command.
|
||||||
|
type Mode uint8
|
||||||
|
|
||||||
|
const (
|
||||||
|
// Native runs Go for the toolchain host and keeps its effective cgo settings.
|
||||||
|
Native Mode = iota
|
||||||
|
// Static runs Go for the selected target with cgo disabled.
|
||||||
|
Static
|
||||||
|
)
|
||||||
|
|
||||||
|
// Target selects a Go operating system and architecture.
|
||||||
|
type Target struct {
|
||||||
|
OS string
|
||||||
|
Arch string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tool holds the host target and effective operational settings resolved from
|
||||||
|
// the process environment and Go's persistent environment file.
|
||||||
|
type Tool struct {
|
||||||
|
host Target
|
||||||
|
settings map[string]string
|
||||||
|
}
|
||||||
|
|
||||||
|
var operationalSettings = []string{
|
||||||
|
"CC", "CXX", "CGO_CFLAGS", "CGO_CPPFLAGS", "CGO_CXXFLAGS", "CGO_ENABLED", "CGO_LDFLAGS",
|
||||||
|
"GOCACHE", "GOCACHEPROG", "GOMODCACHE", "GOPATH", "GOROOT", "GOTMPDIR", "PKG_CONFIG",
|
||||||
|
}
|
||||||
|
|
||||||
|
var architectureFeatures = []string{
|
||||||
|
"GOAMD64", "GOARM", "GOARM64", "GO386", "GOMIPS", "GOMIPS64", "GOPPC64", "GORISCV64", "GOWASM",
|
||||||
|
}
|
||||||
|
|
||||||
|
// New discovers the Go toolchain host and its effective cache, tool, and cgo
|
||||||
|
// settings. Discovery uses the selected local Go command and neutralizes
|
||||||
|
// ambient flags, experiments, and architecture tuning so they cannot prevent
|
||||||
|
// configuration from being read.
|
||||||
|
func New(ctx context.Context, directory string) (*Tool, error) {
|
||||||
|
var host struct {
|
||||||
|
OS string `json:"GOHOSTOS"`
|
||||||
|
Arch string `json:"GOHOSTARCH"`
|
||||||
|
}
|
||||||
|
output, err := discover(ctx, directory, discoveryEnvironment(), "go", "env", "-json", "GOHOSTOS", "GOHOSTARCH")
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("identify Go host: %w", err)
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(output, &host); err != nil {
|
||||||
|
return nil, fmt.Errorf("decode Go host settings: %w", err)
|
||||||
|
}
|
||||||
|
if host.OS == "" || host.Arch == "" {
|
||||||
|
return nil, fmt.Errorf("Go returned an incomplete host target: %s", strings.TrimSpace(string(output)))
|
||||||
|
}
|
||||||
|
tool := &Tool{host: Target{OS: host.OS, Arch: host.Arch}}
|
||||||
|
|
||||||
|
environment := discoveryEnvironment()
|
||||||
|
environment["GOOS"] = tool.host.OS
|
||||||
|
environment["GOARCH"] = tool.host.Arch
|
||||||
|
args := append([]string{"go", "env", "-json"}, operationalSettings...)
|
||||||
|
output, err = discover(ctx, directory, environment, args...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("resolve effective Go settings: %w", err)
|
||||||
|
}
|
||||||
|
var settings map[string]string
|
||||||
|
if err := json.Unmarshal(output, &settings); err != nil {
|
||||||
|
return nil, fmt.Errorf("decode effective Go settings: %w", err)
|
||||||
|
}
|
||||||
|
for _, key := range operationalSettings {
|
||||||
|
if _, ok := settings[key]; !ok {
|
||||||
|
return nil, fmt.Errorf("Go did not report effective setting %s", key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tool.settings = settings
|
||||||
|
return tool, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// PrepareBuildDependencies downloads module dependencies with the available
|
||||||
|
// local Go toolchain. It preserves caller module-network settings and caches,
|
||||||
|
// while disabling workspace discovery and automatic toolchain downloads.
|
||||||
|
func PrepareBuildDependencies(ctx context.Context, directory string) error {
|
||||||
|
captured := &combinedWriter{}
|
||||||
|
err := process.Run(ctx, process.Invocation{
|
||||||
|
Args: []string{"go", "mod", "download"},
|
||||||
|
Dir: directory,
|
||||||
|
Env: map[string]string{
|
||||||
|
"GOWORK": "off",
|
||||||
|
"GOTOOLCHAIN": "local",
|
||||||
|
},
|
||||||
|
Stdout: captured,
|
||||||
|
Stderr: captured,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
if output := strings.TrimSpace(string(captured.Bytes())); output != "" {
|
||||||
|
return fmt.Errorf("go mod download: %w: %s", err, output)
|
||||||
|
}
|
||||||
|
return fmt.Errorf("go mod download: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// HostTarget reports the Go command's host operating system and architecture.
|
||||||
|
func (tool *Tool) HostTarget() Target {
|
||||||
|
return tool.host
|
||||||
|
}
|
||||||
|
|
||||||
|
// Run executes a Go command with ReleaseKit's shared offline baseline. Native
|
||||||
|
// commands use the host target and effective cgo configuration. Static commands
|
||||||
|
// use target and disable cgo. Output, when supplied, receives stdout and stderr
|
||||||
|
// as the command runs; the returned bytes retain both streams for diagnostics.
|
||||||
|
func (tool *Tool) Run(ctx context.Context, directory string, mode Mode, target Target, output io.Writer, args ...string) ([]byte, error) {
|
||||||
|
if len(args) == 0 {
|
||||||
|
return nil, errors.New("Go command requires arguments")
|
||||||
|
}
|
||||||
|
environment := tool.environment(mode, target)
|
||||||
|
captured := &combinedWriter{output: output}
|
||||||
|
commandArgs := append([]string{"go"}, args...)
|
||||||
|
err := process.Run(ctx, process.Invocation{
|
||||||
|
Args: commandArgs,
|
||||||
|
Dir: directory,
|
||||||
|
Env: environment,
|
||||||
|
Stdout: captured,
|
||||||
|
Stderr: captured,
|
||||||
|
})
|
||||||
|
contents := captured.Bytes()
|
||||||
|
if err != nil {
|
||||||
|
if len(contents) != 0 {
|
||||||
|
return contents, fmt.Errorf("go %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(string(contents)))
|
||||||
|
}
|
||||||
|
return contents, fmt.Errorf("go %s: %w", strings.Join(args, " "), err)
|
||||||
|
}
|
||||||
|
return contents, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (tool *Tool) environment(mode Mode, target Target) map[string]string {
|
||||||
|
if mode == Native || target.OS == "" || target.Arch == "" {
|
||||||
|
target = tool.host
|
||||||
|
}
|
||||||
|
values := make(map[string]string, len(tool.settings)+len(architectureFeatures)+12)
|
||||||
|
for key, value := range tool.settings {
|
||||||
|
values[key] = value
|
||||||
|
}
|
||||||
|
values["GOENV"] = "off"
|
||||||
|
values["GOFLAGS"] = "-mod=readonly"
|
||||||
|
values["GOWORK"] = "off"
|
||||||
|
values["GOTOOLCHAIN"] = "local"
|
||||||
|
values["GOPROXY"] = "off"
|
||||||
|
values["GONOPROXY"] = "none"
|
||||||
|
values["GOSUMDB"] = "off"
|
||||||
|
values["GOOS"] = target.OS
|
||||||
|
values["GOARCH"] = target.Arch
|
||||||
|
values["GOEXPERIMENT"] = ""
|
||||||
|
for _, key := range architectureFeatures {
|
||||||
|
values[key] = ""
|
||||||
|
}
|
||||||
|
if mode == Static {
|
||||||
|
values["CGO_ENABLED"] = "0"
|
||||||
|
}
|
||||||
|
return values
|
||||||
|
}
|
||||||
|
|
||||||
|
func discoveryEnvironment() map[string]string {
|
||||||
|
environment := map[string]string{
|
||||||
|
"GOFLAGS": "-mod=readonly",
|
||||||
|
"GOTOOLCHAIN": "local",
|
||||||
|
"GOWORK": "off",
|
||||||
|
"GOEXPERIMENT": "none",
|
||||||
|
}
|
||||||
|
for _, key := range architectureFeatures {
|
||||||
|
environment[key] = ""
|
||||||
|
}
|
||||||
|
return environment
|
||||||
|
}
|
||||||
|
|
||||||
|
func discover(ctx context.Context, directory string, environment map[string]string, args ...string) ([]byte, error) {
|
||||||
|
var configuration, diagnostics bytes.Buffer
|
||||||
|
err := process.Run(ctx, process.Invocation{
|
||||||
|
Args: args,
|
||||||
|
Dir: directory,
|
||||||
|
Env: environment,
|
||||||
|
Stdout: &configuration,
|
||||||
|
Stderr: &diagnostics,
|
||||||
|
})
|
||||||
|
contents := configuration.Bytes()
|
||||||
|
if err != nil {
|
||||||
|
if output := strings.TrimSpace(configuration.String() + diagnostics.String()); output != "" {
|
||||||
|
return contents, fmt.Errorf("%s: %w: %s", strings.Join(args, " "), err, output)
|
||||||
|
}
|
||||||
|
return contents, fmt.Errorf("%s: %w", strings.Join(args, " "), err)
|
||||||
|
}
|
||||||
|
return contents, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type combinedWriter struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
output io.Writer
|
||||||
|
buffer bytes.Buffer
|
||||||
|
}
|
||||||
|
|
||||||
|
func (writer *combinedWriter) Write(contents []byte) (int, error) {
|
||||||
|
writer.mu.Lock()
|
||||||
|
defer writer.mu.Unlock()
|
||||||
|
if writer.output == nil {
|
||||||
|
return writer.buffer.Write(contents)
|
||||||
|
}
|
||||||
|
return io.MultiWriter(&writer.buffer, writer.output).Write(contents)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (writer *combinedWriter) Bytes() []byte {
|
||||||
|
writer.mu.Lock()
|
||||||
|
defer writer.mu.Unlock()
|
||||||
|
return append([]byte(nil), writer.buffer.Bytes()...)
|
||||||
|
}
|
||||||
328
internal/gotool/gotool_test.go
Normal file
328
internal/gotool/gotool_test.go
Normal file
@@ -0,0 +1,328 @@
|
|||||||
|
package gotool
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type goPreparationRecord struct {
|
||||||
|
Arguments []string
|
||||||
|
Directory string
|
||||||
|
Workspace string
|
||||||
|
Toolchain string
|
||||||
|
Proxy string
|
||||||
|
Private string
|
||||||
|
NoSumDB string
|
||||||
|
ModuleCache string
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMain(m *testing.M) {
|
||||||
|
if os.Getenv("RELEASEKIT_GO_FIXTURE") == "1" {
|
||||||
|
os.Exit(runGoPreparationFixture())
|
||||||
|
}
|
||||||
|
os.Exit(m.Run())
|
||||||
|
}
|
||||||
|
|
||||||
|
func runGoPreparationFixture() int {
|
||||||
|
record := goPreparationRecord{
|
||||||
|
Arguments: os.Args[1:], Directory: mustGetwd(),
|
||||||
|
Workspace: os.Getenv("GOWORK"), Toolchain: os.Getenv("GOTOOLCHAIN"),
|
||||||
|
Proxy: os.Getenv("GOPROXY"), Private: os.Getenv("GOPRIVATE"),
|
||||||
|
NoSumDB: os.Getenv("GONOSUMDB"), ModuleCache: os.Getenv("GOMODCACHE"),
|
||||||
|
}
|
||||||
|
contents, err := json.Marshal(record)
|
||||||
|
if err != nil {
|
||||||
|
return 10
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(os.Getenv("RELEASEKIT_GO_FIXTURE_RECORD"), contents, 0o600); err != nil {
|
||||||
|
return 11
|
||||||
|
}
|
||||||
|
switch os.Getenv("RELEASEKIT_GO_FIXTURE_MODE") {
|
||||||
|
case "discovery":
|
||||||
|
settings := make(map[string]string)
|
||||||
|
for _, key := range os.Args[3:] {
|
||||||
|
settings[key] = os.Getenv(key)
|
||||||
|
}
|
||||||
|
settings["GOHOSTOS"] = runtime.GOOS
|
||||||
|
settings["GOHOSTARCH"] = runtime.GOARCH
|
||||||
|
fmt.Fprintln(os.Stderr, "fixture discovery diagnostic")
|
||||||
|
if err := json.NewEncoder(os.Stdout).Encode(settings); err != nil {
|
||||||
|
return 12
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
case "fail":
|
||||||
|
fmt.Fprintln(os.Stderr, "fixture dependency failure")
|
||||||
|
return 23
|
||||||
|
case "wait":
|
||||||
|
for {
|
||||||
|
time.Sleep(time.Second)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDiscoveryAcceptsDiagnosticsWithValidConfiguration(t *testing.T) {
|
||||||
|
repository, _ := installGoPreparationFixture(t)
|
||||||
|
t.Setenv("RELEASEKIT_GO_FIXTURE_MODE", "discovery")
|
||||||
|
cache := filepath.Join(t.TempDir(), "cache")
|
||||||
|
t.Setenv("GOCACHE", cache)
|
||||||
|
tool, err := New(context.Background(), repository)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("New() rejected successful discovery: %v", err)
|
||||||
|
}
|
||||||
|
if tool.HostTarget() != (Target{OS: runtime.GOOS, Arch: runtime.GOARCH}) || tool.settings["GOCACHE"] != cache {
|
||||||
|
t.Fatalf("discovered host=%v cache=%q", tool.HostTarget(), tool.settings["GOCACHE"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDiscoveryPreservesFailureDiagnosticsAndCause(t *testing.T) {
|
||||||
|
repository, _ := installGoPreparationFixture(t)
|
||||||
|
t.Setenv("RELEASEKIT_GO_FIXTURE_MODE", "fail")
|
||||||
|
_, err := New(context.Background(), repository)
|
||||||
|
var exitError *exec.ExitError
|
||||||
|
if !errors.As(err, &exitError) || exitError.ExitCode() != 23 || !strings.Contains(err.Error(), "fixture dependency failure") {
|
||||||
|
t.Fatalf("New() error = %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func mustGetwd() string {
|
||||||
|
directory, err := os.Getwd()
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return directory
|
||||||
|
}
|
||||||
|
|
||||||
|
func installGoPreparationFixture(t *testing.T) (repository, recordPath string) {
|
||||||
|
t.Helper()
|
||||||
|
directory := t.TempDir()
|
||||||
|
repository = t.TempDir()
|
||||||
|
executable, err := os.Executable()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
contents, err := os.ReadFile(executable)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
name := "go"
|
||||||
|
if runtime.GOOS == "windows" {
|
||||||
|
name += ".exe"
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(filepath.Join(directory, name), contents, 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
recordPath = filepath.Join(t.TempDir(), "go-command.json")
|
||||||
|
t.Setenv("PATH", directory+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||||
|
t.Setenv("RELEASEKIT_GO_FIXTURE", "1")
|
||||||
|
t.Setenv("RELEASEKIT_GO_FIXTURE_RECORD", recordPath)
|
||||||
|
return repository, recordPath
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPrepareBuildDependenciesPreservesPreparationEnvironment(t *testing.T) {
|
||||||
|
repository, recordPath := installGoPreparationFixture(t)
|
||||||
|
moduleCache := filepath.Join(t.TempDir(), "module-cache")
|
||||||
|
t.Setenv("GOWORK", filepath.Join(t.TempDir(), "go.work"))
|
||||||
|
t.Setenv("GOTOOLCHAIN", "auto")
|
||||||
|
t.Setenv("GOPROXY", "https://proxy.example.invalid")
|
||||||
|
t.Setenv("GOPRIVATE", "example.invalid/private")
|
||||||
|
t.Setenv("GONOSUMDB", "example.invalid/private")
|
||||||
|
t.Setenv("GOMODCACHE", moduleCache)
|
||||||
|
|
||||||
|
if err := PrepareBuildDependencies(context.Background(), repository); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
contents, err := os.ReadFile(recordPath)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var record goPreparationRecord
|
||||||
|
if err := json.Unmarshal(contents, &record); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if strings.Join(record.Arguments, " ") != "mod download" || record.Directory != repository {
|
||||||
|
t.Fatalf("Go invocation = %#v", record)
|
||||||
|
}
|
||||||
|
if record.Workspace != "off" || record.Toolchain != "local" {
|
||||||
|
t.Fatalf("preparation Go settings = %#v", record)
|
||||||
|
}
|
||||||
|
if record.Proxy != "https://proxy.example.invalid" || record.Private != "example.invalid/private" || record.NoSumDB != "example.invalid/private" || record.ModuleCache != moduleCache {
|
||||||
|
t.Fatalf("caller dependency settings were not preserved: %#v", record)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPrepareBuildDependenciesPropagatesCommandFailure(t *testing.T) {
|
||||||
|
repository, _ := installGoPreparationFixture(t)
|
||||||
|
t.Setenv("RELEASEKIT_GO_FIXTURE_MODE", "fail")
|
||||||
|
err := PrepareBuildDependencies(context.Background(), repository)
|
||||||
|
var exitError *exec.ExitError
|
||||||
|
if !errors.As(err, &exitError) || exitError.ExitCode() != 23 || !strings.Contains(err.Error(), "fixture dependency failure") {
|
||||||
|
t.Fatalf("PrepareBuildDependencies() error = %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPrepareBuildDependenciesPropagatesCancellation(t *testing.T) {
|
||||||
|
repository, recordPath := installGoPreparationFixture(t)
|
||||||
|
t.Setenv("RELEASEKIT_GO_FIXTURE_MODE", "wait")
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
defer cancel()
|
||||||
|
done := make(chan error, 1)
|
||||||
|
go func() { done <- PrepareBuildDependencies(ctx, repository) }()
|
||||||
|
|
||||||
|
deadline := time.Now().Add(5 * time.Second)
|
||||||
|
for {
|
||||||
|
if _, err := os.Stat(recordPath); err == nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if time.Now().After(deadline) {
|
||||||
|
t.Fatal("Go fixture did not start")
|
||||||
|
}
|
||||||
|
time.Sleep(10 * time.Millisecond)
|
||||||
|
}
|
||||||
|
cancel()
|
||||||
|
select {
|
||||||
|
case err := <-done:
|
||||||
|
if !errors.Is(err, context.Canceled) {
|
||||||
|
t.Fatalf("PrepareBuildDependencies() error = %v; want cancellation", err)
|
||||||
|
}
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("Go fixture did not stop after cancellation")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNativeAndStaticCommandsUseOwnedBaseline(t *testing.T) {
|
||||||
|
clearGoSettings(t)
|
||||||
|
t.Setenv("GOENV", "off")
|
||||||
|
t.Setenv("GOFLAGS", "-run=^$")
|
||||||
|
t.Setenv("GOOS", "windows")
|
||||||
|
t.Setenv("GOARCH", "arm64")
|
||||||
|
t.Setenv("GOAMD64", "v2")
|
||||||
|
t.Setenv("GOEXPERIMENT", "loopvar")
|
||||||
|
|
||||||
|
tool, err := New(context.Background(), t.TempDir())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if tool.HostTarget() != (Target{OS: runtime.GOOS, Arch: runtime.GOARCH}) {
|
||||||
|
t.Fatalf("Go host = %#v, want runtime host %s/%s", tool.HostTarget(), runtime.GOOS, runtime.GOARCH)
|
||||||
|
}
|
||||||
|
|
||||||
|
native := readSettings(t, tool, Native, Target{}, "GOENV", "GOOS", "GOARCH", "GOFLAGS", "GOAMD64", "GOEXPERIMENT", "CGO_ENABLED")
|
||||||
|
if native["GOENV"] != "" || native["GOOS"] != runtime.GOOS || native["GOARCH"] != runtime.GOARCH {
|
||||||
|
t.Fatalf("native environment = %#v", native)
|
||||||
|
}
|
||||||
|
if native["GOFLAGS"] != "-mod=readonly" || native["GOAMD64"] == "v2" || native["GOEXPERIMENT"] != "" {
|
||||||
|
t.Fatalf("native Go settings = %#v", native)
|
||||||
|
}
|
||||||
|
if native["CGO_ENABLED"] == "" {
|
||||||
|
t.Fatalf("native cgo setting was not resolved: %#v", native)
|
||||||
|
}
|
||||||
|
|
||||||
|
static := readSettings(t, tool, Static, Target{OS: "linux", Arch: "amd64"}, "GOOS", "GOARCH", "GOFLAGS", "CGO_ENABLED", "GOAMD64", "GOEXPERIMENT")
|
||||||
|
if static["GOOS"] != "linux" || static["GOARCH"] != "amd64" || static["CGO_ENABLED"] != "0" {
|
||||||
|
t.Fatalf("static environment = %#v", static)
|
||||||
|
}
|
||||||
|
if static["GOFLAGS"] != "-mod=readonly" || static["GOAMD64"] != "v1" || static["GOEXPERIMENT"] != "" {
|
||||||
|
t.Fatalf("static baseline settings = %#v", static)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPersistentSettingsPreserveCachesAndNativeCTools(t *testing.T) {
|
||||||
|
clearGoSettings(t)
|
||||||
|
cache := filepath.Join(t.TempDir(), "configured-cache")
|
||||||
|
moduleCache := filepath.Join(t.TempDir(), "configured-module-cache")
|
||||||
|
temporary := filepath.Join(t.TempDir(), "configured-temporary")
|
||||||
|
if err := os.Mkdir(temporary, 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
goEnv := filepath.Join(t.TempDir(), "go-env")
|
||||||
|
contents := strings.Join([]string{
|
||||||
|
"GOFLAGS=-run=^$",
|
||||||
|
"GOOS=windows",
|
||||||
|
"GOARCH=arm64",
|
||||||
|
"GOAMD64=v2",
|
||||||
|
"GOEXPERIMENT=loopvar",
|
||||||
|
"GOCACHE=" + cache,
|
||||||
|
"GOMODCACHE=" + moduleCache,
|
||||||
|
"GOTMPDIR=" + temporary,
|
||||||
|
"CGO_ENABLED=1",
|
||||||
|
"CC=releasekit-test-cc",
|
||||||
|
"CXX=releasekit-test-cxx",
|
||||||
|
"CGO_CFLAGS=-O0 -g",
|
||||||
|
"PKG_CONFIG=releasekit-test-pkg-config",
|
||||||
|
}, "\n") + "\n"
|
||||||
|
if err := os.WriteFile(goEnv, []byte(contents), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Setenv("GOENV", goEnv)
|
||||||
|
|
||||||
|
tool, err := New(context.Background(), t.TempDir())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if tool.HostTarget() != (Target{OS: runtime.GOOS, Arch: runtime.GOARCH}) {
|
||||||
|
t.Fatalf("Go host = %#v, want runtime host %s/%s", tool.HostTarget(), runtime.GOOS, runtime.GOARCH)
|
||||||
|
}
|
||||||
|
native := readSettings(t, tool, Native, Target{}, "GOENV", "GOOS", "GOARCH", "GOFLAGS", "GOAMD64", "GOEXPERIMENT", "CGO_ENABLED", "CC", "CXX", "CGO_CFLAGS", "GOCACHE", "GOMODCACHE", "GOTMPDIR", "PKG_CONFIG")
|
||||||
|
if native["GOENV"] != "" || native["GOOS"] != runtime.GOOS || native["GOARCH"] != runtime.GOARCH {
|
||||||
|
t.Fatalf("native environment = %#v", native)
|
||||||
|
}
|
||||||
|
if native["GOFLAGS"] != "-mod=readonly" || native["GOAMD64"] == "v2" || native["GOEXPERIMENT"] != "" {
|
||||||
|
t.Fatalf("persisted overrides were not cleared: %#v", native)
|
||||||
|
}
|
||||||
|
if native["CGO_ENABLED"] != "1" || native["CC"] != "releasekit-test-cc" || native["CXX"] != "releasekit-test-cxx" || native["CGO_CFLAGS"] != "-O0 -g" || native["PKG_CONFIG"] != "releasekit-test-pkg-config" {
|
||||||
|
t.Fatalf("persistent native C settings = %#v", native)
|
||||||
|
}
|
||||||
|
if native["GOCACHE"] != cache || native["GOMODCACHE"] != moduleCache || native["GOTMPDIR"] != temporary {
|
||||||
|
t.Fatalf("persistent cache settings = %#v", native)
|
||||||
|
}
|
||||||
|
static := readSettings(t, tool, Static, Target{OS: "linux", Arch: "amd64"}, "GOENV", "GOOS", "GOARCH", "GOFLAGS", "CGO_ENABLED", "GOAMD64", "GOEXPERIMENT", "GOCACHE")
|
||||||
|
if static["GOENV"] != "" || static["GOOS"] != "linux" || static["GOARCH"] != "amd64" || static["CGO_ENABLED"] != "0" || static["GOAMD64"] != "v1" || static["GOEXPERIMENT"] != "" || static["GOCACHE"] != cache {
|
||||||
|
t.Fatalf("persistent static environment = %#v", static)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func readSettings(t *testing.T, tool *Tool, mode Mode, target Target, names ...string) map[string]string {
|
||||||
|
t.Helper()
|
||||||
|
args := append([]string{"env", "-json"}, names...)
|
||||||
|
output, err := tool.Run(context.Background(), t.TempDir(), mode, target, nil, args...)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var settings map[string]string
|
||||||
|
if err := json.Unmarshal(output, &settings); err != nil {
|
||||||
|
t.Fatalf("decode Go environment %q: %v", output, err)
|
||||||
|
}
|
||||||
|
return settings
|
||||||
|
}
|
||||||
|
|
||||||
|
func clearGoSettings(t *testing.T) {
|
||||||
|
t.Helper()
|
||||||
|
for _, key := range []string{
|
||||||
|
"GOENV", "GOFLAGS", "GOWORK", "GOTOOLCHAIN", "GOPROXY", "GONOPROXY", "GOSUMDB",
|
||||||
|
"GOOS", "GOARCH", "GOEXPERIMENT", "GOAMD64", "GOARM", "GOARM64", "GO386", "GOMIPS", "GOMIPS64", "GOPPC64", "GORISCV64", "GOWASM",
|
||||||
|
"CGO_ENABLED", "CC", "CXX", "CGO_CFLAGS", "CGO_CPPFLAGS", "CGO_CXXFLAGS", "CGO_LDFLAGS", "GOCACHE", "GOCACHEPROG", "GOMODCACHE", "GOPATH", "GOROOT", "GOTMPDIR", "PKG_CONFIG",
|
||||||
|
} {
|
||||||
|
value, exists := os.LookupEnv(key)
|
||||||
|
if err := os.Unsetenv(key); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() {
|
||||||
|
if exists {
|
||||||
|
_ = os.Setenv(key, value)
|
||||||
|
} else {
|
||||||
|
_ = os.Unsetenv(key)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
43
internal/preparation/preparation.go
Normal file
43
internal/preparation/preparation.go
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
// Package preparation coordinates explicit local checkout and Go module
|
||||||
|
// preparation operations for consumers and CI adapters.
|
||||||
|
package preparation
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/candidate"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/git"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/gotool"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/versioncontract"
|
||||||
|
)
|
||||||
|
|
||||||
|
type TaggedCheckoutRequest struct {
|
||||||
|
RepositoryDir string
|
||||||
|
Version string
|
||||||
|
Remote string
|
||||||
|
ExpectedCommit string
|
||||||
|
}
|
||||||
|
|
||||||
|
func PrepareTaggedCheckout(ctx context.Context, request TaggedCheckoutRequest) error {
|
||||||
|
if !versioncontract.ValidStableVersion(request.Version) {
|
||||||
|
return fmt.Errorf("%w: %q", candidate.ErrInvalidVersion, request.Version)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(request.ExpectedCommit) == "" {
|
||||||
|
return errors.New("expected commit is required")
|
||||||
|
}
|
||||||
|
remote := request.Remote
|
||||||
|
if remote == "" {
|
||||||
|
remote = "origin"
|
||||||
|
}
|
||||||
|
return git.PrepareTaggedCheckout(ctx, request.RepositoryDir, request.Version, remote, request.ExpectedCommit)
|
||||||
|
}
|
||||||
|
|
||||||
|
func PrepareBuildDependencies(ctx context.Context, repositoryDir string) error {
|
||||||
|
if strings.TrimSpace(repositoryDir) == "" {
|
||||||
|
return errors.New("repository directory is required")
|
||||||
|
}
|
||||||
|
return gotool.PrepareBuildDependencies(ctx, repositoryDir)
|
||||||
|
}
|
||||||
76
internal/process/process.go
Normal file
76
internal/process/process.go
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
// Package process runs child commands for ReleaseKit's internal adapters.
|
||||||
|
package process
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Invocation describes one child process. UnsetEnv removes inherited values
|
||||||
|
// before Env overlays values for this child only.
|
||||||
|
type Invocation struct {
|
||||||
|
Args []string
|
||||||
|
Dir string
|
||||||
|
Env map[string]string
|
||||||
|
UnsetEnv []string
|
||||||
|
Stdout io.Writer
|
||||||
|
Stderr io.Writer
|
||||||
|
}
|
||||||
|
|
||||||
|
// Run starts the command in the requested directory and waits for it to exit.
|
||||||
|
// Errors preserve the underlying exec error, including *exec.ExitError.
|
||||||
|
func Run(ctx context.Context, invocation Invocation) error {
|
||||||
|
if len(invocation.Args) == 0 || invocation.Args[0] == "" {
|
||||||
|
return errors.New("process invocation requires a command")
|
||||||
|
}
|
||||||
|
|
||||||
|
command := exec.CommandContext(ctx, invocation.Args[0], invocation.Args[1:]...)
|
||||||
|
command.Dir = invocation.Dir
|
||||||
|
if len(invocation.Env) != 0 || len(invocation.UnsetEnv) != 0 {
|
||||||
|
command.Env = environmentEntries(invocation.Env, invocation.UnsetEnv)
|
||||||
|
}
|
||||||
|
command.Stdout = invocation.Stdout
|
||||||
|
command.Stderr = invocation.Stderr
|
||||||
|
|
||||||
|
if err := command.Run(); err != nil {
|
||||||
|
if contextErr := ctx.Err(); contextErr != nil {
|
||||||
|
return fmt.Errorf("run %q: %w", invocation.Args[0], contextErr)
|
||||||
|
}
|
||||||
|
return fmt.Errorf("run %q: %w", invocation.Args[0], err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func environmentEntries(overlay map[string]string, unset []string) []string {
|
||||||
|
environment := make(map[string]string, len(os.Environ())+len(overlay))
|
||||||
|
for _, entry := range os.Environ() {
|
||||||
|
key, value, ok := strings.Cut(entry, "=")
|
||||||
|
if ok {
|
||||||
|
environment[key] = value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, key := range unset {
|
||||||
|
delete(environment, key)
|
||||||
|
}
|
||||||
|
for key, value := range overlay {
|
||||||
|
environment[key] = value
|
||||||
|
}
|
||||||
|
|
||||||
|
keys := make([]string, 0, len(environment))
|
||||||
|
for key := range environment {
|
||||||
|
keys = append(keys, key)
|
||||||
|
}
|
||||||
|
sort.Strings(keys)
|
||||||
|
|
||||||
|
entries := make([]string, 0, len(keys))
|
||||||
|
for _, key := range keys {
|
||||||
|
entries = append(entries, key+"="+environment[key])
|
||||||
|
}
|
||||||
|
return entries
|
||||||
|
}
|
||||||
172
internal/process/process_test.go
Normal file
172
internal/process/process_test.go
Normal file
@@ -0,0 +1,172 @@
|
|||||||
|
package process
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestRunPassesArgumentsDirectoryAndEnvironment(t *testing.T) {
|
||||||
|
workdir := filepath.Join(t.TempDir(), "directory with spaces")
|
||||||
|
if err := os.Mkdir(workdir, 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Setenv("RELEASEKIT_PROCESS_OVERLAY", "parent")
|
||||||
|
t.Setenv("RELEASEKIT_PROCESS_INHERITED", "inherited")
|
||||||
|
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
err := Run(context.Background(), Invocation{
|
||||||
|
Args: []string{helperExecutable(t), "-test.run=TestProcessHelper", "--", "argument with spaces", "success"},
|
||||||
|
Dir: workdir,
|
||||||
|
Env: map[string]string{
|
||||||
|
"RELEASEKIT_PROCESS_HELPER": "1",
|
||||||
|
"RELEASEKIT_PROCESS_OVERLAY": "child",
|
||||||
|
},
|
||||||
|
Stdout: &stdout,
|
||||||
|
Stderr: &stderr,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
want := fmt.Sprintf("%s|argument with spaces|child|inherited", workdir)
|
||||||
|
if stdout.String() != want {
|
||||||
|
t.Fatalf("stdout = %q, want %q", stdout.String(), want)
|
||||||
|
}
|
||||||
|
if stderr.String() != "child stderr\n" {
|
||||||
|
t.Fatalf("stderr = %q, want %q", stderr.String(), "child stderr\n")
|
||||||
|
}
|
||||||
|
if got := os.Getenv("RELEASEKIT_PROCESS_OVERLAY"); got != "parent" {
|
||||||
|
t.Fatalf("parent environment changed: got %q, want %q", got, "parent")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRunPreservesExitError(t *testing.T) {
|
||||||
|
err := Run(context.Background(), Invocation{
|
||||||
|
Args: []string{helperExecutable(t), "-test.run=TestProcessHelper", "--", "unused", "exit"},
|
||||||
|
Env: map[string]string{"RELEASEKIT_PROCESS_HELPER": "1"},
|
||||||
|
})
|
||||||
|
var exitErr *exec.ExitError
|
||||||
|
if !errors.As(err, &exitErr) || exitErr.ExitCode() != 7 {
|
||||||
|
t.Fatalf("Run() error = %v, want exit code 7", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRunCanRemoveInheritedEnvironment(t *testing.T) {
|
||||||
|
t.Setenv("RELEASEKIT_PROCESS_INHERITED", "inherited")
|
||||||
|
var stdout bytes.Buffer
|
||||||
|
err := Run(context.Background(), Invocation{
|
||||||
|
Args: []string{helperExecutable(t), "-test.run=TestProcessHelper", "--", "argument", "success"},
|
||||||
|
Env: map[string]string{"RELEASEKIT_PROCESS_HELPER": "1"},
|
||||||
|
UnsetEnv: []string{"RELEASEKIT_PROCESS_INHERITED"},
|
||||||
|
Stdout: &stdout,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
want := fmt.Sprintf("%s|argument||", mustGetwd(t))
|
||||||
|
if stdout.String() != want {
|
||||||
|
t.Fatalf("stdout = %q, want %q", stdout.String(), want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRunReportsMissingExecutable(t *testing.T) {
|
||||||
|
err := Run(context.Background(), Invocation{Args: []string{"releasekit-command-that-does-not-exist"}})
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "releasekit-command-that-does-not-exist") {
|
||||||
|
t.Fatalf("Run() error = %v, want missing executable diagnostic", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRunReturnsCancellation(t *testing.T) {
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
defer cancel()
|
||||||
|
started := make(chan struct{}, 1)
|
||||||
|
invocation := Invocation{
|
||||||
|
Args: []string{helperExecutable(t), "-test.run=TestProcessHelper", "--", "unused", "wait"},
|
||||||
|
Env: map[string]string{"RELEASEKIT_PROCESS_HELPER": "1"},
|
||||||
|
Stdout: writerFunc(func([]byte) (int, error) {
|
||||||
|
select {
|
||||||
|
case started <- struct{}{}:
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
return len("started\n"), nil
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
|
||||||
|
result := make(chan error, 1)
|
||||||
|
go func() { result <- Run(ctx, invocation) }()
|
||||||
|
select {
|
||||||
|
case <-started:
|
||||||
|
cancel()
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("child did not start")
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case err := <-result:
|
||||||
|
if !errors.Is(err, context.Canceled) {
|
||||||
|
t.Fatalf("Run() error = %v, want context cancellation", err)
|
||||||
|
}
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("Run() did not return after cancellation")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProcessHelper(t *testing.T) {
|
||||||
|
if os.Getenv("RELEASEKIT_PROCESS_HELPER") != "1" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
args := os.Args
|
||||||
|
if len(args) < 2 {
|
||||||
|
os.Exit(8)
|
||||||
|
}
|
||||||
|
mode := args[len(args)-1]
|
||||||
|
switch mode {
|
||||||
|
case "success":
|
||||||
|
workdir, err := os.Getwd()
|
||||||
|
if err != nil {
|
||||||
|
os.Exit(9)
|
||||||
|
}
|
||||||
|
fmt.Fprintf(os.Stdout, "%s|%s|%s|%s", workdir, args[len(args)-2], os.Getenv("RELEASEKIT_PROCESS_OVERLAY"), os.Getenv("RELEASEKIT_PROCESS_INHERITED"))
|
||||||
|
fmt.Fprintln(os.Stderr, "child stderr")
|
||||||
|
os.Exit(0)
|
||||||
|
case "exit":
|
||||||
|
os.Exit(7)
|
||||||
|
case "wait":
|
||||||
|
fmt.Fprintln(os.Stdout, "started")
|
||||||
|
for {
|
||||||
|
time.Sleep(time.Second)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
os.Exit(10)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type writerFunc func([]byte) (int, error)
|
||||||
|
|
||||||
|
func (write writerFunc) Write(p []byte) (int, error) {
|
||||||
|
return write(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
func helperExecutable(t *testing.T) string {
|
||||||
|
t.Helper()
|
||||||
|
executable, err := os.Executable()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return executable
|
||||||
|
}
|
||||||
|
|
||||||
|
func mustGetwd(t *testing.T) string {
|
||||||
|
t.Helper()
|
||||||
|
workdir, err := os.Getwd()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return workdir
|
||||||
|
}
|
||||||
184
internal/publish/publish.go
Normal file
184
internal/publish/publish.go
Normal file
@@ -0,0 +1,184 @@
|
|||||||
|
// Package publish coordinates candidate validation and exact tag publication.
|
||||||
|
package publish
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/candidate"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/git"
|
||||||
|
)
|
||||||
|
|
||||||
|
type State string
|
||||||
|
|
||||||
|
const (
|
||||||
|
NotAttempted State = "not_attempted"
|
||||||
|
NotPublished State = "not_published"
|
||||||
|
Published State = "published"
|
||||||
|
Conflict State = "conflict"
|
||||||
|
Unknown State = "unknown"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Phase string
|
||||||
|
|
||||||
|
const (
|
||||||
|
Preflight Phase = "preflight"
|
||||||
|
Validation Phase = "validation"
|
||||||
|
TagCreation Phase = "tag_creation"
|
||||||
|
Push Phase = "push"
|
||||||
|
Reconciliation Phase = "reconciliation"
|
||||||
|
Complete Phase = "complete"
|
||||||
|
)
|
||||||
|
|
||||||
|
const recoveryTimeout = 30 * time.Second
|
||||||
|
|
||||||
|
type Request struct {
|
||||||
|
RepositoryDir string
|
||||||
|
Product string
|
||||||
|
Version string
|
||||||
|
Remote string
|
||||||
|
AdditionalChecks func(context.Context, candidate.Candidate) error
|
||||||
|
AfterValidate func(context.Context, candidate.Candidate) error
|
||||||
|
Output io.Writer
|
||||||
|
}
|
||||||
|
|
||||||
|
type Result struct {
|
||||||
|
Version string
|
||||||
|
CandidateCommit string
|
||||||
|
Endpoint string
|
||||||
|
Phase Phase
|
||||||
|
TagObject string
|
||||||
|
State State
|
||||||
|
}
|
||||||
|
|
||||||
|
// Publish validates one captured candidate and pushes only its annotated tag
|
||||||
|
// object. It runs the standard Go suite, then AdditionalChecks when supplied.
|
||||||
|
// A failed push receives one bounded authoritative tag query. Exact
|
||||||
|
// object equality confirms publication; absence and conflict are classified,
|
||||||
|
// while an unreadable result remains Unknown and preserves the push error.
|
||||||
|
func Publish(ctx context.Context, request Request) (Result, error) {
|
||||||
|
result := Result{Version: request.Version, Phase: Preflight, State: NotAttempted}
|
||||||
|
remoteName := request.Remote
|
||||||
|
if remoteName == "" {
|
||||||
|
remoteName = "origin"
|
||||||
|
}
|
||||||
|
checks := candidate.Request{
|
||||||
|
RepositoryDir: request.RepositoryDir,
|
||||||
|
Product: request.Product,
|
||||||
|
Version: request.Version,
|
||||||
|
AdditionalChecks: request.AdditionalChecks,
|
||||||
|
Output: request.Output,
|
||||||
|
}
|
||||||
|
captured, err := candidate.Capture(ctx, checks)
|
||||||
|
if err != nil {
|
||||||
|
return result, fmt.Errorf("capture release candidate: %w", err)
|
||||||
|
}
|
||||||
|
result.CandidateCommit = captured.Commit
|
||||||
|
|
||||||
|
endpoint, err := git.Resolve(ctx, captured.RepositoryDir, remoteName)
|
||||||
|
if err != nil {
|
||||||
|
return result, fmt.Errorf("resolve publication endpoint: %w", err)
|
||||||
|
}
|
||||||
|
result.Endpoint = endpoint.PushURL
|
||||||
|
if err := endpoint.Recheck(ctx, captured.RepositoryDir); err != nil {
|
||||||
|
return result, fmt.Errorf("pre-validation endpoint guard: %w", err)
|
||||||
|
}
|
||||||
|
if _, err := endpoint.RequireCandidate(ctx, captured.RepositoryDir, captured.Version, captured.Commit); err != nil {
|
||||||
|
if isRemoteConflict(err) {
|
||||||
|
result.State = Conflict
|
||||||
|
}
|
||||||
|
return result, fmt.Errorf("pre-validation remote guard: %w", err)
|
||||||
|
}
|
||||||
|
if err := candidate.Recheck(ctx, captured, ""); err != nil {
|
||||||
|
return result, fmt.Errorf("pre-validation local guard: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
result.Phase = Validation
|
||||||
|
if err := candidate.Validate(ctx, checks, captured); err != nil {
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
if request.AfterValidate != nil {
|
||||||
|
if err := request.AfterValidate(ctx, captured); err != nil {
|
||||||
|
return result, fmt.Errorf("after candidate validation: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := candidate.Recheck(ctx, captured, ""); err != nil {
|
||||||
|
return result, fmt.Errorf("post-validation local guard: %w", err)
|
||||||
|
}
|
||||||
|
if err := endpoint.Recheck(ctx, captured.RepositoryDir); err != nil {
|
||||||
|
return result, fmt.Errorf("pre-publication endpoint guard: %w", err)
|
||||||
|
}
|
||||||
|
if _, err := endpoint.RequireCandidate(ctx, captured.RepositoryDir, captured.Version, captured.Commit); err != nil {
|
||||||
|
if isRemoteConflict(err) {
|
||||||
|
result.State = Conflict
|
||||||
|
}
|
||||||
|
return result, fmt.Errorf("pre-publication remote guard: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
result.Phase = TagCreation
|
||||||
|
result.State = NotPublished
|
||||||
|
tagObject, err := git.CreateAnnotatedTag(ctx, captured.RepositoryDir, captured.Version, captured.Commit, []byte(captured.Note))
|
||||||
|
if err != nil {
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
result.TagObject = tagObject
|
||||||
|
if err := candidate.Recheck(ctx, captured, tagObject); err != nil {
|
||||||
|
return result, fmt.Errorf("pre-push local guard: %w", err)
|
||||||
|
}
|
||||||
|
if err := endpoint.Recheck(ctx, captured.RepositoryDir); err != nil {
|
||||||
|
return result, fmt.Errorf("pre-push endpoint guard: %w", err)
|
||||||
|
}
|
||||||
|
if _, err := endpoint.RequireCandidate(ctx, captured.RepositoryDir, captured.Version, captured.Commit); err != nil {
|
||||||
|
if isRemoteConflict(err) {
|
||||||
|
result.State = Conflict
|
||||||
|
}
|
||||||
|
return result, fmt.Errorf("pre-push remote guard: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
result.Phase = Push
|
||||||
|
result.State = Unknown
|
||||||
|
if err := endpoint.PushTag(ctx, captured.RepositoryDir, captured.Version, tagObject); err != nil {
|
||||||
|
return reconcilePush(endpoint, captured, tagObject, result, err)
|
||||||
|
}
|
||||||
|
result.Phase = Complete
|
||||||
|
result.State = Published
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func reconcilePush(endpoint git.Endpoint, captured candidate.Candidate, tagObject string, result Result, pushErr error) (Result, error) {
|
||||||
|
result.Phase = Reconciliation
|
||||||
|
recoveryCtx, cancel := context.WithTimeout(context.Background(), recoveryTimeout)
|
||||||
|
defer cancel()
|
||||||
|
remoteTag, queryErr := endpoint.QueryTag(recoveryCtx, captured.RepositoryDir, captured.Version)
|
||||||
|
if queryErr != nil || remoteTag.State == git.RefUnreadable || remoteTag.State == git.RefConflict {
|
||||||
|
result.State = Unknown
|
||||||
|
if queryErr == nil {
|
||||||
|
if remoteTag.State == git.RefConflict {
|
||||||
|
queryErr = errors.New("authoritative tag query returned inconsistent exact ref records")
|
||||||
|
} else {
|
||||||
|
queryErr = git.ErrRemoteStateUnreadable
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result, fmt.Errorf("push annotated tag %s failed; authoritative reconciliation failed (%w): %w", captured.Version, queryErr, pushErr)
|
||||||
|
}
|
||||||
|
if remoteTag.State == git.RefAbsent {
|
||||||
|
result.State = NotPublished
|
||||||
|
return result, fmt.Errorf("push annotated tag %s failed and the authoritative tag is absent: %w", captured.Version, pushErr)
|
||||||
|
}
|
||||||
|
if remoteTag.State == git.RefPresent && remoteTag.Object == tagObject && (remoteTag.Peeled == "" || remoteTag.Peeled == captured.Commit) {
|
||||||
|
result.Phase = Complete
|
||||||
|
result.State = Published
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
result.State = Conflict
|
||||||
|
return result, fmt.Errorf("push annotated tag %s failed and the authoritative tag identifies object %s, not %s: %w", captured.Version, remoteTag.Object, tagObject, pushErr)
|
||||||
|
}
|
||||||
|
|
||||||
|
func isRemoteConflict(err error) bool {
|
||||||
|
return errors.Is(err, git.ErrRemoteMainMissing) ||
|
||||||
|
errors.Is(err, git.ErrRemoteMainConflict) ||
|
||||||
|
errors.Is(err, git.ErrRemoteTagConflict)
|
||||||
|
}
|
||||||
26
internal/runtimeinfo/version.go
Normal file
26
internal/runtimeinfo/version.go
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
// Package runtimeinfo implements the private runtime version state used by the
|
||||||
|
// public buildinfo facade.
|
||||||
|
package runtimeinfo
|
||||||
|
|
||||||
|
import "runtime/debug"
|
||||||
|
|
||||||
|
var injectedVersion string
|
||||||
|
|
||||||
|
// Version returns the injected version or the running executable's main module
|
||||||
|
// version, falling back to "dev" when neither provides a release identifier.
|
||||||
|
func Version() string {
|
||||||
|
return version(injectedVersion, debug.ReadBuildInfo)
|
||||||
|
}
|
||||||
|
|
||||||
|
func version(injected string, readBuildInfo func() (*debug.BuildInfo, bool)) string {
|
||||||
|
if injected != "" {
|
||||||
|
return injected
|
||||||
|
}
|
||||||
|
|
||||||
|
info, ok := readBuildInfo()
|
||||||
|
if ok && info != nil && info.Main.Version != "" && info.Main.Version != "(devel)" {
|
||||||
|
return info.Main.Version
|
||||||
|
}
|
||||||
|
|
||||||
|
return "dev"
|
||||||
|
}
|
||||||
57
internal/runtimeinfo/version_test.go
Normal file
57
internal/runtimeinfo/version_test.go
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
package runtimeinfo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"runtime/debug"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestVersion(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
injected string
|
||||||
|
info *debug.BuildInfo
|
||||||
|
ok bool
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "injected version takes precedence",
|
||||||
|
injected: "v1.2.3",
|
||||||
|
info: &debug.BuildInfo{Main: debug.Module{Version: "v4.5.6"}},
|
||||||
|
ok: true,
|
||||||
|
want: "v1.2.3",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "main module version",
|
||||||
|
info: &debug.BuildInfo{Main: debug.Module{Version: "v4.5.6"}},
|
||||||
|
ok: true,
|
||||||
|
want: "v4.5.6",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "missing build information",
|
||||||
|
want: "dev",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "development main module",
|
||||||
|
info: &debug.BuildInfo{Main: debug.Module{Version: "(devel)"}},
|
||||||
|
ok: true,
|
||||||
|
want: "dev",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "empty main module version",
|
||||||
|
info: &debug.BuildInfo{Main: debug.Module{}},
|
||||||
|
ok: true,
|
||||||
|
want: "dev",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, test := range tests {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
got := version(test.injected, func() (*debug.BuildInfo, bool) {
|
||||||
|
return test.info, test.ok
|
||||||
|
})
|
||||||
|
if got != test.want {
|
||||||
|
t.Fatalf("version() = %q, want %q", got, test.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
39
internal/tempdir/tempdir.go
Normal file
39
internal/tempdir/tempdir.go
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
// Package tempdir allocates disposable storage outside a source worktree.
|
||||||
|
package tempdir
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Outside uses the system temporary directory and leaves cleanup to its caller.
|
||||||
|
func Outside(repositoryDir, pattern string) (string, error) {
|
||||||
|
directory, err := os.MkdirTemp("", pattern)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
absolute, err := filepath.Abs(directory)
|
||||||
|
if err != nil {
|
||||||
|
os.RemoveAll(directory)
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
directory = absolute
|
||||||
|
repository, err := filepath.Abs(repositoryDir)
|
||||||
|
if err == nil && !strings.EqualFold(filepath.VolumeName(repository), filepath.VolumeName(directory)) {
|
||||||
|
return directory, nil
|
||||||
|
}
|
||||||
|
if err == nil {
|
||||||
|
var relative string
|
||||||
|
relative, err = filepath.Rel(repository, directory)
|
||||||
|
if err == nil && (relative == "." || relative != ".." && !strings.HasPrefix(relative, ".."+string(filepath.Separator))) {
|
||||||
|
err = fmt.Errorf("temporary storage %q is inside repository %q; select an external temporary directory", directory, repository)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
os.RemoveAll(directory)
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return directory, nil
|
||||||
|
}
|
||||||
52
internal/tempdir/tempdir_test.go
Normal file
52
internal/tempdir/tempdir_test.go
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
package tempdir
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestOutsideHonorsRelativeTemporaryDirectory(t *testing.T) {
|
||||||
|
parent := t.TempDir()
|
||||||
|
repository := t.TempDir()
|
||||||
|
cwd, err := os.Getwd()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
relative, err := filepath.Rel(cwd, parent)
|
||||||
|
if err != nil {
|
||||||
|
t.Skip("temporary directory is on another volume")
|
||||||
|
}
|
||||||
|
setTemporaryDirectory(t, relative)
|
||||||
|
directory, err := Outside(repository, "fixture-")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer os.RemoveAll(directory)
|
||||||
|
if !filepath.IsAbs(directory) || filepath.Dir(directory) != parent {
|
||||||
|
t.Fatalf("temporary storage=%q want parent %q", directory, parent)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestOutsideRejectsAndCleansStorageInsideWorktree(t *testing.T) {
|
||||||
|
repository := t.TempDir()
|
||||||
|
setTemporaryDirectory(t, repository)
|
||||||
|
if directory, err := Outside(repository, "fixture-"); err == nil {
|
||||||
|
os.RemoveAll(directory)
|
||||||
|
t.Fatal("storage created inside worktree")
|
||||||
|
}
|
||||||
|
remaining, err := os.ReadDir(repository)
|
||||||
|
if err != nil || len(remaining) != 0 {
|
||||||
|
t.Fatalf("temporary storage left behind: %v %v", remaining, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func setTemporaryDirectory(t *testing.T, directory string) {
|
||||||
|
t.Helper()
|
||||||
|
variable := "TMPDIR"
|
||||||
|
if runtime.GOOS == "windows" {
|
||||||
|
variable = "TMP"
|
||||||
|
}
|
||||||
|
t.Setenv(variable, directory)
|
||||||
|
}
|
||||||
7
internal/versioncontract/injection.go
Normal file
7
internal/versioncontract/injection.go
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
// Package versioncontract holds the internal contract shared by runtime
|
||||||
|
// version reporting and the release builder.
|
||||||
|
package versioncontract
|
||||||
|
|
||||||
|
// InjectedVersionLinkerSymbol is the -X linker target used to set the runtime
|
||||||
|
// version. Keep it in sync with runtimeinfo.injectedVersion.
|
||||||
|
const InjectedVersionLinkerSymbol = "gitea.maximumdirect.net/eric/ReleaseKit/internal/runtimeinfo.injectedVersion"
|
||||||
25
internal/versioncontract/version.go
Normal file
25
internal/versioncontract/version.go
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
package versioncontract
|
||||||
|
|
||||||
|
import "strings"
|
||||||
|
|
||||||
|
// ValidStableVersion reports whether version uses the selected vMAJOR.MINOR.PATCH form.
|
||||||
|
func ValidStableVersion(version string) bool {
|
||||||
|
if !strings.HasPrefix(version, "v") {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
components := strings.Split(version[1:], ".")
|
||||||
|
if len(components) != 3 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, component := range components {
|
||||||
|
if component == "" || len(component) > 1 && component[0] == '0' {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for i := 0; i < len(component); i++ {
|
||||||
|
if component[i] < '0' || component[i] > '9' {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
40
preparation.go
Normal file
40
preparation.go
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
package releasekit
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
internalpreparation "gitea.maximumdirect.net/eric/ReleaseKit/internal/preparation"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TaggedCheckoutRequest selects a stable tag and the full Git object ID
|
||||||
|
// expected by an external build or CI event. An empty Remote selects origin.
|
||||||
|
type TaggedCheckoutRequest struct {
|
||||||
|
RepositoryDir string
|
||||||
|
Version string
|
||||||
|
Remote string
|
||||||
|
ExpectedCommit string
|
||||||
|
}
|
||||||
|
|
||||||
|
// PrepareTaggedCheckout fetches Version from Remote, verifies that its peeled
|
||||||
|
// commit matches ExpectedCommit, and checks out that commit detached. This
|
||||||
|
// operation mutates the selected local repository; use it for disposable
|
||||||
|
// checkouts where tag-fetch and checkout conflicts can be resolved by the
|
||||||
|
// caller. It does not publish a tag or hosted content.
|
||||||
|
func PrepareTaggedCheckout(ctx context.Context, request TaggedCheckoutRequest) error {
|
||||||
|
return internalpreparation.PrepareTaggedCheckout(ctx, internalpreparation.TaggedCheckoutRequest{
|
||||||
|
RepositoryDir: request.RepositoryDir,
|
||||||
|
Version: request.Version,
|
||||||
|
Remote: request.Remote,
|
||||||
|
ExpectedCommit: request.ExpectedCommit,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// PrepareBuildDependencies runs `go mod download` in repositoryDir with
|
||||||
|
// workspace discovery disabled and the locally available compatible Go
|
||||||
|
// toolchain selected. It may access module networks and updates the Go module
|
||||||
|
// cache using the caller's Go proxy, private-module, credential, and cache
|
||||||
|
// settings. If required checksums are missing, the Go command may update
|
||||||
|
// go.sum. Cancellation and Go command failures are returned to the caller.
|
||||||
|
func PrepareBuildDependencies(ctx context.Context, repositoryDir string) error {
|
||||||
|
return internalpreparation.PrepareBuildDependencies(ctx, repositoryDir)
|
||||||
|
}
|
||||||
163
preparation_test.go
Normal file
163
preparation_test.go
Normal file
@@ -0,0 +1,163 @@
|
|||||||
|
package releasekit_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
releasekit "gitea.maximumdirect.net/eric/ReleaseKit"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestPrepareTaggedCheckoutFetchesExpectedCommitAndDetaches(t *testing.T) {
|
||||||
|
repository := newTaggedDeliveryConsumer(t)
|
||||||
|
tagCommit := publishPreparationTag(t, repository)
|
||||||
|
advancePreparationCheckout(t, repository, "later local commit")
|
||||||
|
|
||||||
|
if err := releasekit.PrepareTaggedCheckout(context.Background(), releasekit.TaggedCheckoutRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Version: "v1.2.3",
|
||||||
|
ExpectedCommit: tagCommit,
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if head := buildGit(t, repository, "rev-parse", "HEAD"); head != tagCommit {
|
||||||
|
t.Fatalf("prepared HEAD = %s, want %s", head, tagCommit)
|
||||||
|
}
|
||||||
|
if branch := buildGit(t, repository, "rev-parse", "--abbrev-ref", "HEAD"); branch != "HEAD" {
|
||||||
|
t.Fatalf("prepared checkout branch = %q, want detached HEAD", branch)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPrepareTaggedCheckoutRejectsWrongCommitBeforeCheckout(t *testing.T) {
|
||||||
|
repository := newTaggedDeliveryConsumer(t)
|
||||||
|
tagCommit := publishPreparationTag(t, repository)
|
||||||
|
currentCommit := advancePreparationCheckout(t, repository, "later local commit")
|
||||||
|
remote := buildGit(t, repository, "remote", "get-url", "origin")
|
||||||
|
buildGit(t, repository, "remote", "add", "candidate", remote)
|
||||||
|
|
||||||
|
err := releasekit.PrepareTaggedCheckout(context.Background(), releasekit.TaggedCheckoutRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Remote: "candidate",
|
||||||
|
ExpectedCommit: currentCommit,
|
||||||
|
})
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("PrepareTaggedCheckout() succeeded for a tag that resolves to another commit")
|
||||||
|
}
|
||||||
|
if head := buildGit(t, repository, "rev-parse", "HEAD"); head != currentCommit {
|
||||||
|
t.Fatalf("wrong-tag rejection changed HEAD to %s, want %s (tag commit %s)", head, currentCommit, tagCommit)
|
||||||
|
}
|
||||||
|
if branch := buildGit(t, repository, "rev-parse", "--abbrev-ref", "HEAD"); branch == "HEAD" {
|
||||||
|
t.Fatal("wrong-tag rejection detached the checkout")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPrepareTaggedCheckoutReportsLocalCheckoutConflict(t *testing.T) {
|
||||||
|
repository := newTaggedDeliveryConsumer(t)
|
||||||
|
tagCommit := publishPreparationTag(t, repository)
|
||||||
|
advancePreparationCheckout(t, repository, "later committed content")
|
||||||
|
path := filepath.Join(repository, "cmd/app/main.go")
|
||||||
|
if err := os.WriteFile(path, []byte("uncommitted conflicting content"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
currentCommit := buildGit(t, repository, "rev-parse", "HEAD")
|
||||||
|
|
||||||
|
err := releasekit.PrepareTaggedCheckout(context.Background(), releasekit.TaggedCheckoutRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Version: "v1.2.3",
|
||||||
|
ExpectedCommit: tagCommit,
|
||||||
|
})
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("PrepareTaggedCheckout() succeeded despite a conflicting local edit")
|
||||||
|
}
|
||||||
|
if head := buildGit(t, repository, "rev-parse", "HEAD"); head != currentCommit {
|
||||||
|
t.Fatalf("conflicting checkout changed HEAD to %s, want %s", head, currentCommit)
|
||||||
|
}
|
||||||
|
contents, err := os.ReadFile(path)
|
||||||
|
if err != nil || string(contents) != "uncommitted conflicting content" {
|
||||||
|
t.Fatalf("conflicting local file = %q, %v", contents, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPrepareTaggedCheckoutReportsConflictingLocalTag(t *testing.T) {
|
||||||
|
repository := newTaggedDeliveryConsumer(t)
|
||||||
|
publishPreparationTag(t, repository)
|
||||||
|
currentCommit := advancePreparationCheckout(t, repository, "later local commit")
|
||||||
|
buildGit(t, repository, "tag", "v1.2.3")
|
||||||
|
|
||||||
|
err := releasekit.PrepareTaggedCheckout(context.Background(), releasekit.TaggedCheckoutRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Version: "v1.2.3",
|
||||||
|
ExpectedCommit: buildGit(t, repository, "rev-parse", "HEAD~1"),
|
||||||
|
})
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("PrepareTaggedCheckout() replaced a conflicting local tag")
|
||||||
|
}
|
||||||
|
if head := buildGit(t, repository, "rev-parse", "HEAD"); head != currentCommit {
|
||||||
|
t.Fatalf("conflicting tag fetch changed HEAD to %s, want %s", head, currentCommit)
|
||||||
|
}
|
||||||
|
if tagCommit := buildGit(t, repository, "rev-parse", "refs/tags/v1.2.3^{commit}"); tagCommit != currentCommit {
|
||||||
|
t.Fatalf("conflicting local tag changed to %s, want %s", tagCommit, currentCommit)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPrepareTaggedCheckoutValidatesInputsBeforeFetching(t *testing.T) {
|
||||||
|
repository := newTaggedDeliveryConsumer(t)
|
||||||
|
publishPreparationTag(t, repository)
|
||||||
|
for _, request := range []releasekit.TaggedCheckoutRequest{
|
||||||
|
{RepositoryDir: repository, Version: "not-a-version", ExpectedCommit: buildGit(t, repository, "rev-parse", "HEAD")},
|
||||||
|
{RepositoryDir: repository, Version: "v1.2.3"},
|
||||||
|
{RepositoryDir: repository, Version: "v1.2.3", ExpectedCommit: "not-an-object-id"},
|
||||||
|
} {
|
||||||
|
err := releasekit.PrepareTaggedCheckout(context.Background(), request)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("PrepareTaggedCheckout(%#v) succeeded", request)
|
||||||
|
}
|
||||||
|
if _, err := buildGitOutput(repository, "show-ref", "--verify", "refs/tags/v1.2.3"); err == nil {
|
||||||
|
t.Fatal("input validation fetched the tag before rejecting the request")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := releasekit.PrepareTaggedCheckout(context.Background(), releasekit.TaggedCheckoutRequest{
|
||||||
|
RepositoryDir: repository, Version: "invalid", ExpectedCommit: "bad",
|
||||||
|
}); !errors.Is(err, releasekit.ErrInvalidVersion) {
|
||||||
|
t.Fatalf("invalid-version error = %v, want ErrInvalidVersion", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPrepareBuildDependenciesRequiresRepositoryDirectory(t *testing.T) {
|
||||||
|
if err := releasekit.PrepareBuildDependencies(context.Background(), " "); err == nil {
|
||||||
|
t.Fatal("PrepareBuildDependencies() accepted an empty repository directory")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func publishPreparationTag(t *testing.T, repository string) string {
|
||||||
|
t.Helper()
|
||||||
|
remoteDir := t.TempDir()
|
||||||
|
remote := filepath.Join(remoteDir, "origin.git")
|
||||||
|
buildGit(t, remoteDir, "init", "--bare", remote)
|
||||||
|
buildGit(t, repository, "remote", "add", "origin", remote)
|
||||||
|
commit := buildGit(t, repository, "rev-parse", "refs/tags/v1.2.3^{commit}")
|
||||||
|
buildGit(t, repository, "push", "origin", "refs/tags/v1.2.3")
|
||||||
|
buildGit(t, repository, "tag", "-d", "v1.2.3")
|
||||||
|
return commit
|
||||||
|
}
|
||||||
|
|
||||||
|
func advancePreparationCheckout(t *testing.T, repository, source string) string {
|
||||||
|
t.Helper()
|
||||||
|
path := filepath.Join(repository, "cmd/app/main.go")
|
||||||
|
if err := os.WriteFile(path, []byte("package main\n// "+source+"\nfunc main() {}\n"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
buildGit(t, repository, "add", "cmd/app/main.go")
|
||||||
|
buildGit(t, repository, "commit", "-m", source)
|
||||||
|
return buildGit(t, repository, "rev-parse", "HEAD")
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildGitOutput(repository string, args ...string) ([]byte, error) {
|
||||||
|
command := exec.Command("git", args...)
|
||||||
|
command.Dir = repository
|
||||||
|
return command.Output()
|
||||||
|
}
|
||||||
91
publish.go
Normal file
91
publish.go
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
package releasekit
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
internalbuild "gitea.maximumdirect.net/eric/ReleaseKit/internal/build"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/candidate"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/publish"
|
||||||
|
)
|
||||||
|
|
||||||
|
type PublicationState string
|
||||||
|
|
||||||
|
const (
|
||||||
|
// PublicationNotAttempted means no tag push was attempted.
|
||||||
|
PublicationNotAttempted PublicationState = PublicationState(publish.NotAttempted)
|
||||||
|
// PublicationNotPublished means this invocation knows the tag was not published.
|
||||||
|
PublicationNotPublished PublicationState = PublicationState(publish.NotPublished)
|
||||||
|
// PublicationPublished means Git reported a successful push of the intended tag object.
|
||||||
|
PublicationPublished PublicationState = PublicationState(publish.Published)
|
||||||
|
// PublicationConflict means an authoritative branch or tag guard failed.
|
||||||
|
PublicationConflict PublicationState = PublicationState(publish.Conflict)
|
||||||
|
// PublicationUnknown means a tag push failed and its remote outcome is unresolved.
|
||||||
|
PublicationUnknown PublicationState = PublicationState(publish.Unknown)
|
||||||
|
)
|
||||||
|
|
||||||
|
type PublicationPhase string
|
||||||
|
|
||||||
|
const (
|
||||||
|
// PublicationPreflight identifies local and remote candidate inspection.
|
||||||
|
PublicationPreflight PublicationPhase = PublicationPhase(publish.Preflight)
|
||||||
|
// PublicationValidation identifies the standard suite and additional checks.
|
||||||
|
PublicationValidation PublicationPhase = PublicationPhase(publish.Validation)
|
||||||
|
// PublicationTagCreation identifies creation and inspection of the local annotated tag.
|
||||||
|
PublicationTagCreation PublicationPhase = PublicationPhase(publish.TagCreation)
|
||||||
|
// PublicationPush identifies the remote tag push attempt.
|
||||||
|
PublicationPush PublicationPhase = PublicationPhase(publish.Push)
|
||||||
|
// PublicationReconciliation identifies the single authoritative tag query after a push error.
|
||||||
|
PublicationReconciliation PublicationPhase = PublicationPhase(publish.Reconciliation)
|
||||||
|
// PublicationComplete identifies a successful tag push.
|
||||||
|
PublicationComplete PublicationPhase = PublicationPhase(publish.Complete)
|
||||||
|
)
|
||||||
|
|
||||||
|
// PublicationResult describes the publication state reached by this call.
|
||||||
|
type PublicationResult struct {
|
||||||
|
Version string // selected stable version
|
||||||
|
CandidateCommit string // captured main commit
|
||||||
|
Endpoint string // captured effective push URL
|
||||||
|
Phase PublicationPhase // last operation phase reached
|
||||||
|
TagObject string // local annotated tag object ID, when created
|
||||||
|
State PublicationState // publication outcome for this invocation
|
||||||
|
}
|
||||||
|
|
||||||
|
// Publish always runs the offline Go test suite for the captured candidate,
|
||||||
|
// then calls AdditionalChecks when supplied. It optionally builds selected
|
||||||
|
// targets in temporary storage outside the worktree and pushes the exact
|
||||||
|
// annotated tag object to the selected remote. It returns a result with errors: preflight
|
||||||
|
// failures are not_attempted, failed authoritative guards are conflict, and
|
||||||
|
// errors after local tag creation but before push are not_published. A failed
|
||||||
|
// push gets one bounded authoritative tag query: an exact object match confirms
|
||||||
|
// publication, absence is not_published, a different object is conflict, and
|
||||||
|
// an unreadable result is unknown. A nil error means publication is confirmed
|
||||||
|
// by the successful push or exact remote object match.
|
||||||
|
func Publish(ctx context.Context, request ReleaseRequest) (PublicationResult, error) {
|
||||||
|
var validate func(context.Context, candidate.Candidate) error
|
||||||
|
if request.AdditionalChecks != nil {
|
||||||
|
validate = func(ctx context.Context, captured candidate.Candidate) error {
|
||||||
|
return request.AdditionalChecks(ctx, Candidate{
|
||||||
|
RepositoryDir: captured.RepositoryDir,
|
||||||
|
Commit: captured.Commit,
|
||||||
|
Version: captured.Version,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result, err := publish.Publish(ctx, publish.Request{
|
||||||
|
RepositoryDir: request.RepositoryDir,
|
||||||
|
Product: request.Product,
|
||||||
|
Version: request.Version,
|
||||||
|
Remote: request.Remote,
|
||||||
|
AdditionalChecks: validate,
|
||||||
|
AfterValidate: internalbuild.CandidateCallback(internalBuildSpec(request.Build), request.Output),
|
||||||
|
Output: request.Output,
|
||||||
|
})
|
||||||
|
return PublicationResult{
|
||||||
|
Version: result.Version,
|
||||||
|
CandidateCommit: result.CandidateCommit,
|
||||||
|
Endpoint: result.Endpoint,
|
||||||
|
Phase: PublicationPhase(result.Phase),
|
||||||
|
TagObject: result.TagObject,
|
||||||
|
State: PublicationState(result.State),
|
||||||
|
}, err
|
||||||
|
}
|
||||||
654
publish_test.go
Normal file
654
publish_test.go
Normal file
@@ -0,0 +1,654 @@
|
|||||||
|
package releasekit_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
releasekit "gitea.maximumdirect.net/eric/ReleaseKit"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/git"
|
||||||
|
)
|
||||||
|
|
||||||
|
const releaseNote = "# Sample App v1.2.3\n\nA source release.\n\nUpgrade notes stay intact.\n"
|
||||||
|
|
||||||
|
func TestPublishPushesOnlyTheCapturedAnnotatedTag(t *testing.T) {
|
||||||
|
repo := newPublishFixture(t)
|
||||||
|
wrapper := installGitWrapper(t, repo, "pass")
|
||||||
|
t.Setenv("PATH", wrapper.bin+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||||
|
suiteRuns := filepath.Join(t.TempDir(), "suite-runs")
|
||||||
|
t.Setenv("RELEASEKIT_FIXTURE_SUITE_RUNS", suiteRuns)
|
||||||
|
refsBefore := gitText(t, repo.bare, "show-ref", "--heads", "--tags")
|
||||||
|
commit := repo.commit
|
||||||
|
var validations int
|
||||||
|
result, err := releasekit.Publish(context.Background(), releasekit.ReleaseRequest{
|
||||||
|
RepositoryDir: repo.work,
|
||||||
|
Product: "Sample App",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
AdditionalChecks: func(_ context.Context, candidate releasekit.Candidate) error {
|
||||||
|
validations++
|
||||||
|
runs, readErr := os.ReadFile(suiteRuns)
|
||||||
|
if readErr != nil || string(runs) != "ran\n" {
|
||||||
|
return fmt.Errorf("standard suite runs before additional checks: contents=%q error=%v", runs, readErr)
|
||||||
|
}
|
||||||
|
if candidate.RepositoryDir != repo.work || candidate.Commit != commit || candidate.Version != "v1.2.3" {
|
||||||
|
t.Fatalf("callback candidate = %#v", candidate)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if validations != 1 {
|
||||||
|
t.Fatalf("validation calls = %d, want 1", validations)
|
||||||
|
}
|
||||||
|
if runs, err := os.ReadFile(suiteRuns); err != nil || string(runs) != "ran\n" {
|
||||||
|
t.Fatalf("standard suite runs = %q, error = %v; want one run", runs, err)
|
||||||
|
}
|
||||||
|
if queries := countLines(t, wrapper.queryLog); queries != 3 {
|
||||||
|
t.Fatalf("authoritative tag query count = %d, want 3 guards and no success read-back", queries)
|
||||||
|
}
|
||||||
|
if result.State != releasekit.PublicationPublished || result.Phase != releasekit.PublicationComplete {
|
||||||
|
t.Fatalf("publication result = %#v", result)
|
||||||
|
}
|
||||||
|
if result.CandidateCommit != commit || result.Endpoint != repo.bare || result.TagObject == "" {
|
||||||
|
t.Fatalf("publication identity = %#v", result)
|
||||||
|
}
|
||||||
|
|
||||||
|
refsAfter := gitText(t, repo.bare, "show-ref", "--heads", "--tags")
|
||||||
|
for _, ref := range strings.Split(refsBefore, "\n") {
|
||||||
|
if !strings.Contains(refsAfter, ref) {
|
||||||
|
t.Fatalf("preexisting remote ref %q changed or disappeared; refs now:\n%s", ref, refsAfter)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
remoteTag := gitText(t, repo.bare, "rev-parse", "refs/tags/v1.2.3")
|
||||||
|
if remoteTag != result.TagObject {
|
||||||
|
t.Fatalf("remote tag object = %s, want %s", remoteTag, result.TagObject)
|
||||||
|
}
|
||||||
|
if peeled := gitText(t, repo.bare, "rev-parse", "refs/tags/v1.2.3^{}"); peeled != commit {
|
||||||
|
t.Fatalf("remote tag peels to %s, want %s", peeled, commit)
|
||||||
|
}
|
||||||
|
if tagType := gitText(t, repo.bare, "cat-file", "-t", "refs/tags/v1.2.3"); tagType != "tag" {
|
||||||
|
t.Fatalf("remote tag object type = %q, want tag", tagType)
|
||||||
|
}
|
||||||
|
tagContents := gitBytes(t, repo.bare, "cat-file", "tag", "refs/tags/v1.2.3")
|
||||||
|
separator := strings.Index(tagContents, "\n\n")
|
||||||
|
if separator < 0 || tagContents[separator+2:] != releaseNote {
|
||||||
|
t.Fatalf("annotated tag message = %q, want %q", tagContents[separator+2:], releaseNote)
|
||||||
|
}
|
||||||
|
if strings.Contains(tagContents, "-----BEGIN PGP SIGNATURE-----") {
|
||||||
|
t.Fatal("publication tag unexpectedly contains a signature")
|
||||||
|
}
|
||||||
|
if !strings.Contains(refsAfter, "refs/heads/unrelated") || !strings.Contains(refsAfter, "refs/tags/v0.9.0") {
|
||||||
|
t.Fatalf("publication changed unrelated refs:\n%s", refsAfter)
|
||||||
|
}
|
||||||
|
if !strings.Contains(refsAfter, "refs/tags/v1.2.3") || strings.Count(refsAfter, "refs/tags/") != 2 {
|
||||||
|
t.Fatalf("publication pushed unexpected tag refs:\n%s", refsAfter)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPublishFailedStandardSuiteSkipsAdditionalChecksAndTagCreation(t *testing.T) {
|
||||||
|
repo := newPublishFixture(t)
|
||||||
|
t.Setenv("RELEASEKIT_FAIL_FIXTURE_SUITE", "1")
|
||||||
|
var checks int
|
||||||
|
result, err := releasekit.Publish(context.Background(), releasekit.ReleaseRequest{
|
||||||
|
RepositoryDir: repo.work,
|
||||||
|
Product: "Sample App",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
AdditionalChecks: func(context.Context, releasekit.Candidate) error {
|
||||||
|
checks++
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "fixture standard suite failure") {
|
||||||
|
t.Fatalf("Publish() error = %v, want fixture standard suite failure", err)
|
||||||
|
}
|
||||||
|
if checks != 0 || result.TagObject != "" || result.State != releasekit.PublicationNotAttempted {
|
||||||
|
t.Fatalf("failed standard suite result=%#v additional checks=%d", result, checks)
|
||||||
|
}
|
||||||
|
for _, command := range [][]string{
|
||||||
|
{"git", "-C", repo.work, "show-ref", "--verify", "--quiet", "refs/tags/v1.2.3"},
|
||||||
|
{"git", "--git-dir", repo.bare, "show-ref", "--verify", "--quiet", "refs/tags/v1.2.3"},
|
||||||
|
} {
|
||||||
|
if _, err := exec.Command(command[0], command[1:]...).CombinedOutput(); err == nil {
|
||||||
|
t.Fatalf("failed standard suite created release tag with %v", command)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPublishAdditionalCheckFailurePreservesCauseAndPreventsTagCreation(t *testing.T) {
|
||||||
|
repo := newPublishFixture(t)
|
||||||
|
suiteRuns := filepath.Join(t.TempDir(), "suite-runs")
|
||||||
|
t.Setenv("RELEASEKIT_FIXTURE_SUITE_RUNS", suiteRuns)
|
||||||
|
wantErr := errors.New("additional product check failed")
|
||||||
|
var checks int
|
||||||
|
result, err := releasekit.Publish(context.Background(), releasekit.ReleaseRequest{
|
||||||
|
RepositoryDir: repo.work,
|
||||||
|
Product: "Sample App",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
AdditionalChecks: func(context.Context, releasekit.Candidate) error {
|
||||||
|
checks++
|
||||||
|
return wantErr
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if !errors.Is(err, wantErr) {
|
||||||
|
t.Fatalf("Publish() error = %v, want wrapped additional-check error", err)
|
||||||
|
}
|
||||||
|
if runs, readErr := os.ReadFile(suiteRuns); readErr != nil || string(runs) != "ran\n" {
|
||||||
|
t.Fatalf("standard suite runs = %q, error = %v; want one successful run", runs, readErr)
|
||||||
|
}
|
||||||
|
if checks != 1 || result.TagObject != "" || result.State != releasekit.PublicationNotAttempted {
|
||||||
|
t.Fatalf("additional-check failure result=%#v checks=%d", result, checks)
|
||||||
|
}
|
||||||
|
for _, command := range [][]string{
|
||||||
|
{"git", "-C", repo.work, "show-ref", "--verify", "--quiet", "refs/tags/v1.2.3"},
|
||||||
|
{"git", "--git-dir", repo.bare, "show-ref", "--verify", "--quiet", "refs/tags/v1.2.3"},
|
||||||
|
} {
|
||||||
|
if _, err := exec.Command(command[0], command[1:]...).CombinedOutput(); err == nil {
|
||||||
|
t.Fatalf("additional-check failure created release tag with %v", command)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPublishRejectedPushKeepsLocalTagAndReportsNotPublished(t *testing.T) {
|
||||||
|
repo := newPublishFixture(t)
|
||||||
|
wrapper := installGitWrapper(t, repo, "pass")
|
||||||
|
t.Setenv("PATH", wrapper.bin+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||||
|
hook := filepath.Join(repo.bare, "hooks", "pre-receive")
|
||||||
|
if err := os.WriteFile(hook, []byte("#!/bin/sh\ncat >/dev/null\nexit 1\n"), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
result, err := releasekit.Publish(context.Background(), releasekit.ReleaseRequest{
|
||||||
|
RepositoryDir: repo.work,
|
||||||
|
Product: "Sample App",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
AdditionalChecks: func(context.Context, releasekit.Candidate) error { return nil },
|
||||||
|
})
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("Publish() succeeded despite rejected push hook")
|
||||||
|
}
|
||||||
|
if result.State != releasekit.PublicationNotPublished || result.Phase != releasekit.PublicationReconciliation || result.TagObject == "" {
|
||||||
|
t.Fatalf("publication result = %#v", result)
|
||||||
|
}
|
||||||
|
if !strings.Contains(err.Error(), "failed to push some refs") || !strings.Contains(err.Error(), "authoritative tag is absent") {
|
||||||
|
t.Fatalf("push error was not preserved with absence evidence: %v", err)
|
||||||
|
}
|
||||||
|
if queries := countLines(t, wrapper.queryLog); queries != 4 {
|
||||||
|
t.Fatalf("authoritative tag query count = %d, want one reconciliation query", queries)
|
||||||
|
}
|
||||||
|
if got := gitText(t, repo.work, "rev-parse", "refs/tags/v1.2.3"); got != result.TagObject {
|
||||||
|
t.Fatalf("local tag object = %s, want retained object %s", got, result.TagObject)
|
||||||
|
}
|
||||||
|
if _, err := exec.Command("git", "--git-dir", repo.bare, "show-ref", "--verify", "--quiet", "refs/tags/v1.2.3").CombinedOutput(); err == nil {
|
||||||
|
t.Fatal("rejected push unexpectedly published the tag")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPublishLostAcknowledgmentConfirmsExactRemoteObject(t *testing.T) {
|
||||||
|
repo := newPublishFixture(t)
|
||||||
|
wrapper := installGitWrapper(t, repo, "lost-ack-cancel")
|
||||||
|
t.Setenv("PATH", wrapper.bin+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
defer cancel()
|
||||||
|
finished := make(chan struct{})
|
||||||
|
watcherDone := make(chan struct{})
|
||||||
|
result, err := releasekit.Publish(ctx, releasekit.ReleaseRequest{
|
||||||
|
RepositoryDir: repo.work,
|
||||||
|
Product: "Sample App",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
AdditionalChecks: func(context.Context, releasekit.Candidate) error {
|
||||||
|
go func() {
|
||||||
|
defer close(watcherDone)
|
||||||
|
for {
|
||||||
|
if _, statErr := os.Stat(wrapper.pushDone); statErr == nil {
|
||||||
|
cancel()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case <-finished:
|
||||||
|
return
|
||||||
|
case <-time.After(time.Millisecond):
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
close(finished)
|
||||||
|
<-watcherDone
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if result.State != releasekit.PublicationPublished || result.Phase != releasekit.PublicationComplete {
|
||||||
|
t.Fatalf("publication result = %#v", result)
|
||||||
|
}
|
||||||
|
if queries := countLines(t, wrapper.queryLog); queries != 4 {
|
||||||
|
t.Fatalf("authoritative tag query count = %d, want one cancellation recovery query", queries)
|
||||||
|
}
|
||||||
|
if got := gitText(t, repo.bare, "rev-parse", "refs/tags/v1.2.3"); got != result.TagObject {
|
||||||
|
t.Fatalf("remote tag object = %s, want %s", got, result.TagObject)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPublishLostAcknowledgmentWithChangedEndpointRemainsUnknown(t *testing.T) {
|
||||||
|
repo := newPublishFixture(t)
|
||||||
|
base := t.TempDir()
|
||||||
|
emptyRemote := filepath.Join(base, "empty.git")
|
||||||
|
gitRun(t, base, "init", "--bare", emptyRemote)
|
||||||
|
wrapper := installGitWrapperWithMutationMode(t, repo, "lost-ack-rewrite", emptyRemote)
|
||||||
|
t.Setenv("PATH", wrapper.bin+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||||
|
|
||||||
|
result, err := releasekit.Publish(context.Background(), releasekit.ReleaseRequest{
|
||||||
|
RepositoryDir: repo.work,
|
||||||
|
Product: "Sample App",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
AdditionalChecks: func(context.Context, releasekit.Candidate) error { return nil },
|
||||||
|
})
|
||||||
|
if err == nil || result.State != releasekit.PublicationUnknown || result.Phase != releasekit.PublicationReconciliation {
|
||||||
|
t.Fatalf("result = %#v, error = %v", result, err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(err.Error(), "scoped URL resolves") || !strings.Contains(err.Error(), "lost acknowledgment") {
|
||||||
|
t.Fatalf("error does not preserve endpoint verification and push failures: %v", err)
|
||||||
|
}
|
||||||
|
if !errors.Is(err, git.ErrEndpointChanged) || !errors.Is(err, git.ErrRemoteStateUnreadable) {
|
||||||
|
t.Fatalf("endpoint verification error identity was not preserved: %v", err)
|
||||||
|
}
|
||||||
|
var exitErr *exec.ExitError
|
||||||
|
if !errors.As(err, &exitErr) || exitErr.ExitCode() != 77 {
|
||||||
|
t.Fatalf("push cause identity was not preserved: %v", err)
|
||||||
|
}
|
||||||
|
if queries := countLines(t, wrapper.queryLog); queries != 3 {
|
||||||
|
t.Fatalf("authoritative tag query count = %d, want no tag query after endpoint verification failed", queries)
|
||||||
|
}
|
||||||
|
if got := gitText(t, repo.work, "rev-parse", "refs/tags/v1.2.3"); got != result.TagObject {
|
||||||
|
t.Fatalf("local tag object = %s, want retained object %s", got, result.TagObject)
|
||||||
|
}
|
||||||
|
if got := gitText(t, repo.bare, "rev-parse", "refs/tags/v1.2.3"); got != result.TagObject {
|
||||||
|
t.Fatalf("original remote tag object = %s, want published object %s", got, result.TagObject)
|
||||||
|
}
|
||||||
|
if got := gitText(t, repo.bare, "rev-parse", "refs/tags/v1.2.3^{}"); got != repo.commit {
|
||||||
|
t.Fatalf("original remote tag peels to %s, want candidate commit %s", got, repo.commit)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPublishConflictingRemoteTagIsNotReportedAsAbsent(t *testing.T) {
|
||||||
|
repo := newPublishFixture(t)
|
||||||
|
wrapper := installGitWrapper(t, repo, "pass")
|
||||||
|
t.Setenv("PATH", wrapper.bin+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||||
|
hook := filepath.Join(repo.work, ".git", "hooks", "pre-push")
|
||||||
|
conflictingObject := gitText(t, repo.work, "rev-parse", "refs/tags/v0.9.0")
|
||||||
|
script := fmt.Sprintf("#!/bin/sh\n%s --git-dir=%s update-ref refs/tags/v1.2.3 %s\nexit 1\n", shellQuote(mustLookPath(t, "git")), shellQuote(repo.bare), conflictingObject)
|
||||||
|
if err := os.WriteFile(hook, []byte(script), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
result, err := releasekit.Publish(context.Background(), releasekit.ReleaseRequest{
|
||||||
|
RepositoryDir: repo.work,
|
||||||
|
Product: "Sample App",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
AdditionalChecks: func(context.Context, releasekit.Candidate) error { return nil },
|
||||||
|
})
|
||||||
|
if err == nil || result.State != releasekit.PublicationConflict || result.Phase != releasekit.PublicationReconciliation {
|
||||||
|
t.Fatalf("result = %#v, error = %v", result, err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(err.Error(), "authoritative tag identifies object") || !strings.Contains(err.Error(), "failed to push some refs") {
|
||||||
|
t.Fatalf("error does not distinguish conflict and preserve push failure: %v", err)
|
||||||
|
}
|
||||||
|
if queries := countLines(t, wrapper.queryLog); queries != 4 {
|
||||||
|
t.Fatalf("authoritative tag query count = %d, want one reconciliation query", queries)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPublishStopsWhenLocalTagChangesBeforePush(t *testing.T) {
|
||||||
|
repo := newPublishFixture(t)
|
||||||
|
gitRun(t, repo.work, "-c", "tag.gpgSign=false", "tag", "--annotate", "--message", "different tag", "v0.8.0", repo.commit)
|
||||||
|
conflictingObject := gitText(t, repo.work, "rev-parse", "refs/tags/v0.8.0")
|
||||||
|
wrapper := installGitWrapperWithMutation(t, repo, conflictingObject)
|
||||||
|
t.Setenv("PATH", wrapper.bin+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||||
|
result, err := releasekit.Publish(context.Background(), releasekit.ReleaseRequest{
|
||||||
|
RepositoryDir: repo.work,
|
||||||
|
Product: "Sample App",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
AdditionalChecks: func(context.Context, releasekit.Candidate) error { return nil },
|
||||||
|
})
|
||||||
|
if err == nil || result.State != releasekit.PublicationNotPublished || result.Phase != releasekit.PublicationTagCreation {
|
||||||
|
t.Fatalf("result = %#v, error = %v", result, err)
|
||||||
|
}
|
||||||
|
if got := gitText(t, repo.work, "rev-parse", "refs/tags/v1.2.3"); got != conflictingObject {
|
||||||
|
t.Fatalf("changed local tag object = %s, want %s", got, conflictingObject)
|
||||||
|
}
|
||||||
|
if result.TagObject == "" || result.TagObject == conflictingObject {
|
||||||
|
t.Fatalf("captured tag object = %q, want the prior object; publish error: %v", result.TagObject, err)
|
||||||
|
}
|
||||||
|
if queries := countLines(t, wrapper.queryLog); queries != 2 {
|
||||||
|
t.Fatalf("remote query count = %d, want only the pre-validation and prepublication guards", queries)
|
||||||
|
}
|
||||||
|
if _, err := exec.Command("git", "--git-dir", repo.bare, "show-ref", "--verify", "--quiet", "refs/tags/v1.2.3").CombinedOutput(); err == nil {
|
||||||
|
t.Fatal("changed local tag was pushed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPublishUnavailableReconciliationRemainsUnknownAndPreservesPushError(t *testing.T) {
|
||||||
|
repo := newPublishFixture(t)
|
||||||
|
wrapper := installGitWrapper(t, repo, "query-failure")
|
||||||
|
t.Setenv("PATH", wrapper.bin+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||||
|
hook := filepath.Join(repo.bare, "hooks", "pre-receive")
|
||||||
|
if err := os.WriteFile(hook, []byte("#!/bin/sh\ncat >/dev/null\nexit 1\n"), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
result, err := releasekit.Publish(context.Background(), releasekit.ReleaseRequest{
|
||||||
|
RepositoryDir: repo.work,
|
||||||
|
Product: "Sample App",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
AdditionalChecks: func(context.Context, releasekit.Candidate) error { return nil },
|
||||||
|
})
|
||||||
|
if err == nil || result.State != releasekit.PublicationUnknown || result.Phase != releasekit.PublicationReconciliation {
|
||||||
|
t.Fatalf("result = %#v, error = %v", result, err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(err.Error(), "reconciliation unavailable") || !strings.Contains(err.Error(), "failed to push some refs") {
|
||||||
|
t.Fatalf("error does not preserve both query and push failure: %v", err)
|
||||||
|
}
|
||||||
|
if queries := countLines(t, wrapper.queryLog); queries != 4 {
|
||||||
|
t.Fatalf("authoritative tag query count = %d, want one failed reconciliation query", queries)
|
||||||
|
}
|
||||||
|
if got := gitText(t, repo.work, "rev-parse", "refs/tags/v1.2.3"); got != result.TagObject {
|
||||||
|
t.Fatalf("local tag object = %s, want retained object %s", got, result.TagObject)
|
||||||
|
}
|
||||||
|
var exitErr *exec.ExitError
|
||||||
|
if !errors.As(err, &exitErr) || exitErr.ExitCode() == 0 {
|
||||||
|
t.Fatalf("push cause was not preserved in error chain: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPublishUninterpretableReconciliationRemainsUnknown(t *testing.T) {
|
||||||
|
repo := newPublishFixture(t)
|
||||||
|
other := gitText(t, repo.work, "rev-parse", "refs/tags/v0.9.0")
|
||||||
|
wrapper := installGitWrapperWithMutationMode(t, repo, "query-conflict", other)
|
||||||
|
t.Setenv("PATH", wrapper.bin+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||||
|
hook := filepath.Join(repo.work, ".git", "hooks", "pre-push")
|
||||||
|
if err := os.WriteFile(hook, []byte("#!/bin/sh\nexit 1\n"), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
result, err := releasekit.Publish(context.Background(), releasekit.ReleaseRequest{
|
||||||
|
RepositoryDir: repo.work,
|
||||||
|
Product: "Sample App",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
AdditionalChecks: func(context.Context, releasekit.Candidate) error { return nil },
|
||||||
|
})
|
||||||
|
if err == nil || result.State != releasekit.PublicationUnknown || result.Phase != releasekit.PublicationReconciliation {
|
||||||
|
t.Fatalf("result = %#v, error = %v", result, err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(err.Error(), "inconsistent exact ref records") || !strings.Contains(err.Error(), "failed to push some refs") {
|
||||||
|
t.Fatalf("error does not preserve uninterpretable remote state and push failure: %v", err)
|
||||||
|
}
|
||||||
|
if queries := countLines(t, wrapper.queryLog); queries != 4 {
|
||||||
|
t.Fatalf("authoritative tag query count = %d, want one uninterpretable reconciliation query", queries)
|
||||||
|
}
|
||||||
|
if got := gitText(t, repo.work, "rev-parse", "refs/tags/v1.2.3"); got != result.TagObject {
|
||||||
|
t.Fatalf("local tag object = %s, want retained object %s", got, result.TagObject)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPublishRemoteConflictStopsBeforeValidation(t *testing.T) {
|
||||||
|
repo := newPublishFixture(t)
|
||||||
|
gitRun(t, repo.bare, "update-ref", "refs/heads/main", repo.unrelatedCommit)
|
||||||
|
var validations int
|
||||||
|
result, err := releasekit.Publish(context.Background(), releasekit.ReleaseRequest{
|
||||||
|
RepositoryDir: repo.work,
|
||||||
|
Product: "Sample App",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
AdditionalChecks: func(context.Context, releasekit.Candidate) error {
|
||||||
|
validations++
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("Publish() succeeded with a conflicting authoritative main")
|
||||||
|
}
|
||||||
|
if validations != 0 || result.State != releasekit.PublicationConflict || result.TagObject != "" {
|
||||||
|
t.Fatalf("validation calls = %d, result = %#v, error = %v", validations, result, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPublishRemoteChangeDuringValidationPreventsLocalTag(t *testing.T) {
|
||||||
|
repo := newPublishFixture(t)
|
||||||
|
result, err := releasekit.Publish(context.Background(), releasekit.ReleaseRequest{
|
||||||
|
RepositoryDir: repo.work,
|
||||||
|
Product: "Sample App",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
AdditionalChecks: func(context.Context, releasekit.Candidate) error {
|
||||||
|
gitRun(t, repo.bare, "update-ref", "refs/heads/main", repo.unrelatedCommit)
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("Publish() succeeded after authoritative main changed during validation")
|
||||||
|
}
|
||||||
|
if result.State != releasekit.PublicationConflict || result.Phase != releasekit.PublicationValidation || result.TagObject != "" {
|
||||||
|
t.Fatalf("publication result = %#v, error = %v", result, err)
|
||||||
|
}
|
||||||
|
if _, err := exec.Command("git", "-C", repo.work, "show-ref", "--verify", "--quiet", "refs/tags/v1.2.3").CombinedOutput(); err == nil {
|
||||||
|
t.Fatal("tag was created after the remote guard failed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type publishFixture struct {
|
||||||
|
work string
|
||||||
|
bare string
|
||||||
|
commit string
|
||||||
|
unrelatedCommit string
|
||||||
|
}
|
||||||
|
|
||||||
|
type gitWrapper struct {
|
||||||
|
bin string
|
||||||
|
queryLog string
|
||||||
|
pushDone string
|
||||||
|
realGit string
|
||||||
|
}
|
||||||
|
|
||||||
|
func installGitWrapper(t *testing.T, repo publishFixture, mode string) gitWrapper {
|
||||||
|
t.Helper()
|
||||||
|
return installGitWrapperWithMutationMode(t, repo, mode, "")
|
||||||
|
}
|
||||||
|
|
||||||
|
func installGitWrapperWithMutation(t *testing.T, repo publishFixture, object string) gitWrapper {
|
||||||
|
t.Helper()
|
||||||
|
return installGitWrapperWithMutationMode(t, repo, "mutate-tag", object)
|
||||||
|
}
|
||||||
|
|
||||||
|
func installGitWrapperWithMutationMode(t *testing.T, repo publishFixture, mode, mutationObject string) gitWrapper {
|
||||||
|
t.Helper()
|
||||||
|
realGit, err := exec.LookPath("git")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
bin := filepath.Join(t.TempDir(), "bin")
|
||||||
|
if err := os.MkdirAll(bin, 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
queryLog := filepath.Join(t.TempDir(), "tag-queries.log")
|
||||||
|
pushDone := filepath.Join(t.TempDir(), "push-attempted")
|
||||||
|
contents := fmt.Sprintf(`#!/bin/sh
|
||||||
|
REAL_GIT=%s
|
||||||
|
QUERY_LOG=%s
|
||||||
|
PUSH_DONE=%s
|
||||||
|
MODE=%s
|
||||||
|
MUTATE_OBJECT=%s
|
||||||
|
ARGS=" $* "
|
||||||
|
IS_PUSH=0
|
||||||
|
IS_LS_REMOTE=0
|
||||||
|
for ARG in "$@"; do
|
||||||
|
[ "$ARG" = "push" ] && IS_PUSH=1
|
||||||
|
[ "$ARG" = "ls-remote" ] && IS_LS_REMOTE=1
|
||||||
|
done
|
||||||
|
if [ "$IS_LS_REMOTE" = "1" ]; then
|
||||||
|
case "$ARGS" in *refs/tags/v1.2.3*) echo query >> "$QUERY_LOG";; esac
|
||||||
|
if [ "$MODE" = "query-failure" ] && [ -f "$PUSH_DONE" ]; then
|
||||||
|
case "$ARGS" in *refs/tags/v1.2.3*) echo "reconciliation unavailable" >&2; exit 77;; esac
|
||||||
|
fi
|
||||||
|
if [ "$MODE" = "query-conflict" ] && [ -f "$PUSH_DONE" ]; then
|
||||||
|
case "$ARGS" in
|
||||||
|
*refs/tags/v1.2.3*)
|
||||||
|
OBJECT=$("$REAL_GIT" rev-parse refs/tags/v1.2.3)
|
||||||
|
printf '%%s\trefs/tags/v1.2.3\n' "$OBJECT"
|
||||||
|
printf '%%s\trefs/tags/v1.2.3\n' "$MUTATE_OBJECT"
|
||||||
|
exit 0
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
if [ "$IS_PUSH" = "1" ]; then
|
||||||
|
"$REAL_GIT" "$@"
|
||||||
|
STATUS=$?
|
||||||
|
: > "$PUSH_DONE"
|
||||||
|
if [ "$MODE" = "lost-ack-cancel" ] && [ "$STATUS" = "0" ]; then kill -STOP $$; fi
|
||||||
|
if [ "$MODE" = "lost-ack-rewrite" ] && [ "$STATUS" = "0" ]; then
|
||||||
|
"$REAL_GIT" config --local "url.\"$MUTATE_OBJECT\".insteadOf" %s
|
||||||
|
echo "lost acknowledgment after tag was accepted" >&2
|
||||||
|
exit 77
|
||||||
|
fi
|
||||||
|
exit "$STATUS"
|
||||||
|
fi
|
||||||
|
if [ "$MODE" = "mutate-tag" ]; then
|
||||||
|
case "$ARGS" in
|
||||||
|
*"cat-file tag refs/tags/v1.2.3"*)
|
||||||
|
"$REAL_GIT" "$@"
|
||||||
|
STATUS=$?
|
||||||
|
[ "$STATUS" = "0" ] && "$REAL_GIT" update-ref refs/tags/v1.2.3 "$MUTATE_OBJECT"
|
||||||
|
exit "$STATUS"
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
exec "$REAL_GIT" "$@"
|
||||||
|
`, shellQuote(realGit), shellQuote(queryLog), shellQuote(pushDone), shellQuote(mode), shellQuote(mutationObject), shellQuote(repo.bare))
|
||||||
|
if err := os.WriteFile(filepath.Join(bin, "git"), []byte(contents), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return gitWrapper{bin: bin, queryLog: queryLog, pushDone: pushDone, realGit: realGit}
|
||||||
|
}
|
||||||
|
|
||||||
|
func countLines(t *testing.T, path string) int {
|
||||||
|
t.Helper()
|
||||||
|
contents, err := os.ReadFile(path)
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return len(strings.Fields(string(contents)))
|
||||||
|
}
|
||||||
|
|
||||||
|
func mustLookPath(t *testing.T, name string) string {
|
||||||
|
t.Helper()
|
||||||
|
path, err := exec.LookPath(name)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return path
|
||||||
|
}
|
||||||
|
|
||||||
|
func shellQuote(value string) string {
|
||||||
|
return "'" + strings.ReplaceAll(value, "'", "'\\''") + "'"
|
||||||
|
}
|
||||||
|
|
||||||
|
func newPublishFixture(t *testing.T) publishFixture {
|
||||||
|
t.Helper()
|
||||||
|
base := t.TempDir()
|
||||||
|
work := filepath.Join(base, "work")
|
||||||
|
bare := filepath.Join(base, "remote.git")
|
||||||
|
gitRun(t, base, "init", "-b", "main", work)
|
||||||
|
gitRun(t, work, "config", "user.name", "ReleaseKit Test")
|
||||||
|
gitRun(t, work, "config", "user.email", "releasekit@example.invalid")
|
||||||
|
writeFile(t, work, "go.mod", "module example.com/releasekit-publish-fixture\n\ngo 1.25.0\n")
|
||||||
|
writeFile(t, work, "fixture_test.go", `package fixture
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestFixture(t *testing.T) {
|
||||||
|
if path := os.Getenv("RELEASEKIT_FIXTURE_SUITE_RUNS"); path != "" {
|
||||||
|
file, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := file.WriteString("ran\n"); err != nil {
|
||||||
|
_ = file.Close()
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := file.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if os.Getenv("RELEASEKIT_FAIL_FIXTURE_SUITE") == "1" {
|
||||||
|
t.Fatal("fixture standard suite failure")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`)
|
||||||
|
writeFile(t, work, "docs/releases/v1.2.3.md", releaseNote)
|
||||||
|
writeFile(t, work, "source.txt", "candidate")
|
||||||
|
gitRun(t, work, "add", ".")
|
||||||
|
gitRun(t, work, "commit", "-m", "Candidate")
|
||||||
|
commit := gitText(t, work, "rev-parse", "HEAD")
|
||||||
|
gitRun(t, work, "init", "--bare", bare)
|
||||||
|
gitRun(t, work, "remote", "add", "origin", bare)
|
||||||
|
gitRun(t, work, "push", "origin", "HEAD:refs/heads/main")
|
||||||
|
gitRun(t, work, "push", "origin", "HEAD:refs/heads/unrelated")
|
||||||
|
gitRun(t, work, "tag", "v0.9.0", commit)
|
||||||
|
gitRun(t, work, "push", "origin", "refs/tags/v0.9.0:refs/tags/v0.9.0")
|
||||||
|
other := gitText(t, work, "commit-tree", gitText(t, work, "rev-parse", "HEAD^{tree}"), "-p", commit, "-m", "Other remote commit")
|
||||||
|
gitRun(t, work, "push", "origin", other+":refs/heads/other")
|
||||||
|
gitRun(t, work, "config", "remote.origin.mirror", "true")
|
||||||
|
gitRun(t, work, "config", "push.followTags", "true")
|
||||||
|
gitRun(t, work, "config", "tag.gpgSign", "true")
|
||||||
|
return publishFixture{work: work, bare: bare, commit: commit, unrelatedCommit: other}
|
||||||
|
}
|
||||||
|
|
||||||
|
func gitRun(t *testing.T, dir string, args ...string) {
|
||||||
|
t.Helper()
|
||||||
|
cmd := exec.Command("git", args...)
|
||||||
|
cmd.Dir = dir
|
||||||
|
if output, err := cmd.CombinedOutput(); err != nil {
|
||||||
|
t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, output)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func gitText(t *testing.T, dir string, args ...string) string {
|
||||||
|
t.Helper()
|
||||||
|
cmd := exec.Command("git", args...)
|
||||||
|
cmd.Dir = dir
|
||||||
|
output, err := cmd.CombinedOutput()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, output)
|
||||||
|
}
|
||||||
|
return strings.TrimSuffix(string(output), "\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
func gitBytes(t *testing.T, dir string, args ...string) string {
|
||||||
|
t.Helper()
|
||||||
|
cmd := exec.Command("git", args...)
|
||||||
|
cmd.Dir = dir
|
||||||
|
output, err := cmd.CombinedOutput()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, output)
|
||||||
|
}
|
||||||
|
return string(output)
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeFile(t *testing.T, root, name, contents string) {
|
||||||
|
t.Helper()
|
||||||
|
path := filepath.Join(root, filepath.FromSlash(name))
|
||||||
|
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(path, []byte(contents), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
10
releasekit.json
Normal file
10
releasekit.json
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
{
|
||||||
|
"product": "ReleaseKit",
|
||||||
|
"remote": "origin",
|
||||||
|
"delivery": {
|
||||||
|
"base_url": "https://gitea.maximumdirect.net",
|
||||||
|
"owner": "eric",
|
||||||
|
"repository": "ReleaseKit",
|
||||||
|
"token_env": "RELEASEKIT_GITEA_TOKEN"
|
||||||
|
}
|
||||||
|
}
|
||||||
11
scripts/release
Executable file
11
scripts/release
Executable file
@@ -0,0 +1,11 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
|
||||||
|
if [ "$#" -ne 1 ]; then
|
||||||
|
printf '%s\n' 'usage: ./scripts/release VERSION' >&2
|
||||||
|
exit 2
|
||||||
|
fi
|
||||||
|
|
||||||
|
mkdir -p .releasekit/bin
|
||||||
|
GOTOOLCHAIN=local go build -o .releasekit/bin/releasekit ./cmd/releasekit
|
||||||
|
exec .releasekit/bin/releasekit publish "$1"
|
||||||
Reference in New Issue
Block a user