Files
releasekit/cmd/releasekit/internal/cli/config.go

469 lines
18 KiB
Go

// 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"
"go.maximumdirect.net/releasekit/internal/process"
"go.maximumdirect.net/releasekit/internal/releaseidentity"
)
const Usage = "usage: releasekit version\n releasekit validate [--repo DIR] [--config FILE] [--context local|ci] [--operation NAME ...] [--offline] [--assets DIR] [--json]\n releasekit check [--repo DIR] [--config FILE] VERSION\n releasekit publish [--repo DIR] [--config FILE] [--record-dir DIR] [--expected-module DIR] [--expected-source DIR] VERSION\n releasekit build [--repo DIR] [--config FILE] [--output DIR] VERSION\n releasekit deliver [--repo DIR] [--config FILE] [--assets DIR] VERSION\n releasekit ci-deliver [--repo DIR] [--config FILE] [--remote NAME] [--prepared] [--expected-module DIR] [--expected-source DIR] --commit OID TAG\n releasekit reconcile --record FILE [--json]\n releasekit publication-attempts [--repo DIR] [--record-dir DIR] [--json]"
type Command string
const (
VersionCommand Command = "version"
ValidateAction Command = "validate"
CheckAction Command = "check"
PublishAction Command = "publish"
BuildAction Command = "build"
DeliveryAction Command = "deliver"
CIDeliveryAction Command = "ci-deliver"
ReconcileAction Command = "reconcile"
PublicationAttemptsAction Command = "publication-attempts"
)
// Invocation contains parsed command settings owned by the CLI adapter.
type Invocation struct {
Command Command
Repository string
ConfigPath string
OutputDir string
AssetsDir string
Remote string
Commit string
Version string
ExpectedModule string
ExpectedSource string
ExpectedTag string
Prepared bool
RecordPath string
RecordDir string
JSON bool
Context string
Operations []string
Offline bool
}
type operationFlags []string
func (values *operationFlags) String() string { return strings.Join(*values, ",") }
func (values *operationFlags) Set(value string) error {
switch value {
case "publication", "go", "build", "delivery", "rehearsal":
default:
return fmt.Errorf("unknown validation operation %q", value)
}
for _, existing := range *values {
if existing == value {
return nil
}
}
*values = append(*values, value)
return nil
}
// Parse accepts only commands that have been implemented by the executable.
func Parse(args []string) (Invocation, error) {
if len(args) == 0 {
return Invocation{}, errors.New("a command is required")
}
switch args[0] {
case string(ValidateAction):
flags := flag.NewFlagSet(string(ValidateAction), flag.ContinueOnError)
flags.SetOutput(io.Discard)
repository := flags.String("repo", ".", "repository directory")
configPath := flags.String("config", "", "profile path")
credentialContext := flags.String("context", "local", "credential context")
var operations operationFlags
flags.Var(&operations, "operation", "selected readiness operation")
offline := flags.Bool("offline", false, "omit remote observations")
assets := flags.String("assets", "", "existing build assets directory")
structured := flags.Bool("json", false, "write structured JSON")
if err := flags.Parse(args[1:]); err != nil {
return Invocation{}, err
}
if flags.NArg() != 0 {
return Invocation{}, errors.New("validate takes no positional arguments")
}
if *credentialContext != "local" && *credentialContext != "ci" {
return Invocation{}, errors.New("validate --context must be local or ci")
}
return Invocation{Command: ValidateAction, Repository: *repository, ConfigPath: *configPath, Context: *credentialContext, Operations: operations, Offline: *offline, AssetsDir: *assets, JSON: *structured}, nil
case string(ReconcileAction), string(PublicationAttemptsAction):
action := Command(args[0])
flags := flag.NewFlagSet(string(action), flag.ContinueOnError)
flags.SetOutput(io.Discard)
record := ""
recordDir := ""
repository := "."
if action == ReconcileAction {
flags.StringVar(&record, "record", "", "attempt record file")
} else {
flags.StringVar(&repository, "repo", ".", "repository directory")
flags.StringVar(&recordDir, "record-dir", "", "attempt-record directory")
}
structured := flags.Bool("json", false, "write structured JSON")
if err := flags.Parse(args[1:]); err != nil {
return Invocation{}, err
}
if flags.NArg() != 0 {
return Invocation{}, fmt.Errorf("%s takes no positional arguments", action)
}
if action == ReconcileAction && record == "" {
return Invocation{}, errors.New("reconcile requires --record FILE")
}
return Invocation{Command: action, Repository: repository, RecordPath: record, RecordDir: recordDir, JSON: *structured}, nil
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
expectedModule := ""
expectedSource := ""
if action == PublishAction || action == CIDeliveryAction {
flags.StringVar(&expectedModule, "expected-module", "", "expected module directory from a launcher mapping")
flags.StringVar(&expectedSource, "expected-source", "", "expected source directory from a launcher mapping")
}
recordDir := ""
if action == PublishAction {
flags.StringVar(&recordDir, "record-dir", "", "publication attempt-record directory")
}
expectedCommit := ""
prepared := false
if action == CIDeliveryAction {
remote = flags.String("remote", "origin", "Git remote")
flags.StringVar(&expectedCommit, "commit", "", "expected tagged commit")
flags.BoolVar(&prepared, "prepared", false, "verify an already prepared tagged checkout without fetching or checkout")
}
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")
}
version := flags.Arg(0)
expectedTag := ""
if action == CIDeliveryAction {
expectedTag = version
if slash := strings.LastIndex(version, "/"); slash >= 0 {
version = version[slash+1:]
}
}
parsedRemote := ""
if remote != nil {
parsedRemote = *remote
}
return Invocation{Command: action, Repository: *repository, ConfigPath: *configPath, OutputDir: outputDir, AssetsDir: assetsDir, Remote: parsedRemote, Commit: expectedCommit, Version: version, ExpectedModule: expectedModule, ExpectedSource: expectedSource, ExpectedTag: expectedTag, Prepared: prepared, RecordDir: recordDir}, 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"`
ModuleDir string `json:"module_dir,omitempty"`
Source *SourceSettings `json:"source,omitempty"`
Go *struct{} `json:"go,omitempty"`
Publication *PublicationSettings `json:"publication,omitempty"`
Version *VersionSettings `json:"version,omitempty"`
Remote string `json:"remote,omitempty"`
ExpectedPushURL string `json:"expected_push_url,omitempty"`
Checks []CheckCommand `json:"checks,omitempty"`
Validation *ValidationSettings `json:"validation,omitempty"`
Build *BuildSettings `json:"build,omitempty"`
Delivery *DeliverySettings `json:"delivery,omitempty"`
Readiness *ReadinessSettings `json:"readiness,omitempty"`
}
// ReadinessSettings lists files deliberately required for setup diagnostics.
type ReadinessSettings struct {
RequiredFiles []string `json:"required_files,omitempty"`
}
type SourceSettings struct {
Dir string `json:"dir,omitempty"`
TagPrefix *string `json:"tag_prefix,omitempty"`
}
type PublicationSettings struct {
Mode string `json:"mode,omitempty"`
}
type VersionSettings struct {
Format string `json:"format,omitempty"`
Prefix *string `json:"prefix,omitempty"`
}
// SourceSpec maps the optional profile selection to the internal selection.
func (s Settings) SourceSpec() *releaseidentity.SourceSpec {
if s.Source == nil && s.Go == nil && s.Publication == nil && s.Version == nil {
return nil
}
result := &releaseidentity.SourceSpec{GoEnabled: s.Go != nil}
if s.Source != nil {
result.Dir, result.TagPrefix = s.Source.Dir, s.Source.TagPrefix
}
if s.Publication != nil {
result.Publication = s.Publication.Mode
}
if s.Version != nil {
result.VersionFormat, result.VersionPrefix = s.Version.Format, s.Version.Prefix
}
return result
}
// ValidationSettings selects shared candidate checks in a release profile.
type ValidationSettings struct {
// SharedFiles selects committed files relative to the repository root.
// Nil uses optional defaults; a non-nil empty slice selects no shared files.
SharedFiles []string `json:"shared_files"`
ForbiddenFiles []string `json:"forbidden_files,omitempty"`
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 forge release destination.
type DeliverySettings struct {
Forge string `json:"forge,omitempty"`
BaseURL string `json:"base_url"`
Owner string `json:"owner"`
Repository string `json:"repository"`
Credentials *DeliveryCredentials `json:"credentials,omitempty"`
LegacyTokenEnv json.RawMessage `json:"token_env,omitempty"`
LegacyTokenFile json.RawMessage `json:"token_file,omitempty"`
}
type DeliveryCredentials struct {
Local *LocalCredential `json:"local,omitempty"`
CI *CICredential `json:"ci,omitempty"`
}
type LocalCredential struct {
TokenFile string `json:"token_file"`
}
type CICredential struct {
TokenEnvironmentVariable string `json:"token_environment_variable,omitempty"`
}
// BuildSettings selects the Go application package, artifact name, and targets.
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 delivery := settings.Delivery; delivery != nil {
if delivery.LegacyTokenFile != nil {
return Settings{}, fmt.Errorf("profile %q: delivery.token_file has moved to delivery.credentials.local.token_file", configPath)
}
if delivery.LegacyTokenEnv != nil {
return Settings{}, fmt.Errorf("profile %q: delivery.token_env has moved to delivery.credentials.ci.token_environment_variable", configPath)
}
}
if source := settings.SourceSpec(); source != nil {
_, err := releaseidentity.NormalizeSource(settings.ModuleDir, source)
if err != nil {
return Settings{}, fmt.Errorf("profile %q: source selection: %w", configPath, err)
}
}
if settings.Remote == "" {
settings.Remote = "origin"
}
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 dir. Each command receives
// its own environment overlay and inherits the remaining process environment.
func RunChecks(ctx context.Context, dir 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: dir,
Env: environment,
Stdout: stdout,
Stderr: stderr,
}); err != nil {
return fmt.Errorf("run check %d: %w", i+1, err)
}
}
return nil
}