257 lines
7.4 KiB
Go
257 lines
7.4 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"
|
|
)
|
|
|
|
var ErrInvalidVersion = errors.New("invalid stable version")
|
|
|
|
type Candidate struct {
|
|
RepositoryDir string
|
|
Commit string
|
|
Version 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) {
|
|
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)
|
|
}
|
|
|
|
captured := Candidate{RepositoryDir: repositoryDir, Commit: state.commit, Version: request.Version}
|
|
if request.Validate == nil {
|
|
err = runDefaultValidation(ctx, captured.RepositoryDir, request.Output)
|
|
} else {
|
|
err = request.Validate(ctx, captured)
|
|
}
|
|
if err != nil {
|
|
return Candidate{}, fmt.Errorf("validate candidate %s: %w", captured.Commit, err)
|
|
}
|
|
|
|
current, err := inspectLocalState(ctx, repositoryDir)
|
|
if err != nil {
|
|
return Candidate{}, fmt.Errorf("recheck local candidate state: %w", err)
|
|
}
|
|
if current.branch != "main" {
|
|
return Candidate{}, fmt.Errorf("release candidate branch changed during validation to %q", current.branch)
|
|
}
|
|
if current.commit != captured.Commit {
|
|
return Candidate{}, fmt.Errorf("HEAD changed during validation from %s to %s", captured.Commit, current.commit)
|
|
}
|
|
if current.status != "" {
|
|
return Candidate{}, fmt.Errorf("worktree or index changed during validation:\n%s", current.status)
|
|
}
|
|
if exists, err := hasLocalTag(ctx, repositoryDir, request.Version); err != nil {
|
|
return Candidate{}, fmt.Errorf("recheck local tag %q: %w", request.Version, err)
|
|
} else if exists {
|
|
return Candidate{}, fmt.Errorf("local tag %q appeared during validation", request.Version)
|
|
}
|
|
|
|
return captured, 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 {
|
|
if !strings.HasPrefix(version, "v") {
|
|
return false
|
|
}
|
|
components := strings.Split(version[1:], ".")
|
|
if len(components) != 3 {
|
|
return false
|
|
}
|
|
for _, component := range components {
|
|
if component == "" || len(component) > 1 && component[0] == '0' {
|
|
return false
|
|
}
|
|
for i := 0; i < len(component); i++ {
|
|
if component[i] < '0' || component[i] > '9' {
|
|
return false
|
|
}
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
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
|
|
}
|