Files
ReleaseKit/internal/candidate/check.go

283 lines
8.8 KiB
Go

// Package candidate captures and validates a committed local release candidate.
package candidate
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"os/exec"
"path/filepath"
"strings"
"sync"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/process"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/versioncontract"
)
var ErrInvalidVersion = errors.New("invalid stable version")
type Candidate struct {
RepositoryDir string
Commit string
Version string
Note string
}
type Request struct {
RepositoryDir string
Product string
Version string
Validate 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 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 complete selected validation once for the captured
// candidate. A supplied callback replaces the default offline Go validation.
func Validate(ctx context.Context, request Request, captured Candidate) error {
var err error
if request.Validate == nil {
err = runDefaultValidation(ctx, captured.RepositoryDir, request.Output)
} else {
err = request.Validate(ctx, captured)
}
if err != nil {
return fmt.Errorf("validate candidate %s: %w", captured.Commit, err)
}
return nil
}
// Recheck verifies that the captured local source is unchanged. When
// expectedTagObject is empty, the selected local version tag must still be
// absent; otherwise the existing annotated tag must still have that object ID.
func Recheck(ctx context.Context, captured Candidate, expectedTagObject string) error {
current, err := inspectLocalState(ctx, captured.RepositoryDir)
if err != nil {
return fmt.Errorf("recheck local candidate state: %w", err)
}
if current.branch != "main" {
return fmt.Errorf("release candidate branch changed to %q", current.branch)
}
if current.commit != captured.Commit {
return fmt.Errorf("HEAD changed from %s to %s", captured.Commit, current.commit)
}
if current.status != "" {
return fmt.Errorf("worktree or index changed:\n%s", current.status)
}
if expectedTagObject == "" {
if exists, err := hasLocalTag(ctx, captured.RepositoryDir, captured.Version); err != nil {
return fmt.Errorf("recheck local tag %q: %w", captured.Version, err)
} else if exists {
return fmt.Errorf("local tag %q appeared during validation", captured.Version)
}
return nil
}
object, err := gitOutput(ctx, captured.RepositoryDir, "rev-parse", "--verify", "refs/tags/"+captured.Version)
if err != nil {
return fmt.Errorf("read local tag %q: %w", captured.Version, err)
}
tagType, err := gitOutput(ctx, captured.RepositoryDir, "cat-file", "-t", "refs/tags/"+captured.Version)
if err != nil {
return fmt.Errorf("inspect local tag %q: %w", captured.Version, err)
}
if strings.TrimSpace(string(object)) != expectedTagObject || strings.TrimSpace(string(tagType)) != "tag" {
return fmt.Errorf("local tag %q no longer identifies annotated tag object %s", captured.Version, expectedTagObject)
}
return nil
}
type localState struct {
branch string
commit string
status string
}
func inspectLocalState(ctx context.Context, repositoryDir string) (localState, error) {
branchOutput, err := gitOutput(ctx, repositoryDir, "branch", "--show-current")
if err != nil {
return localState{}, fmt.Errorf("inspect current branch: %w", err)
}
commitOutput, err := gitOutput(ctx, repositoryDir, "rev-parse", "--verify", "HEAD^{commit}")
if err != nil {
return localState{}, fmt.Errorf("capture HEAD commit: %w", err)
}
statusOutput, err := gitOutput(ctx, repositoryDir, "status", "--porcelain=v1", "--untracked-files=all")
if err != nil {
return localState{}, fmt.Errorf("inspect worktree and index: %w", err)
}
return localState{
branch: strings.TrimSpace(string(branchOutput)),
commit: strings.TrimSpace(string(commitOutput)),
status: strings.TrimSpace(string(statusOutput)),
}, nil
}
func gitOutput(ctx context.Context, repositoryDir string, args ...string) ([]byte, error) {
var stdout, stderr bytes.Buffer
commandArgs := append([]string{"git"}, args...)
err := process.Run(ctx, process.Invocation{
Args: commandArgs,
Dir: repositoryDir,
Stdout: &stdout,
Stderr: &stderr,
})
if err != nil {
message := strings.TrimSpace(stderr.String())
if message != "" {
return nil, fmt.Errorf("git %s: %s: %w", strings.Join(args, " "), message, err)
}
return nil, fmt.Errorf("git %s: %w", strings.Join(args, " "), err)
}
return stdout.Bytes(), nil
}
func hasLocalTag(ctx context.Context, repositoryDir, version string) (bool, error) {
var stderr bytes.Buffer
err := process.Run(ctx, process.Invocation{
Args: []string{"git", "show-ref", "--verify", "--quiet", "refs/tags/" + version},
Dir: repositoryDir,
Stderr: &stderr,
})
if err == nil {
return true, nil
}
var exitErr *exec.ExitError
if errors.As(err, &exitErr) && exitErr.ExitCode() == 1 {
return false, nil
}
message := strings.TrimSpace(stderr.String())
if message != "" {
return false, fmt.Errorf("%s: %w", message, err)
}
return false, err
}
func runDefaultValidation(ctx context.Context, repositoryDir string, output io.Writer) error {
environment := map[string]string{
"GOWORK": "off",
"GOPROXY": "off",
"GONOPROXY": "none",
"GOSUMDB": "off",
"GOTOOLCHAIN": "local",
}
var writer io.Writer = output
if output != nil {
writer = &synchronizedWriter{writer: output}
}
return process.Run(ctx, process.Invocation{
Args: []string{"go", "test", "-mod=readonly", "-count=1", "./..."},
Dir: repositoryDir,
Env: environment,
Stdout: writer,
Stderr: writer,
})
}
type synchronizedWriter struct {
mu sync.Mutex
writer io.Writer
}
func (w *synchronizedWriter) Write(p []byte) (int, error) {
w.mu.Lock()
defer w.mu.Unlock()
return w.writer.Write(p)
}
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
}
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
}