Compare commits
112 Commits
3cbb3f3406
...
v0.2.0
| Author | SHA1 | Date | |
|---|---|---|---|
| e030794969 | |||
| 10964bebd4 | |||
| e84d28d249 | |||
| 8314e0e4d8 | |||
| b6a490cefc | |||
| 2e0d302178 | |||
| 95599e96f6 | |||
| 1eb1cc6491 | |||
| edd670e62f | |||
| c8fa8ef85f | |||
| eee979db7b | |||
| b80d4ee071 | |||
| 40068af1bf | |||
| 6397d41517 | |||
| b3b959ce77 | |||
| f80970a9d4 | |||
| eed95896f4 | |||
| 45dd827dda | |||
| c5f925c949 | |||
| 368043984e | |||
| cabc56b134 | |||
| 1c41f7a0d1 | |||
| 30fe4fe206 | |||
| 89981abbe5 | |||
| 9086306498 | |||
| 3974a4686a | |||
| 1dfa774164 | |||
| 9d2ca66a79 | |||
| 02050016c1 | |||
| ff83af1e34 | |||
| 56e652aae3 | |||
| 1498ec7498 | |||
| f53354be5f | |||
| 89c5b2c1fd | |||
| 1ebd45c975 | |||
| 8bac90a9a8 | |||
| 5848307948 | |||
| 1cad13649e | |||
| 136a97fb6c | |||
| 1de7555b3e | |||
| 0c7129ab75 | |||
| 8c742cd11d | |||
| 7afc0de092 | |||
| 2a246990fe | |||
| f9f0349eca | |||
| f4a32dae73 | |||
| a4b1b6d5d2 | |||
| f55f6331cb | |||
| 8ff8efa4a2 | |||
| 6de0428675 | |||
| 9e480f0b4f | |||
| 60175d6690 | |||
| 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.
|
||||||
73
README.md
73
README.md
@@ -1,3 +1,74 @@
|
|||||||
# 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.
|
||||||
|
|
||||||
|
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 suite with any selected shared validation checks, and then runs
|
||||||
|
configured product 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
|
||||||
|
|
||||||
|
- [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
|
||||||
|
}
|
||||||
654
build_test.go
Normal file
654
build_test.go
Normal file
@@ -0,0 +1,654 @@
|
|||||||
|
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)
|
||||||
|
writeFile(t, repository.work, "guide.md", "# Guide\n[section](#guide)\n")
|
||||||
|
gitRun(t, repository.work, "add", "guide.md")
|
||||||
|
gitRun(t, repository.work, "commit", "-m", "add Markdown guide")
|
||||||
|
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",
|
||||||
|
Validation: releasekit.ValidationSpec{Markdown: &releasekit.MarkdownValidationSpec{}},
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
212
check.go
Normal file
212
check.go
Normal file
@@ -0,0 +1,212 @@
|
|||||||
|
package releasekit
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"io"
|
||||||
|
|
||||||
|
internalbuild "gitea.maximumdirect.net/eric/ReleaseKit/internal/build"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/candidate"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/publish"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/validation"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ErrInvalidVersion reports a version that is not stable vMAJOR.MINOR.PATCH.
|
||||||
|
var ErrInvalidVersion = candidate.ErrInvalidVersion
|
||||||
|
|
||||||
|
// ErrUnexpectedPushURL reports that the effective publication push URL does
|
||||||
|
// not exactly match ReleaseRequest.ExpectedPushURL.
|
||||||
|
var ErrUnexpectedPushURL = publish.ErrUnexpectedPushURL
|
||||||
|
|
||||||
|
// 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
|
||||||
|
// ExpectedPushURL optionally requires Publish's resolved push URL to match
|
||||||
|
// this string exactly before validation or tag creation. Check ignores this
|
||||||
|
// publication-only expectation. A mismatch returns ErrUnexpectedPushURL.
|
||||||
|
ExpectedPushURL string
|
||||||
|
// Validation selects optional checks run against the captured candidate.
|
||||||
|
Validation ValidationSpec
|
||||||
|
// AdditionalChecks optionally runs product checks after shared validation.
|
||||||
|
AdditionalChecks func(context.Context, Candidate) error
|
||||||
|
Build *BuildSpec // optional selected-target build after validation.
|
||||||
|
Output io.Writer
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidationSpec selects optional shared validation checks. Its zero value
|
||||||
|
// preserves the current validation behavior.
|
||||||
|
type ValidationSpec struct {
|
||||||
|
Go GoValidationSpec
|
||||||
|
// GoFormat checks the formatting of committed regular Go source files. It
|
||||||
|
// does not modify repository contents and is disabled when false.
|
||||||
|
GoFormat bool
|
||||||
|
// Markdown selects committed Markdown destination and fragment checking.
|
||||||
|
// Nil disables the check; an empty object enables it with the default
|
||||||
|
// behavior, reporting outside-checkout destinations as out of scope.
|
||||||
|
Markdown *MarkdownValidationSpec
|
||||||
|
// ModuleDistribution selects checks for files that affect module-source
|
||||||
|
// distribution. Its zero value disables those checks.
|
||||||
|
ModuleDistribution ModuleDistributionValidationSpec
|
||||||
|
// FileSize selects a committed-file size check. Nil disables it; an empty
|
||||||
|
// object selects the 1,000,000-byte default.
|
||||||
|
FileSize *FileSizeValidationSpec
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarkdownValidationSpec selects behavior for committed Markdown links.
|
||||||
|
type MarkdownValidationSpec struct {
|
||||||
|
// EnforceCheckoutBoundary fails when a local destination resolves outside
|
||||||
|
// the candidate checkout. Submodule contents remain out of scope.
|
||||||
|
EnforceCheckoutBoundary bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// FileSizeValidationSpec selects a maximum size for each committed blob.
|
||||||
|
type FileSizeValidationSpec struct {
|
||||||
|
// LimitBytes is the maximum decimal byte count. Nil selects 1,000,000;
|
||||||
|
// zero is a zero-byte limit, and negative values are invalid.
|
||||||
|
LimitBytes *int64
|
||||||
|
// Exclusions are literal repository-relative file or directory paths.
|
||||||
|
// A directory exclusion includes committed descendants.
|
||||||
|
Exclusions []string
|
||||||
|
}
|
||||||
|
|
||||||
|
// ModuleDistributionValidationSpec selects independent module-source
|
||||||
|
// distribution checks.
|
||||||
|
type ModuleDistributionValidationSpec struct {
|
||||||
|
// WorkspaceFiles rejects committed go.work and go.work.sum blobs, including
|
||||||
|
// nested paths and symlink entries. It does not select Go's test workspace.
|
||||||
|
WorkspaceFiles bool
|
||||||
|
// LocalReplacements rejects filesystem replacements in committed go.mod
|
||||||
|
// declarations, including nested modules. It does not select Go's workspace.
|
||||||
|
LocalReplacements bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// GoValidationSpec selects checks performed by the Go toolchain.
|
||||||
|
type GoValidationSpec struct {
|
||||||
|
// Race runs the one standard Go test suite with the race detector enabled.
|
||||||
|
Race bool
|
||||||
|
// FullVet runs go vet after the suite instead of the test-time vet pass.
|
||||||
|
// Failures use the go-vet validation check identity.
|
||||||
|
FullVet bool
|
||||||
|
// CompileTargets checks that every package builds for each complete target
|
||||||
|
// pair after testing and vet. Compilation uses CGO_ENABLED=0 and does not
|
||||||
|
// produce artifacts or execute target binaries. Failures use the
|
||||||
|
// package-compile validation check identity.
|
||||||
|
CompileTargets []Target
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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. Validation.Go.Race runs that one suite with
|
||||||
|
// the race detector, Validation.Go.FullVet runs go vet after the suite instead
|
||||||
|
// of test-time vet, and Validation.Go.CompileTargets compiles all packages for
|
||||||
|
// each selected GOOS/GOARCH pair after tests and vet with cgo disabled. Package
|
||||||
|
// compilation produces no artifacts and does not execute target binaries.
|
||||||
|
// Validation.GoFormat checks regular committed Go source after those selected
|
||||||
|
// Go checks and before AdditionalChecks. Its zero value disables formatting.
|
||||||
|
// Validation.ModuleDistribution.WorkspaceFiles rejects committed workspace
|
||||||
|
// files after formatting. Its zero value disables that distribution check and
|
||||||
|
// does not change Go's workspace environment.
|
||||||
|
// Validation.ModuleDistribution.LocalReplacements parses committed go.mod
|
||||||
|
// declarations, including nested modules, and rejects filesystem replacements
|
||||||
|
// after workspace-file inspection. Its zero value disables that check.
|
||||||
|
// Validation.FileSize checks each selected committed blob after module
|
||||||
|
// distribution checks. Its nil value disables size checks; an empty object
|
||||||
|
// enables the default limit.
|
||||||
|
// Validation.Markdown checks committed local Markdown destinations and
|
||||||
|
// supported fragments after file-size inspection and before AdditionalChecks.
|
||||||
|
// Nil disables the check; an empty object enables it. Outside-checkout
|
||||||
|
// destinations are reported as out of scope unless the selected specification
|
||||||
|
// enforces the checkout boundary. Submodule contents remain out of scope.
|
||||||
|
// The zero values of all selections preserve the ordinary suite. If
|
||||||
|
// 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) {
|
||||||
|
checked, err := candidate.Check(ctx, candidateRequest(request))
|
||||||
|
if err != nil {
|
||||||
|
return Candidate{}, convertValidationError(err)
|
||||||
|
}
|
||||||
|
return Candidate{
|
||||||
|
RepositoryDir: checked.RepositoryDir,
|
||||||
|
Commit: checked.Commit,
|
||||||
|
Version: checked.Version,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func candidateRequest(request ReleaseRequest) candidate.Request {
|
||||||
|
fileSize := internalFileSizeSettings(request.Validation.FileSize)
|
||||||
|
result := candidate.Request{
|
||||||
|
RepositoryDir: request.RepositoryDir,
|
||||||
|
Product: request.Product,
|
||||||
|
Version: request.Version,
|
||||||
|
Validation: validation.Settings{
|
||||||
|
Race: request.Validation.Go.Race,
|
||||||
|
FullVet: request.Validation.Go.FullVet,
|
||||||
|
CompileTargets: make([]validation.Target, len(request.Validation.Go.CompileTargets)),
|
||||||
|
GoFormat: request.Validation.GoFormat,
|
||||||
|
Markdown: internalMarkdownSettings(request.Validation.Markdown),
|
||||||
|
ModuleDistribution: validation.ModuleDistributionSettings{
|
||||||
|
WorkspaceFiles: request.Validation.ModuleDistribution.WorkspaceFiles,
|
||||||
|
LocalReplacements: request.Validation.ModuleDistribution.LocalReplacements,
|
||||||
|
},
|
||||||
|
FileSize: fileSize,
|
||||||
|
},
|
||||||
|
AdditionalChecks: candidateChecks(request.AdditionalChecks),
|
||||||
|
AfterValidate: internalbuild.CandidateCallback(internalBuildSpec(request.Build), request.Output),
|
||||||
|
Output: request.Output,
|
||||||
|
}
|
||||||
|
for index, target := range request.Validation.Go.CompileTargets {
|
||||||
|
result.Validation.CompileTargets[index] = validation.Target{OS: target.OS, Arch: target.Arch}
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func internalMarkdownSettings(spec *MarkdownValidationSpec) *validation.MarkdownSettings {
|
||||||
|
if spec == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return &validation.MarkdownSettings{EnforceCheckoutBoundary: spec.EnforceCheckoutBoundary}
|
||||||
|
}
|
||||||
|
|
||||||
|
func internalFileSizeSettings(spec *FileSizeValidationSpec) *validation.FileSizeSettings {
|
||||||
|
if spec == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var limitBytes *int64
|
||||||
|
if spec.LimitBytes != nil {
|
||||||
|
limit := *spec.LimitBytes
|
||||||
|
limitBytes = &limit
|
||||||
|
}
|
||||||
|
return &validation.FileSizeSettings{
|
||||||
|
LimitBytes: limitBytes,
|
||||||
|
Exclusions: append([]string(nil), spec.Exclusions...),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func candidateChecks(checks func(context.Context, Candidate) error) func(context.Context, candidate.Candidate) error {
|
||||||
|
if checks == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return func(ctx context.Context, captured candidate.Candidate) error {
|
||||||
|
return checks(ctx, Candidate{
|
||||||
|
RepositoryDir: captured.RepositoryDir,
|
||||||
|
Commit: captured.Commit,
|
||||||
|
Version: captured.Version,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
294
cmd/releasekit/internal/cli/config.go
Normal file
294
cmd/releasekit/internal/cli/config.go
Normal file
@@ -0,0 +1,294 @@
|
|||||||
|
// 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, publication expectation, shared
|
||||||
|
// validation selections, and check commands read from a releasekit.json profile.
|
||||||
|
type Settings struct {
|
||||||
|
Product string `json:"product"`
|
||||||
|
Remote string `json:"remote,omitempty"`
|
||||||
|
ExpectedPushURL string `json:"expected_push_url,omitempty"`
|
||||||
|
Checks []CheckCommand `json:"checks,omitempty"`
|
||||||
|
Validation *ValidationSettings `json:"validation,omitempty"`
|
||||||
|
Build *BuildSettings `json:"build,omitempty"`
|
||||||
|
Delivery *DeliverySettings `json:"delivery,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidationSettings selects shared candidate checks in a release profile.
|
||||||
|
type ValidationSettings struct {
|
||||||
|
Go GoValidationSettings `json:"go,omitempty"`
|
||||||
|
// GoFormat checks the formatting of committed regular Go source files.
|
||||||
|
// Omitted or false disables the check.
|
||||||
|
GoFormat bool `json:"go_format,omitempty"`
|
||||||
|
Markdown *MarkdownSettings `json:"markdown,omitempty"`
|
||||||
|
ModuleDistribution ModuleDistributionSettings `json:"module_distribution,omitempty"`
|
||||||
|
// FileSize checks the size of each committed blob. Null or omission disables
|
||||||
|
// the check; an empty object enables the default limit.
|
||||||
|
FileSize *FileSizeSettings `json:"file_size,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarkdownSettings selects committed Markdown destination and fragment checks.
|
||||||
|
type MarkdownSettings struct {
|
||||||
|
// EnforceCheckoutBoundary fails local destinations that resolve outside
|
||||||
|
// the candidate checkout. Submodule contents remain out of scope.
|
||||||
|
EnforceCheckoutBoundary bool `json:"enforce_checkout_boundary,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// FileSizeSettings selects the maximum committed-file size and literal exclusions.
|
||||||
|
type FileSizeSettings struct {
|
||||||
|
LimitBytes *int64 `json:"limit_bytes,omitempty"`
|
||||||
|
Exclusions []string `json:"exclusions,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ModuleDistributionSettings selects committed module-source distribution checks.
|
||||||
|
type ModuleDistributionSettings struct {
|
||||||
|
// WorkspaceFiles rejects committed go.work and go.work.sum blobs.
|
||||||
|
// Omitted or false disables the check.
|
||||||
|
WorkspaceFiles bool `json:"workspace_files,omitempty"`
|
||||||
|
// LocalReplacements rejects filesystem replacements in committed go.mod files.
|
||||||
|
// Omitted or false disables the check.
|
||||||
|
LocalReplacements bool `json:"local_replacements,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// GoValidationSettings selects checks performed by the Go toolchain.
|
||||||
|
type GoValidationSettings struct {
|
||||||
|
Race bool `json:"race,omitempty"`
|
||||||
|
FullVet bool `json:"full_vet,omitempty"`
|
||||||
|
CompileTargets []string `json:"compile_targets,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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if settings.Validation != nil {
|
||||||
|
if fileSize := settings.Validation.FileSize; fileSize != nil && fileSize.LimitBytes != nil && *fileSize.LimitBytes < 0 {
|
||||||
|
return Settings{}, fmt.Errorf("profile %q: validation.file_size.limit_bytes must not be negative", configPath)
|
||||||
|
}
|
||||||
|
for i, target := range settings.Validation.Go.CompileTargets {
|
||||||
|
if strings.Count(target, "/") != 1 {
|
||||||
|
return Settings{}, fmt.Errorf("profile %q: validation.go.compile_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: validation.go.compile_targets[%d] must be GOOS/GOARCH", 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
|
||||||
|
}
|
||||||
354
cmd/releasekit/internal/cli/config_test.go
Normal file
354
cmd/releasekit/internal/cli/config_test.go
Normal file
@@ -0,0 +1,354 @@
|
|||||||
|
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 TestLoadSettingsReadsGoValidation(t *testing.T) {
|
||||||
|
repoDir := t.TempDir()
|
||||||
|
profilePath := filepath.Join(repoDir, "releasekit.json")
|
||||||
|
if err := os.WriteFile(profilePath, []byte(`{"product":"Example","expected_push_url":"ssh://git.example/owner/repo.git","validation":{"go_format":true,"markdown":{"enforce_checkout_boundary":true},"module_distribution":{"workspace_files":true,"local_replacements":true},"file_size":{"limit_bytes":0,"exclusions":["assets"]},"go":{"race":true,"full_vet":true,"compile_targets":["linux/amd64","linux/arm64","darwin/arm64"]}}}`), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
settings, err := LoadSettings(repoDir, "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if settings.Validation == nil || !settings.Validation.GoFormat || settings.Validation.Markdown == nil || !settings.Validation.Markdown.EnforceCheckoutBoundary || !settings.Validation.ModuleDistribution.WorkspaceFiles || !settings.Validation.ModuleDistribution.LocalReplacements || !settings.Validation.Go.Race || !settings.Validation.Go.FullVet {
|
||||||
|
t.Fatalf("validation settings = %#v, want Go formatting, workspace inspection, race, and full vet enabled", settings.Validation)
|
||||||
|
}
|
||||||
|
if settings.Validation.FileSize == nil || settings.Validation.FileSize.LimitBytes == nil || *settings.Validation.FileSize.LimitBytes != 0 || len(settings.Validation.FileSize.Exclusions) != 1 || settings.Validation.FileSize.Exclusions[0] != "assets" {
|
||||||
|
t.Fatalf("file size settings = %#v, want explicit zero limit and exclusions", settings.Validation.FileSize)
|
||||||
|
}
|
||||||
|
if got, want := strings.Join(settings.Validation.Go.CompileTargets, ","), "linux/amd64,linux/arm64,darwin/arm64"; got != want {
|
||||||
|
t.Fatalf("compile targets = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
if settings.ExpectedPushURL != "ssh://git.example/owner/repo.git" {
|
||||||
|
t.Fatalf("expected push URL = %q", settings.ExpectedPushURL)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadSettingsPreservesMarkdownObjectSelection(t *testing.T) {
|
||||||
|
repoDir := t.TempDir()
|
||||||
|
profilePath := filepath.Join(repoDir, "releasekit.json")
|
||||||
|
for _, test := range []struct {
|
||||||
|
name string
|
||||||
|
profile string
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{name: "omitted", profile: `{"product":"Example","validation":{}}`},
|
||||||
|
{name: "null", profile: `{"product":"Example","validation":{"markdown":null}}`},
|
||||||
|
{name: "empty object", profile: `{"product":"Example","validation":{"markdown":{}}}`, want: true},
|
||||||
|
{name: "boundary enabled", profile: `{"product":"Example","validation":{"markdown":{"enforce_checkout_boundary":true}}}`, want: true},
|
||||||
|
} {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
if err := os.WriteFile(profilePath, []byte(test.profile), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
settings, err := LoadSettings(repoDir, "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
got := settings.Validation != nil && settings.Validation.Markdown != nil
|
||||||
|
if got != test.want {
|
||||||
|
t.Fatalf("Markdown selected = %t, want %t", got, test.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadSettingsPreservesEmptyAndNullFileSize(t *testing.T) {
|
||||||
|
for _, test := range []struct {
|
||||||
|
name string
|
||||||
|
profile string
|
||||||
|
enabled bool
|
||||||
|
}{
|
||||||
|
{name: "empty object", profile: `{"product":"Example","validation":{"file_size":{}}}`, enabled: true},
|
||||||
|
{name: "default limit", profile: `{"product":"Example","validation":{"file_size":{"limit_bytes":null}}}`, enabled: true},
|
||||||
|
{name: "null object", profile: `{"product":"Example","validation":{"file_size":null}}`},
|
||||||
|
{name: "omitted object", profile: `{"product":"Example","validation":{}}`},
|
||||||
|
} {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
repoDir := t.TempDir()
|
||||||
|
profilePath := filepath.Join(repoDir, "releasekit.json")
|
||||||
|
if err := os.WriteFile(profilePath, []byte(test.profile), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
settings, err := LoadSettings(repoDir, profilePath)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
got := settings.Validation != nil && settings.Validation.FileSize != nil
|
||||||
|
if got != test.enabled {
|
||||||
|
t.Fatalf("FileSize enabled = %t, want %t", got, test.enabled)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadSettingsRejectsNegativeFileSizeLimit(t *testing.T) {
|
||||||
|
repoDir := t.TempDir()
|
||||||
|
profilePath := filepath.Join(repoDir, "releasekit.json")
|
||||||
|
profile := `{"product":"Example","validation":{"file_size":{"limit_bytes":-1}}}`
|
||||||
|
if err := os.WriteFile(profilePath, []byte(profile), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := LoadSettings(repoDir, profilePath); err == nil || !strings.Contains(err.Error(), "validation.file_size.limit_bytes") {
|
||||||
|
t.Fatalf("LoadSettings() error = %v, want invalid negative file-size limit", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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: "compile target format", content: `{"product":"Example","validation":{"go":{"compile_targets":["linux"]}}}`, want: "validation.go.compile_targets[0] must be GOOS/GOARCH"},
|
||||||
|
{name: "compile target missing architecture", content: `{"product":"Example","validation":{"go":{"compile_targets":["linux/"]}}}`, want: "validation.go.compile_targets[0] must be GOOS/GOARCH"},
|
||||||
|
{name: "compile target missing operating system", content: `{"product":"Example","validation":{"go":{"compile_targets":["/amd64"]}}}`, want: "validation.go.compile_targets[0] must be GOOS/GOARCH"},
|
||||||
|
{name: "compile target repeated separator", content: `{"product":"Example","validation":{"go":{"compile_targets":["linux/amd64/arm64"]}}}`, want: "validation.go.compile_targets[0] 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)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
419
cmd/releasekit/main.go
Normal file
419
cmd/releasekit/main.go
Normal file
@@ -0,0 +1,419 @@
|
|||||||
|
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 := candidateRequest(invocation, settings, stderr)
|
||||||
|
if invocation.Command == cli.PublishAction {
|
||||||
|
request.ExpectedPushURL = settings.ExpectedPushURL
|
||||||
|
fmt.Fprintf(stderr, "validating and publishing %s\n", invocation.Version)
|
||||||
|
result, err := releasekit.Publish(ctx, request)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "publication state=%s phase=%s version=%s commit=%s tag-object=%s endpoint=%q: %s\n", result.State, result.Phase, result.Version, result.CandidateCommit, result.TagObject, result.Endpoint, candidateFailureText(err))
|
||||||
|
if errors.Is(err, releasekit.ErrInvalidVersion) {
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
if result.State == releasekit.PublicationUnknown {
|
||||||
|
return 3
|
||||||
|
}
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
fmt.Fprintf(stdout, "published %s at %s (tag object %s)\n", result.Version, result.CandidateCommit, result.TagObject)
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
candidate, err := releasekit.Check(ctx, request)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "check failed: %s\n", candidateFailureText(err))
|
||||||
|
if errors.Is(err, releasekit.ErrInvalidVersion) {
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
fmt.Fprintf(stdout, "local candidate %s at %s is valid\n", candidate.Version, candidate.Commit)
|
||||||
|
return 0
|
||||||
|
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 candidateRequest(invocation cli.Invocation, settings cli.Settings, output io.Writer) releasekit.ReleaseRequest {
|
||||||
|
request := releasekit.ReleaseRequest{
|
||||||
|
RepositoryDir: invocation.Repository,
|
||||||
|
Product: settings.Product,
|
||||||
|
Version: invocation.Version,
|
||||||
|
Remote: settings.Remote,
|
||||||
|
Validation: validationSpec(settings.Validation),
|
||||||
|
Build: configuredBuildSpec(settings.Build),
|
||||||
|
Output: output,
|
||||||
|
}
|
||||||
|
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,
|
||||||
|
}, output, output)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return request
|
||||||
|
}
|
||||||
|
|
||||||
|
func validationSpec(settings *cli.ValidationSettings) releasekit.ValidationSpec {
|
||||||
|
if settings == nil {
|
||||||
|
return releasekit.ValidationSpec{}
|
||||||
|
}
|
||||||
|
result := releasekit.ValidationSpec{
|
||||||
|
GoFormat: settings.GoFormat,
|
||||||
|
ModuleDistribution: releasekit.ModuleDistributionValidationSpec{
|
||||||
|
WorkspaceFiles: settings.ModuleDistribution.WorkspaceFiles,
|
||||||
|
LocalReplacements: settings.ModuleDistribution.LocalReplacements,
|
||||||
|
},
|
||||||
|
Go: releasekit.GoValidationSpec{
|
||||||
|
Race: settings.Go.Race,
|
||||||
|
FullVet: settings.Go.FullVet,
|
||||||
|
CompileTargets: make([]releasekit.Target, len(settings.Go.CompileTargets)),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if settings.Markdown != nil {
|
||||||
|
result.Markdown = &releasekit.MarkdownValidationSpec{
|
||||||
|
EnforceCheckoutBoundary: settings.Markdown.EnforceCheckoutBoundary,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if settings.FileSize != nil {
|
||||||
|
var limitBytes *int64
|
||||||
|
if settings.FileSize.LimitBytes != nil {
|
||||||
|
limit := *settings.FileSize.LimitBytes
|
||||||
|
limitBytes = &limit
|
||||||
|
}
|
||||||
|
result.FileSize = &releasekit.FileSizeValidationSpec{
|
||||||
|
LimitBytes: limitBytes,
|
||||||
|
Exclusions: append([]string(nil), settings.FileSize.Exclusions...),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for index, target := range settings.Go.CompileTargets {
|
||||||
|
goos, goarch, _ := strings.Cut(target, "/")
|
||||||
|
result.Go.CompileTargets[index] = releasekit.Target{OS: goos, Arch: goarch}
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func candidateFailureText(err error) string {
|
||||||
|
return err.Error()
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
1364
cmd/releasekit/main_test.go
Normal file
1364
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
|
||||||
|
}
|
||||||
117
cmd/releasekit/releasekit_delivery_workflow_test.go
Normal file
117
cmd/releasekit/releasekit_delivery_workflow_test.go
Normal file
@@ -0,0 +1,117 @@
|
|||||||
|
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)
|
||||||
|
}
|
||||||
|
cliGitRun(t, repository, "add", "docs/releases/"+version+".md")
|
||||||
|
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)
|
||||||
|
|
||||||
|
template, err := os.ReadFile(filepath.Join(root, "examples", "woodpecker", "releasekit-source-delivery.yml"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
block, err := extractWoodpeckerCommand(string(template), "deliver")
|
||||||
|
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",
|
||||||
|
"GOTOOLCHAIN": "local",
|
||||||
|
"GOPROXY": "off",
|
||||||
|
"GOSUMDB": "off",
|
||||||
|
}
|
||||||
|
command := strings.ReplaceAll(block, "$${", "${")
|
||||||
|
|
||||||
|
state.remoteCommit = strings.Repeat("f", 40)
|
||||||
|
if output, err := executeWoodpeckerBlock(command, repository, env); err == nil {
|
||||||
|
t.Fatalf("delivery with a mismatched hosted tag succeeded: %s", output)
|
||||||
|
}
|
||||||
|
if state.releaseCreates != 0 || cliGitOutput(t, repository, "rev-parse", "refs/tags/"+version+"^{commit}") != state.commit {
|
||||||
|
t.Fatal("delivery failure changed hosted release state or source tag")
|
||||||
|
}
|
||||||
|
state.remoteCommit = ""
|
||||||
|
|
||||||
|
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 || 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
652
cmd/releasekit/woodpecker_test.go
Normal file
652
cmd/releasekit/woodpecker_test.go
Normal file
@@ -0,0 +1,652 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"archive/zip"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync/atomic"
|
||||||
|
"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)
|
||||||
|
}
|
||||||
|
block, err := extractWoodpeckerCommand(string(contents), "deliver")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
command := strings.ReplaceAll(block, "$${", "${")
|
||||||
|
|
||||||
|
t.Run("source-only", func(t *testing.T) {
|
||||||
|
repository := newCLIRepository(t)
|
||||||
|
selectReleaseKitModule(t, repository, root, false)
|
||||||
|
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
|
||||||
|
|
||||||
|
goDir, goLog := installGoBootstrapShim(t)
|
||||||
|
env := templateEnvironment(repository, commit, goDir, goLog)
|
||||||
|
moduleBefore := readWoodpeckerFixtureFile(t, filepath.Join(repository, "go.mod"))
|
||||||
|
output := runWoodpeckerBlock(t, command, repository, env)
|
||||||
|
if !strings.Contains(output, "state complete") {
|
||||||
|
t.Fatalf("delivery output=%q", output)
|
||||||
|
}
|
||||||
|
if state.releaseCreates != 1 || state.assetUploads != 0 {
|
||||||
|
t.Fatalf("source-only calls = creates:%d uploads:%d", state.releaseCreates, state.assetUploads)
|
||||||
|
}
|
||||||
|
assertModuleBootstrap(t, repository, goLog, moduleBefore)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("binary", func(t *testing.T) {
|
||||||
|
repository := newDeliveryBuildRepository(t)
|
||||||
|
selectReleaseKitModule(t, repository, root, true)
|
||||||
|
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
|
||||||
|
|
||||||
|
goDir, goLog := installGoBootstrapShim(t)
|
||||||
|
env := templateEnvironment(repository, commit, goDir, goLog)
|
||||||
|
moduleBefore := readWoodpeckerFixtureFile(t, filepath.Join(repository, "go.mod"))
|
||||||
|
sumBefore := readWoodpeckerFixtureFile(t, filepath.Join(repository, "go.sum"))
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
assertModuleBootstrap(t, repository, goLog, moduleBefore, sumBefore)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("wrong tag stops before Go", func(t *testing.T) {
|
||||||
|
repository := newCLIRepository(t)
|
||||||
|
selectReleaseKitModule(t, repository, root, false)
|
||||||
|
commit := pushTaggedCLIRepository(t, repository)
|
||||||
|
goDir, goLog := installControlledGoBootstrapShim(t)
|
||||||
|
env := templateEnvironment(repository, strings.Repeat("f", len(commit)), goDir, goLog)
|
||||||
|
if output, err := executeWoodpeckerBlock(command, repository, env); err == nil {
|
||||||
|
t.Fatalf("wrong tag succeeded: %s", output)
|
||||||
|
}
|
||||||
|
assertNoCommands(t, goLog)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("dirty module stops before Go", func(t *testing.T) {
|
||||||
|
repository := newCLIRepository(t)
|
||||||
|
selectReleaseKitModule(t, repository, root, false)
|
||||||
|
commit := pushTaggedCLIRepository(t, repository)
|
||||||
|
writeRepositoryFile(t, repository, "go.mod", "module example.com/different-tool-selection\n\ngo 1.25.0\n")
|
||||||
|
goDir, goLog := installControlledGoBootstrapShim(t)
|
||||||
|
env := templateEnvironment(repository, commit, goDir, goLog)
|
||||||
|
if output, err := executeWoodpeckerBlock(command, repository, env); err == nil {
|
||||||
|
t.Fatalf("dirty module succeeded: %s", output)
|
||||||
|
}
|
||||||
|
assertNoCommands(t, goLog)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("selected executable receives event arguments and its status", func(t *testing.T) {
|
||||||
|
repository := newCLIRepository(t)
|
||||||
|
selectReleaseKitModule(t, repository, root, false)
|
||||||
|
commit := pushTaggedCLIRepository(t, repository)
|
||||||
|
goDir, goLog := installControlledGoBootstrapShim(t)
|
||||||
|
toolArgs := filepath.Join(t.TempDir(), "tool-arguments")
|
||||||
|
env := templateEnvironment(repository, strings.ToUpper(commit), goDir, goLog)
|
||||||
|
env["RELEASEKIT_TOOL_ARGS_LOG"] = toolArgs
|
||||||
|
env["RELEASEKIT_TOOL_EXIT"] = "37"
|
||||||
|
output, err := executeWoodpeckerBlock(command, repository, env)
|
||||||
|
var exitError *exec.ExitError
|
||||||
|
if !errors.As(err, &exitError) || exitError.ExitCode() != 37 {
|
||||||
|
t.Fatalf("template error = %v, want propagated exit 37; output=%q", err, output)
|
||||||
|
}
|
||||||
|
args := readWoodpeckerFixtureFile(t, toolArgs)
|
||||||
|
for _, expected := range []string{"<ci-deliver>", "<--repo>", "<" + repository + ">", "<--commit>", "<" + strings.ToUpper(commit) + ">", "<v1.2.3>"} {
|
||||||
|
if !strings.Contains(args, expected) {
|
||||||
|
t.Errorf("selected executable arguments %q omit %q", args, expected)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertGoSelection(t, repository, goLog)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWoodpeckerTagDeliveryUsesTaggedModuleVersion(t *testing.T) {
|
||||||
|
root := cliRepositoryRoot(t)
|
||||||
|
contents, err := os.ReadFile(filepath.Join(root, "examples", "woodpecker", "tag-delivery.yml"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
block, err := extractWoodpeckerCommand(string(contents), "deliver")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
command := strings.ReplaceAll(block, "$${", "${")
|
||||||
|
proxy := writeReleaseKitModuleProxy(t)
|
||||||
|
|
||||||
|
t.Run("older tag retry uses its committed module selection", func(t *testing.T) {
|
||||||
|
goDir, goLog := installGoBootstrapShim(t)
|
||||||
|
repository := newCLIRepository(t)
|
||||||
|
const module = "gitea.maximumdirect.net/eric/ReleaseKit"
|
||||||
|
writeRepositoryFile(t, repository, "go.mod", "module example.com/cli-candidate\n\ngo 1.25.0\n\nrequire "+module+" v0.2.197\n")
|
||||||
|
cliGitRun(t, repository, "add", "go.mod")
|
||||||
|
cliGitRun(t, repository, "commit", "-m", "select the earlier ReleaseKit version")
|
||||||
|
oldCommit := cliGitOutput(t, repository, "rev-parse", "HEAD")
|
||||||
|
cliGitRun(t, repository, "tag", "v1.2.3")
|
||||||
|
writeRepositoryFile(t, repository, "go.mod", "module example.com/cli-candidate\n\ngo 1.25.0\n\nrequire "+module+" v0.2.198\n")
|
||||||
|
cliGitRun(t, repository, "add", "go.mod")
|
||||||
|
cliGitRun(t, repository, "commit", "-m", "upgrade the default branch tool")
|
||||||
|
cliGitRun(t, repository, "init", "--bare", filepath.Join(filepath.Dir(repository), "origin.git"))
|
||||||
|
remote := filepath.Join(filepath.Dir(repository), "origin.git")
|
||||||
|
cliGitRun(t, repository, "remote", "add", "origin", remote)
|
||||||
|
cliGitRun(t, repository, "push", "origin", "refs/heads/main", "refs/tags/v1.2.3")
|
||||||
|
cliGitRun(t, repository, "checkout", "--detach", oldCommit)
|
||||||
|
if mainModule := cliGitOutput(t, repository, "show", "main:go.mod"); !strings.Contains(mainModule, module+" v0.2.198") {
|
||||||
|
t.Fatalf("default branch module = %q, want upgraded tool selection", mainModule)
|
||||||
|
}
|
||||||
|
moduleBefore := readWoodpeckerFixtureFile(t, filepath.Join(repository, "go.mod"))
|
||||||
|
commit := oldCommit
|
||||||
|
env := templateEnvironment(repository, commit, goDir, goLog)
|
||||||
|
env["GOPROXY"] = "file://" + filepath.ToSlash(proxy)
|
||||||
|
sumLog := filepath.Join(t.TempDir(), "tool-only-sums")
|
||||||
|
env["RELEASEKIT_SUM_LOG"] = sumLog
|
||||||
|
output := runWoodpeckerBlock(t, command, repository, env)
|
||||||
|
if !strings.Contains(output, "tool-version=v0.2.197") || !strings.Contains(output, "helper=tool-only dependency") || strings.Contains(output, "tool-version=v0.2.198") {
|
||||||
|
t.Fatalf("retry selected the wrong tool version: %q", output)
|
||||||
|
}
|
||||||
|
assertModuleBootstrap(t, repository, goLog, moduleBefore)
|
||||||
|
assertToolOnlyChecksums(t, sumLog)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("versioned replacement selects its declared source", func(t *testing.T) {
|
||||||
|
goDir, goLog := installGoBootstrapShim(t)
|
||||||
|
repository := newCLIRepository(t)
|
||||||
|
const module = "gitea.maximumdirect.net/eric/ReleaseKit"
|
||||||
|
goMod := "module example.com/cli-candidate\n\ngo 1.25.0\n\nrequire " + module + " v0.2.197\n\nreplace " + module + " v0.2.197 => " + module + " v0.2.198\n"
|
||||||
|
writeRepositoryFile(t, repository, "go.mod", goMod)
|
||||||
|
cliGitRun(t, repository, "add", "go.mod")
|
||||||
|
cliGitRun(t, repository, "commit", "-m", "select a versioned tool replacement")
|
||||||
|
commit := pushTaggedCLIRepository(t, repository)
|
||||||
|
moduleBefore := readWoodpeckerFixtureFile(t, filepath.Join(repository, "go.mod"))
|
||||||
|
env := templateEnvironment(repository, commit, goDir, goLog)
|
||||||
|
env["GOPROXY"] = "file://" + filepath.ToSlash(proxy)
|
||||||
|
sumLog := filepath.Join(t.TempDir(), "tool-only-sums")
|
||||||
|
env["RELEASEKIT_SUM_LOG"] = sumLog
|
||||||
|
output := runWoodpeckerBlock(t, command, repository, env)
|
||||||
|
if !strings.Contains(output, "tool-version=v0.2.198") || !strings.Contains(output, "helper=tool-only dependency") {
|
||||||
|
t.Fatalf("versioned replacement was not selected: %q", output)
|
||||||
|
}
|
||||||
|
assertModuleBootstrap(t, repository, goLog, moduleBefore)
|
||||||
|
assertToolOnlyChecksums(t, sumLog)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWoodpeckerSourceDeliveryTemplateSelfBootstraps(t *testing.T) {
|
||||||
|
root := cliRepositoryRoot(t)
|
||||||
|
contents, err := os.ReadFile(filepath.Join(root, "examples", "woodpecker", "releasekit-source-delivery.yml"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
block, err := extractWoodpeckerCommand(string(contents), "deliver")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
command := strings.ReplaceAll(block, "$${", "${")
|
||||||
|
repository := newCLIRepository(t)
|
||||||
|
const dependency = "example.com/releasekit-helper"
|
||||||
|
proxyDir := t.TempDir()
|
||||||
|
writeModuleProxyVersion(t, proxyDir, dependency, "v1.0.0", "module "+dependency+"\n\ngo 1.25.0\n", map[string]string{
|
||||||
|
"helper.go": "package helper\n\nconst Message = \"prepared tool dependency\"\n",
|
||||||
|
})
|
||||||
|
var proxyRequests atomic.Int64
|
||||||
|
files := http.FileServer(http.Dir(proxyDir))
|
||||||
|
proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
proxyRequests.Add(1)
|
||||||
|
files.ServeHTTP(w, r)
|
||||||
|
}))
|
||||||
|
defer proxy.Close()
|
||||||
|
writeRepositoryFile(t, repository, "go.mod", "module example.com/cli-candidate\n\ngo 1.25.0\n\nrequire "+dependency+" v1.0.0\n")
|
||||||
|
writeRepositoryFile(t, repository, "cmd/releasekit/main.go", "package main\n\nimport (\"fmt\"; \"os\"; helper \""+dependency+"\")\n\nfunc main() {\n\tfmt.Println(\"self-bootstrap \" + helper.Message)\n\tfmt.Printf(\"tool-args=%q\\n\", os.Args[1:])\n}\n")
|
||||||
|
preparationEnv := map[string]string{
|
||||||
|
"GOPROXY": proxy.URL, "GOSUMDB": "off", "GONOPROXY": "none", "GOPRIVATE": "",
|
||||||
|
"GOWORK": "off", "GOTOOLCHAIN": "local", "GOENV": "off", "GOFLAGS": "-modcacherw",
|
||||||
|
"GOMODCACHE": t.TempDir(),
|
||||||
|
}
|
||||||
|
runWoodpeckerBlock(t, "go mod download "+dependency, repository, preparationEnv)
|
||||||
|
cliGitRun(t, repository, "add", "cmd/releasekit/main.go", "go.mod", "go.sum")
|
||||||
|
cliGitRun(t, repository, "commit", "-m", "add the self-bootstrapped command")
|
||||||
|
commit := pushTaggedCLIRepository(t, repository)
|
||||||
|
goDir, goLog := installGoBootstrapShim(t)
|
||||||
|
env := templateEnvironment(repository, commit, goDir, goLog)
|
||||||
|
for key, value := range preparationEnv {
|
||||||
|
env[key] = value
|
||||||
|
}
|
||||||
|
env["GOMODCACHE"] = t.TempDir()
|
||||||
|
proxyRequests.Store(0)
|
||||||
|
env["CI_COMMIT_SHA"] = strings.Repeat("0", len(commit))
|
||||||
|
if output, err := executeWoodpeckerBlock(command, repository, env); err == nil {
|
||||||
|
t.Fatalf("wrong commit unexpectedly bootstrapped the tool: %s", output)
|
||||||
|
}
|
||||||
|
assertNoCommands(t, goLog)
|
||||||
|
if proxyRequests.Load() != 0 {
|
||||||
|
t.Fatal("wrong commit reached tool dependency preparation")
|
||||||
|
}
|
||||||
|
env["CI_COMMIT_SHA"] = commit
|
||||||
|
output := runWoodpeckerBlock(t, command, repository, env)
|
||||||
|
if !strings.Contains(output, "self-bootstrap prepared tool dependency") || !strings.Contains(output, `"`+commit+`"`) {
|
||||||
|
t.Fatalf("self-bootstrap output = %q", output)
|
||||||
|
}
|
||||||
|
if proxyRequests.Load() == 0 {
|
||||||
|
t.Fatal("self-bootstrap did not prepare its dependency from the local proxy")
|
||||||
|
}
|
||||||
|
if !strings.Contains(output, `"ci-deliver"`) || !strings.Contains(output, `"`+repository+`"`) || !strings.Contains(output, `"v1.2.3"`) {
|
||||||
|
t.Fatalf("self-bootstrapped command arguments = %q", output)
|
||||||
|
}
|
||||||
|
log := readWoodpeckerFixtureFile(t, goLog)
|
||||||
|
if !strings.Contains(log, "GOWORK=off GOTOOLCHAIN=local") || !strings.Contains(log, "build -mod=readonly -o ") || !strings.Contains(log, "./cmd/releasekit") {
|
||||||
|
t.Fatalf("self-bootstrap Go command = %q", log)
|
||||||
|
}
|
||||||
|
var executable string
|
||||||
|
for index, field := range strings.Fields(log) {
|
||||||
|
if field == "-o" && index+1 < len(strings.Fields(log)) {
|
||||||
|
executable = strings.Fields(log)[index+1]
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if executable == "" {
|
||||||
|
t.Fatalf("self-bootstrap output path missing from Go command: %q", log)
|
||||||
|
}
|
||||||
|
if relative, err := filepath.Rel(repository, executable); err != nil || relative == "." || (!strings.HasPrefix(relative, ".."+string(filepath.Separator)) && relative != "..") {
|
||||||
|
t.Fatalf("self-bootstrap executable %q is not outside source %q: relative=%q error=%v", executable, repository, relative, err)
|
||||||
|
}
|
||||||
|
if status := cliGitOutput(t, repository, "status", "--porcelain", "--untracked-files=all"); status != "" {
|
||||||
|
t.Fatalf("self-bootstrap changed the tagged source: %q", status)
|
||||||
|
}
|
||||||
|
if branch := cliGitOutput(t, repository, "rev-parse", "--abbrev-ref", "HEAD"); branch != "HEAD" {
|
||||||
|
t.Fatalf("self-bootstrap checkout branch = %q, want detached HEAD", branch)
|
||||||
|
}
|
||||||
|
entries, err := os.ReadDir(filepath.Dir(repository))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, entry := range entries {
|
||||||
|
if strings.HasPrefix(entry.Name(), ".releasekit-source.") {
|
||||||
|
t.Fatalf("self-bootstrap temporary directory remains: %s", entry.Name())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 installGoBootstrapShim(t *testing.T) (string, string) {
|
||||||
|
t.Helper()
|
||||||
|
shimDir := t.TempDir()
|
||||||
|
goLog := filepath.Join(shimDir, "go-commands")
|
||||||
|
shim := `#!/bin/sh
|
||||||
|
printf 'cwd=%s GOWORK=%s GOTOOLCHAIN=%s %s\n' "$PWD" "$GOWORK" "$GOTOOLCHAIN" "$*" >> "$RELEASEKIT_GO_LOG"
|
||||||
|
"$RELEASEKIT_REAL_GO" "$@"
|
||||||
|
status=$?
|
||||||
|
if [ "$status" -eq 0 ] && [ "$1" = "build" ] && [ -n "${RELEASEKIT_SUM_LOG:-}" ]; then
|
||||||
|
modfile=
|
||||||
|
for argument in "$@"; do
|
||||||
|
case "$argument" in -modfile=*) modfile=${argument#-modfile=} ;; esac
|
||||||
|
done
|
||||||
|
cp "${modfile%.mod}.sum" "$RELEASEKIT_SUM_LOG"
|
||||||
|
fi
|
||||||
|
exit "$status"
|
||||||
|
`
|
||||||
|
if err := os.WriteFile(filepath.Join(shimDir, "go"), []byte(shim), 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return shimDir, goLog
|
||||||
|
}
|
||||||
|
|
||||||
|
func installControlledGoBootstrapShim(t *testing.T) (string, string) {
|
||||||
|
t.Helper()
|
||||||
|
shimDir := t.TempDir()
|
||||||
|
goLog := filepath.Join(shimDir, "go-commands")
|
||||||
|
shim := `#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
printf 'cwd=%s GOWORK=%s GOTOOLCHAIN=%s %s\n' "$PWD" "$GOWORK" "$GOTOOLCHAIN" "$*" >> "$RELEASEKIT_GO_LOG"
|
||||||
|
modfile=
|
||||||
|
for argument in "$@"; do
|
||||||
|
case "$argument" in -modfile=*) modfile=${argument#-modfile=} ;; esac
|
||||||
|
done
|
||||||
|
[ -n "$modfile" ] && [ -f "$modfile" ] || { echo 'alternate module file is missing' >&2; exit 89; }
|
||||||
|
[ -f "${modfile%.mod}.sum" ] || { echo 'alternate checksum file is missing' >&2; exit 88; }
|
||||||
|
grep -F "$RELEASEKIT_MODULE v0.2.0" "$modfile" >/dev/null || { echo 'module selection was not copied' >&2; exit 87; }
|
||||||
|
case "$1" in
|
||||||
|
list)
|
||||||
|
printf '%s v0.2.0\n' "$RELEASEKIT_MODULE"
|
||||||
|
;;
|
||||||
|
build)
|
||||||
|
output=
|
||||||
|
previous=
|
||||||
|
for argument in "$@"; do
|
||||||
|
if [ "$previous" = "-o" ]; then output=$argument; break; fi
|
||||||
|
previous=$argument
|
||||||
|
done
|
||||||
|
[ -n "$output" ] || { echo 'go build omitted output path' >&2; exit 90; }
|
||||||
|
cat > "$output" <<'TOOL'
|
||||||
|
#!/bin/sh
|
||||||
|
printf '<%s>\n' "$@" > "$RELEASEKIT_TOOL_ARGS_LOG"
|
||||||
|
exit "${RELEASEKIT_TOOL_EXIT:-0}"
|
||||||
|
TOOL
|
||||||
|
chmod +x "$output"
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
echo "unexpected Go command: $1" >&2
|
||||||
|
exit 91
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
`
|
||||||
|
if err := os.WriteFile(filepath.Join(shimDir, "go"), []byte(shim), 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return shimDir, goLog
|
||||||
|
}
|
||||||
|
|
||||||
|
func templateEnvironment(repository, commit, 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_MODULE": "gitea.maximumdirect.net/eric/ReleaseKit",
|
||||||
|
"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()
|
||||||
|
output, err := executeWoodpeckerBlock(block, repository, environment)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Woodpecker command failed: %v\ncommand: %s\noutput: %s", err, block, output)
|
||||||
|
}
|
||||||
|
return output
|
||||||
|
}
|
||||||
|
|
||||||
|
func executeWoodpeckerBlock(block, repository string, environment map[string]string) (string, error) {
|
||||||
|
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()
|
||||||
|
return string(output), err
|
||||||
|
}
|
||||||
|
|
||||||
|
func selectReleaseKitModule(t *testing.T, repository, releaseKitSource string, includeSum bool) {
|
||||||
|
t.Helper()
|
||||||
|
const module = "gitea.maximumdirect.net/eric/ReleaseKit"
|
||||||
|
goMod := fmt.Sprintf("module example.com/tagged-app\n\ngo 1.25.0\n\nrequire %s v0.2.0\n\nreplace %s => %s\n", module, module, strconv.Quote(releaseKitSource))
|
||||||
|
writeRepositoryFile(t, repository, "go.mod", goMod)
|
||||||
|
cliGitRun(t, repository, "add", "go.mod")
|
||||||
|
if includeSum {
|
||||||
|
writeRepositoryFile(t, repository, "go.sum", "")
|
||||||
|
cliGitRun(t, repository, "add", "go.sum")
|
||||||
|
}
|
||||||
|
cliGitRun(t, repository, "commit", "-m", "select ReleaseKit from module configuration")
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeReleaseKitModuleProxy(t *testing.T) string {
|
||||||
|
t.Helper()
|
||||||
|
const module = "gitea.maximumdirect.net/eric/ReleaseKit"
|
||||||
|
const toolDependency = "example.com/releasekit-helper"
|
||||||
|
proxyDir := t.TempDir()
|
||||||
|
toolModule := "module " + module + "\n\ngo 1.25.0\n\nrequire " + toolDependency + " v1.0.0\n"
|
||||||
|
for _, version := range []string{"v0.2.197", "v0.2.198"} {
|
||||||
|
files := map[string]string{
|
||||||
|
"cmd/releasekit/main.go": "package main\n\nimport (\"fmt\"; \"os\"; tooldep \"example.com/releasekit-helper\")\n\nfunc main() {\n\tfmt.Println(\"tool-version=" + version + " helper=\" + tooldep.Version)\n\tfmt.Printf(\"tool-args=%q\\n\", os.Args[1:])\n}\n",
|
||||||
|
}
|
||||||
|
writeModuleProxyVersion(t, proxyDir, module, version, toolModule, files)
|
||||||
|
}
|
||||||
|
writeModuleProxyVersion(t, proxyDir, toolDependency, "v1.0.0", "module "+toolDependency+"\n\ngo 1.25.0\n", map[string]string{"tooldep.go": "package tooldep\n\nconst Version = \"tool-only dependency\"\n"})
|
||||||
|
return proxyDir
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeModuleProxyVersion(t *testing.T, proxyDir, module, version, moduleFile string, files map[string]string) {
|
||||||
|
t.Helper()
|
||||||
|
var escaped strings.Builder
|
||||||
|
for _, character := range module {
|
||||||
|
if character >= 'A' && character <= 'Z' {
|
||||||
|
escaped.WriteByte('!')
|
||||||
|
character += 'a' - 'A'
|
||||||
|
}
|
||||||
|
escaped.WriteRune(character)
|
||||||
|
}
|
||||||
|
moduleVersions := filepath.Join(proxyDir, filepath.FromSlash(escaped.String()), "@v")
|
||||||
|
if err := os.MkdirAll(moduleVersions, 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(moduleVersions, "list")); os.IsNotExist(err) {
|
||||||
|
if err := os.WriteFile(filepath.Join(moduleVersions, "list"), []byte(version+"\n"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
listPath := filepath.Join(moduleVersions, "list")
|
||||||
|
list := readWoodpeckerFixtureFile(t, listPath)
|
||||||
|
if !strings.Contains(list, version+"\n") {
|
||||||
|
if err := os.WriteFile(listPath, []byte(list+version+"\n"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(filepath.Join(moduleVersions, version+".mod"), []byte(moduleFile), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
info := fmt.Sprintf("{\"Version\":%q,\"Time\":\"2026-10-01T00:00:00Z\"}\n", version)
|
||||||
|
if err := os.WriteFile(filepath.Join(moduleVersions, version+".info"), []byte(info), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
archive, err := os.Create(filepath.Join(moduleVersions, version+".zip"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
writer := zip.NewWriter(archive)
|
||||||
|
prefix := module + "@" + version + "/"
|
||||||
|
files["go.mod"] = moduleFile
|
||||||
|
for name, contents := range files {
|
||||||
|
file, err := writer.Create(prefix + name)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := file.Write([]byte(contents)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := writer.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := archive.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func assertModuleBootstrap(t *testing.T, repository, goLog, moduleBefore string, sumBefore ...string) {
|
||||||
|
t.Helper()
|
||||||
|
assertGoSelection(t, repository, goLog)
|
||||||
|
if got := readWoodpeckerFixtureFile(t, filepath.Join(repository, "go.mod")); got != moduleBefore {
|
||||||
|
t.Fatalf("source go.mod changed during bootstrap: got %q, want %q", got, moduleBefore)
|
||||||
|
}
|
||||||
|
sumPath := filepath.Join(repository, "go.sum")
|
||||||
|
if len(sumBefore) == 0 {
|
||||||
|
if _, err := os.Stat(sumPath); !os.IsNotExist(err) {
|
||||||
|
t.Fatalf("source go.sum state changed: stat error = %v", err)
|
||||||
|
}
|
||||||
|
} else if got := readWoodpeckerFixtureFile(t, sumPath); got != sumBefore[0] {
|
||||||
|
t.Fatalf("source go.sum changed during bootstrap: got %q, want %q", got, sumBefore[0])
|
||||||
|
}
|
||||||
|
if status := cliGitOutput(t, repository, "status", "--porcelain", "--untracked-files=all"); status != "" {
|
||||||
|
t.Fatalf("bootstrap changed tagged source: %q", status)
|
||||||
|
}
|
||||||
|
if branch := cliGitOutput(t, repository, "rev-parse", "--abbrev-ref", "HEAD"); branch != "HEAD" {
|
||||||
|
t.Fatalf("checkout branch = %q, want detached HEAD", branch)
|
||||||
|
}
|
||||||
|
entries, err := os.ReadDir(filepath.Dir(repository))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, entry := range entries {
|
||||||
|
if strings.HasPrefix(entry.Name(), ".releasekit-bootstrap.") {
|
||||||
|
t.Fatalf("temporary bootstrap directory remains: %s", entry.Name())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func assertGoSelection(t *testing.T, repository, goLog string) {
|
||||||
|
t.Helper()
|
||||||
|
log := readWoodpeckerFixtureFile(t, goLog)
|
||||||
|
list := "list -mod=mod -modfile="
|
||||||
|
build := "build -mod=mod -modfile="
|
||||||
|
module := "gitea.maximumdirect.net/eric/ReleaseKit"
|
||||||
|
if !strings.Contains(log, "GOWORK=off GOTOOLCHAIN=local") || !strings.Contains(log, list) || !strings.Contains(log, "-m "+module) {
|
||||||
|
t.Fatalf("Go module selection command is missing required settings: %q", log)
|
||||||
|
}
|
||||||
|
if !strings.Contains(log, build) || !strings.Contains(log, module+"/cmd/releasekit") || strings.Contains(log, "@v0.2.0") {
|
||||||
|
t.Fatalf("Go build did not use the selected module without a version suffix: %q", log)
|
||||||
|
}
|
||||||
|
if strings.Index(log, list) > strings.Index(log, build) {
|
||||||
|
t.Fatalf("Go build ran before module selection: %q", log)
|
||||||
|
}
|
||||||
|
var modfile string
|
||||||
|
for _, field := range strings.Fields(log) {
|
||||||
|
if strings.HasPrefix(field, "-modfile=") {
|
||||||
|
modfile = strings.TrimPrefix(field, "-modfile=")
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if modfile == "" {
|
||||||
|
t.Fatalf("Go commands did not receive an alternate module file: %q", log)
|
||||||
|
}
|
||||||
|
if relative, err := filepath.Rel(repository, modfile); err != nil || relative == "." || (!strings.HasPrefix(relative, ".."+string(filepath.Separator)) && relative != "..") {
|
||||||
|
t.Fatalf("alternate module file %q is not outside source %q: relative=%q error=%v", modfile, repository, relative, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func assertNoCommands(t *testing.T, goLog string) {
|
||||||
|
t.Helper()
|
||||||
|
contents, err := os.ReadFile(goLog)
|
||||||
|
if err != nil && !os.IsNotExist(err) {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(contents) != 0 {
|
||||||
|
t.Fatalf("Go ran before tag/source verification: %q", contents)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func assertToolOnlyChecksums(t *testing.T, path string) {
|
||||||
|
t.Helper()
|
||||||
|
sums := readWoodpeckerFixtureFile(t, path)
|
||||||
|
if !strings.Contains(sums, "example.com/releasekit-helper v1.0.0 h1:") {
|
||||||
|
t.Fatalf("temporary module sum file omitted the tool-only dependency checksum: %q", sums)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func readWoodpeckerFixtureFile(t *testing.T, path string) string {
|
||||||
|
t.Helper()
|
||||||
|
contents, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return string(contents)
|
||||||
|
}
|
||||||
|
|
||||||
|
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.
|
||||||
76
docs/adr/0003-declarative-validation.md
Normal file
76
docs/adr/0003-declarative-validation.md
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
# ADR 0003: Declare optional validation through a shared specification
|
||||||
|
|
||||||
|
## Status
|
||||||
|
|
||||||
|
Accepted.
|
||||||
|
|
||||||
|
## Date
|
||||||
|
|
||||||
|
2026-10-07
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
Consumers have different release-validation needs. Their additional checks
|
||||||
|
include reusable mechanics such as formatting inspection and Go toolchain
|
||||||
|
invocations, alongside assertions about product behavior. Maintaining the
|
||||||
|
reusable mechanics in each application duplicates code and coordination work.
|
||||||
|
|
||||||
|
[ADR 0001](0001-public-facade.md) establishes facade ownership of public
|
||||||
|
contracts. [ADR 0002](0002-routine-releases.md) prioritizes routine releases
|
||||||
|
with little application-owned code or recurring developer effort. Optional
|
||||||
|
validation needs a common selection and execution model that supports these
|
||||||
|
decisions as shared capabilities grow.
|
||||||
|
|
||||||
|
## Decision
|
||||||
|
|
||||||
|
Consumers select shared validation through a typed, facade-owned specification
|
||||||
|
and equivalent release-profile settings. Related settings belong together.
|
||||||
|
Omitted optional settings preserve existing default validation behavior.
|
||||||
|
|
||||||
|
`Check` and `Publish` use one internal validation path bound to the captured
|
||||||
|
candidate. ReleaseKit owns execution, ordering, coordination between selected
|
||||||
|
checks, and propagation of failures and cancellation. The CLI maps profile
|
||||||
|
settings to the facade and owns presentation.
|
||||||
|
|
||||||
|
Shared validation exposes consistent diagnostics through facade-owned errors.
|
||||||
|
Findings identify the check and provide actionable detail where applicable.
|
||||||
|
Error wrapping preserves underlying causes and cancellation semantics.
|
||||||
|
Validation failures and publication outcomes retain their distinct meanings.
|
||||||
|
|
||||||
|
The existing `AdditionalChecks` callback and profile `checks` support
|
||||||
|
product-specific assertions. Publication guards, artifact builds, and delivery
|
||||||
|
retain their separate configuration and responsibilities. Validation execution
|
||||||
|
and coordination remain internal implementation responsibilities.
|
||||||
|
|
||||||
|
Evaluate optional capabilities by the application maintenance they remove,
|
||||||
|
their clarity of scope, configuration burden, and maintenance cost. A
|
||||||
|
capability can serve a small subset of consumers when those benefits justify
|
||||||
|
shared support. Consumers select the checks appropriate to their products.
|
||||||
|
|
||||||
|
GoDoc owns exact public API contracts, and the configuration reference owns
|
||||||
|
profile settings. Roadmaps own feature scope and implementation sequencing.
|
||||||
|
|
||||||
|
## Alternatives considered
|
||||||
|
|
||||||
|
- Consumer-owned commands preserve local control and leave applications
|
||||||
|
maintaining reusable inspection, invocation, and coordination code.
|
||||||
|
- Independently configured check and publication paths allow separate
|
||||||
|
validation choices and require consumers to keep those choices aligned.
|
||||||
|
- A public validator-registration framework supports custom composition and
|
||||||
|
expands the public lifecycle and ordering contracts. The existing
|
||||||
|
additional-check extension point supports current product-specific needs.
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
|
||||||
|
Applications can replace repeated release mechanics with small declarations.
|
||||||
|
Go callers and CLI users receive equivalent selected validation through the
|
||||||
|
same release operations. Existing consumers retain their default behavior and
|
||||||
|
additional-check integration as optional capabilities are introduced.
|
||||||
|
|
||||||
|
ReleaseKit assumes responsibility for maintaining shared checks, coordinating
|
||||||
|
their interactions, and presenting useful diagnostics. Public selections and
|
||||||
|
error contracts carry compatibility obligations. Verification must cover
|
||||||
|
default behavior, equivalent API and profile selections, and failure propagation.
|
||||||
|
|
||||||
|
Internal execution can evolve within the facade boundaries. Each new capability
|
||||||
|
requires a clear scope and evidence that shared ownership reduces consumer work.
|
||||||
68
docs/adr/0004-module-selected-tooling.md
Normal file
68
docs/adr/0004-module-selected-tooling.md
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
# ADR 0004: Select release tooling from the released application's module configuration
|
||||||
|
|
||||||
|
## Status
|
||||||
|
|
||||||
|
Accepted.
|
||||||
|
|
||||||
|
## Date
|
||||||
|
|
||||||
|
2026-10-07
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
Applications can declare ReleaseKit as a Go module dependency and use that
|
||||||
|
selection to build their local release tool. A separate CI version pin creates
|
||||||
|
a second declaration that maintainers must coordinate during upgrades. The two
|
||||||
|
paths can then use different ReleaseKit versions for the same release.
|
||||||
|
|
||||||
|
Hosted delivery runs after source publication and may be retried for an older
|
||||||
|
release. It needs a stable source for tool-version selection associated with
|
||||||
|
that release. [ADR 0002](0002-routine-releases.md) prioritizes reducing repeated
|
||||||
|
configuration and routine release decisions.
|
||||||
|
|
||||||
|
## Decision
|
||||||
|
|
||||||
|
For applications that declare ReleaseKit as a module dependency, the standard
|
||||||
|
integration selects the tool through the application's module configuration.
|
||||||
|
Local publication uses the candidate's module configuration. CI delivery uses
|
||||||
|
the released source's module configuration. Both paths follow the same
|
||||||
|
module-based selection approach.
|
||||||
|
|
||||||
|
CI verifies the triggering tag and commit and checks out that source before
|
||||||
|
resolving and building the release tool. Delivery retries use the same released
|
||||||
|
source for tool selection. The application maintains its ReleaseKit dependency
|
||||||
|
as the shared version declaration for these operations.
|
||||||
|
|
||||||
|
Tool bootstrap and dependency preparation remain separate from offline
|
||||||
|
validation and builds. The CI integration supplies the event, environment, and
|
||||||
|
credentials; the application profile supplies product and delivery settings.
|
||||||
|
Source publication and hosted delivery retain their separate outcomes.
|
||||||
|
|
||||||
|
Consumers using a separately installed tool and ReleaseKit's own source
|
||||||
|
bootstrap remain supported use cases. Adoption guidance describes the
|
||||||
|
appropriate bootstrap for each integration.
|
||||||
|
|
||||||
|
## Alternatives considered
|
||||||
|
|
||||||
|
- An independent CI version pin makes tool selection explicit in the workflow
|
||||||
|
and requires maintainers to coordinate it with the application's dependency.
|
||||||
|
- Selecting from the current default branch follows ongoing dependency
|
||||||
|
updates and allows delivery retries for an older release to select a newer
|
||||||
|
tool.
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
|
||||||
|
Applications using the standard module-based integration update one dependency
|
||||||
|
declaration for local publication and CI delivery. Tool selection follows the
|
||||||
|
released source when delivery is retried, preserving the release's dependency
|
||||||
|
choice as the application evolves.
|
||||||
|
|
||||||
|
CI must establish the released checkout before tool bootstrap. Its environment
|
||||||
|
must provide a compatible Go toolchain and access to the dependencies needed
|
||||||
|
to build the selected tool. Retrying delivery for an older release retains
|
||||||
|
those preparation requirements.
|
||||||
|
|
||||||
|
Maintained templates and adoption guidance must preserve this selection order.
|
||||||
|
Verification should exercise a dependency-version change and selection from
|
||||||
|
the triggering release's source. Exact commands and bootstrap mechanics belong
|
||||||
|
in the maintained integration guidance and examples.
|
||||||
232
docs/cli.md
Normal file
232
docs/cli.md
Normal file
@@ -0,0 +1,232 @@
|
|||||||
|
# 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 and
|
||||||
|
local Git state, runs the standard offline Go test suite (with `-race` when
|
||||||
|
`validation.go.race` is true), and runs a separate `go vet -mod=readonly ./...`
|
||||||
|
pass after successful tests when `validation.go.full_vet` is true. It then runs
|
||||||
|
selected package compilation and committed Go formatting, followed by
|
||||||
|
configured additional checks in profile order. It does not inspect remote
|
||||||
|
availability or publish a tag.
|
||||||
|
|
||||||
|
When `validation.go.compile_targets` is selected, `check` compiles all packages
|
||||||
|
for each configured `GOOS/GOARCH` pair after tests and full vet, using static
|
||||||
|
mode with cgo disabled. This check produces no artifacts and does not execute
|
||||||
|
target binaries. Compilation failures use the `package-compile` identity and
|
||||||
|
show the selected target. When `validation.go_format` is true, `check` examines
|
||||||
|
regular committed Go files with the Go formatter after tests, vet, and package
|
||||||
|
compilation. It includes vendor and nested-module source, ignores the worktree
|
||||||
|
and symlink blobs, and reports unformatted paths as `go-format` without
|
||||||
|
modifying files. When `validation.module_distribution.workspace_files` is true,
|
||||||
|
`check` reports committed `go.work` and `go.work.sum` blobs, including nested
|
||||||
|
and symlink entries, as `workspace-files`. This inspection is independent of
|
||||||
|
`GOWORK` and ignores uncommitted files. Any artifact build selected by the
|
||||||
|
separate `build` setting runs after shared validation and configured checks.
|
||||||
|
When `validation.markdown` is a non-null object, `check` checks committed local
|
||||||
|
Markdown destinations and supported heading fragments after file-size
|
||||||
|
inspection. An empty object enables the check; omission or `null` disables it.
|
||||||
|
Outside-checkout links are written as out-of-scope observations to standard
|
||||||
|
error by default. Setting `validation.markdown.enforce_checkout_boundary` to
|
||||||
|
true makes those links fail; submodule-content observations remain
|
||||||
|
nonfailures. Failures use the `markdown-links` identity with the source location
|
||||||
|
and target.
|
||||||
|
|
||||||
|
`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. Shared validation failures identify the
|
||||||
|
failed check and retain useful findings and cause context in one diagnostic;
|
||||||
|
separate full-vet failures use the `go-vet` identity.
|
||||||
|
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, validation, and additional-check
|
||||||
|
settings as `check`. It checks the authoritative remote and validates the
|
||||||
|
candidate: the single standard offline Go test suite runs first, with `-race`
|
||||||
|
when `validation.go.race` is true. When `validation.go.full_vet` is true,
|
||||||
|
test-time vet is disabled and `go vet -mod=readonly ./...` runs after successful
|
||||||
|
tests. Selected package compilation and committed Go formatting follow. The
|
||||||
|
selected file checks then run in order: workspace files, local replacements,
|
||||||
|
file size, and Markdown. Configured checks run afterward in profile order. It
|
||||||
|
then creates an annotated local tag
|
||||||
|
and pushes only its exact tag object. It prints the confirmed version,
|
||||||
|
candidate commit, and tag object
|
||||||
|
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.
|
||||||
|
Shared validation failures use the same check and finding presentation as
|
||||||
|
`check`, alongside publication state and phase.
|
||||||
|
|
||||||
|
When `validation.go.compile_targets` is selected, package compilation runs
|
||||||
|
after tests and full vet and before configured checks. Each failure is reported
|
||||||
|
as `package-compile` with its selected target; this does not create build
|
||||||
|
artifacts or execute target binaries. When `validation.go_format` is true,
|
||||||
|
committed Go formatting runs after package compilation and before configured
|
||||||
|
checks. The selected workspace-file check then reports committed go.work and
|
||||||
|
go.work.sum paths as `workspace-files`. Formatting failures are reported as
|
||||||
|
`go-format` with affected paths and preserve parser or source-inspection causes.
|
||||||
|
|
||||||
|
When `validation.module_distribution.local_replacements` is true, the command
|
||||||
|
parses committed `go.mod` declarations, including nested and vendor modules,
|
||||||
|
after workspace-file inspection. Filesystem replacements use the
|
||||||
|
`local-replacements` identity and include the declaration path, source line,
|
||||||
|
and target; versioned replacements are permitted. Committed module symlinks are
|
||||||
|
resolved within the candidate, regardless of `GOWORK`.
|
||||||
|
When `validation.file_size` is a non-null object, the command checks each
|
||||||
|
committed blob after module-distribution checks. An omitted or null object
|
||||||
|
disables the check; an empty object enables the 1,000,000 decimal-byte default.
|
||||||
|
Oversized files use the `file-size` identity and report their path and measured
|
||||||
|
size against the limit. See the [configuration reference](config.md) for
|
||||||
|
literal exclusions and the current-candidate scope.
|
||||||
|
When `validation.markdown` is a non-null object, `publish` checks committed
|
||||||
|
Markdown destinations after file-size inspection and before configured checks.
|
||||||
|
It reports outside-checkout links to standard error unless boundary enforcement
|
||||||
|
is selected; submodule contents remain out of scope. Markdown failures stop
|
||||||
|
publication before product checks or tag creation.
|
||||||
|
|
||||||
|
The optional profile field `expected_push_url` applies only to `publish`. A
|
||||||
|
nonempty value must exactly match the effective push URL resolved by Git;
|
||||||
|
mismatches fail during preflight before Go validation or tag creation. Git URL
|
||||||
|
rewrites are resolved first, and the push URL is used when fetch and push URLs
|
||||||
|
differ. `check` ignores this field.
|
||||||
|
|
||||||
|
The command 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.
|
||||||
|
|
||||||
|
The maintained module-based tag workflow verifies and checks out the event tag
|
||||||
|
before resolving the consumer module. It builds the ReleaseKit version already
|
||||||
|
selected by that tagged `go.mod`, using temporary alternate module files outside
|
||||||
|
the source checkout. This tool bootstrap is separate from `ci-deliver`'s
|
||||||
|
application dependency preparation for binary profiles. ReleaseKit's own
|
||||||
|
source workflow self-bootstraps `./cmd/releasekit`; consumers without a declared
|
||||||
|
ReleaseKit module dependency can use the separately installed-tool command.
|
||||||
|
See the [delivery guide](consumers/delivery.md#woodpecker-tag-workflows) for
|
||||||
|
compatible Go environments, retries, and preparation details.
|
||||||
198
docs/config.md
Normal file
198
docs/config.md
Normal file
@@ -0,0 +1,198 @@
|
|||||||
|
# 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`. |
|
||||||
|
| `expected_push_url` | No | Exact effective push URL required by `publish`; ignored by local `check`. |
|
||||||
|
| `checks` | No | Ordered additional child commands, each with an argument vector and optional environment map. |
|
||||||
|
| `validation` | No | Optional shared checks selected by ReleaseKit. |
|
||||||
|
| `build` | No | Optional main package, binary name, and selected `GOOS/GOARCH` target strings. |
|
||||||
|
| `delivery` | No | Optional Gitea `base_url`, `owner`, `repository`, and `token_env` settings for tagged-source delivery. |
|
||||||
|
|
||||||
|
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 optional `validation` object selects shared checks implemented by ReleaseKit.
|
||||||
|
`validation.go.race` enables the race detector for the single standard Go test
|
||||||
|
suite. `validation.go.full_vet` runs a separate native `go vet` pass after that
|
||||||
|
suite succeeds; ReleaseKit disables test-time vet for that suite to avoid
|
||||||
|
running vet twice. `validation.go.compile_targets` is an ordered array of
|
||||||
|
`GOOS/GOARCH` pairs. After tests and selected full vet pass, ReleaseKit compiles
|
||||||
|
all packages for each target with cgo disabled. Each pair must include both
|
||||||
|
components; the selected Go toolchain reports unsupported complete targets.
|
||||||
|
This source compatibility check does not name or produce binaries, run a target
|
||||||
|
executable, or create an artifact manifest. Omitted or empty `compile_targets`
|
||||||
|
selects no package-compilation pass. When `full_vet` is omitted or false, the
|
||||||
|
test command keeps its existing vet behavior. These settings are independent.
|
||||||
|
`validation.go_format` checks regular committed Go blobs with the Go formatter
|
||||||
|
used to build ReleaseKit. It includes vendor and nested-module source, ignores
|
||||||
|
symlink blobs and the worktree, and reports every selected path whose bytes
|
||||||
|
change under formatting. It never writes formatted bytes back. Omitted or false
|
||||||
|
disables the check. It runs after tests, selected full vet, and selected package
|
||||||
|
compilation, before configured product checks.
|
||||||
|
|
||||||
|
When `validation.markdown` is an object, ReleaseKit checks local destinations
|
||||||
|
and supported heading fragments in committed regular Markdown files. Omission
|
||||||
|
or `null` disables the check; `{}` enables it. Schemed and protocol-relative
|
||||||
|
links are skipped, URI query components do not affect path checks, and other
|
||||||
|
existing files or directories receive existence checks only. Missing local
|
||||||
|
destinations, symlink cycles, and missing Markdown headings fail with the
|
||||||
|
`markdown-links` identity. Outside-checkout destinations are reported as out
|
||||||
|
of scope by default. Set
|
||||||
|
`validation.markdown.enforce_checkout_boundary` to `true` to fail those links;
|
||||||
|
submodule contents remain out of scope under either setting.
|
||||||
|
|
||||||
|
The parser recognizes inline links, images, reference links, and CommonMark
|
||||||
|
autolinks; link-like text in code is ignored, and raw HTML destinations are
|
||||||
|
outside this check. For linked images, the image source and enclosing link
|
||||||
|
target are checked. Image labels supply alternative text.
|
||||||
|
Relative paths resolve from the source document in the
|
||||||
|
captured commit. Query components are ignored for file existence, and percent
|
||||||
|
escapes in local paths and fragments are decoded once. Fragments are compared
|
||||||
|
in lowercase with anchors derived from visible ATX or Setext heading text.
|
||||||
|
Anchors keep Unicode letters and numbers, underscores, and hyphens; spaces
|
||||||
|
become hyphens, and repeated headings receive numeric suffixes.
|
||||||
|
|
||||||
|
When `validation.module_distribution.workspace_files` is true, it reports
|
||||||
|
committed blob entries whose basename is `go.work` or `go.work.sum`, including
|
||||||
|
nested paths and symlinks. It checks candidate distribution contents regardless
|
||||||
|
of `GOWORK`; it does not select or change the workspace used by Go commands,
|
||||||
|
and it does not alter existing vendor behavior. Omitted or false disables it.
|
||||||
|
When `validation.module_distribution.local_replacements` is true, it parses all
|
||||||
|
committed `go.mod` declarations, including vendor and nested modules, and reports
|
||||||
|
`replace` directives whose replacement has no version. These filesystem
|
||||||
|
replacements include relative and absolute paths; versioned module replacements
|
||||||
|
are permitted. Committed `go.mod` symlinks are resolved within the candidate,
|
||||||
|
and unavailable selected contents or parse failures are reported as inspection
|
||||||
|
errors. This selection is independent of `workspace_files` and Go's `GOWORK`
|
||||||
|
setting. Omitted or false disables it.
|
||||||
|
For example:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"product": "Example",
|
||||||
|
"validation": {
|
||||||
|
"go": {
|
||||||
|
"race": true,
|
||||||
|
"full_vet": true,
|
||||||
|
"compile_targets": ["linux/amd64", "linux/arm64"]
|
||||||
|
},
|
||||||
|
"go_format": true,
|
||||||
|
"markdown": {},
|
||||||
|
"module_distribution": {
|
||||||
|
"workspace_files": true,
|
||||||
|
"local_replacements": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
When `validation.file_size` is an object, ReleaseKit compares each committed
|
||||||
|
blob's size with `limit_bytes`. The limit uses decimal bytes and rejects only
|
||||||
|
sizes strictly greater than the limit. An omitted or null object disables the
|
||||||
|
check; `{}` enables it with a default of 1,000,000 bytes. A missing or null
|
||||||
|
`limit_bytes` selects that default, zero is a valid limit, and negative limits
|
||||||
|
are invalid.
|
||||||
|
|
||||||
|
`validation.file_size.exclusions` contains literal repository-relative file or
|
||||||
|
directory paths. Directory exclusions include committed descendants, using path
|
||||||
|
boundaries (`assets` does not exclude `assets-old`). Ordinary relative path
|
||||||
|
normalization applies; metacharacters are literal and unmatched paths have no
|
||||||
|
effect. The check measures regular and symlink blobs, including small binaries;
|
||||||
|
symlink size is the committed link text. Gitlinks have no measured size. Only
|
||||||
|
the captured candidate is checked, one offending file is reported at a time,
|
||||||
|
and historical or aggregate repository size is not measured.
|
||||||
|
|
||||||
|
The `delivery` object contains `base_url`, `owner`, `repository`, and optional
|
||||||
|
`token_env`. Its values are required when running `deliver`, but credentials are
|
||||||
|
not required for `check`, `publish`, or `build`. `token_env` names the
|
||||||
|
environment variable containing the Gitea token; it defaults to
|
||||||
|
`RELEASEKIT_GITEA_TOKEN`. The CLI reads this variable only for `deliver` and
|
||||||
|
passes its value explicitly to the library operation.
|
||||||
|
|
||||||
|
`expected_push_url`, when nonempty, is compared exactly with Git's resolved
|
||||||
|
effective push URL during `publish`, before candidate validation. It applies
|
||||||
|
to the push destination when fetch and push URLs differ, and Git URL rewrites
|
||||||
|
such as `insteadOf` are resolved before comparison. A mismatch fails preflight;
|
||||||
|
omitting the field keeps the selected remote's existing behavior. `check` is
|
||||||
|
local-only and ignores this publication expectation.
|
||||||
|
|
||||||
|
The `check` and `publish` commands run one
|
||||||
|
`go test -mod=readonly -count=1 ./...` suite with Go module and toolchain network
|
||||||
|
access disabled, adding `-race` when `validation.go.race` is true. When
|
||||||
|
`validation.go.full_vet` is true, they add `-vet=off` to that test command and
|
||||||
|
run native `go vet -mod=readonly ./...` after successful tests. They then run
|
||||||
|
`go build -mod=readonly -o <os.DevNull> ./...` in static mode for each
|
||||||
|
`validation.go.compile_targets` entry, in profile order. Compile failures use
|
||||||
|
the `package-compile` identity and include the selected target. When selected,
|
||||||
|
`validation.go_format` checks regular committed Go source with go/format after
|
||||||
|
package compilation; unformatted paths use the `go-format` identity. When
|
||||||
|
`validation.module_distribution.workspace_files` is true, shared validation
|
||||||
|
also reports committed go.work and go.work.sum blobs after Go formatting, using
|
||||||
|
the workspace-files identity. Uncommitted workspace files are not inspected.
|
||||||
|
When `validation.module_distribution.local_replacements` is true, shared
|
||||||
|
validation parses committed `go.mod` files after workspace inspection and reports
|
||||||
|
filesystem replacements as `local-replacements`, with path, directive line, and
|
||||||
|
target. Versioned replacements are permitted; parse and inspection failures
|
||||||
|
preserve their causes.
|
||||||
|
When `validation.file_size` is selected, shared validation checks committed
|
||||||
|
blob sizes after module-distribution checks and reports the first oversized
|
||||||
|
path with the `file-size` identity and measured and limit byte counts.
|
||||||
|
When `validation.markdown` is selected, Markdown checking follows file-size
|
||||||
|
inspection and runs before configured product checks. Out-of-scope observations
|
||||||
|
are written to the command's standard error and do not fail validation unless
|
||||||
|
the checkout boundary is enforced. Submodule observations remain nonfailures.
|
||||||
|
Configured `checks` commands run afterward, once each in order, as additional
|
||||||
|
product checks. Artifact builds selected by the separate `build` setting run
|
||||||
|
after shared validation and product checks.
|
||||||
|
|
||||||
|
Do not repeat the standard suite or vet in `checks`; doing so repeats work. 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.
|
||||||
|
|
||||||
|
This application dependency preparation is separate from bootstrapping the
|
||||||
|
ReleaseKit executable. The maintained module-based tag workflow verifies the
|
||||||
|
tag first, then uses temporary copies of that tag's module files to build the
|
||||||
|
ReleaseKit version selected by the consumer's `go.mod`. The
|
||||||
|
[delivery guide](consumers/delivery.md#woodpecker-tag-workflows) describes that
|
||||||
|
bootstrap, the self-bootstrapped source workflow, and the separately installed
|
||||||
|
tool option.
|
||||||
|
|
||||||
|
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.
|
||||||
110
docs/consumers/check.md
Normal file
110
docs/consumers/check.md
Normal file
@@ -0,0 +1,110 @@
|
|||||||
|
# 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",
|
||||||
|
Validation: releasekit.ValidationSpec{
|
||||||
|
Go: releasekit.GoValidationSpec{Race: true, FullVet: true},
|
||||||
|
},
|
||||||
|
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 runs one `go test -mod=readonly -count=1 ./...` suite with the
|
||||||
|
available compatible local Go toolchain. Set `Validation.Go.Race` to run that
|
||||||
|
suite with `-race`; set `Validation.Go.FullVet` to run
|
||||||
|
`go vet -mod=readonly ./...` after successful tests, with test-time vet disabled
|
||||||
|
for the suite. Set `Validation.Go.CompileTargets` to compile packages for each
|
||||||
|
complete target pair after tests and vet. Package compilation uses
|
||||||
|
`CGO_ENABLED=0`, writes no artifact, and does not execute a target binary; its
|
||||||
|
failures use the `package-compile` identity and include the target. The zero
|
||||||
|
values retain the ordinary native test behavior and select no compilation.
|
||||||
|
Set `Validation.GoFormat` to check committed regular Go files using the Go
|
||||||
|
formatter built into ReleaseKit. It includes vendor and nested-module source,
|
||||||
|
ignores symlink blobs and worktree changes, and reports unformatted paths as
|
||||||
|
`go-format` without rewriting files. Its zero value disables the check; it runs
|
||||||
|
after tests, selected vet, and package compilation, before `AdditionalChecks`.
|
||||||
|
|
||||||
|
Set `Validation.ModuleDistribution.WorkspaceFiles` to reject committed
|
||||||
|
`go.work` and `go.work.sum` blobs, including nested and symlink entries. It
|
||||||
|
examines the captured candidate even when `GOWORK=off`, ignores uncommitted
|
||||||
|
files, and does not change Go test workspace selection or vendor behavior. The
|
||||||
|
zero value disables the check; failures use `workspace-files`.
|
||||||
|
Set `Validation.ModuleDistribution.LocalReplacements` independently to parse
|
||||||
|
committed `go.mod` declarations throughout the candidate, including nested and
|
||||||
|
vendor modules. It reports filesystem `replace` directives with their source
|
||||||
|
path, line, and target as `local-replacements`; versioned replacements are
|
||||||
|
permitted. Committed module symlinks are resolved within the candidate. Parse
|
||||||
|
and inspection errors retain their causes, and the rule applies even when
|
||||||
|
`GOWORK=off`. Its zero value disables the check.
|
||||||
|
Set `Validation.FileSize` to check each committed blob against a byte limit.
|
||||||
|
Nil disables the check; an empty object enables the default of 1,000,000
|
||||||
|
decimal bytes. `LimitBytes` is strict greater-than, accepts zero, and rejects
|
||||||
|
negative values. `Exclusions` contains literal repository-relative files or
|
||||||
|
directories; excluded directories include descendants. Symlink blobs are
|
||||||
|
measured by link-text bytes, and gitlinks are omitted. The check applies to the
|
||||||
|
captured candidate and reports one oversized file with its measurement as
|
||||||
|
`file-size`; it does not measure historical or aggregate size.
|
||||||
|
Set `Validation.Markdown` to check committed local Markdown destinations and
|
||||||
|
supported heading fragments. Nil disables the check; an empty object enables
|
||||||
|
it with outside-checkout destinations reported as out of scope. Set
|
||||||
|
`EnforceCheckoutBoundary` to fail outside-checkout links. Submodule contents
|
||||||
|
remain out of scope under either setting. The checker runs after file-size
|
||||||
|
inspection and before `AdditionalChecks`; its nonfailure observations use the
|
||||||
|
request's output writer. Markdown failures use the `markdown-links` identity
|
||||||
|
and include the source location and destination.
|
||||||
|
|
||||||
|
Use these selections for ReleaseKit-owned validation rather than repeating the
|
||||||
|
standard suite, selected vet/format/distribution checks, or Markdown navigation
|
||||||
|
checks in `AdditionalChecks` or profile `checks`. Keep release-note rules and
|
||||||
|
consumer-specific assertions—such as tests of maintained examples—in those
|
||||||
|
product-owned checks.
|
||||||
|
ReleaseKit calls `AdditionalChecks` once after shared validation when supplied.
|
||||||
|
It does not download a different toolchain automatically. If race prerequisites
|
||||||
|
are unavailable, the `go-test` check fails rather than being skipped; a selected
|
||||||
|
full-vet failure is reported as `go-vet`. The suite uses the Go host target,
|
||||||
|
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.
|
||||||
216
docs/consumers/delivery.md
Normal file
216
docs/consumers/delivery.md
Normal file
@@ -0,0 +1,216 @@
|
|||||||
|
# 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 local Go version compatible with the
|
||||||
|
consumer module. It uses `GOTOOLCHAIN=local`; Go does not download a different
|
||||||
|
toolchain. The tag's `go.mod` must select ReleaseKit as a module dependency.
|
||||||
|
Configure the Woodpecker repository secret `releasekit_gitea_token`; the
|
||||||
|
template maps it to `RELEASEKIT_GITEA_TOKEN` for delivery. The repository needs
|
||||||
|
a `delivery` profile. Page-only and binary behavior both use this template; the
|
||||||
|
profile's build target list selects whether application binaries are built and
|
||||||
|
delivered.
|
||||||
|
|
||||||
|
Before running Go, the template fetches the explicit event tag, compares its
|
||||||
|
peeled commit with the provider's full commit ID without regard to hex case,
|
||||||
|
checks out that commit detached, and confirms the source tree is clean. It then
|
||||||
|
copies the tagged `go.mod` and any `go.sum` to a temporary directory outside
|
||||||
|
the checkout. `go list -m` confirms that the module selects ReleaseKit; Go uses
|
||||||
|
an alternate `-modfile` to prepare dependencies and build the selected
|
||||||
|
`cmd/releasekit` package without changing the tagged module files. The template
|
||||||
|
invokes that executable with `CI_WORKSPACE`, `CI_COMMIT_SHA`, and
|
||||||
|
`CI_COMMIT_TAG`. A cleanup trap removes the temporary metadata and executable.
|
||||||
|
|
||||||
|
Tool bootstrap and application artifact preparation are separate. The bootstrap
|
||||||
|
resolves and builds ReleaseKit from the tagged consumer's module configuration.
|
||||||
|
Afterward, `ci-deliver` loads the profile and downloads application dependencies
|
||||||
|
only when build targets are selected; it builds and delivers those targets with
|
||||||
|
the note page. Source-only profiles skip application dependency downloads and
|
||||||
|
binary work. Dependency preparation for binaries may use the network and may
|
||||||
|
update an uncommitted checksum file in the checkout. A retry still uses the
|
||||||
|
same immutable tag and that tag's module settings, even after the default branch
|
||||||
|
selects a newer ReleaseKit version.
|
||||||
|
|
||||||
|
If the application does not declare ReleaseKit as a module dependency, install
|
||||||
|
the executable separately and invoke the same `ci-deliver` command. For
|
||||||
|
ReleaseKit's own source workflow, the maintained
|
||||||
|
[source-delivery template](../../examples/woodpecker/releasekit-source-delivery.yml)
|
||||||
|
checks out the tag and self-bootstraps `./cmd/releasekit` into temporary storage.
|
||||||
|
Its readonly tool build uses committed module metadata and can fetch missing
|
||||||
|
dependencies through normal Go proxy, private-module, checksum, and cache
|
||||||
|
settings. Tool bootstrap follows tag verification; offline candidate validation
|
||||||
|
and application artifact compilation retain their separate environments.
|
||||||
|
|
||||||
|
The normal Go module and build caches are sufficient. Cache mounts may be added
|
||||||
|
as deployment configuration when they help the runner; they are not needed by
|
||||||
|
the template. A separately installed executable can be installed with
|
||||||
|
`go install gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit@PIN`, then run
|
||||||
|
with the same arguments:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
releasekit ci-deliver --repo "$CI_WORKSPACE" --commit "$CI_COMMIT_SHA" "$CI_COMMIT_TAG"
|
||||||
|
```
|
||||||
|
|
||||||
|
The module-based workflow follows the ReleaseKit version selected by the tagged
|
||||||
|
consumer's `go.mod`, so retries use that source's original selection. Update the
|
||||||
|
consumer module configuration when adopting a newer ReleaseKit version and
|
||||||
|
verify it with a tag fixture. The command and profile behavior are documented
|
||||||
|
in the [CLI contract](../cli.md) and [configuration reference](../config.md).
|
||||||
|
|
||||||
|
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.
|
||||||
105
docs/consumers/publish.md
Normal file
105
docs/consumers/publish.md
Normal file
@@ -0,0 +1,105 @@
|
|||||||
|
# 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",
|
||||||
|
ExpectedPushURL: "ssh://git.example/owner/example.git",
|
||||||
|
Validation: releasekit.ValidationSpec{
|
||||||
|
Go: releasekit.GoValidationSpec{Race: true, FullVet: true},
|
||||||
|
},
|
||||||
|
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.
|
||||||
|
Set `ExpectedPushURL` to require the effective push destination to match an
|
||||||
|
exact string. Git URL rewrites are resolved first, and the push URL is compared
|
||||||
|
when fetch and push URLs differ. A mismatch fails preflight before Go validation,
|
||||||
|
callbacks, or tag creation; detect it with
|
||||||
|
`errors.Is(err, releasekit.ErrUnexpectedPushURL)`. `Check` ignores this
|
||||||
|
publication-only field.
|
||||||
|
It runs one `go test -mod=readonly -count=1 ./...` suite with the available
|
||||||
|
compatible local Go toolchain. Set `Validation.Go.Race` to run that suite with
|
||||||
|
`-race`. Set `Validation.Go.FullVet` to run `go vet -mod=readonly ./...` after
|
||||||
|
successful tests, with test-time vet disabled for that suite. The zero values
|
||||||
|
keep ordinary test-time vet behavior. 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 race prerequisites are unavailable, the selected suite fails as `go-test`
|
||||||
|
instead of silently running without the race detector. Full-vet failures are
|
||||||
|
reported as `go-vet` and stop publication before tag creation.
|
||||||
|
|
||||||
|
Set `Validation.Go.CompileTargets` to compile packages for each complete target
|
||||||
|
pair after tests and vet. This uses `CGO_ENABLED=0`, produces no artifact, and
|
||||||
|
does not execute target binaries. A failure is reported as `package-compile`
|
||||||
|
with the selected target and prevents tag creation.
|
||||||
|
|
||||||
|
Set `Validation.GoFormat` to check committed regular Go source using the Go
|
||||||
|
formatter built into ReleaseKit. It includes vendor and nested modules, ignores
|
||||||
|
worktree changes and symlink blobs, and reports unformatted paths as
|
||||||
|
`go-format` without changing files. The default is disabled. The check follows
|
||||||
|
tests, selected vet, and package compilation, and a failure stops publication
|
||||||
|
before product checks or tag creation.
|
||||||
|
|
||||||
|
Set `Validation.ModuleDistribution.WorkspaceFiles` to reject committed
|
||||||
|
`go.work` and `go.work.sum` blobs, including nested paths and symlink entries.
|
||||||
|
The rule reads the captured candidate regardless of `GOWORK`; uncommitted files
|
||||||
|
are ignored, and Go workspace selection and vendor behavior are unchanged. Its
|
||||||
|
zero value disables the check. Findings use `workspace-files` and stop
|
||||||
|
publication before product checks or tag creation.
|
||||||
|
Set `Validation.ModuleDistribution.LocalReplacements` independently to parse
|
||||||
|
committed `go.mod` declarations across the candidate, including nested and
|
||||||
|
vendor modules. Filesystem `replace` directives are reported with their source
|
||||||
|
path, line, and target as `local-replacements`; versioned replacements are
|
||||||
|
permitted. Committed module symlinks are resolved within the candidate, and
|
||||||
|
parse or inspection errors retain their causes. This check is independent of
|
||||||
|
`GOWORK`; its zero value disables it, and a failure stops publication before
|
||||||
|
product checks or tag creation.
|
||||||
|
Set `Validation.FileSize` to check each committed blob against a byte limit.
|
||||||
|
Nil disables the check; an empty object enables the default of 1,000,000
|
||||||
|
decimal bytes. `LimitBytes` uses strict greater-than, accepts zero, and rejects
|
||||||
|
negative values. `Exclusions` contains literal repository-relative files or
|
||||||
|
directories, including committed descendants of excluded directories. Symlink
|
||||||
|
blob size is its link text; gitlinks are omitted. This check measures only the
|
||||||
|
captured candidate and reports one oversized file with its measurement as
|
||||||
|
`file-size`; it stops publication before product checks or tag creation.
|
||||||
|
|
||||||
|
Set `Validation.Markdown` to check committed local Markdown destinations and
|
||||||
|
supported heading fragments during publication. Nil disables the check; an
|
||||||
|
empty object enables it with outside-checkout links reported as out of scope.
|
||||||
|
Set `EnforceCheckoutBoundary` to fail those links. Submodule contents remain
|
||||||
|
out of scope under either setting. Observations use the request's output writer;
|
||||||
|
failures use `markdown-links` and stop publication before product checks or tag
|
||||||
|
creation.
|
||||||
|
|
||||||
|
ReleaseKit-owned selections replace duplicate generic suite, vet, formatting,
|
||||||
|
distribution, and Markdown checks in configured product checks. Keep
|
||||||
|
release-note rules and consumer-specific assertions, such as maintained-example
|
||||||
|
tests, in `AdditionalChecks` or profile `checks`.
|
||||||
|
|
||||||
|
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.
|
||||||
77
docs/development.md
Normal file
77
docs/development.md
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
# 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.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
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.
|
||||||
49
docs/internal/gotool.md
Normal file
49
docs/internal/gotool.md
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
# Go command environments
|
||||||
|
|
||||||
|
`internal/gotool` resolves effective Go settings once for a validation or build
|
||||||
|
operation and applies the shared environment to its Go commands. It uses
|
||||||
|
`internal/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 and
|
||||||
|
selected full `go vet` pass. Package-compilation checks use static mode for each
|
||||||
|
selected target and direct Go's output to the operating system null device, so
|
||||||
|
they leave no binary artifact. Artifact builds also use static mode for
|
||||||
|
selected-target compilation, then build the native version-check executable;
|
||||||
|
that executable runs as a normal child process.
|
||||||
102
docs/internal/overview.md
Normal file
102
docs/internal/overview.md
Normal file
@@ -0,0 +1,102 @@
|
|||||||
|
# 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` requires `golang.org/x/mod` and Goldmark for internal
|
||||||
|
validation; public facades do not expose either dependency. `go list ./...`
|
||||||
|
reports these implemented packages:
|
||||||
|
|
||||||
|
| Package | Responsibility |
|
||||||
|
| --- | --- |
|
||||||
|
| `releasekit` | Public orchestration facade and consumer-owned request/result types. |
|
||||||
|
| `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, committed-tree and blob reads, push-destination resolution, exact ref inspection, tagged checkout preparation, and tag operations, including captured-endpoint verification during recovery. |
|
||||||
|
| `internal/gitea` | Gitea API transport, hosted release pages, asset inspection, manifests, and uploads. |
|
||||||
|
| `internal/gotool` | Effective Go configuration discovery, shared native-validation and static-build environments, and network-capable dependency preparation; see [Go command environments](gotool.md). |
|
||||||
|
| `internal/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/validation` | Shared Go validation with optional race, full-vet, and static package-compilation target selections, formatting, workspace-file and filesystem-replacement checks, per-blob size limits, and selected Markdown destination and fragment checking; `internal/candidate` retains capture, callback sequencing, and local-state rechecks. |
|
||||||
|
| `internal/publish` | Publication guards, one validation run, annotated tag creation, push, and recovery state. |
|
||||||
|
| `internal/runtimeinfo` | Private version lookup used by the runtime facade. |
|
||||||
|
| `internal/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).
|
||||||
|
|
||||||
|
Candidate checking captures and validates one clean committed source revision
|
||||||
|
in `internal/candidate`. Its validation bridge calls `internal/validation` for
|
||||||
|
the default offline Go suite, then runs product-specific checks once. The
|
||||||
|
candidate package owns post-validation builds and local-state rechecks;
|
||||||
|
publication owns endpoint guards, tag creation, push, and recovery around that
|
||||||
|
same candidate validation path. `internal/validation.CandidateTree` reads
|
||||||
|
committed blobs lazily and resolves local destinations from committed entries;
|
||||||
|
it does not consult neighboring files or traverse submodule checkouts.
|
||||||
|
See the [shared validation guide](validation.md) for checker, Go command, and
|
||||||
|
candidate-file integration mechanics.
|
||||||
|
|
||||||
|
## 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, shared validation, public diagnostics, additional checks, and rechecks | `releasekit.Check`, `releasekit.Publish`, `internal/candidate`, `internal/validation`, `cmd/releasekit/internal/cli` | `TestRunUsesOneSuiteWithSelectedRaceSetting`, `TestRunReportsRacePrerequisiteFailureWithoutFallback`, `TestRunExecutesRaceEnabledSuiteOnHost`, `TestRunCompilesTargetsAfterTestAndVetInSelectionOrder`, `TestRunAttributesTargetCompileFailureAndStops`, `TestRunCompilesSourceOnlyAndExecutablePackagesWithoutArtifacts`, `TestCandidateRequestMapsGoValidation`, `TestCandidateRequestPreservesMarkdownObjectSelection`, `TestLoadSettingsReadsGoValidation`, `TestLoadSettingsPreservesMarkdownObjectSelection`, `TestCheckUsesSelectedRaceSuiteBeforeAdditionalChecks`, `TestCheckCapturesCandidateAndCallsAdditionalChecksOnce`, `TestCheckReturnsPublicValidationError`, `TestMarkdownValidationRunsThroughCheckAndPublish`, `TestCheckStopsBeforeProductAndBuildCallbacksWhenMarkdownBoundaryFails`, `TestCheckCommandBindsConfiguredChecksToCapturedCandidate`, `TestPublishCommandPublishesConfiguredCandidate`, `TestCandidateCommandsPresentValidationDiagnosticsOnce`, `TestDeliverPageOnlyCreatesAndReusesRelease` |
|
||||||
|
| Committed-file validation: formatting, workspace files, local replacements, and file size | `internal/validation`, `internal/candidate`, `releasekit.Check`, `releasekit.Publish`, CLI profile conversion | `TestCheckGoFormatUsesCapturedRegularGoBlobs`, `TestCheckWorkspaceFilesReportsCommittedBlobNames`, `TestCheckLocalReplacementsParsesCommittedModuleDeclarations`, `TestCheckLocalReplacementsFollowsCommittedModuleSymlinks`, `TestCheckFileSizeUsesStrictLimitsAndDefault`, `TestCheckFileSizeAppliesLiteralPathExclusions`, `TestCheckFileSizeUsesCommittedBlobSizes`, `TestCheckFileSizeUsesOnlyCandidateFilesIndividually` |
|
||||||
|
| Internal Markdown parsing, committed destinations, fragments, boundary observations, and public selection | `releasekit.Check`, `releasekit.Publish`, `internal/candidate`, `internal/validation`, `cmd/releasekit/internal/cli` | `TestParseMarkdownLinksAndSourceLocations`, `TestParseMarkdownDecodesEntitiesInDestinations`, `TestParseMarkdownHeadingAnchors`, `TestMarkdownCacheKeepsParsedDocumentsPerCandidatePath`, `TestCheckMarkdownLinksResolvesCommittedDestinationsAndFragments`, `TestCheckMarkdownLinksReportsMissingPathsAnchorsAndCycles`, `TestCheckMarkdownLinksUsesResolvedMarkdownIdentity`, `TestCheckMarkdownLinksReportsBoundaryAndSubmoduleObservations`, `TestCheckMarkdownLinksPreservesResolverCauseAndCancellation`, `TestCheckMarkdownLinksPreservesAnchorReadCause`, `TestRunSelectsMarkdownWithCombinedGoChecksAndReportsOutOfScopeLinks`, `TestMarkdownValidationRunsThroughCheckAndPublish`, `TestLoadSettingsPreservesMarkdownObjectSelection`, `TestValidationSpecPreservesMarkdownObjectSelection` |
|
||||||
|
| Shared Go settings for validation and builds | `internal/gotool`, `internal/process`, `internal/candidate`, `internal/build` | `TestDefaultValidationDoesNotInheritGOFLAGSRunFilter`, `TestNativeAndStaticCommandsUseOwnedBaseline`, `TestPersistentSettingsPreserveCachesAndNativeCTools`, `TestBuildIgnoresAmbientAndPersistentArchitectureTuning` |
|
||||||
|
| Authoritative endpoint and exact annotated tag publication | `releasekit.Publish`, `internal/publish`, `internal/git` | `TestPublishPushesOnlyTheCapturedAnnotatedTag`, `TestPublishRejectsUnexpectedPushURLBeforeValidation`, `TestPublishComparesExpectedURLWithResolvedInsteadOfDestination`, `TestPublishExpectedPushURLUsesPushURLWhenFetchAndPushDiffer`, `TestCheckIgnoresExpectedPushURL`, `TestResolveUsesPushURLAndQueriesWithoutMutation` |
|
||||||
|
| Publication partial and uncertain recovery | `internal/publish`, `internal/git` | `TestPublishRejectedPushKeepsLocalTagAndReportsNotPublished`, `TestPublishLostAcknowledgmentConfirmsExactRemoteObject`, `TestPublishLostAcknowledgmentWithChangedEndpointRemainsUnknown`, `TestPublishUnavailableReconciliationRemainsUnknownAndPreservesPushError` |
|
||||||
|
| Cross-builds, version smoke checks, empty target sets, and partial outputs | `releasekit.Build`, `internal/build`, `buildinfo` | `TestBuildCreatesSelectedTargetsAndInjectsVersion`, `TestBuildWithNoTargetsDoesNotInvokeCompiler`, `TestBuildReturnsPartialArtifactsAfterTargetFailure` |
|
||||||
|
| Page-only and managed or prebuilt binary delivery | `releasekit.Deliver`, `internal/delivery`, `internal/gitea`, CLI | `TestDeliverPageOnlySkipsBuildAndHostedAssets`, `TestDeliverManagedBuildUploadsArtifactsAndCleansTemporaryOutput`, `TestDeliverBinaryConsumerWithBuildinfoAndSelectedTargets`, `TestDeliverPrebuiltArtifactsRemainCallerOwned`, `TestDeliverManagedBuildFailureCleansTemporaryOutputBeforeHostedWrites`, `TestDeliverManagedBuildCancellationCleansTemporaryOutput`, `TestDeliverBuildsTaggedArtifactsAndReusesAssets`, `TestDeliverRejectsTamperedAssetsAndStaleReceiptBeforeRemoteWrites` |
|
||||||
|
| Tagged checkout and build dependency preparation | `releasekit.PrepareTaggedCheckout`, `releasekit.PrepareBuildDependencies`, `internal/preparation`, `internal/git`, `internal/gotool` | `TestPrepareTaggedCheckoutFetchesExpectedCommitAndDetaches`, `TestPrepareTaggedCheckoutRejectsWrongCommitBeforeCheckout`, `TestPrepareTaggedCheckoutReportsLocalCheckoutConflict`, `TestPrepareTaggedCheckoutReportsConflictingLocalTag`, `TestPrepareBuildDependenciesPreservesPreparationEnvironment`, `TestPrepareBuildDependenciesPropagatesCommandFailure`, `TestPrepareBuildDependenciesPropagatesCancellation` |
|
||||||
|
| Page, manifest, asset comparison, and additive retry outcomes | `internal/gitea` | `TestEnsureReleaseCreatesMissingPageFromCommittedNote`, `TestInspectAssetsDetectsSameNameAndSizeWithDifferentBytes`, `TestUploadMissingPartialFailureThenRerunOnlyMissingAssets` |
|
||||||
|
| CLI profiles and prepared Woodpecker sequences | `cmd/releasekit`, `cmd/releasekit/internal/cli`, `examples/woodpecker/` | `TestLoadSettingsRejectsInvalidProfiles`, `TestWoodpeckerTagDeliveryTemplate`, `TestWoodpeckerTagDeliveryUsesTaggedModuleVersion`, `TestWoodpeckerSourceDeliveryTemplateSelfBootstraps`, `TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout` |
|
||||||
|
|
||||||
|
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.
|
||||||
143
docs/internal/validation.md
Normal file
143
docs/internal/validation.md
Normal file
@@ -0,0 +1,143 @@
|
|||||||
|
# Shared validation mechanics
|
||||||
|
|
||||||
|
`internal/validation` owns reusable checks for one captured candidate.
|
||||||
|
`internal/candidate` captures the clean source revision and keeps the
|
||||||
|
validation sequence shared by local checking and publication. It calls the
|
||||||
|
shared executor, runs product-specific `AdditionalChecks` once, and owns the
|
||||||
|
post-validation build callback and local-state recheck. `internal/publish`
|
||||||
|
adds its endpoint guards, tag creation, push, and recovery around that same
|
||||||
|
candidate path.
|
||||||
|
|
||||||
|
The executor runs one offline Go suite, optionally with the race detector when
|
||||||
|
selected. When full vet is selected, it disables test-time vet for that suite
|
||||||
|
and runs native `go vet -mod=readonly ./...` after the suite succeeds. It then
|
||||||
|
runs `go build -mod=readonly -o <os.DevNull> ./...` in static mode for each
|
||||||
|
selected package-compilation target, preserving target order and stopping on
|
||||||
|
the first failure. This compiles source without producing an artifact or
|
||||||
|
executing a target binary. Test, vet, and package-compilation failures retain
|
||||||
|
their `go-test`, `go-vet`, and `package-compile` identities, selected target
|
||||||
|
where applicable, and underlying causes. Its
|
||||||
|
request carries the captured repository directory and commit, output writer,
|
||||||
|
and internal settings. When selected, the Go-format check loads the candidate
|
||||||
|
tree once, reads regular Go blobs from the captured commit, and compares them
|
||||||
|
with go/format output. It includes vendor and nested-module files, skips
|
||||||
|
symlink blobs, reports all unformatted paths, and stops with a contextual cause
|
||||||
|
on parse or inspection errors. It runs before product checks and build callbacks.
|
||||||
|
`Request.ReadCandidateTree` lets selected file checks request candidate
|
||||||
|
contents; the Go-only path does not enumerate the tree.
|
||||||
|
|
||||||
|
The workspace-file check uses that same candidate inventory and reports blob
|
||||||
|
entries named go.work or go.work.sum, including nested paths and symlink blobs.
|
||||||
|
It does not read workspace contents or depend on the workspace selected for Go
|
||||||
|
commands.
|
||||||
|
The local-replacement check parses every committed go.mod blob with
|
||||||
|
`golang.org/x/mod/modfile`, including nested modules and vendor declarations.
|
||||||
|
It follows committed symlink declarations through the captured tree and fails
|
||||||
|
with an inspection cause when their selected contents are unavailable. A
|
||||||
|
replacement with no parsed version is reported with its go.mod path, line,
|
||||||
|
directive, and target; versioned replacements are allowed. It runs after the
|
||||||
|
workspace-file check using the same candidate inventory.
|
||||||
|
The optional file-size check uses each blob's captured Git size, including
|
||||||
|
symlink link-text bytes, and skips entries without a blob size such as gitlinks.
|
||||||
|
It applies normalized literal file/directory exclusions with path-boundary
|
||||||
|
matching, then returns the first oversized path with `FileSizeMeasurement`.
|
||||||
|
The optional Markdown check follows file-size inspection and uses the same
|
||||||
|
candidate tree. It parses regular Markdown blobs, resolves local destinations,
|
||||||
|
and checks supported anchors; outside-checkout and submodule observations are
|
||||||
|
written to the shared output writer. A nil writer keeps library use quiet.
|
||||||
|
`CandidateTree` gets metadata and bytes from Git objects, reads blob bytes
|
||||||
|
lazily, and resolves destinations without consulting the worktree or
|
||||||
|
neighboring files.
|
||||||
|
|
||||||
|
The internal Markdown parser uses Goldmark to record inline, reference, and
|
||||||
|
autolinks, images, titles, and their source use sites, and to build heading
|
||||||
|
anchors from visible AST text. It supports ATX and Setext headings, decodes
|
||||||
|
Markdown text through the parser, and assigns collision-free numeric suffixes
|
||||||
|
to repeated anchors. Link locations use one-based line and byte-column values.
|
||||||
|
A per-path cache retains parsed records and anchors for candidate documents.
|
||||||
|
|
||||||
|
`checkMarkdownLinks` examines regular `.md` blobs from the captured tree. It
|
||||||
|
skips schemed and protocol-relative URIs, strips query components, and decodes
|
||||||
|
percent escapes once in local paths and fragments. It resolves destinations
|
||||||
|
through `CandidateTree.ResolveDestination`; decoded fragments are compared in
|
||||||
|
lowercase against anchors from the resolved regular Markdown document. Missing
|
||||||
|
paths, symlink cycles, and missing anchors produce `markdown-links` findings at
|
||||||
|
the source use site. Outside-checkout links produce out-of-scope observations by
|
||||||
|
default and findings when boundary enforcement is selected. Submodule-content
|
||||||
|
observations remain out of scope under either setting. Observations go to the
|
||||||
|
provided writer; a nil writer keeps library use quiet. Public selection is
|
||||||
|
defined in the [configuration reference](../config.md) and GoDoc.
|
||||||
|
|
||||||
|
Committed-tree metadata and blob reads disable lazy fetching and Git transports
|
||||||
|
for those child commands. Missing local objects produce inspection errors;
|
||||||
|
source preparation retains its separate network-capable operations. See Git's
|
||||||
|
[lazy-fetch controls](https://git-scm.com/docs/git) for the command mechanism.
|
||||||
|
|
||||||
|
Public validation errors convert their diagnostic fields to the internal
|
||||||
|
failure model for shared formatting. Converted failures retain their original
|
||||||
|
contextual cause and reuse its rendering when it already contains the same
|
||||||
|
diagnostics. The CLI presents the complete error chain, including candidate
|
||||||
|
context around callback-supplied diagnostics.
|
||||||
|
|
||||||
|
## Adding a shared check
|
||||||
|
|
||||||
|
When an optional check is accepted for implementation:
|
||||||
|
|
||||||
|
1. Define its typed Go setting in the root facade and its equivalent CLI-owned
|
||||||
|
JSON field. Specify zero-value and omitted-profile behavior in GoDoc and the
|
||||||
|
configuration reference. Keep future settings in the roadmap until their
|
||||||
|
check is implemented.
|
||||||
|
2. Add the corresponding internal setting and explicit conversions. Use the
|
||||||
|
same root request conversion for `Check` and `Publish`, and the shared CLI
|
||||||
|
request conversion for profile-based candidate commands.
|
||||||
|
3. Implement a plain check function owned by `internal/validation`. Keep its
|
||||||
|
rule semantics in the capability owner and pass only the captured candidate
|
||||||
|
inputs it needs. A file-oriented check can call `Request.ReadCandidateTree`
|
||||||
|
and read only the blobs it inspects.
|
||||||
|
4. Return an internal `*Failure` with the check identity, repository-relative
|
||||||
|
findings, useful locations where available, and the underlying cause. Let
|
||||||
|
the root facade convert those records to its own diagnostic types. Preserve
|
||||||
|
cancellation and process errors through `Unwrap`.
|
||||||
|
5. Add the check to the shared executor at the ordering point selected by its
|
||||||
|
capability. Stop on failure. Keep product assertions in `AdditionalChecks`
|
||||||
|
and profile `checks`; keep artifact building in `internal/build`.
|
||||||
|
6. Cover observable behavior through both the Go facade and profile path when
|
||||||
|
both are supported. Check default behavior, useful findings, cause
|
||||||
|
preservation, cancellation where relevant, and failure stopping. Reuse the
|
||||||
|
existing local Git and CLI fixtures.
|
||||||
|
7. Update only the canonical owners for behavior that has landed: GoDoc for the
|
||||||
|
API, configuration and CLI references for profile behavior, and this
|
||||||
|
inventory for internal ownership. Record proposed checks under
|
||||||
|
`docs/roadmap/`.
|
||||||
|
|
||||||
|
Do not add a public validator registration interface. The public specification
|
||||||
|
selects ReleaseKit-owned checks; `AdditionalChecks` remains the extension point
|
||||||
|
for product behavior.
|
||||||
|
|
||||||
|
## Go command environment reuse
|
||||||
|
|
||||||
|
The current executor uses the [shared Go command environment](gotool.md) for
|
||||||
|
its offline suite, vet pass, and selected-target package compilation.
|
||||||
|
|
||||||
|
Reuse `internal/gotool` for native and static environments and target handling.
|
||||||
|
Keep toolchain and module-cache discovery in `gotool`; do not reproduce its
|
||||||
|
environment logic in a checker. Artifact output names, version injection,
|
||||||
|
native smoke checks, and artifact digests remain owned by `internal/build`.
|
||||||
|
|
||||||
|
## File-check coordination
|
||||||
|
|
||||||
|
File checks consume the captured tree and return findings to the shared error
|
||||||
|
model. They do not read sibling worktrees or follow live symlink targets.
|
||||||
|
`CandidateTree.ResolveDestination` returns data describing entries,
|
||||||
|
directories, missing paths, checkout boundaries, submodule paths, and symlink
|
||||||
|
cycles; the caller selects which observations fail validation or are reported
|
||||||
|
as out of scope.
|
||||||
|
|
||||||
|
Resolution walks committed components and symlink targets in order. Active
|
||||||
|
symlink expansion detects cycles, and traversal honors cancellation. Absolute
|
||||||
|
destinations and symlink targets within the repository directory map back to
|
||||||
|
candidate-relative paths; existence still comes from committed entries.
|
||||||
|
|
||||||
|
The public selection is owned by the facade and profile;
|
||||||
|
the internal checker uses the committed-file and destination-resolution
|
||||||
|
primitives described here.
|
||||||
41
docs/oss/attribution.md
Normal file
41
docs/oss/attribution.md
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
# Open Source Attribution Notices
|
||||||
|
|
||||||
|
## Go Authors
|
||||||
|
|
||||||
|
Selected module: `golang.org/x/mod` at `v0.40.0`.
|
||||||
|
|
||||||
|
Copyright 2009 The Go Authors.
|
||||||
|
|
||||||
|
SPDX-License-Identifier: BSD-3-Clause
|
||||||
|
|
||||||
|
License and notices: [BSD 3-Clause](licenses/BSD-3-Clause.txt) | [LICENSE](https://go.googlesource.com/mod/+/d3398d06de5fa5c71083d3d1c26f2cda73508e0f/LICENSE).
|
||||||
|
|
||||||
|
[Source](https://go.googlesource.com/mod/+/d3398d06de5fa5c71083d3d1c26f2cda73508e0f).
|
||||||
|
|
||||||
|
## Goldmark
|
||||||
|
|
||||||
|
Selected module: `github.com/yuin/goldmark/v2` at `v2.1.6`.
|
||||||
|
|
||||||
|
Copyright (c) 2019 Yusuke Inuzuka.
|
||||||
|
|
||||||
|
SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
License and notices: [MIT](licenses/MIT.txt) |
|
||||||
|
[LICENSE](https://github.com/yuin/goldmark/blob/a8d4ee5a0bd7d5493fdd1e339b4e75df92f8684c/LICENSE).
|
||||||
|
|
||||||
|
[Source](https://github.com/yuin/goldmark/tree/a8d4ee5a0bd7d5493fdd1e339b4e75df92f8684c).
|
||||||
|
|
||||||
|
## 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).
|
||||||
27
docs/oss/licenses/BSD-3-Clause.txt
Normal file
27
docs/oss/licenses/BSD-3-Clause.txt
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
Copyright 2009 The Go Authors.
|
||||||
|
|
||||||
|
Redistribution and use in source and binary forms, with or without
|
||||||
|
modification, are permitted provided that the following conditions are
|
||||||
|
met:
|
||||||
|
|
||||||
|
* Redistributions of source code must retain the above copyright
|
||||||
|
notice, this list of conditions and the following disclaimer.
|
||||||
|
* Redistributions in binary form must reproduce the above
|
||||||
|
copyright notice, this list of conditions and the following disclaimer
|
||||||
|
in the documentation and/or other materials provided with the
|
||||||
|
distribution.
|
||||||
|
* Neither the name of Google LLC nor the names of its
|
||||||
|
contributors may be used to endorse or promote products derived from
|
||||||
|
this software without specific prior written permission.
|
||||||
|
|
||||||
|
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||||
|
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||||
|
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||||
|
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||||
|
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||||
|
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||||
|
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||||
|
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||||
|
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||||
|
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||||
|
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||||
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.
|
||||||
21
docs/oss/licenses/MIT.txt
Normal file
21
docs/oss/licenses/MIT.txt
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2019 Yusuke Inuzuka
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
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. Roadmaps own 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.
|
||||||
|
Roadmaps record 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.
|
||||||
214
docs/policy/release.md
Normal file
214
docs/policy/release.md
Normal file
@@ -0,0 +1,214 @@
|
|||||||
|
# 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 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.
|
||||||
135
docs/release.md
Normal file
135
docs/release.md
Normal file
@@ -0,0 +1,135 @@
|
|||||||
|
# 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"
|
||||||
|
GOTOOLCHAIN=local go mod download
|
||||||
|
mkdir -p .releasekit/bin
|
||||||
|
GOTOOLCHAIN=local GOPROXY=off GOSUMDB=off go build -o .releasekit/bin/releasekit ./cmd/releasekit
|
||||||
|
RELEASEKIT_GITEA_TOKEN="$GITEA_TOKEN" .releasekit/bin/releasekit deliver "vX.Y.Z"
|
||||||
|
```
|
||||||
|
|
||||||
|
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)
|
||||||
106
docs/releases/v0.2.0.md
Normal file
106
docs/releases/v0.2.0.md
Normal file
@@ -0,0 +1,106 @@
|
|||||||
|
# ReleaseKit v0.2.0
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
ReleaseKit adds declarative candidate validation and module-selected release
|
||||||
|
tooling for Woodpecker. Consumers can replace repeated release checks with typed
|
||||||
|
Go selections or equivalent profile settings, while retaining product-specific
|
||||||
|
assertions through `AdditionalChecks` and profile `checks`.
|
||||||
|
|
||||||
|
## New features
|
||||||
|
|
||||||
|
- A facade-owned `ValidationSpec` on `ReleaseRequest` and corresponding profile
|
||||||
|
`validation` object select shared checks for both `Check` and `Publish`.
|
||||||
|
Structured `ValidationError` diagnostics identify the failed check, relevant
|
||||||
|
paths and locations, compilation targets, directives, and size measurements.
|
||||||
|
Wrapping preserves underlying causes and cancellation.
|
||||||
|
- Race testing selects the race detector for the one standard Go suite. Separate
|
||||||
|
full vet automatically disables test-time vet and runs after successful tests.
|
||||||
|
Selected package-compilation targets run afterward with `CGO_ENABLED=0`,
|
||||||
|
independently of executable artifacts. Source-only libraries can check target
|
||||||
|
compatibility and retain page-only delivery.
|
||||||
|
- Go formatting checks inspect committed regular Go source and report formatting
|
||||||
|
differences while preserving files.
|
||||||
|
- Offline Markdown validation checks local destinations and supported heading
|
||||||
|
fragments, including inline/reference links, images, and autolinks. Heading
|
||||||
|
anchors support visible text, duplicate headings, and Unicode. Outside-checkout
|
||||||
|
destinations are reported as out of scope by default; consumers can select
|
||||||
|
boundary enforcement. Submodule contents remain out of scope.
|
||||||
|
- Independent module-distribution selections inspect committed workspace files
|
||||||
|
and filesystem module replacements. Versioned replacements are permitted.
|
||||||
|
- Optional file-size validation checks individual committed blobs, including
|
||||||
|
symlink text, with a configurable limit and literal file/directory exclusions.
|
||||||
|
Enabling the check selects a default limit of 1,000,000 bytes; only sizes
|
||||||
|
strictly greater than the selected limit fail.
|
||||||
|
- `ExpectedPushURL` and profile `expected_push_url` require an exact match with
|
||||||
|
Git's effective push destination during publication preflight. A mismatch
|
||||||
|
returns `ErrUnexpectedPushURL` before candidate validation or tag creation.
|
||||||
|
Local `Check` ignores the publication expectation.
|
||||||
|
- The maintained Woodpecker consumer template selects ReleaseKit from the
|
||||||
|
released application's module configuration. It verifies the event tag and
|
||||||
|
commit before building the tool, prepares tool dependencies in temporary module
|
||||||
|
metadata, and preserves tagged module files. Retries use the triggering tag's
|
||||||
|
dependency selection. ReleaseKit's self-bootstrap template also supports
|
||||||
|
fetching missing tool dependencies after tag verification.
|
||||||
|
|
||||||
|
See the [configuration reference](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.2.0/docs/config.md),
|
||||||
|
[candidate check guide](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.2.0/docs/consumers/check.md),
|
||||||
|
[publication guide](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.2.0/docs/consumers/publish.md),
|
||||||
|
and [delivery guide](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.2.0/docs/consumers/delivery.md)
|
||||||
|
for supported behavior and adoption examples.
|
||||||
|
|
||||||
|
## Compatibility
|
||||||
|
|
||||||
|
The minimum Go version remains 1.25.0. The root orchestration facade and separate
|
||||||
|
lightweight `buildinfo` runtime facade keep their existing responsibilities.
|
||||||
|
Goldmark and `golang.org/x/mod` are new internal dependencies; prepare the module
|
||||||
|
cache before offline validation or builds.
|
||||||
|
|
||||||
|
Omitted validation selections preserve v0.1.0 defaults. Existing profiles and
|
||||||
|
product-specific checks continue to work. Race testing requires the native
|
||||||
|
toolchain's race prerequisites and reports an error when they are unavailable.
|
||||||
|
Markdown and file-size checks are enabled by non-nil Go specifications or profile
|
||||||
|
objects, including empty objects; omission or `null` disables them.
|
||||||
|
|
||||||
|
`ReleaseRequest` gains fields, so callers using positional struct literals must
|
||||||
|
convert them to keyed literals. Validation diagnostics now include structured
|
||||||
|
detail and additional context. Go callers can inspect `ValidationError` with
|
||||||
|
`errors.As` and underlying causes with `errors.Is`; CLI integrations should use
|
||||||
|
exit classifications rather than complete diagnostic strings.
|
||||||
|
|
||||||
|
Source publication still completes at confirmed publication of the intended
|
||||||
|
annotated tag. Hosted Gitea delivery retains its separate status. ReleaseKit's
|
||||||
|
deliverables remain the source tag and hosted note page.
|
||||||
|
|
||||||
|
## Upgrade guidance
|
||||||
|
|
||||||
|
1. Update the module dependency:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go get gitea.maximumdirect.net/eric/ReleaseKit@v0.2.0
|
||||||
|
```
|
||||||
|
|
||||||
|
Consumers using a separately installed executable can update it with:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go install gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit@v0.2.0
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Use v0.2.0 tooling before adding new profile fields. Select the shared checks
|
||||||
|
appropriate to the product and remove the corresponding duplicate commands
|
||||||
|
from additional checks. Retain assertions about product behavior. Package
|
||||||
|
compilation belongs under validation; executable deliverables use `build`.
|
||||||
|
|
||||||
|
3. For module-based CI, adopt the updated
|
||||||
|
[tag-delivery template](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.2.0/examples/woodpecker/tag-delivery.yml)
|
||||||
|
and remove the independent `RELEASEKIT_VERSION` workflow pin. Ensure the
|
||||||
|
application module declares ReleaseKit, align local tool bootstrap with that
|
||||||
|
selection, and retain the product's Go image, delivery profile, and secret
|
||||||
|
mapping. The
|
||||||
|
[Woodpecker guidance](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.2.0/docs/consumers/delivery.md#woodpecker-tag-workflows)
|
||||||
|
describes temporary module metadata, older-tag retries, self-bootstrap, and
|
||||||
|
separately installed tools.
|
||||||
|
|
||||||
|
[COPYRIGHT](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.2.0/COPYRIGHT) |
|
||||||
|
[LICENSE](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.2.0/LICENSE) |
|
||||||
|
[ATTRIBUTION](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.2.0/docs/oss/attribution.md)
|
||||||
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"
|
||||||
|
}
|
||||||
|
}
|
||||||
33
examples/woodpecker/releasekit-source-delivery.yml
Normal file
33
examples/woodpecker/releasekit-source-delivery.yml
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
when:
|
||||||
|
- event: tag
|
||||||
|
ref: refs/tags/v*
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: deliver
|
||||||
|
image: golang:1.25.0-bookworm
|
||||||
|
environment:
|
||||||
|
RELEASEKIT_GITEA_TOKEN:
|
||||||
|
from_secret: releasekit_gitea_token
|
||||||
|
commands:
|
||||||
|
- |
|
||||||
|
set -eu
|
||||||
|
test -n "$${CI_COMMIT_TAG}"
|
||||||
|
test -n "$${CI_COMMIT_SHA}"
|
||||||
|
git check-ref-format "refs/tags/$${CI_COMMIT_TAG}"
|
||||||
|
git fetch origin "refs/tags/$${CI_COMMIT_TAG}:refs/tags/$${CI_COMMIT_TAG}"
|
||||||
|
tag_commit=$(git rev-parse "refs/tags/$${CI_COMMIT_TAG}^{commit}")
|
||||||
|
expected_commit=$(printf '%s' "$${CI_COMMIT_SHA}" | tr '[:upper:]' '[:lower:]')
|
||||||
|
test "$(printf '%s' "$${tag_commit}" | tr '[:upper:]' '[:lower:]')" = "$${expected_commit}"
|
||||||
|
git checkout --detach "$${tag_commit}"
|
||||||
|
test "$(git rev-parse HEAD | tr '[:upper:]' '[:lower:]')" = "$${expected_commit}"
|
||||||
|
test -z "$(git status --porcelain --untracked-files=all)"
|
||||||
|
|
||||||
|
bootstrap_dir=$(mktemp -d "$${CI_WORKSPACE%/*}/.releasekit-source.XXXXXX")
|
||||||
|
trap 'rm -rf "$${bootstrap_dir}"' EXIT
|
||||||
|
export GOWORK=off
|
||||||
|
export GOTOOLCHAIN=local
|
||||||
|
go build -mod=readonly -o "$${bootstrap_dir}/releasekit" ./cmd/releasekit
|
||||||
|
"$${bootstrap_dir}/releasekit" ci-deliver \
|
||||||
|
--repo "$${CI_WORKSPACE}" \
|
||||||
|
--commit "$${CI_COMMIT_SHA}" \
|
||||||
|
"$${CI_COMMIT_TAG}"
|
||||||
49
examples/woodpecker/tag-delivery.yml
Normal file
49
examples/woodpecker/tag-delivery.yml
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
- GO_IMAGE: golang:1.25.0-bookworm
|
||||||
|
|
||||||
|
when:
|
||||||
|
- event: tag
|
||||||
|
ref: refs/tags/v*
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: deliver
|
||||||
|
image: ${GO_IMAGE}
|
||||||
|
environment:
|
||||||
|
RELEASEKIT_GITEA_TOKEN:
|
||||||
|
from_secret: releasekit_gitea_token
|
||||||
|
commands:
|
||||||
|
- |
|
||||||
|
set -eu
|
||||||
|
test -n "$${CI_COMMIT_TAG}"
|
||||||
|
test -n "$${CI_COMMIT_SHA}"
|
||||||
|
git check-ref-format "refs/tags/$${CI_COMMIT_TAG}"
|
||||||
|
git fetch origin "refs/tags/$${CI_COMMIT_TAG}:refs/tags/$${CI_COMMIT_TAG}"
|
||||||
|
tag_commit=$(git rev-parse "refs/tags/$${CI_COMMIT_TAG}^{commit}")
|
||||||
|
expected_commit=$(printf '%s' "$${CI_COMMIT_SHA}" | tr '[:upper:]' '[:lower:]')
|
||||||
|
test "$(printf '%s' "$${tag_commit}" | tr '[:upper:]' '[:lower:]')" = "$${expected_commit}"
|
||||||
|
git checkout --detach "$${tag_commit}"
|
||||||
|
test "$(git rev-parse HEAD | tr '[:upper:]' '[:lower:]')" = "$${expected_commit}"
|
||||||
|
test -z "$(git status --porcelain --untracked-files=all)"
|
||||||
|
|
||||||
|
bootstrap_dir=$(mktemp -d "$${CI_WORKSPACE%/*}/.releasekit-bootstrap.XXXXXX")
|
||||||
|
trap 'rm -rf "$${bootstrap_dir}"' EXIT
|
||||||
|
cp go.mod "$${bootstrap_dir}/go.mod"
|
||||||
|
if [ -f go.sum ]; then
|
||||||
|
cp go.sum "$${bootstrap_dir}/go.sum"
|
||||||
|
else
|
||||||
|
: > "$${bootstrap_dir}/go.sum"
|
||||||
|
fi
|
||||||
|
cp "$${bootstrap_dir}/go.mod" "$${bootstrap_dir}/releasekit.mod"
|
||||||
|
cp "$${bootstrap_dir}/go.sum" "$${bootstrap_dir}/releasekit.sum"
|
||||||
|
|
||||||
|
export GOWORK=off
|
||||||
|
export GOTOOLCHAIN=local
|
||||||
|
releasekit_module=gitea.maximumdirect.net/eric/ReleaseKit
|
||||||
|
go list -mod=mod -modfile="$${bootstrap_dir}/releasekit.mod" -m "$${releasekit_module}"
|
||||||
|
go build -mod=mod -modfile="$${bootstrap_dir}/releasekit.mod" \
|
||||||
|
-o "$${bootstrap_dir}/releasekit" "$${releasekit_module}/cmd/releasekit"
|
||||||
|
"$${bootstrap_dir}/releasekit" ci-deliver \
|
||||||
|
--repo "$${CI_WORKSPACE}" \
|
||||||
|
--commit "$${CI_COMMIT_SHA}" \
|
||||||
|
"$${CI_COMMIT_TAG}"
|
||||||
8
go.mod
Normal file
8
go.mod
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
module gitea.maximumdirect.net/eric/ReleaseKit
|
||||||
|
|
||||||
|
go 1.25.0
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/yuin/goldmark/v2 v2.1.6
|
||||||
|
golang.org/x/mod v0.40.0
|
||||||
|
)
|
||||||
4
go.sum
Normal file
4
go.sum
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
github.com/yuin/goldmark/v2 v2.1.6 h1:igy0q9JcqovoFXFx/XjtU8sHVhcUHavPj2sA3EoKJUE=
|
||||||
|
github.com/yuin/goldmark/v2 v2.1.6/go.mod h1:G6M4/qOFtfn01/o14BU1UR2Lo5N3S9Qo7xCuz/sHjGQ=
|
||||||
|
golang.org/x/mod v0.40.0 h1:hUv+3cXcdRHz08UmSiOob7sadHig73uo5bkXxQ/tvUs=
|
||||||
|
golang.org/x/mod v0.40.0/go.mod h1:0/weTWkPWGBikyTWAX3dkjVztMmBA5hM0DH6BElSupE=
|
||||||
6
ideas.md
Normal file
6
ideas.md
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
# ReleaseKit ideas
|
||||||
|
|
||||||
|
The [architecture policy](docs/policy/architecture.md) and
|
||||||
|
[ADRs](docs/adr/) record the adopted design decisions. The
|
||||||
|
[v0.2.0 release note](docs/releases/v0.2.0.md) summarizes the implemented
|
||||||
|
capabilities.
|
||||||
436
internal/apicheck/main.go
Normal file
436
internal/apicheck/main.go
Normal file
@@ -0,0 +1,436 @@
|
|||||||
|
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 "))
|
||||||
|
}
|
||||||
|
if path == modulePath {
|
||||||
|
if violations := checkValidationTypes(pkg); len(violations) != 0 {
|
||||||
|
return fmt.Errorf("facade %s has invalid validation diagnostics:\n %s", path, strings.Join(violations, "\n "))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkValidationTypes(pkg *types.Package) []string {
|
||||||
|
var violations []string
|
||||||
|
for _, name := range []string{"ValidationCheck", "ValidationFinding", "FileSizeMeasurement", "ValidationError"} {
|
||||||
|
object, ok := pkg.Scope().Lookup(name).(*types.TypeName)
|
||||||
|
if !ok {
|
||||||
|
violations = append(violations, fmt.Sprintf("missing facade-owned type %s", name))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
named, ok := types.Unalias(object.Type()).(*types.Named)
|
||||||
|
if !ok || named.Obj().Pkg() == nil || named.Obj().Pkg().Path() != pkg.Path() {
|
||||||
|
violations = append(violations, fmt.Sprintf("%s is not a facade-owned named type", name))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
validationError, ok := pkg.Scope().Lookup("ValidationError").(*types.TypeName)
|
||||||
|
if !ok {
|
||||||
|
return violations
|
||||||
|
}
|
||||||
|
named, ok := types.Unalias(validationError.Type()).(*types.Named)
|
||||||
|
if !ok {
|
||||||
|
return violations
|
||||||
|
}
|
||||||
|
structure, ok := named.Underlying().(*types.Struct)
|
||||||
|
if !ok {
|
||||||
|
return append(violations, "ValidationError is not a struct")
|
||||||
|
}
|
||||||
|
fields := map[string]string{
|
||||||
|
"Check": "ValidationCheck",
|
||||||
|
"Findings": "[]ValidationFinding",
|
||||||
|
"Measurement": "*FileSizeMeasurement",
|
||||||
|
}
|
||||||
|
for fieldName, expected := range fields {
|
||||||
|
fieldIndex := -1
|
||||||
|
for index := 0; index < structure.NumFields(); index++ {
|
||||||
|
if structure.Field(index).Name() == fieldName && structure.Field(index).Exported() {
|
||||||
|
fieldIndex = index
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if fieldIndex < 0 || !validationFieldMatches(structure.Field(fieldIndex).Type(), expected, pkg.Path()) {
|
||||||
|
violations = append(violations, fmt.Sprintf("ValidationError.%s must expose %s", fieldName, expected))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if cause := fieldByName(structure, "Cause"); cause == nil || !cause.Exported() || !types.Identical(cause.Type(), types.Universe.Lookup("error").Type()) {
|
||||||
|
violations = append(violations, "ValidationError.Cause must expose error")
|
||||||
|
}
|
||||||
|
return violations
|
||||||
|
}
|
||||||
|
|
||||||
|
func fieldByName(structure *types.Struct, name string) *types.Var {
|
||||||
|
for index := 0; index < structure.NumFields(); index++ {
|
||||||
|
if structure.Field(index).Name() == name {
|
||||||
|
return structure.Field(index)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func validationFieldMatches(fieldType types.Type, expected, packagePath string) bool {
|
||||||
|
switch expected {
|
||||||
|
case "[]ValidationFinding":
|
||||||
|
slice, ok := types.Unalias(fieldType).(*types.Slice)
|
||||||
|
if !ok {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
fieldType = slice.Elem()
|
||||||
|
case "*FileSizeMeasurement":
|
||||||
|
pointer, ok := types.Unalias(fieldType).(*types.Pointer)
|
||||||
|
if !ok {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
fieldType = pointer.Elem()
|
||||||
|
}
|
||||||
|
named, ok := types.Unalias(fieldType).(*types.Named)
|
||||||
|
return ok && named.Obj().Pkg() != nil && named.Obj().Pkg().Path() == packagePath && named.Obj().Name() == strings.TrimLeft(expected, "*[]")
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
237
internal/apicheck/main_test.go
Normal file
237
internal/apicheck/main_test.go
Normal file
@@ -0,0 +1,237 @@
|
|||||||
|
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 TestValidationDiagnosticTypesBelongToFacade(t *testing.T) {
|
||||||
|
valid := `package facade
|
||||||
|
type ValidationCheck string
|
||||||
|
type ValidationFinding struct{}
|
||||||
|
type FileSizeMeasurement struct{}
|
||||||
|
type ValidationError struct {
|
||||||
|
Check ValidationCheck
|
||||||
|
Findings []ValidationFinding
|
||||||
|
Measurement *FileSizeMeasurement
|
||||||
|
Cause error
|
||||||
|
}
|
||||||
|
`
|
||||||
|
pkg := typecheck(t, token.NewFileSet(), modulePath, valid)
|
||||||
|
if violations := checkValidationTypes(pkg); len(violations) != 0 {
|
||||||
|
t.Fatalf("checkValidationTypes() = %v, want facade-owned diagnostics", violations)
|
||||||
|
}
|
||||||
|
|
||||||
|
implementation := typecheck(t, token.NewFileSet(), "example.com/implementation", `package implementation
|
||||||
|
type State string
|
||||||
|
`)
|
||||||
|
fset := token.NewFileSet()
|
||||||
|
fixtureImporter := singlePackageImporter{path: "example.com/implementation", pkg: implementation}
|
||||||
|
invalid := strings.Replace(valid, "type ValidationCheck string", "import \"example.com/implementation\"\ntype ValidationCheck = implementation.State", 1)
|
||||||
|
pkg = typecheckWithImporter(t, fset, modulePath, invalid, fixtureImporter)
|
||||||
|
if violations := checkValidationTypes(pkg); !strings.Contains(strings.Join(violations, "\n"), "ValidationCheck is not a facade-owned named type") {
|
||||||
|
t.Fatalf("checkValidationTypes() = %v, want ownership violation", 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
|
||||||
|
}
|
||||||
|
}
|
||||||
266
internal/candidate/check.go
Normal file
266
internal/candidate/check.go
Normal file
@@ -0,0 +1,266 @@
|
|||||||
|
// 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/process"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/validation"
|
||||||
|
"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
|
||||||
|
Validation validation.Settings
|
||||||
|
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 selected offline Go suite, followed by AdditionalChecks
|
||||||
|
// when supplied, for the captured candidate.
|
||||||
|
func Validate(ctx context.Context, request Request, captured Candidate) error {
|
||||||
|
if err := validation.Run(ctx, validation.Request{
|
||||||
|
RepositoryDir: captured.RepositoryDir,
|
||||||
|
Commit: captured.Commit,
|
||||||
|
Output: request.Output,
|
||||||
|
Settings: request.Validation,
|
||||||
|
}); 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 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
|
||||||
|
}
|
||||||
497
internal/candidate/check_test.go
Normal file
497
internal/candidate/check_test.go
Normal file
@@ -0,0 +1,497 @@
|
|||||||
|
package candidate
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/validation"
|
||||||
|
)
|
||||||
|
|
||||||
|
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")
|
||||||
|
writeTestFile(t, repository, "guide.md", "# Guide\n[section](#guide)\n")
|
||||||
|
gitRun(t, repository, "add", "guide.md")
|
||||||
|
gitRun(t, repository, "commit", "-m", "add Markdown guide")
|
||||||
|
calls := 0
|
||||||
|
var seen Candidate
|
||||||
|
candidate, err := Check(context.Background(), Request{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Example Product",
|
||||||
|
Version: testVersion,
|
||||||
|
Validation: validation.Settings{Markdown: &validation.MarkdownSettings{}},
|
||||||
|
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 TestCheckStopsBeforeProductAndBuildCallbacksWhenGoFormatFails(t *testing.T) {
|
||||||
|
repository := newRepository(t, "# Example Product v1.2.3\n\nRelease note.\n")
|
||||||
|
writeTestFile(t, repository, "unformatted.go", "package candidate\nfunc Value( ) int{return 1}\n")
|
||||||
|
gitRun(t, repository, "add", "unformatted.go")
|
||||||
|
gitRun(t, repository, "commit", "-m", "add unformatted Go source")
|
||||||
|
productCalls := 0
|
||||||
|
buildCalls := 0
|
||||||
|
_, err := Check(context.Background(), Request{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Example Product",
|
||||||
|
Version: testVersion,
|
||||||
|
Validation: validation.Settings{GoFormat: true},
|
||||||
|
AdditionalChecks: func(context.Context, Candidate) error {
|
||||||
|
productCalls++
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
AfterValidate: func(context.Context, Candidate) error {
|
||||||
|
buildCalls++
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
var failure *validation.Failure
|
||||||
|
if !errors.As(err, &failure) || failure.Check != validation.GoFormat {
|
||||||
|
t.Fatalf("Check error = %v, want go-format failure", err)
|
||||||
|
}
|
||||||
|
if productCalls != 0 || buildCalls != 0 {
|
||||||
|
t.Fatalf("product callback calls = %d, build callback calls = %d; want neither after formatting failure", productCalls, buildCalls)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckStopsBeforeProductAndBuildCallbacksWhenMarkdownBoundaryFails(t *testing.T) {
|
||||||
|
repository := newRepository(t, "# Example Product v1.2.3\n\nRelease note.\n")
|
||||||
|
writeTestFile(t, repository, "guide.md", "[outside](../../outside.md)\n")
|
||||||
|
gitRun(t, repository, "add", "guide.md")
|
||||||
|
gitRun(t, repository, "commit", "-m", "add outside Markdown destination")
|
||||||
|
productCalls := 0
|
||||||
|
buildCalls := 0
|
||||||
|
_, err := Check(context.Background(), Request{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Example Product",
|
||||||
|
Version: testVersion,
|
||||||
|
Validation: validation.Settings{
|
||||||
|
Markdown: &validation.MarkdownSettings{EnforceCheckoutBoundary: true},
|
||||||
|
},
|
||||||
|
AdditionalChecks: func(context.Context, Candidate) error {
|
||||||
|
productCalls++
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
AfterValidate: func(context.Context, Candidate) error {
|
||||||
|
buildCalls++
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
var failure *validation.Failure
|
||||||
|
if !errors.As(err, &failure) || failure.Check != validation.MarkdownLinks {
|
||||||
|
t.Fatalf("Check() error = %v, want markdown-links failure", err)
|
||||||
|
}
|
||||||
|
if productCalls != 0 || buildCalls != 0 {
|
||||||
|
t.Fatalf("product callback calls = %d, build callback calls = %d; want neither after Markdown failure", productCalls, buildCalls)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckReportsCommittedWorkspaceFilesWhenGoWorkspaceIsDisabled(t *testing.T) {
|
||||||
|
t.Setenv("GOWORK", "off")
|
||||||
|
repository := newRepository(t, "# Example Product v1.2.3\n\nRelease note.\n")
|
||||||
|
writeTestFile(t, repository, "go.work", "go 1.25.0\n")
|
||||||
|
writeTestFile(t, repository, "nested/go.work.sum", "workspace-sum\n")
|
||||||
|
if err := os.MkdirAll(filepath.Join(repository, "linked"), 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.Symlink("../go.work", filepath.Join(repository, "linked", "go.work")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
gitRun(t, repository, "add", "go.work", "nested/go.work.sum", "linked/go.work")
|
||||||
|
gitRun(t, repository, "commit", "-m", "add workspace files")
|
||||||
|
_, err := Check(context.Background(), Request{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Example Product",
|
||||||
|
Version: testVersion,
|
||||||
|
Validation: validation.Settings{ModuleDistribution: validation.ModuleDistributionSettings{
|
||||||
|
WorkspaceFiles: true,
|
||||||
|
}},
|
||||||
|
})
|
||||||
|
var failure *validation.Failure
|
||||||
|
if !errors.As(err, &failure) || failure.Check != validation.WorkspaceFiles {
|
||||||
|
t.Fatalf("Check error = %v, want workspace-files failure", err)
|
||||||
|
}
|
||||||
|
want := map[string]bool{
|
||||||
|
"go.work": false,
|
||||||
|
"linked/go.work": false,
|
||||||
|
"nested/go.work.sum": false,
|
||||||
|
}
|
||||||
|
if len(failure.Findings) != len(want) {
|
||||||
|
t.Fatalf("workspace findings = %#v, want %d paths", failure.Findings, len(want))
|
||||||
|
}
|
||||||
|
for _, finding := range failure.Findings {
|
||||||
|
if _, ok := want[finding.Path]; !ok {
|
||||||
|
t.Errorf("unexpected workspace path %q", finding.Path)
|
||||||
|
}
|
||||||
|
want[finding.Path] = true
|
||||||
|
}
|
||||||
|
for path, found := range want {
|
||||||
|
if !found {
|
||||||
|
t.Errorf("workspace path %q was not reported", path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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())
|
||||||
|
}
|
||||||
|
var failure *validation.Failure
|
||||||
|
if !errors.As(err, &failure) || failure.Check != validation.GoTest {
|
||||||
|
t.Fatalf("Check() error = %v; want a go-test validation failure", err)
|
||||||
|
}
|
||||||
|
var exitErr *exec.ExitError
|
||||||
|
if !errors.As(err, &exitErr) {
|
||||||
|
t.Fatalf("Check() error = %v; want the Go process exit error preserved", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
214
internal/git/source.go
Normal file
214
internal/git/source.go
Normal file
@@ -0,0 +1,214 @@
|
|||||||
|
package git
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"path"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/process"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TreeEntry records one committed path and its Git object metadata.
|
||||||
|
type TreeEntry struct {
|
||||||
|
Path string
|
||||||
|
ObjectID string
|
||||||
|
Mode string
|
||||||
|
Type string
|
||||||
|
Size int64
|
||||||
|
HasSize bool
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReadTree enumerates all entries in a commit and records blob sizes. Paths
|
||||||
|
// are NUL-delimited by Git so whitespace in a filename is preserved.
|
||||||
|
func ReadTree(ctx context.Context, repositoryDir, commit string) ([]TreeEntry, error) {
|
||||||
|
if !validObjectID(commit) {
|
||||||
|
return nil, fmt.Errorf("invalid commit object ID %q", commit)
|
||||||
|
}
|
||||||
|
output, err := readLocalObjects(ctx, repositoryDir, nil, "ls-tree", "-r", "-z", "--full-tree", commit)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("enumerate committed tree %s: %w", commit, err)
|
||||||
|
}
|
||||||
|
entries, err := parseTreeEntries(output)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("parse committed tree %s: %w", commit, err)
|
||||||
|
}
|
||||||
|
if err := populateBlobSizes(ctx, repositoryDir, entries); err != nil {
|
||||||
|
return nil, fmt.Errorf("read committed blob sizes for %s: %w", commit, err)
|
||||||
|
}
|
||||||
|
return entries, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReadBlob reads the bytes for a Git blob object ID without consulting the
|
||||||
|
// worktree.
|
||||||
|
func ReadBlob(ctx context.Context, repositoryDir, objectID string) ([]byte, error) {
|
||||||
|
if !validObjectID(objectID) {
|
||||||
|
return nil, fmt.Errorf("invalid blob object ID %q", objectID)
|
||||||
|
}
|
||||||
|
content, err := readLocalObjects(ctx, repositoryDir, nil, "cat-file", "blob", objectID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("read blob %s: %w", objectID, err)
|
||||||
|
}
|
||||||
|
return content, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseTreeEntries(output []byte) ([]TreeEntry, error) {
|
||||||
|
if len(output) == 0 {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
var entries []TreeEntry
|
||||||
|
for _, record := range bytes.Split(output, []byte{0}) {
|
||||||
|
if len(record) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
tab := bytes.IndexByte(record, '\t')
|
||||||
|
if tab < 0 {
|
||||||
|
return nil, fmt.Errorf("tree record has no path separator")
|
||||||
|
}
|
||||||
|
fields := strings.Fields(string(record[:tab]))
|
||||||
|
if len(fields) != 3 || !validObjectID(fields[2]) {
|
||||||
|
return nil, fmt.Errorf("invalid tree record metadata %q", record[:tab])
|
||||||
|
}
|
||||||
|
entries = append(entries, TreeEntry{
|
||||||
|
Mode: fields[0],
|
||||||
|
Type: fields[1],
|
||||||
|
ObjectID: fields[2],
|
||||||
|
Path: string(record[tab+1:]),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return entries, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func populateBlobSizes(ctx context.Context, repositoryDir string, entries []TreeEntry) error {
|
||||||
|
var blobIndexes []int
|
||||||
|
var input strings.Builder
|
||||||
|
for index := range entries {
|
||||||
|
if entries[index].Type != "blob" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
blobIndexes = append(blobIndexes, index)
|
||||||
|
input.WriteString(entries[index].ObjectID)
|
||||||
|
input.WriteByte('\n')
|
||||||
|
}
|
||||||
|
if len(blobIndexes) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
output, err := readLocalObjects(ctx, repositoryDir, strings.NewReader(input.String()),
|
||||||
|
"cat-file", "--batch-check=%(objectname) %(objecttype) %(objectsize)")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
lines := strings.Split(strings.TrimSuffix(string(output), "\n"), "\n")
|
||||||
|
if len(lines) != len(blobIndexes) {
|
||||||
|
return fmt.Errorf("git returned %d blob sizes for %d blobs", len(lines), len(blobIndexes))
|
||||||
|
}
|
||||||
|
for index, line := range lines {
|
||||||
|
fields := strings.Fields(line)
|
||||||
|
entry := &entries[blobIndexes[index]]
|
||||||
|
if len(fields) == 2 && fields[0] == entry.ObjectID && fields[1] == "missing" {
|
||||||
|
return fmt.Errorf("committed blob %s is unavailable locally", entry.ObjectID)
|
||||||
|
}
|
||||||
|
if len(fields) != 3 || fields[0] != entry.ObjectID || fields[1] != "blob" {
|
||||||
|
return fmt.Errorf("unexpected blob size record %q", line)
|
||||||
|
}
|
||||||
|
size, err := strconv.ParseInt(fields[2], 10, 64)
|
||||||
|
if err != nil || size < 0 {
|
||||||
|
return fmt.Errorf("invalid blob size in record %q", line)
|
||||||
|
}
|
||||||
|
entry.Size = size
|
||||||
|
entry.HasSize = true
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// readLocalObjects keeps source inspection separate from network preparation.
|
||||||
|
func readLocalObjects(ctx context.Context, repositoryDir string, input io.Reader, args ...string) ([]byte, error) {
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
err := process.Run(ctx, process.Invocation{
|
||||||
|
Args: append([]string{"git"}, args...),
|
||||||
|
Dir: repositoryDir,
|
||||||
|
// Disable transports as well for Git versions predating lazy-fetch control.
|
||||||
|
Env: map[string]string{"GIT_NO_LAZY_FETCH": "1", "GIT_ALLOW_PROTOCOL": ""},
|
||||||
|
Stdin: input,
|
||||||
|
Stdout: &stdout,
|
||||||
|
Stderr: &stderr,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
if message := strings.TrimSpace(stderr.String()); message != "" {
|
||||||
|
return nil, fmt.Errorf("read local Git objects: %s: %w", message, err)
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return stdout.Bytes(), nil
|
||||||
|
}
|
||||||
91
internal/git/source_test.go
Normal file
91
internal/git/source_test.go
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
package git
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"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 TestCandidateObjectReadsStayLocalInPartialClones(t *testing.T) {
|
||||||
|
fixture := newRemoteFixture(t)
|
||||||
|
gitRun(t, fixture.work, "config", "uploadpack.allowFilter", "true")
|
||||||
|
blob := strings.TrimSpace(gitText(t, fixture.work, "rev-parse", "HEAD:source.txt"))
|
||||||
|
for _, filter := range []string{"blob:none", "tree:0"} {
|
||||||
|
t.Run(filter, func(t *testing.T) {
|
||||||
|
repository := filepath.Join(t.TempDir(), "partial")
|
||||||
|
gitRun(t, fixture.work, "clone", "--filter="+filter, "--no-checkout", "file://"+filepath.ToSlash(fixture.work), repository)
|
||||||
|
before := gitText(t, repository, "cat-file", "--batch-all-objects", "--batch-check=%(objectname)")
|
||||||
|
if strings.Contains(before, blob) {
|
||||||
|
t.Fatal("fixture contains the filtered blob")
|
||||||
|
}
|
||||||
|
gitRun(t, repository, "config", "remote.origin.url", "ssh://releasekit-test.invalid/source")
|
||||||
|
attempts := filepath.Join(t.TempDir(), "attempts")
|
||||||
|
transport := filepath.Join(t.TempDir(), "ssh")
|
||||||
|
if err := os.WriteFile(transport, []byte("#!/bin/sh\nprintf 'remote accessed\\n' >> \"$RELEASEKIT_GIT_ATTEMPTS\"\nexit 1\n"), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Setenv("GIT_SSH_COMMAND", transport)
|
||||||
|
t.Setenv("RELEASEKIT_GIT_ATTEMPTS", attempts)
|
||||||
|
t.Setenv("GIT_NO_LAZY_FETCH", "0")
|
||||||
|
t.Setenv("GIT_ALLOW_PROTOCOL", "ssh")
|
||||||
|
if _, err := ReadTree(t.Context(), repository, fixture.commit); err == nil {
|
||||||
|
t.Fatal("tree inspection succeeded with unavailable objects")
|
||||||
|
}
|
||||||
|
_, err := ReadBlob(t.Context(), repository, blob)
|
||||||
|
var exitError *exec.ExitError
|
||||||
|
if !errors.As(err, &exitError) {
|
||||||
|
t.Fatalf("blob error %v lost its Git process cause", err)
|
||||||
|
}
|
||||||
|
if data, err := os.ReadFile(attempts); !errors.Is(err, os.ErrNotExist) {
|
||||||
|
t.Fatalf("object inspection invoked remote transport: %q, %v", data, err)
|
||||||
|
}
|
||||||
|
after := gitText(t, repository, "cat-file", "--batch-all-objects", "--batch-check=%(objectname)")
|
||||||
|
if before != after {
|
||||||
|
t.Fatal("object inspection populated the object database")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
78
internal/process/process.go
Normal file
78
internal/process/process.go
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
// 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
|
||||||
|
Stdin io.Reader
|
||||||
|
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
|
||||||
|
command.Stdin = invocation.Stdin
|
||||||
|
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
|
||||||
|
}
|
||||||
197
internal/publish/publish.go
Normal file
197
internal/publish/publish.go
Normal file
@@ -0,0 +1,197 @@
|
|||||||
|
// 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"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/validation"
|
||||||
|
)
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
// ErrUnexpectedPushURL reports that the resolved push URL differs from the
|
||||||
|
// caller's expected publication destination.
|
||||||
|
var ErrUnexpectedPushURL = errors.New("unexpected publication push URL")
|
||||||
|
|
||||||
|
type Request struct {
|
||||||
|
RepositoryDir string
|
||||||
|
Product string
|
||||||
|
Version string
|
||||||
|
Remote string
|
||||||
|
ExpectedPushURL string
|
||||||
|
Validation validation.Settings
|
||||||
|
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 captures a candidate, resolves and checks the optional expected push
|
||||||
|
// URL, then validates the candidate and pushes only its annotated tag object.
|
||||||
|
// It runs one standard Go suite, with the selected settings, 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,
|
||||||
|
Validation: request.Validation,
|
||||||
|
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 request.ExpectedPushURL != "" && request.ExpectedPushURL != endpoint.PushURL {
|
||||||
|
return result, fmt.Errorf("%w: expected %q, resolved %q", ErrUnexpectedPushURL, request.ExpectedPushURL, 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)
|
||||||
|
}
|
||||||
204
internal/validation/compile_test.go
Normal file
204
internal/validation/compile_test.go
Normal file
@@ -0,0 +1,204 @@
|
|||||||
|
package validation
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestRunCompilesTargetsAfterTestAndVetInSelectionOrder(t *testing.T) {
|
||||||
|
logPath := installGoShim(t, "", false)
|
||||||
|
targets := []Target{{OS: "linux", Arch: "amd64"}, {OS: "linux", Arch: "arm64"}, {OS: "darwin", Arch: "arm64"}}
|
||||||
|
err := Run(context.Background(), Request{
|
||||||
|
RepositoryDir: t.TempDir(),
|
||||||
|
Settings: Settings{FullVet: true, CompileTargets: targets},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Run() error = %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var commands []string
|
||||||
|
for _, command := range readGoShimLog(t, logPath) {
|
||||||
|
if strings.HasPrefix(command, "test ") || strings.HasPrefix(command, "vet ") || strings.HasPrefix(command, "build ") {
|
||||||
|
commands = append(commands, command)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(commands) != len(targets)+2 || !strings.HasPrefix(commands[0], "test ") || !strings.HasPrefix(commands[1], "vet ") {
|
||||||
|
t.Fatalf("validation commands = %q, want test, vet, then one build per target", commands)
|
||||||
|
}
|
||||||
|
for index, target := range targets {
|
||||||
|
command := commands[index+2]
|
||||||
|
if !strings.HasPrefix(command, "build ") {
|
||||||
|
t.Fatalf("command %d = %q, want package build", index+2, command)
|
||||||
|
}
|
||||||
|
for _, argument := range []string{"build", "-mod=readonly", "-o " + os.DevNull, "./..."} {
|
||||||
|
if !strings.Contains(" "+command+" ", " "+argument+" ") {
|
||||||
|
t.Errorf("build command %q does not contain %q", command, argument)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if got, want := strings.Fields(command)[0], "build"; got != want {
|
||||||
|
t.Errorf("command = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
if target.OS == "" || target.Arch == "" {
|
||||||
|
t.Fatalf("test target is incomplete: %#v", target)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
environments, err := os.ReadFile(os.Getenv("RELEASEKIT_GO_ENV_LOG"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
got := strings.Split(strings.TrimSpace(string(environments)), "\n")
|
||||||
|
if len(got) != len(targets) {
|
||||||
|
t.Fatalf("static build environments = %q, want %d entries", got, len(targets))
|
||||||
|
}
|
||||||
|
for index, target := range targets {
|
||||||
|
if want := fmt.Sprintf("%s/%s|0", target.OS, target.Arch); got[index] != want {
|
||||||
|
t.Errorf("static build environment %d = %q, want %q", index, got[index], want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRunAttributesTargetCompileFailureAndStops(t *testing.T) {
|
||||||
|
logPath := installGoShim(t, "darwin/arm64", false)
|
||||||
|
targets := []Target{{OS: "linux", Arch: "amd64"}, {OS: "darwin", Arch: "arm64"}, {OS: "windows", Arch: "amd64"}}
|
||||||
|
err := Run(context.Background(), Request{
|
||||||
|
RepositoryDir: t.TempDir(),
|
||||||
|
Settings: Settings{FullVet: true, CompileTargets: targets},
|
||||||
|
})
|
||||||
|
var failure *Failure
|
||||||
|
if !errors.As(err, &failure) || failure.Check != PackageCompile {
|
||||||
|
t.Fatalf("Run() error = %v, want a package-compile failure", err)
|
||||||
|
}
|
||||||
|
if len(failure.Findings) != 1 || failure.Findings[0].Target != "darwin/arm64" {
|
||||||
|
t.Fatalf("package compilation findings = %#v, want target darwin/arm64", failure.Findings)
|
||||||
|
}
|
||||||
|
var exitError *exec.ExitError
|
||||||
|
if !errors.As(err, &exitError) {
|
||||||
|
t.Fatalf("Run() error = %v, want the Go command failure preserved", err)
|
||||||
|
}
|
||||||
|
var commands []string
|
||||||
|
for _, command := range readGoShimLog(t, logPath) {
|
||||||
|
if strings.HasPrefix(command, "test ") || strings.HasPrefix(command, "vet ") || strings.HasPrefix(command, "build ") {
|
||||||
|
commands = append(commands, command)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(commands) != 4 || !strings.HasPrefix(commands[0], "test ") || !strings.HasPrefix(commands[1], "vet ") || !strings.HasPrefix(commands[2], "build ") || !strings.HasPrefix(commands[3], "build ") {
|
||||||
|
t.Fatalf("validation commands after target failure = %q, want test, vet, two builds", commands)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRunRejectsIncompleteCompileTargets(t *testing.T) {
|
||||||
|
installGoShim(t, "", false)
|
||||||
|
for _, target := range []Target{{OS: "linux"}, {Arch: "amd64"}, {OS: " ", Arch: "amd64"}, {OS: "linux/other", Arch: "amd64"}} {
|
||||||
|
err := Run(context.Background(), Request{
|
||||||
|
RepositoryDir: t.TempDir(),
|
||||||
|
Settings: Settings{CompileTargets: []Target{target}},
|
||||||
|
})
|
||||||
|
var failure *Failure
|
||||||
|
if !errors.As(err, &failure) || failure.Check != PackageCompile {
|
||||||
|
t.Errorf("Run(%#v) error = %v, want a package-compile validation failure", target, err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if len(failure.Findings) != 1 || failure.Findings[0].Target != target.OS+"/"+target.Arch {
|
||||||
|
t.Errorf("Run(%#v) findings = %#v, want the incomplete target", target, failure.Findings)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRunCompilesSourceOnlyAndExecutablePackagesWithoutArtifacts(t *testing.T) {
|
||||||
|
fixtures := []struct {
|
||||||
|
name string
|
||||||
|
files map[string]string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "source library",
|
||||||
|
files: map[string]string{
|
||||||
|
"library.go": "package fixture\n\nconst Value = 1\n",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "single main",
|
||||||
|
files: map[string]string{
|
||||||
|
"library.go": "package fixture\n\nconst Value = 1\n",
|
||||||
|
"cmd/app/main.go": "package main\n\nfunc main() {}\n",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "multiple mains with repeated basenames",
|
||||||
|
files: map[string]string{
|
||||||
|
"library.go": "package fixture\n\nconst Value = 1\n",
|
||||||
|
"cmd/one/tool/main.go": "package main\n\nfunc main() {}\n",
|
||||||
|
"cmd/two/tool/main.go": "package main\n\nfunc main() {}\n",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, fixture := range fixtures {
|
||||||
|
t.Run(fixture.name, func(t *testing.T) {
|
||||||
|
module := writeCompileFixture(t, fixture.files)
|
||||||
|
before := readCompileFixture(t, module, fixture.files)
|
||||||
|
var targets []Target
|
||||||
|
if fixture.name == "source library" {
|
||||||
|
targets = []Target{{OS: "linux", Arch: "amd64"}, {OS: "linux", Arch: "arm64"}, {OS: "darwin", Arch: "arm64"}}
|
||||||
|
} else {
|
||||||
|
targets = []Target{{OS: "linux", Arch: "amd64"}}
|
||||||
|
}
|
||||||
|
if err := Run(context.Background(), Request{
|
||||||
|
RepositoryDir: module,
|
||||||
|
Settings: Settings{CompileTargets: targets},
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatalf("Run() error = %v", err)
|
||||||
|
}
|
||||||
|
after := readCompileFixture(t, module, fixture.files)
|
||||||
|
for path, contents := range before {
|
||||||
|
if string(after[path]) != string(contents) {
|
||||||
|
t.Errorf("candidate file %q changed during compilation", path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeCompileFixture(t *testing.T, files map[string]string) string {
|
||||||
|
t.Helper()
|
||||||
|
module := t.TempDir()
|
||||||
|
if err := os.WriteFile(filepath.Join(module, "go.mod"), []byte("module example.com/compilefixture\n\ngo 1.25.0\n"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for path, contents := range files {
|
||||||
|
filename := filepath.Join(module, filepath.FromSlash(path))
|
||||||
|
if err := os.MkdirAll(filepath.Dir(filename), 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(filename, []byte(contents), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return module
|
||||||
|
}
|
||||||
|
|
||||||
|
func readCompileFixture(t *testing.T, module string, files map[string]string) map[string][]byte {
|
||||||
|
t.Helper()
|
||||||
|
contents := make(map[string][]byte, len(files)+1)
|
||||||
|
for _, path := range append([]string{"go.mod"}, fixturePaths(files)...) {
|
||||||
|
data, err := os.ReadFile(filepath.Join(module, filepath.FromSlash(path)))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
contents[path] = data
|
||||||
|
}
|
||||||
|
return contents
|
||||||
|
}
|
||||||
|
|
||||||
|
func fixturePaths(files map[string]string) []string {
|
||||||
|
paths := make([]string, 0, len(files))
|
||||||
|
for path := range files {
|
||||||
|
paths = append(paths, path)
|
||||||
|
}
|
||||||
|
return paths
|
||||||
|
}
|
||||||
296
internal/validation/destination_test.go
Normal file
296
internal/validation/destination_test.go
Normal file
@@ -0,0 +1,296 @@
|
|||||||
|
package validation
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestResolveDestinationClassifiesCommittedPaths(t *testing.T) {
|
||||||
|
repository := newTreeRepository(t)
|
||||||
|
writeTreeFile(t, repository, "README.md", []byte("root\n"))
|
||||||
|
writeTreeFile(t, repository, "docs/page.md", []byte("source\n"))
|
||||||
|
writeTreeFile(t, repository, "docs/target.md", []byte("target\n"))
|
||||||
|
writeTreeFile(t, repository, "docs/nested/item.txt", []byte("nested\n"))
|
||||||
|
writeTreeFile(t, repository, "docs/dir/item.txt", []byte("directory\n"))
|
||||||
|
for name, target := range map[string]string{
|
||||||
|
"docs/inside": "target.md",
|
||||||
|
"docs/through-dir": "nested",
|
||||||
|
"docs/outside": "../../neighbor/file",
|
||||||
|
"docs/absolute": "/outside/file",
|
||||||
|
"docs/dangling": "missing-target",
|
||||||
|
"docs/cycle-a": "cycle-b",
|
||||||
|
"docs/cycle-b": "cycle-a",
|
||||||
|
} {
|
||||||
|
if err := os.Symlink(target, filepath.Join(repository, filepath.FromSlash(name))); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
submoduleSource := newTreeRepository(t)
|
||||||
|
writeTreeFile(t, submoduleSource, "sub.txt", []byte("submodule\n"))
|
||||||
|
gitTree(t, submoduleSource, "add", "--all")
|
||||||
|
gitTree(t, submoduleSource, "commit", "-m", "create submodule source")
|
||||||
|
submoduleOID := strings.TrimSpace(gitTree(t, submoduleSource, "rev-parse", "HEAD"))
|
||||||
|
gitTree(t, repository, "add", "--all")
|
||||||
|
gitTree(t, repository, "update-index", "--add", "--cacheinfo", "160000,"+submoduleOID+",docs/submodule")
|
||||||
|
gitTree(t, repository, "commit", "-m", "capture destination fixtures")
|
||||||
|
commit := strings.TrimSpace(gitTree(t, repository, "rev-parse", "HEAD"))
|
||||||
|
tree, err := ReadCandidateTree(context.Background(), repository, commit)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.Remove(filepath.Join(repository, "docs", "inside")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.Symlink("../../neighbor/file", filepath.Join(repository, "docs", "inside")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
source string
|
||||||
|
destination string
|
||||||
|
kind DestinationKind
|
||||||
|
path string
|
||||||
|
}{
|
||||||
|
{name: "relative file", source: "docs/page.md", destination: "target.md", kind: DestinationEntry, path: "docs/target.md"},
|
||||||
|
{name: "parent traversal inside root", source: "docs/page.md", destination: "../README.md", kind: DestinationEntry, path: "README.md"},
|
||||||
|
{name: "outside root", source: "docs/page.md", destination: "../../neighbor/file", kind: DestinationOutsideCheckout, path: "../neighbor/file"},
|
||||||
|
{name: "repository root directory", source: "docs/page.md", destination: "..", kind: DestinationDirectory, path: "."},
|
||||||
|
{name: "directory", source: "docs/page.md", destination: "dir", kind: DestinationDirectory, path: "docs/dir"},
|
||||||
|
{name: "symlink to file", source: "docs/page.md", destination: "inside", kind: DestinationEntry, path: "docs/target.md"},
|
||||||
|
{name: "symlinked directory", source: "docs/page.md", destination: "through-dir/item.txt", kind: DestinationEntry, path: "docs/nested/item.txt"},
|
||||||
|
{name: "absolute symlink", source: "docs/page.md", destination: "absolute", kind: DestinationOutsideCheckout, path: "/outside/file"},
|
||||||
|
{name: "missing entry", source: "docs/page.md", destination: "missing", kind: DestinationMissing, path: "docs/missing"},
|
||||||
|
{name: "dangling symlink", source: "docs/page.md", destination: "dangling", kind: DestinationMissing, path: "docs/missing-target"},
|
||||||
|
{name: "symlink cycle", source: "docs/page.md", destination: "cycle-a", kind: DestinationSymlinkCycle, path: "docs/cycle-a"},
|
||||||
|
{name: "submodule contents", source: "docs/page.md", destination: "submodule/child", kind: DestinationSubmodule, path: "docs/submodule/child"},
|
||||||
|
}
|
||||||
|
for _, test := range cases {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
got, err := tree.ResolveDestination(context.Background(), test.source, test.destination)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ResolveDestination() error = %v", err)
|
||||||
|
}
|
||||||
|
if got.Kind != test.kind || got.Path != test.path {
|
||||||
|
t.Fatalf("ResolveDestination() = %#v, want kind %q path %q", got, test.kind, test.path)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestResolveDestinationHandlesExpandingCyclesAndRepeatedLinks(t *testing.T) {
|
||||||
|
repository := newTreeRepository(t)
|
||||||
|
writeTreeFile(t, repository, "README.md", []byte("source\n"))
|
||||||
|
for name, target := range map[string]string{
|
||||||
|
"direct": "direct/child",
|
||||||
|
"mutual-a": "mutual-b/child",
|
||||||
|
"mutual-b": "mutual-a/child",
|
||||||
|
"alias": ".",
|
||||||
|
} {
|
||||||
|
if err := os.Symlink(target, filepath.Join(repository, name)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
gitTree(t, repository, "add", "--all")
|
||||||
|
gitTree(t, repository, "commit", "-m", "capture recursive links")
|
||||||
|
tree, err := ReadCandidateTree(t.Context(), repository, strings.TrimSpace(gitTree(t, repository, "rev-parse", "HEAD")))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, test := range []struct {
|
||||||
|
destination string
|
||||||
|
kind DestinationKind
|
||||||
|
}{
|
||||||
|
{"direct", DestinationSymlinkCycle},
|
||||||
|
{"mutual-a", DestinationSymlinkCycle},
|
||||||
|
{"alias/alias/README.md", DestinationEntry},
|
||||||
|
} {
|
||||||
|
t.Run(test.destination, func(t *testing.T) {
|
||||||
|
type result struct {
|
||||||
|
destination Destination
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
done := make(chan result, 1)
|
||||||
|
ctx, cancel := context.WithTimeout(t.Context(), time.Second)
|
||||||
|
defer cancel()
|
||||||
|
go func() {
|
||||||
|
destination, err := tree.ResolveDestination(ctx, "README.md", test.destination)
|
||||||
|
done <- result{destination, err}
|
||||||
|
}()
|
||||||
|
select {
|
||||||
|
case got := <-done:
|
||||||
|
if got.err != nil || got.destination.Kind != test.kind {
|
||||||
|
t.Fatalf("resolution = %#v, %v; want %s", got.destination, got.err, test.kind)
|
||||||
|
}
|
||||||
|
if test.kind == DestinationEntry && got.destination.Path != "README.md" {
|
||||||
|
t.Fatalf("finite repeated link resolved to %q", got.destination.Path)
|
||||||
|
}
|
||||||
|
case <-ctx.Done():
|
||||||
|
t.Fatal("symlink resolution did not finish")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithCancel(t.Context())
|
||||||
|
cancel()
|
||||||
|
if _, err := tree.ResolveDestination(ctx, "README.md", "alias/README.md"); !errors.Is(err, context.Canceled) {
|
||||||
|
t.Fatalf("canceled resolution error = %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestResolveDestinationIgnoresNeighboringFiles(t *testing.T) {
|
||||||
|
repository := newTreeRepository(t)
|
||||||
|
writeTreeFile(t, repository, "docs/page.md", []byte("source\n"))
|
||||||
|
if err := os.Symlink("../../neighbor/file", filepath.Join(repository, "docs", "outside")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
gitTree(t, repository, "add", "--all")
|
||||||
|
gitTree(t, repository, "commit", "-m", "capture outside link")
|
||||||
|
commit := strings.TrimSpace(gitTree(t, repository, "rev-parse", "HEAD"))
|
||||||
|
tree, err := ReadCandidateTree(context.Background(), repository, commit)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
gotWithoutNeighbor, err := tree.ResolveDestination(context.Background(), "docs/page.md", "outside")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
neighbor := filepath.Join(filepath.Dir(repository), "neighbor", "file")
|
||||||
|
if err := os.MkdirAll(filepath.Dir(neighbor), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(neighbor, []byte("outside source\n"), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
gotWithNeighbor, err := tree.ResolveDestination(context.Background(), "docs/page.md", "outside")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if gotWithNeighbor != gotWithoutNeighbor || gotWithNeighbor.Kind != DestinationOutsideCheckout {
|
||||||
|
t.Fatalf("neighbor changed resolution: absent=%#v present=%#v", gotWithoutNeighbor, gotWithNeighbor)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestResolveDestinationPreservesParentTraversalOrder(t *testing.T) {
|
||||||
|
repository := newTreeRepository(t)
|
||||||
|
for _, name := range []string{"README.md", "docs/file.md", "nested/file.md", "nested/inner/item.txt"} {
|
||||||
|
writeTreeFile(t, repository, name, []byte("captured\n"))
|
||||||
|
}
|
||||||
|
for name, target := range map[string]string{
|
||||||
|
"docs/link": "../nested/inner",
|
||||||
|
"docs/parent-link": "link/../file.md",
|
||||||
|
"escape": "../neighbor",
|
||||||
|
} {
|
||||||
|
if err := os.Symlink(target, filepath.Join(repository, filepath.FromSlash(name))); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
gitTree(t, repository, "add", "--all")
|
||||||
|
gitTree(t, repository, "commit", "-m", "capture parent traversal")
|
||||||
|
tree, err := ReadCandidateTree(t.Context(), repository, strings.TrimSpace(gitTree(t, repository, "rev-parse", "HEAD")))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, test := range []struct {
|
||||||
|
destination string
|
||||||
|
kind DestinationKind
|
||||||
|
resolved string
|
||||||
|
}{
|
||||||
|
{"docs/link/../file.md", DestinationEntry, "nested/file.md"},
|
||||||
|
{"docs/parent-link", DestinationEntry, "nested/file.md"},
|
||||||
|
{"escape/../README.md", DestinationOutsideCheckout, ""},
|
||||||
|
{"missing/../README.md", DestinationMissing, ""},
|
||||||
|
{"README.md/../README.md", DestinationMissing, ""},
|
||||||
|
{"README.md/.", DestinationMissing, ""},
|
||||||
|
} {
|
||||||
|
t.Run(test.destination, func(t *testing.T) {
|
||||||
|
got, err := tree.ResolveDestination(t.Context(), "README.md", test.destination)
|
||||||
|
if err != nil || got.Kind != test.kind || (test.resolved != "" && got.Path != test.resolved) {
|
||||||
|
t.Fatalf("resolution = %#v, %v; want %s %q", got, err, test.kind, test.resolved)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
before, err := tree.ResolveDestination(t.Context(), "README.md", "escape/../README.md")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
neighbor := filepath.Join(filepath.Dir(repository), "neighbor")
|
||||||
|
if err := os.MkdirAll(neighbor, 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(filepath.Join(neighbor, "file.md"), []byte("neighbor"), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
after, err := tree.ResolveDestination(t.Context(), "README.md", "escape/../README.md")
|
||||||
|
if err != nil || before != after {
|
||||||
|
t.Fatalf("neighbor changed resolution: %#v -> %#v, %v", before, after, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestResolveDestinationMapsAbsolutePathsIntoCandidate(t *testing.T) {
|
||||||
|
repository := newTreeRepository(t)
|
||||||
|
for _, name := range []string{"README.md", "docs/file.md", "nested/file.md", "nested/inner/item.txt"} {
|
||||||
|
writeTreeFile(t, repository, name, []byte("captured\n"))
|
||||||
|
}
|
||||||
|
for name, target := range map[string]string{
|
||||||
|
"absolute-file": filepath.ToSlash(filepath.Join(repository, "README.md")),
|
||||||
|
"absolute-directory": filepath.ToSlash(filepath.Join(repository, "nested", "inner")),
|
||||||
|
"absolute-outside": filepath.ToSlash(repository + "-neighbor/README.md"),
|
||||||
|
"docs/link": "../nested/inner",
|
||||||
|
"absolute-parent": filepath.ToSlash(repository) + "/docs/link/../file.md",
|
||||||
|
} {
|
||||||
|
if err := os.Symlink(target, filepath.Join(repository, filepath.FromSlash(name))); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
gitTree(t, repository, "add", "--all")
|
||||||
|
gitTree(t, repository, "commit", "-m", "capture absolute links")
|
||||||
|
tree, err := ReadCandidateTree(t.Context(), repository, strings.TrimSpace(gitTree(t, repository, "rev-parse", "HEAD")))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.Remove(filepath.Join(repository, "README.md")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
writeTreeFile(t, repository, "live-only.md", []byte("not committed"))
|
||||||
|
neighbor := repository + "-neighbor"
|
||||||
|
if err := os.MkdirAll(neighbor, 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(filepath.Join(neighbor, "README.md"), []byte("outside"), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() {
|
||||||
|
if err := os.RemoveAll(neighbor); err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
root := filepath.ToSlash(repository)
|
||||||
|
for _, test := range []struct {
|
||||||
|
destination string
|
||||||
|
kind DestinationKind
|
||||||
|
resolved string
|
||||||
|
}{
|
||||||
|
{root + "/README.md", DestinationEntry, "README.md"},
|
||||||
|
{root, DestinationDirectory, "."},
|
||||||
|
{root + "/nested/inner", DestinationDirectory, "nested/inner"},
|
||||||
|
{"absolute-file", DestinationEntry, "README.md"},
|
||||||
|
{"absolute-directory/item.txt", DestinationEntry, "nested/inner/item.txt"},
|
||||||
|
{root + "/docs/link/../file.md", DestinationEntry, "nested/file.md"},
|
||||||
|
{"absolute-parent", DestinationEntry, "nested/file.md"},
|
||||||
|
{root + "/live-only.md", DestinationMissing, "live-only.md"},
|
||||||
|
{root + "-neighbor/README.md", DestinationOutsideCheckout, root + "-neighbor/README.md"},
|
||||||
|
{"absolute-outside", DestinationOutsideCheckout, root + "-neighbor/README.md"},
|
||||||
|
} {
|
||||||
|
t.Run(test.destination, func(t *testing.T) {
|
||||||
|
got, err := tree.ResolveDestination(t.Context(), "README.md", test.destination)
|
||||||
|
if err != nil || got.Kind != test.kind || got.Path != test.resolved {
|
||||||
|
t.Fatalf("resolution = %#v, %v; want %s %q", got, err, test.kind, test.resolved)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
112
internal/validation/diagnostic.go
Normal file
112
internal/validation/diagnostic.go
Normal file
@@ -0,0 +1,112 @@
|
|||||||
|
package validation
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Check identifies one shared validation check.
|
||||||
|
type Check string
|
||||||
|
|
||||||
|
const (
|
||||||
|
// GoTest identifies the base Go test suite.
|
||||||
|
GoTest Check = "go-test"
|
||||||
|
// GoVet identifies the separate full vet pass.
|
||||||
|
GoVet Check = "go-vet"
|
||||||
|
// PackageCompile identifies selected-target package compilation.
|
||||||
|
PackageCompile Check = "package-compile"
|
||||||
|
// GoFormat identifies committed Go source formatting.
|
||||||
|
GoFormat Check = "go-format"
|
||||||
|
// WorkspaceFiles identifies committed workspace files in module source.
|
||||||
|
WorkspaceFiles Check = "workspace-files"
|
||||||
|
// LocalReplacements identifies filesystem replacements in committed modules.
|
||||||
|
LocalReplacements Check = "local-replacements"
|
||||||
|
// FileSize identifies committed blobs that exceed a selected size limit.
|
||||||
|
FileSize Check = "file-size"
|
||||||
|
// MarkdownLinks identifies missing committed Markdown destinations or anchors.
|
||||||
|
MarkdownLinks Check = "markdown-links"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Finding describes a validation observation at an optional source location.
|
||||||
|
type Finding struct {
|
||||||
|
Path string
|
||||||
|
Line int
|
||||||
|
Column int
|
||||||
|
Message string
|
||||||
|
Target string
|
||||||
|
Directive string
|
||||||
|
}
|
||||||
|
|
||||||
|
// FileSizeMeasurement describes a measured file size and its selected limit.
|
||||||
|
type FileSizeMeasurement struct {
|
||||||
|
Bytes int64
|
||||||
|
LimitBytes int64
|
||||||
|
}
|
||||||
|
|
||||||
|
// Failure describes a failed shared validation check and preserves its cause.
|
||||||
|
type Failure struct {
|
||||||
|
Check Check
|
||||||
|
Findings []Finding
|
||||||
|
Measurement *FileSizeMeasurement
|
||||||
|
Cause error
|
||||||
|
}
|
||||||
|
|
||||||
|
// Error returns a useful summary of the failed check.
|
||||||
|
func (failure *Failure) Error() string {
|
||||||
|
return formatFailure(failure)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unwrap returns the underlying validation error.
|
||||||
|
func (failure *Failure) Unwrap() error {
|
||||||
|
if failure == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return failure.Cause
|
||||||
|
}
|
||||||
|
|
||||||
|
func formatFailure(failure *Failure) string {
|
||||||
|
if failure == nil {
|
||||||
|
return "<nil>"
|
||||||
|
}
|
||||||
|
var summary strings.Builder
|
||||||
|
if failure.Check == "" {
|
||||||
|
summary.WriteString("validation failed")
|
||||||
|
} else {
|
||||||
|
fmt.Fprintf(&summary, "%s validation failed", failure.Check)
|
||||||
|
}
|
||||||
|
for _, finding := range failure.Findings {
|
||||||
|
summary.WriteString(": ")
|
||||||
|
if finding.Path != "" {
|
||||||
|
summary.WriteString(finding.Path)
|
||||||
|
if finding.Line > 0 {
|
||||||
|
fmt.Fprintf(&summary, ":%d", finding.Line)
|
||||||
|
if finding.Column > 0 {
|
||||||
|
fmt.Fprintf(&summary, ":%d", finding.Column)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
summary.WriteString(": ")
|
||||||
|
}
|
||||||
|
summary.WriteString(finding.Message)
|
||||||
|
if finding.Target != "" {
|
||||||
|
fmt.Fprintf(&summary, " (target %q)", finding.Target)
|
||||||
|
}
|
||||||
|
if finding.Directive != "" {
|
||||||
|
fmt.Fprintf(&summary, " (directive %q)", finding.Directive)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if failure.Measurement != nil {
|
||||||
|
fmt.Fprintf(&summary, ": measured %d bytes against a %d byte limit", failure.Measurement.Bytes, failure.Measurement.LimitBytes)
|
||||||
|
}
|
||||||
|
if failure.Cause != nil {
|
||||||
|
if len(failure.Findings) == 0 && failure.Measurement == nil {
|
||||||
|
summary.WriteString(": ")
|
||||||
|
} else {
|
||||||
|
summary.WriteString("; ")
|
||||||
|
}
|
||||||
|
summary.WriteString(failure.Cause.Error())
|
||||||
|
}
|
||||||
|
return summary.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ error = (*Failure)(nil)
|
||||||
|
var _ interface{ Unwrap() error } = (*Failure)(nil)
|
||||||
49
internal/validation/diagnostic_test.go
Normal file
49
internal/validation/diagnostic_test.go
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
package validation
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestRunPreservesCanceledGoSetup(t *testing.T) {
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
cancel()
|
||||||
|
|
||||||
|
err := Run(ctx, Request{RepositoryDir: t.TempDir()})
|
||||||
|
var failure *Failure
|
||||||
|
if !errors.As(err, &failure) {
|
||||||
|
t.Fatalf("Run() error = %v, want a validation failure", err)
|
||||||
|
}
|
||||||
|
if failure.Check != GoTest {
|
||||||
|
t.Fatalf("failure check = %q, want %q", failure.Check, GoTest)
|
||||||
|
}
|
||||||
|
if !errors.Is(err, context.Canceled) {
|
||||||
|
t.Fatalf("Run() error = %v, want context cancellation preserved", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFailureFormatsDiagnosticsAndUnwrapsCause(t *testing.T) {
|
||||||
|
wantCause := errors.New("underlying check error")
|
||||||
|
failure := &Failure{
|
||||||
|
Check: GoTest,
|
||||||
|
Findings: []Finding{{
|
||||||
|
Path: "README.md",
|
||||||
|
Line: 4,
|
||||||
|
Column: 2,
|
||||||
|
Message: "broken destination",
|
||||||
|
}},
|
||||||
|
Measurement: &FileSizeMeasurement{Bytes: 12, LimitBytes: 10},
|
||||||
|
Cause: wantCause,
|
||||||
|
}
|
||||||
|
|
||||||
|
if !errors.Is(failure, wantCause) {
|
||||||
|
t.Fatalf("Failure does not unwrap its cause")
|
||||||
|
}
|
||||||
|
for _, part := range []string{"go-test", "README.md:4:2", "broken destination", "12 bytes", "10 byte limit", wantCause.Error()} {
|
||||||
|
if !strings.Contains(failure.Error(), part) {
|
||||||
|
t.Errorf("Failure.Error() = %q; want it to include %q", failure.Error(), part)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
52
internal/validation/file_size.go
Normal file
52
internal/validation/file_size.go
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
package validation
|
||||||
|
|
||||||
|
import (
|
||||||
|
"path"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
const defaultFileSizeLimit int64 = 1_000_000
|
||||||
|
|
||||||
|
func checkFileSize(tree *CandidateTree, settings *FileSizeSettings) error {
|
||||||
|
limit := defaultFileSizeLimit
|
||||||
|
if settings.LimitBytes != nil {
|
||||||
|
limit = *settings.LimitBytes
|
||||||
|
}
|
||||||
|
exclusions := normalizedExclusions(settings.Exclusions)
|
||||||
|
for _, entry := range tree.Entries() {
|
||||||
|
if entry.Type != "blob" || !entry.HasSize || excludedByPath(entry.Path, exclusions) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if entry.Size > limit {
|
||||||
|
return &Failure{
|
||||||
|
Check: FileSize,
|
||||||
|
Findings: []Finding{{
|
||||||
|
Path: entry.Path,
|
||||||
|
Message: "committed file exceeds the selected size limit",
|
||||||
|
}},
|
||||||
|
Measurement: &FileSizeMeasurement{Bytes: entry.Size, LimitBytes: limit},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizedExclusions(exclusions []string) []string {
|
||||||
|
result := make([]string, 0, len(exclusions))
|
||||||
|
for _, exclusion := range exclusions {
|
||||||
|
if exclusion == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
result = append(result, path.Clean(exclusion))
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func excludedByPath(filePath string, exclusions []string) bool {
|
||||||
|
for _, exclusion := range exclusions {
|
||||||
|
if exclusion == "." || filePath == exclusion || strings.HasPrefix(filePath, exclusion+"/") {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
192
internal/validation/file_size_test.go
Normal file
192
internal/validation/file_size_test.go
Normal file
@@ -0,0 +1,192 @@
|
|||||||
|
package validation
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/git"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCheckFileSizeUsesStrictLimitsAndDefault(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
limit *int64
|
||||||
|
size int64
|
||||||
|
wantLimit int64
|
||||||
|
wantError bool
|
||||||
|
}{
|
||||||
|
{name: "below", limit: int64Pointer(10), size: 9, wantLimit: 10},
|
||||||
|
{name: "at", limit: int64Pointer(10), size: 10, wantLimit: 10},
|
||||||
|
{name: "above", limit: int64Pointer(10), size: 11, wantLimit: 10, wantError: true},
|
||||||
|
{name: "default at", size: 1_000_000, wantLimit: 1_000_000},
|
||||||
|
{name: "default above", size: 1_000_001, wantLimit: 1_000_000, wantError: true},
|
||||||
|
{name: "zero empty", limit: int64Pointer(0), size: 0},
|
||||||
|
{name: "zero nonempty", limit: int64Pointer(0), size: 1, wantError: true},
|
||||||
|
}
|
||||||
|
for _, test := range tests {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
tree := &CandidateTree{entries: []git.TreeEntry{{
|
||||||
|
Path: "file.bin", Type: "blob", Mode: "100644", Size: test.size, HasSize: true,
|
||||||
|
}}}
|
||||||
|
err := checkFileSize(tree, &FileSizeSettings{LimitBytes: test.limit})
|
||||||
|
if !test.wantError {
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("checkFileSize() error = %v, want nil", err)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
failure, ok := err.(*Failure)
|
||||||
|
if !ok || failure.Check != FileSize || len(failure.Findings) != 1 || failure.Findings[0].Path != "file.bin" {
|
||||||
|
t.Fatalf("checkFileSize() error = %v, want file-size finding", err)
|
||||||
|
}
|
||||||
|
if failure.Measurement == nil || failure.Measurement.Bytes != test.size || failure.Measurement.LimitBytes != test.wantLimit {
|
||||||
|
t.Fatalf("measurement = %#v, want %d bytes against %d", failure.Measurement, test.size, test.wantLimit)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckFileSizeAppliesLiteralPathExclusions(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
entries []git.TreeEntry
|
||||||
|
exclusions []string
|
||||||
|
wantPath string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "directory boundary and normalized paths",
|
||||||
|
entries: []git.TreeEntry{
|
||||||
|
{Path: "assets/icon.png", Type: "blob", Size: 20, HasSize: true},
|
||||||
|
{Path: "assets-other/icon.png", Type: "blob", Size: 20, HasSize: true},
|
||||||
|
},
|
||||||
|
exclusions: []string{"./assets/"},
|
||||||
|
wantPath: "assets-other/icon.png",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "glob metacharacters are literal",
|
||||||
|
entries: []git.TreeEntry{
|
||||||
|
{Path: "[ab].dat", Type: "blob", Size: 20, HasSize: true},
|
||||||
|
{Path: "a.dat", Type: "blob", Size: 20, HasSize: true},
|
||||||
|
},
|
||||||
|
exclusions: []string{"[ab].dat", "literal[set]"},
|
||||||
|
wantPath: "a.dat",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "directory metacharacters are literal",
|
||||||
|
entries: []git.TreeEntry{
|
||||||
|
{Path: "literal[set]/file.dat", Type: "blob", Size: 20, HasSize: true},
|
||||||
|
{Path: "literalx/file.dat", Type: "blob", Size: 20, HasSize: true},
|
||||||
|
},
|
||||||
|
exclusions: []string{"literal[set]"},
|
||||||
|
wantPath: "literalx/file.dat",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "unmatched exclusion",
|
||||||
|
entries: []git.TreeEntry{
|
||||||
|
{Path: "selected.dat", Type: "blob", Size: 20, HasSize: true},
|
||||||
|
},
|
||||||
|
exclusions: []string{"not-present"},
|
||||||
|
wantPath: "selected.dat",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "exact file exclusion",
|
||||||
|
entries: []git.TreeEntry{
|
||||||
|
{Path: "selected.dat", Type: "blob", Size: 20, HasSize: true},
|
||||||
|
{Path: "other.dat", Type: "blob", Size: 20, HasSize: true},
|
||||||
|
},
|
||||||
|
exclusions: []string{"selected.dat"},
|
||||||
|
wantPath: "other.dat",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, test := range tests {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
err := checkFileSize(&CandidateTree{entries: test.entries}, &FileSizeSettings{
|
||||||
|
LimitBytes: int64Pointer(10),
|
||||||
|
Exclusions: test.exclusions,
|
||||||
|
})
|
||||||
|
failure, ok := err.(*Failure)
|
||||||
|
if !ok || failure.Check != FileSize || len(failure.Findings) != 1 || failure.Findings[0].Path != test.wantPath {
|
||||||
|
t.Fatalf("checkFileSize() error = %v, want only %q to exceed the limit", err, test.wantPath)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckFileSizeUsesCommittedBlobSizes(t *testing.T) {
|
||||||
|
repository := newTreeRepository(t)
|
||||||
|
writeTreeFile(t, repository, "small.bin", []byte{0, 1})
|
||||||
|
writeTreeFile(t, repository, "boundary.bin", []byte{0, 1, 2})
|
||||||
|
if err := os.Symlink("small.bin", filepath.Join(repository, "link")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
submodule := newTreeRepository(t)
|
||||||
|
writeTreeFile(t, submodule, "submodule.txt", []byte("submodule"))
|
||||||
|
gitTree(t, submodule, "add", "--all")
|
||||||
|
gitTree(t, submodule, "commit", "-m", "create nested source")
|
||||||
|
submoduleCommit := strings.TrimSpace(gitTree(t, submodule, "rev-parse", "HEAD"))
|
||||||
|
gitTree(t, repository, "add", "--all")
|
||||||
|
gitTree(t, repository, "update-index", "--add", "--cacheinfo", "160000,"+submoduleCommit+",submodule")
|
||||||
|
commit := commitCandidateTree(t, repository)
|
||||||
|
tree, err := ReadCandidateTree(context.Background(), repository, commit)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = checkFileSize(tree, &FileSizeSettings{LimitBytes: int64Pointer(3), Exclusions: []string{"link"}})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("checkFileSize() error = %v, want small binary and exact-limit blob to pass", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = checkFileSize(tree, &FileSizeSettings{LimitBytes: int64Pointer(3), Exclusions: []string{"small.bin", "boundary.bin"}})
|
||||||
|
failure, ok := err.(*Failure)
|
||||||
|
if !ok || failure.Check != FileSize || len(failure.Findings) != 1 || failure.Findings[0].Path != "link" {
|
||||||
|
t.Fatalf("checkFileSize() error = %v, want symlink blob to exceed the limit", err)
|
||||||
|
}
|
||||||
|
if failure.Measurement == nil || failure.Measurement.Bytes != int64(len("small.bin")) {
|
||||||
|
t.Fatalf("symlink measurement = %#v, want link-text size %d", failure.Measurement, len("small.bin"))
|
||||||
|
}
|
||||||
|
|
||||||
|
err = checkFileSize(tree, &FileSizeSettings{LimitBytes: int64Pointer(0), Exclusions: []string{"small.bin", "boundary.bin", "link"}})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("checkFileSize() error = %v, want omitted gitlink size", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckFileSizeUsesOnlyCandidateFilesIndividually(t *testing.T) {
|
||||||
|
repository := newTreeRepository(t)
|
||||||
|
writeTreeFile(t, repository, "historical-large.dat", []byte(strings.Repeat("h", 20)))
|
||||||
|
commitCandidateTree(t, repository)
|
||||||
|
if err := os.Remove(filepath.Join(repository, "historical-large.dat")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
writeTreeFile(t, repository, "one.dat", []byte(strings.Repeat("a", 6)))
|
||||||
|
writeTreeFile(t, repository, "two.dat", []byte(strings.Repeat("b", 6)))
|
||||||
|
commit := commitCandidateTree(t, repository)
|
||||||
|
tree, err := ReadCandidateTree(context.Background(), repository, commit)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := checkFileSize(tree, &FileSizeSettings{LimitBytes: int64Pointer(10)}); err != nil {
|
||||||
|
t.Fatalf("checkFileSize() error = %v, want current individual files to pass", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRunRejectsNegativeFileSizeLimitBeforeGoChecks(t *testing.T) {
|
||||||
|
negative := int64(-1)
|
||||||
|
err := Run(context.Background(), Request{Settings: Settings{
|
||||||
|
FileSize: &FileSizeSettings{LimitBytes: &negative},
|
||||||
|
}})
|
||||||
|
failure, ok := err.(*Failure)
|
||||||
|
if !ok || failure.Check != FileSize || len(failure.Findings) != 1 || !strings.Contains(failure.Findings[0].Message, "negative") {
|
||||||
|
t.Fatalf("Run() error = %v, want invalid file-size limit failure", err)
|
||||||
|
}
|
||||||
|
if errors.Unwrap(failure) != nil {
|
||||||
|
t.Fatalf("invalid limit failure cause = %v, want none", failure.Cause)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func int64Pointer(value int64) *int64 { return &value }
|
||||||
133
internal/validation/format_test.go
Normal file
133
internal/validation/format_test.go
Normal file
@@ -0,0 +1,133 @@
|
|||||||
|
package validation
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/git"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCheckGoFormatUsesCapturedRegularGoBlobs(t *testing.T) {
|
||||||
|
repository := newTreeRepository(t)
|
||||||
|
writeTreeFile(t, repository, "main.go", []byte("package main\n\nfunc main() {}\n"))
|
||||||
|
writeTreeFile(t, repository, "vendor/example/format.go", []byte("package example\nfunc Value( ){return 1}\n"))
|
||||||
|
writeTreeFile(t, repository, "nested/module/odd name.go", []byte("package nested\nfunc Value( ){return 2}\n"))
|
||||||
|
writeTreeFile(t, repository, "notes.txt", []byte("not Go source\n"))
|
||||||
|
if err := os.Symlink("main.go", filepath.Join(repository, "link.go")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
gitTree(t, repository, "add", ".")
|
||||||
|
gitTree(t, repository, "commit", "-m", "capture Go files")
|
||||||
|
commit := strings.TrimSpace(gitTree(t, repository, "rev-parse", "HEAD"))
|
||||||
|
|
||||||
|
// Worktree edits must not affect the formatting result for the captured commit.
|
||||||
|
writeTreeFile(t, repository, "main.go", []byte("package main\nfunc main( ){}\n"))
|
||||||
|
writeTreeFile(t, repository, "vendor/example/format.go", []byte("package example\n\nfunc Value() { return 1 }\n"))
|
||||||
|
worktreeMain, err := os.ReadFile(filepath.Join(repository, "main.go"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
tree, err := ReadCandidateTree(context.Background(), repository, commit)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
err = checkGoFormat(context.Background(), tree)
|
||||||
|
var failure *Failure
|
||||||
|
if !errors.As(err, &failure) || failure.Check != GoFormat {
|
||||||
|
t.Fatalf("checkGoFormat error = %v, want go-format failure", err)
|
||||||
|
}
|
||||||
|
wantPaths := []string{"nested/module/odd name.go", "vendor/example/format.go"}
|
||||||
|
if len(failure.Findings) != len(wantPaths) {
|
||||||
|
t.Fatalf("format findings = %#v, want paths %q", failure.Findings, wantPaths)
|
||||||
|
}
|
||||||
|
for index, path := range wantPaths {
|
||||||
|
if failure.Findings[index].Path != path {
|
||||||
|
t.Errorf("format finding %d path = %q, want %q", index, failure.Findings[index].Path, path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
worktreeMainAfter, err := os.ReadFile(filepath.Join(repository, "main.go"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if string(worktreeMainAfter) != string(worktreeMain) {
|
||||||
|
t.Fatalf("format check changed worktree source: got %q, want %q", worktreeMainAfter, worktreeMain)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckGoFormatPreservesParserAndInspectionCauses(t *testing.T) {
|
||||||
|
t.Run("parser", func(t *testing.T) {
|
||||||
|
repository := newTreeRepository(t)
|
||||||
|
writeTreeFile(t, repository, "broken.go", []byte("package broken\nfunc ( {\n"))
|
||||||
|
gitTree(t, repository, "add", ".")
|
||||||
|
gitTree(t, repository, "commit", "-m", "capture invalid Go source")
|
||||||
|
commit := strings.TrimSpace(gitTree(t, repository, "rev-parse", "HEAD"))
|
||||||
|
tree, err := ReadCandidateTree(context.Background(), repository, commit)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
err = checkGoFormat(context.Background(), tree)
|
||||||
|
var failure *Failure
|
||||||
|
if !errors.As(err, &failure) || failure.Check != GoFormat || failure.Cause == nil {
|
||||||
|
t.Fatalf("parser failure = %#v, want go-format failure with cause", err)
|
||||||
|
}
|
||||||
|
if len(failure.Findings) != 1 || failure.Findings[0].Path != "broken.go" {
|
||||||
|
t.Fatalf("parser findings = %#v, want broken.go", failure.Findings)
|
||||||
|
}
|
||||||
|
if !strings.Contains(failure.Cause.Error(), "broken.go") {
|
||||||
|
t.Fatalf("parser cause = %v, want committed filename context", failure.Cause)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("inspection", func(t *testing.T) {
|
||||||
|
tree := &CandidateTree{
|
||||||
|
repositoryDir: t.TempDir(),
|
||||||
|
entries: []git.TreeEntry{{Path: "missing.go", ObjectID: strings.Repeat("0", 40), Mode: "100644", Type: "blob"}},
|
||||||
|
byPath: map[string]int{"missing.go": 0},
|
||||||
|
blobs: make(map[string][]byte),
|
||||||
|
}
|
||||||
|
err := checkGoFormat(context.Background(), tree)
|
||||||
|
var failure *Failure
|
||||||
|
if !errors.As(err, &failure) || failure.Check != GoFormat || failure.Cause == nil {
|
||||||
|
t.Fatalf("inspection failure = %#v, want go-format failure with cause", err)
|
||||||
|
}
|
||||||
|
if len(failure.Findings) != 1 || failure.Findings[0].Path != "missing.go" {
|
||||||
|
t.Fatalf("inspection findings = %#v, want missing.go", failure.Findings)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRunGoFormatIsOptionalAndStopsAfterFinding(t *testing.T) {
|
||||||
|
repository := newTreeRepository(t)
|
||||||
|
writeTreeFile(t, repository, "unformatted.go", []byte("package fixture\nfunc Value( ){return 1}\n"))
|
||||||
|
gitTree(t, repository, "add", ".")
|
||||||
|
gitTree(t, repository, "commit", "-m", "capture unformatted Go source")
|
||||||
|
commit := strings.TrimSpace(gitTree(t, repository, "rev-parse", "HEAD"))
|
||||||
|
|
||||||
|
logPath := installGoShim(t, "", false)
|
||||||
|
if err := Run(context.Background(), Request{RepositoryDir: repository, Commit: commit}); err != nil {
|
||||||
|
t.Fatalf("default validation = %v, want success with formatting disabled", err)
|
||||||
|
}
|
||||||
|
if got := strings.Join(readGoShimLog(t, logPath), "\n"); !strings.Contains(got, "test -mod=readonly -count=1 ./...") {
|
||||||
|
t.Fatalf("default Go commands = %q, want standard suite", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
logPath = installGoShim(t, "", false)
|
||||||
|
err := Run(context.Background(), Request{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Commit: commit,
|
||||||
|
Settings: Settings{GoFormat: true},
|
||||||
|
})
|
||||||
|
var failure *Failure
|
||||||
|
if !errors.As(err, &failure) || failure.Check != GoFormat {
|
||||||
|
t.Fatalf("selected formatting error = %v, want go-format failure", err)
|
||||||
|
}
|
||||||
|
commands := strings.Join(readGoShimLog(t, logPath), "\n")
|
||||||
|
if strings.Contains(commands, "build ") || strings.Contains(commands, "vet ") {
|
||||||
|
t.Fatalf("later Go commands ran after formatting failure: %q", commands)
|
||||||
|
}
|
||||||
|
}
|
||||||
92
internal/validation/local_replacements.go
Normal file
92
internal/validation/local_replacements.go
Normal file
@@ -0,0 +1,92 @@
|
|||||||
|
package validation
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"path"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/git"
|
||||||
|
"golang.org/x/mod/modfile"
|
||||||
|
)
|
||||||
|
|
||||||
|
func checkLocalReplacements(ctx context.Context, tree *CandidateTree) error {
|
||||||
|
var findings []Finding
|
||||||
|
for _, entry := range tree.Entries() {
|
||||||
|
if path.Base(entry.Path) != "go.mod" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
contents, err := readModuleDeclaration(ctx, tree, entry)
|
||||||
|
if err != nil {
|
||||||
|
return &Failure{
|
||||||
|
Check: LocalReplacements,
|
||||||
|
Findings: []Finding{{Path: entry.Path, Message: "could not inspect committed module declaration"}},
|
||||||
|
Cause: fmt.Errorf("inspect committed %s: %w", entry.Path, err),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
moduleFile, err := modfile.Parse(entry.Path, contents, nil)
|
||||||
|
if err != nil {
|
||||||
|
return &Failure{
|
||||||
|
Check: LocalReplacements,
|
||||||
|
Findings: []Finding{{Path: entry.Path, Message: "could not parse committed module declaration"}},
|
||||||
|
Cause: fmt.Errorf("parse committed %s: %w", entry.Path, err),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, replacement := range moduleFile.Replace {
|
||||||
|
if replacement.New.Version != "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
finding := Finding{
|
||||||
|
Path: entry.Path,
|
||||||
|
Message: "filesystem module replacement is committed",
|
||||||
|
Target: replacement.New.Path,
|
||||||
|
Directive: "replace",
|
||||||
|
}
|
||||||
|
if replacement.Syntax != nil {
|
||||||
|
finding.Line = replacement.Syntax.Start.Line
|
||||||
|
}
|
||||||
|
findings = append(findings, finding)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(findings) != 0 {
|
||||||
|
return &Failure{Check: LocalReplacements, Findings: findings}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func readModuleDeclaration(ctx context.Context, tree *CandidateTree, entry git.TreeEntry) ([]byte, error) {
|
||||||
|
if entry.Type != "blob" {
|
||||||
|
return nil, fmt.Errorf("entry has type %q, not a blob", entry.Type)
|
||||||
|
}
|
||||||
|
if entry.Mode != "120000" {
|
||||||
|
if entry.Mode != "100644" && entry.Mode != "100755" {
|
||||||
|
return nil, fmt.Errorf("entry has unsupported mode %q", entry.Mode)
|
||||||
|
}
|
||||||
|
contents, err := tree.ReadFile(ctx, entry.Path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("read module declaration: %w", err)
|
||||||
|
}
|
||||||
|
return contents, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
target, err := tree.ReadFile(ctx, entry.Path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("read symlink declaration: %w", err)
|
||||||
|
}
|
||||||
|
destination, err := tree.ResolveDestination(ctx, entry.Path, string(target))
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("resolve symlink declaration target %q: %w", target, err)
|
||||||
|
}
|
||||||
|
if destination.Kind != DestinationEntry {
|
||||||
|
return nil, fmt.Errorf("symlink declaration target %q resolves to %s", target, destination.Kind)
|
||||||
|
}
|
||||||
|
resolved, ok := tree.Entry(destination.Path)
|
||||||
|
if !ok || resolved.Type != "blob" || (resolved.Mode != "100644" && resolved.Mode != "100755") {
|
||||||
|
return nil, fmt.Errorf("symlink declaration target %q does not resolve to a regular committed file", target)
|
||||||
|
}
|
||||||
|
contents, err := tree.ReadFile(ctx, destination.Path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("read resolved module declaration %q: %w", destination.Path, err)
|
||||||
|
}
|
||||||
|
return contents, nil
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user