diff --git a/cmd/releasekit/internal/cli/config.go b/cmd/releasekit/internal/cli/config.go index 457a44d..ce1ebfa 100644 --- a/cmd/releasekit/internal/cli/config.go +++ b/cmd/releasekit/internal/cli/config.go @@ -17,12 +17,13 @@ import ( "go.maximumdirect.net/releasekit/internal/releaseidentity" ) -const Usage = "usage: releasekit version\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]" +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" @@ -49,6 +50,27 @@ type Invocation struct { 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. @@ -57,6 +79,27 @@ func Parse(args []string) (Invocation, error) { 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) @@ -181,6 +224,12 @@ type Settings struct { 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 { diff --git a/cmd/releasekit/internal/cli/config_test.go b/cmd/releasekit/internal/cli/config_test.go index cf5ba61..5a63698 100644 --- a/cmd/releasekit/internal/cli/config_test.go +++ b/cmd/releasekit/internal/cli/config_test.go @@ -157,6 +157,18 @@ func TestLoadSettingsResolvesPathsAndPreservesArguments(t *testing.T) { } } +func TestParseValidateSelectsAndDeduplicatesOperations(t *testing.T) { + invocation, err := Parse([]string{"validate", "--context", "ci", "--operation", "delivery", "--operation", "go", "--operation", "delivery", "--offline", "--assets", "dist", "--json"}) + if err != nil || invocation.Command != ValidateAction || invocation.Context != "ci" || !invocation.Offline || !invocation.JSON || invocation.AssetsDir != "dist" || len(invocation.Operations) != 2 || invocation.Operations[0] != "delivery" || invocation.Operations[1] != "go" { + t.Fatalf("invocation = %+v, error = %v", invocation, err) + } + for _, args := range [][]string{{"validate", "v1.0.0"}, {"validate", "--context", "other"}, {"validate", "--operation", "other"}} { + if _, err := Parse(args); err == nil { + t.Errorf("Parse(%q) accepted invalid arguments", args) + } + } +} + func TestLoadSettingsReportsObsoleteDeliveryCredentials(t *testing.T) { for _, test := range []struct{ field, replacement string }{ {"token_file", "delivery.credentials.local.token_file"}, diff --git a/cmd/releasekit/main.go b/cmd/releasekit/main.go index cb653c7..61d12da 100644 --- a/cmd/releasekit/main.go +++ b/cmd/releasekit/main.go @@ -38,6 +38,9 @@ func run(ctx context.Context, args []string, stdout, stderr io.Writer) int { if invocation.Command == cli.ReconcileAction || invocation.Command == cli.PublicationAttemptsAction { return runRecovery(ctx, invocation, stdout, stderr) } + if invocation.Command == cli.ValidateAction { + return runValidate(ctx, invocation, stdout) + } if invocation.Command != cli.VersionCommand { invocation.Repository, err = git.RepositoryRoot(ctx, invocation.Repository) if err != nil { diff --git a/cmd/releasekit/readiness.go b/cmd/releasekit/readiness.go new file mode 100644 index 0000000..cdd5b78 --- /dev/null +++ b/cmd/releasekit/readiness.go @@ -0,0 +1,162 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "io" + "path/filepath" + "strings" + + "go.maximumdirect.net/releasekit" + "go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli" + "go.maximumdirect.net/releasekit/internal/artifact" + "go.maximumdirect.net/releasekit/internal/git" + "go.maximumdirect.net/releasekit/internal/releaseidentity" +) + +type readinessCheckDocument struct { + ID string `json:"id"` + Operation releasekit.ReadinessOperation `json:"operation"` + Status releasekit.ReadinessStatus `json:"status"` + Reason string `json:"reason,omitempty"` + Message string `json:"message"` +} +type readinessCredentialDocument struct { + Context string `json:"context"` + Source string `json:"source,omitempty"` + Declared bool `json:"declared"` +} +type readinessDocument struct { + SchemaVersion int `json:"schema_version"` + Command string `json:"command"` + InputSource string `json:"input_source"` + RepositoryDir string `json:"repository_dir,omitempty"` + Operations []releasekit.ReadinessOperation `json:"operations"` + Context string `json:"context"` + Offline bool `json:"offline"` + GitDestination string `json:"git_destination,omitempty"` + DeliveryDestination string `json:"delivery_destination,omitempty"` + Credentials []readinessCredentialDocument `json:"credentials,omitempty"` + Checks []readinessCheckDocument `json:"checks"` +} + +func runValidate(ctx context.Context, invocation cli.Invocation, output io.Writer) int { + report := releasekit.ValidationReport{InputSource: "working", Context: invocation.Context, Offline: invocation.Offline} + for _, operation := range invocation.Operations { + report.Operations = append(report.Operations, releasekit.ReadinessOperation(operation)) + } + var reportErr error + root, err := git.RepositoryRoot(ctx, invocation.Repository) + if err != nil { + report.Checks = append(report.Checks, releasekit.ReadinessResult{ID: "repository", Operation: "configuration", Status: releasekit.ReadinessFailed, Reason: "required_input", Message: git.DisplayDiagnostic(err.Error()), Cause: err}) + reportErr = err + } else { + invocation.Repository = root + settings, loadErr := cli.LoadSettings(root, invocation.ConfigPath) + if loadErr != nil { + report.RepositoryDir = root + report.Checks = append(report.Checks, releasekit.ReadinessResult{ID: "profile", Operation: "configuration", Status: releasekit.ReadinessFailed, Reason: "configuration", Message: git.DisplayDiagnostic(loadErr.Error()), Cause: loadErr}) + reportErr = loadErr + } else { + request := releasekit.ValidateRequest{RepositoryDir: root, ModuleDir: settings.ModuleDir, Source: sourceSpec(settings), Product: settings.Product, Remote: settings.Remote, ExpectedPushURL: settings.ExpectedPushURL, Context: invocation.Context, Offline: invocation.Offline, Build: configuredBuildSpec(settings.Build)} + for _, operation := range invocation.Operations { + request.Operations = append(request.Operations, releasekit.ReadinessOperation(operation)) + } + if settings.Readiness != nil { + request.RequiredFiles = append([]string(nil), settings.Readiness.RequiredFiles...) + } + wantsDelivery := len(invocation.Operations) == 0 && settings.Delivery != nil + for _, operation := range invocation.Operations { + if operation == "delivery" || operation == "rehearsal" { + wantsDelivery = true + } + } + if delivery := settings.Delivery; delivery != nil { + request.Destination = &releasekit.DeliveryDestination{Forge: releasekit.Forge(delivery.Forge), BaseURL: delivery.BaseURL, Owner: delivery.Owner, Repository: delivery.Repository} + if credentials := delivery.Credentials; credentials != nil { + if credentials.Local != nil { + request.Credentials = append(request.Credentials, releasekit.ReadinessCredential{Context: "local", Source: git.DisplayDiagnostic(credentials.Local.TokenFile), Declared: true}) + } + if credentials.CI != nil { + name := credentials.CI.TokenEnvironmentVariable + if strings.TrimSpace(name) == "" { + name = "RELEASEKIT_DELIVERY_TOKEN" + } + request.Credentials = append(request.Credentials, releasekit.ReadinessCredential{Context: "ci", Source: git.DisplayDiagnostic(name), Declared: true}) + } + } + if wantsDelivery { + token, _, tokenErr := cli.ResolveDeliveryCredential(root, delivery.Credentials, cli.CredentialContext(invocation.Context)) + request.Destination.Token = token + request.CredentialError = tokenErr + } + } + var assetErr error + assetSkipped := false + if invocation.AssetsDir != "" { + if !wantsDelivery { + assetErr = fmt.Errorf("--assets requires delivery selection") + } else { + selection, selectionErr := releaseidentity.ResolveWorkingSource(root, settings.ModuleDir, settings.SourceSpec()) + if selectionErr != nil { + assetSkipped = true + } else { + directory := artifact.OutputDirectory(selection.ModuleDir, invocation.AssetsDir) + receipt, receiptErr := cli.LoadBuildReceipt(filepath.Join(directory, cli.BuildReceiptName)) + if receiptErr != nil { + assetErr = receiptErr + } else { + request.Prebuilt = buildResultFromReceipt(receipt) + } + } + } + } + report, reportErr = releasekit.Validate(ctx, request) + if assetSkipped { + report.Checks = append(report.Checks, releasekit.ReadinessResult{ID: "prebuilt", Operation: releasekit.ReadinessDelivery, Status: releasekit.ReadinessSkipped, Reason: "dependency", Message: "selected source unavailable"}) + } + if assetErr != nil { + report.Checks = append(report.Checks, releasekit.ReadinessResult{ID: "prebuilt", Operation: releasekit.ReadinessDelivery, Status: releasekit.ReadinessFailed, Reason: "configuration", Message: git.DisplayDiagnostic(assetErr.Error()), Cause: assetErr}) + reportErr = assetErr + } + } + } + if err := writeReadinessReport(output, invocation.JSON, report); err != nil { + return 1 + } + if reportErr == nil { + return 0 + } + if ctx.Err() != nil { + return 1 + } + for _, check := range report.Checks { + if check.Status == releasekit.ReadinessFailed && (check.Reason == "configuration" || check.Reason == "required_input") { + return 2 + } + } + return 1 +} + +func writeReadinessReport(output io.Writer, structured bool, report releasekit.ValidationReport) error { + document := readinessDocument{SchemaVersion: 1, Command: "validate", InputSource: report.InputSource, RepositoryDir: git.DisplayDiagnostic(report.RepositoryDir), Operations: append([]releasekit.ReadinessOperation{}, report.Operations...), Context: report.Context, Offline: report.Offline, GitDestination: git.DisplayURL(report.GitDestination), DeliveryDestination: git.DisplayDiagnostic(report.DeliveryDestination), Checks: make([]readinessCheckDocument, 0, len(report.Checks))} + for _, credential := range report.Credentials { + document.Credentials = append(document.Credentials, readinessCredentialDocument{Context: credential.Context, Source: git.DisplayDiagnostic(credential.Source), Declared: credential.Declared}) + } + for _, check := range report.Checks { + document.Checks = append(document.Checks, readinessCheckDocument{ID: check.ID, Operation: check.Operation, Status: check.Status, Reason: check.Reason, Message: git.DisplayDiagnostic(check.Message)}) + } + if structured { + return json.NewEncoder(output).Encode(document) + } + if _, err := fmt.Fprintf(output, "readiness source=%s context=%s offline=%t operations=%v\n", document.InputSource, document.Context, document.Offline, document.Operations); err != nil { + return err + } + for _, check := range document.Checks { + if _, err := fmt.Fprintf(output, "%s %s [%s]: %s\n", check.Status, check.ID, check.Operation, check.Message); err != nil { + return err + } + } + return nil +} diff --git a/cmd/releasekit/readiness_test.go b/cmd/releasekit/readiness_test.go new file mode 100644 index 0000000..a908e69 --- /dev/null +++ b/cmd/releasekit/readiness_test.go @@ -0,0 +1,246 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli" +) + +func TestValidateReportsUnavailableOnlineObservation(t *testing.T) { + repo, _ := newSimplePublishRepository(t, false) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + t.Errorf("unexpected remote write %s", r.Method) + } + http.Error(w, "unavailable", http.StatusServiceUnavailable) + })) + defer server.Close() + profile := fmt.Sprintf(`{"product":"Config","source":{},"delivery":{"forge":"gitea","base_url":%q,"owner":"owner","repository":"example","credentials":{"ci":{}}}}`, server.URL) + writeRepositoryFile(t, repo, "releasekit.json", profile) + t.Setenv("RELEASEKIT_DELIVERY_TOKEN", "fixture-token") + var output bytes.Buffer + status := run(context.Background(), []string{"validate", "--repo", repo, "--context", "ci", "--operation", "delivery", "--json"}, &output, &bytes.Buffer{}) + if status != 1 || !strings.Contains(output.String(), `"reason":"remote"`) || strings.Contains(output.String(), "fixture-token") { + t.Fatalf("status=%d output=%s", status, &output) + } +} + +func TestValidateAggregatesDestinationAndCredentialFailures(t *testing.T) { + repo, _ := newSimplePublishRepository(t, false) + writeRepositoryFile(t, repo, "releasekit.json", `{"product":"Config","source":{},"delivery":{"forge":"gitea","base_url":"ssh://invalid","owner":"owner","repository":"example","credentials":{"local":{"token_file":"missing"}}}}`) + var output bytes.Buffer + status := run(context.Background(), []string{"validate", "--repo", repo, "--operation", "delivery", "--json"}, &output, &bytes.Buffer{}) + if status != 2 || !strings.Contains(output.String(), `"id":"delivery-inputs","operation":"delivery","status":"failed"`) || !strings.Contains(output.String(), `"id":"delivery-credential","operation":"delivery","status":"failed"`) || !strings.Contains(output.String(), `"id":"delivery-access","operation":"delivery","status":"skipped"`) { + t.Fatalf("status=%d output=%s", status, &output) + } +} + +func TestValidatePrebuiltInputsWithoutWorkingReleaseNote(t *testing.T) { + repo := newCLIRepository(t) + build := cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}} + writeDeliveryProfile(t, repo, cli.Settings{Product: "Example Product", Build: &build, Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: "https://gitea.example", Owner: "owner", Repository: "example"}}) + assets, binary := writeDeliveryReceipt(t, repo, build) + if err := os.Remove(filepath.Join(repo, "docs", "releases", "v1.2.3.md")); err != nil { + t.Fatal(err) + } + var output bytes.Buffer + args := []string{"validate", "--repo", repo, "--operation", "delivery", "--offline", "--assets", assets, "--json"} + if status := run(context.Background(), args, &output, &bytes.Buffer{}); status != 0 { + t.Fatalf("status=%d report=%s", status, &output) + } + if err := os.WriteFile(binary, []byte("tampered artifact"), 0600); err != nil { + t.Fatal(err) + } + output.Reset() + if status := run(context.Background(), args, &output, &bytes.Buffer{}); status != 2 || !strings.Contains(output.String(), `"id":"prebuilt"`) { + t.Fatalf("tampered status=%d report=%s", status, &output) + } +} + +func TestValidateOnlineUsesReadOnlyDeliveryPreflight(t *testing.T) { + repo, _ := newSimplePublishRepository(t, false) + state := &deliveryServerState{} + server := newDeliveryServer(t, state) + defer server.Close() + profile := fmt.Sprintf(`{"product":"Config","source":{},"delivery":{"forge":"gitea","base_url":%q,"owner":"owner","repository":"example","credentials":{"ci":{"token_environment_variable":"READINESS_TEST_TOKEN"}}}}`, server.URL) + writeRepositoryFile(t, repo, "releasekit.json", profile) + t.Setenv("READINESS_TEST_TOKEN", "fixture-token") + var output bytes.Buffer + status := run(context.Background(), []string{"validate", "--repo", repo, "--context", "ci", "--operation", "delivery", "--json"}, &output, &bytes.Buffer{}) + if status != 0 || state.snapshot().apiRequests != 2 || state.snapshot().releaseCreates != 0 || state.snapshot().assetUploads != 0 || strings.Contains(output.String(), "fixture-token") { + t.Fatalf("status=%d requests=%d creates=%d output=%s", status, state.snapshot().apiRequests, state.snapshot().releaseCreates, &output) + } +} + +func TestValidateBuildChecksInputsWithoutBuilding(t *testing.T) { + repo := newCLIRepository(t) + writeRepositoryFile(t, repo, "main.go", "package main\nfunc main() {}\n") + writeRepositoryFile(t, repo, "releasekit.json", `{"product":"Example Product","build":{"main_package":".","binary_name":"helper","targets":["linux/amd64"]},"checks":[{"args":["false"]}]}`) + shim := t.TempDir() + log := filepath.Join(shim, "calls") + script := "#!/bin/sh\nprintf '%s\\n' \"$*\" >> \"$READINESS_GO_LOG\"\nif [ \"$1\" = version ]; then echo 'go version go1.27.4 linux/amd64'; exit 0; fi\nexit 99\n" + if err := os.WriteFile(filepath.Join(shim, "go"), []byte(script), 0700); err != nil { + t.Fatal(err) + } + t.Setenv("READINESS_GO_LOG", log) + t.Setenv("PATH", shim+string(os.PathListSeparator)+os.Getenv("PATH")) + var output bytes.Buffer + status := run(context.Background(), []string{"validate", "--repo", repo, "--operation", "build", "--offline", "--json"}, &output, &bytes.Buffer{}) + calls, err := os.ReadFile(log) + if err != nil || status != 0 || string(calls) != "version\n" || !strings.Contains(output.String(), `"id":"go-dependencies","operation":"go","status":"unchecked"`) { + t.Fatalf("status=%d calls=%q error=%v output=%s", status, calls, err, &output) + } + if _, err := os.Stat(filepath.Join(repo, "dist")); !os.IsNotExist(err) { + t.Fatalf("validation created build outputs: %v", err) + } + writeRepositoryFile(t, repo, "go.mod", "module example.com/cli-candidate\n\ngo 1.28.0\n") + output.Reset() + status = run(context.Background(), []string{"validate", "--repo", repo, "--operation", "build", "--offline", "--json"}, &output, &bytes.Buffer{}) + if status != 2 || !strings.Contains(output.String(), "older than declared Go 1.28.0") { + t.Fatalf("toolchain status=%d report=%s", status, &output) + } +} + +func TestValidateOfflineInspectsWorkingSourceWithoutReleaseNote(t *testing.T) { + repo, remote := newSimplePublishRepository(t, false) + writeRepositoryFile(t, repo, "releasekit.json", `{"product":"Config","source":{},"readiness":{"required_files":["required.txt"]}}`) + writeRepositoryFile(t, repo, "required.txt", "local input\n") + before := cliGitOutput(t, remote, "show-ref", "--heads") + var output bytes.Buffer + status := run(context.Background(), []string{"validate", "--repo", repo, "--offline", "--json"}, &output, &bytes.Buffer{}) + var report readinessDocument + if err := json.Unmarshal(output.Bytes(), &report); err != nil { + t.Fatalf("decode: %v: %s", err, output.String()) + } + if status != 0 || report.SchemaVersion != 1 || report.Command != "validate" || report.InputSource != "working" || !report.Offline || len(report.Operations) != 1 || report.Operations[0] != "publication" { + t.Fatalf("status=%d report=%+v", status, report) + } + found := false + for _, check := range report.Checks { + if check.ID == "git-main" && check.Status == "unchecked" && check.Reason == "offline" { + found = true + } + } + if !found { + t.Fatalf("missing offline evidence: %+v", report.Checks) + } + if got := cliGitOutput(t, remote, "show-ref", "--heads"); got != before { + t.Fatalf("validation changed remote refs: %s != %s", got, before) + } +} + +func TestValidatePublicationReadsMainWithoutRequiringCurrentCommit(t *testing.T) { + repo, remote := newSimplePublishRepository(t, false) + before := cliGitOutput(t, remote, "rev-parse", "refs/heads/main") + writeRepositoryFile(t, repo, "new-file", "unpublished\n") + cliGitRun(t, repo, "add", "new-file") + cliGitRun(t, repo, "commit", "-m", "unpublished work") + writeRepositoryFile(t, repo, "releasekit.json", `{"product":"Config","source":{}}`) + var output bytes.Buffer + status := run(context.Background(), []string{"validate", "--repo", repo, "--operation", "publication", "--json"}, &output, &bytes.Buffer{}) + if status != 0 || !strings.Contains(output.String(), `"id":"git-main","operation":"publication","status":"passed"`) { + t.Fatalf("status=%d output=%s", status, &output) + } + if got := cliGitOutput(t, remote, "rev-parse", "refs/heads/main"); got != before { + t.Fatalf("validation changed remote main to %s", got) + } +} + +func TestValidateOfflineChecksGitIdentity(t *testing.T) { + repo, _ := newSimplePublishRepository(t, false) + writeRepositoryFile(t, repo, "releasekit.json", `{"product":"Config","source":{}}`) + cliGitRun(t, repo, "config", "--unset", "user.name") + cliGitRun(t, repo, "config", "--unset", "user.email") + t.Setenv("GIT_CONFIG_GLOBAL", os.DevNull) + t.Setenv("GIT_CONFIG_NOSYSTEM", "1") + t.Setenv("GIT_COMMITTER_NAME", "") + t.Setenv("GIT_COMMITTER_EMAIL", "") + t.Setenv("EMAIL", "") + var output bytes.Buffer + status := run(context.Background(), []string{"validate", "--repo", repo, "--offline", "--json"}, &output, &bytes.Buffer{}) + if status != 2 || !strings.Contains(output.String(), `"id":"git-identity","operation":"publication","status":"failed"`) { + t.Fatalf("status=%d output=%s", status, &output) + } +} + +func TestValidateAggregatesInputsAndKeepsCredentialContextsSeparate(t *testing.T) { + repo, _ := newSimplePublishRepository(t, false) + profile := `{"product":"Config","source":{},"readiness":{"required_files":["absent"]},"delivery":{"forge":"gitea","base_url":"https://gitea.example","owner":"owner","repository":"project","credentials":{"local":{"token_file":"absent-token"},"ci":{"token_environment_variable":"READINESS_TEST_TOKEN"}}}}` + writeRepositoryFile(t, repo, "releasekit.json", profile) + t.Setenv("READINESS_TEST_TOKEN", "secret-value") + var output bytes.Buffer + status := run(context.Background(), []string{"validate", "--repo", repo, "--context", "ci", "--operation", "delivery", "--offline", "--json"}, &output, &bytes.Buffer{}) + var report readinessDocument + if err := json.Unmarshal(output.Bytes(), &report); err != nil { + t.Fatal(err) + } + if status != 2 || strings.Contains(output.String(), "secret-value") { + t.Fatalf("status=%d report=%s", status, &output) + } + required, destination := false, false + for _, check := range report.Checks { + if check.ID == "required-file" && check.Status == "failed" { + required = true + } + if check.ID == "delivery-inputs" && check.Status == "passed" { + destination = true + } + } + if !required || !destination { + t.Fatalf("checks = %+v", report.Checks) + } + writeRepositoryFile(t, repo, "absent", "present\n") + output.Reset() + status = run(context.Background(), []string{"validate", "--repo", repo, "--context", "local", "--operation", "delivery", "--offline", "--json"}, &output, &bytes.Buffer{}) + if status != 2 || strings.Contains(output.String(), "secret-value") || !strings.Contains(output.String(), "absent-token") { + t.Fatalf("local status=%d report=%s", status, &output) + } +} + +func TestValidateReportsMalformedProfileAsJSON(t *testing.T) { + repo := newCLIRepository(t) + if err := os.WriteFile(filepath.Join(repo, "releasekit.json"), []byte("{"), 0600); err != nil { + t.Fatal(err) + } + var output bytes.Buffer + status := run(context.Background(), []string{"validate", "--repo", repo, "--json"}, &output, &bytes.Buffer{}) + var report readinessDocument + if err := json.Unmarshal(output.Bytes(), &report); err != nil || status != 2 || len(report.Checks) != 1 || report.Checks[0].ID != "profile" { + t.Fatalf("status=%d report=%s err=%v", status, &output, err) + } +} + +func TestValidateSkipsAssetsWhenSourceIsUnavailable(t *testing.T) { + repo := newCLIRepository(t) + writeRepositoryFile(t, repo, "releasekit.json", `{"product":"Example","source":{"dir":"missing"},"delivery":{"forge":"gitea","base_url":"https://gitea.example","owner":"owner","repository":"example","credentials":{"ci":{}}}}`) + t.Setenv("RELEASEKIT_DELIVERY_TOKEN", "fixture-token") + var output bytes.Buffer + status := run(context.Background(), []string{"validate", "--repo", repo, "--context", "ci", "--operation", "delivery", "--offline", "--assets", "dist", "--json"}, &output, &bytes.Buffer{}) + if status != 2 || !strings.Contains(output.String(), `"id":"prebuilt","operation":"delivery","status":"skipped"`) { + t.Fatalf("status=%d output=%s", status, &output) + } +} + +func TestValidateRejectsInconsistentSourceSelection(t *testing.T) { + repo := newCLIRepository(t) + for _, profile := range []string{ + `{"product":"Example","go":{},"publication":{"mode":"go-module"},"version":{"format":"date"}}`, + `{"product":"Example","source":{"tag_prefix":"bad..tag"}}`, + } { + writeRepositoryFile(t, repo, "releasekit.json", profile) + var output bytes.Buffer + status := run(context.Background(), []string{"validate", "--repo", repo, "--operation", "go", "--offline", "--json"}, &output, &bytes.Buffer{}) + if status != 2 || !strings.Contains(output.String(), `"id":"source","operation":"configuration","status":"failed"`) { + t.Fatalf("status=%d output=%s profile=%s", status, &output, profile) + } + } +} diff --git a/cmd/releasekit/releasekit_delivery_workflow_test.go b/cmd/releasekit/releasekit_delivery_workflow_test.go index 24cb03c..265d731 100644 --- a/cmd/releasekit/releasekit_delivery_workflow_test.go +++ b/cmd/releasekit/releasekit_delivery_workflow_test.go @@ -36,7 +36,8 @@ func TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout(t *testing.T) { cliGitRun(t, repository, "config", "user.email", "releasekit@example.test") // The workflow builds the tagged CLI, including changes under test that may // not yet be committed in the repository from which this fixture was cloned. - for _, name := range []string{"cmd/releasekit/main.go", "cmd/releasekit/internal/cli/config.go", "cmd/releasekit/internal/cli/credentials.go"} { + files := []string{"cmd/releasekit/main.go", "cmd/releasekit/readiness.go", "cmd/releasekit/internal/cli/config.go", "cmd/releasekit/internal/cli/credentials.go", "readiness.go", "internal/readiness/readiness.go", "internal/git/remote.go", "internal/git/source.go", "internal/gitea/backend.go", "internal/gotool/gotool.go"} + for _, name := range files { contents, err := os.ReadFile(filepath.Join(root, filepath.FromSlash(name))) if err != nil { t.Fatal(err) @@ -56,7 +57,7 @@ func TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout(t *testing.T) { if err := os.WriteFile(notePath, []byte(note), 0o600); err != nil { t.Fatal(err) } - cliGitRun(t, repository, "add", "docs/releases/"+version+".md", "cmd/releasekit/main.go", "cmd/releasekit/internal/cli/config.go", "cmd/releasekit/internal/cli/credentials.go") + cliGitRun(t, repository, append([]string{"add", "docs/releases/" + version + ".md"}, files...)...) cliGitRun(t, repository, "commit", "-m", "prepare source-only delivery") state := &deliveryServerState{data: deliveryServerData{product: "ReleaseKit"}} diff --git a/docs/cli.md b/docs/cli.md index 653399a..fe08172 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -242,6 +242,17 @@ 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. +Inspect working release configuration without creating a release: + +```sh +releasekit validate [--repo DIR] [--config FILE] [--context local|ci] [--operation NAME ...] [--offline] [--assets DIR] [--json] +``` + +Validation defaults to local credentials and read-only remote access. Operation +flags narrow the selected capabilities; `--offline` omits remote observations. +See the [readiness guide](consumers/readiness.md) for scope, evidence, and exit +statuses. + Deliver a tagged source release: ```sh diff --git a/docs/config.md b/docs/config.md index f048e48..a2da656 100644 --- a/docs/config.md +++ b/docs/config.md @@ -177,6 +177,11 @@ local files to exist, or inspect Git history. Existing clean-index/worktree requirements still apply to candidate operations. An ignore rule alone does not remove a previously committed file from the candidate. +`readiness.required_files` optionally lists literal repository-root-relative or +absolute files whose readability `validate` checks. These are explicit local +inputs, not inferred SSH authentication requirements; see the +[readiness guide](consumers/readiness.md). + The `delivery` object contains `forge`, `base_url`, `owner`, `repository`, and context-specific `credentials`. A delivery request must set `forge` to `"gitea"`; a missing or unsupported selection is an error for delivery. These diff --git a/docs/consumers/readiness.md b/docs/consumers/readiness.md new file mode 100644 index 0000000..e91fcb5 --- /dev/null +++ b/docs/consumers/readiness.md @@ -0,0 +1,45 @@ +# Readiness validation + +`releasekit validate` inspects the working profile and source inputs before a +release candidate is ready. It does not run product checks, build, download +dependencies, change the checkout, or write to a remote. It does not require a +version or release note. Its results are optional setup evidence, not a release +gate or proof of later write permission. + +```sh +releasekit validate +releasekit validate --context ci --operation delivery --json +releasekit validate --offline --operation publication +``` + +By default, the command selects publication, configured Go and build work, and +delivery when declared. Repeated `--operation` flags select only the named +operations: `publication`, `go`, `build`, `delivery`, and `rehearsal`. +Rehearsal is explicit. The selected `local` or `ci` context controls credential +loading independently of network scope. Online validation reads authoritative +Git `main` from the effective push endpoint and performs hosted delivery +preflight. Offline mode omits those remote reads and identifies the omitted +checks. Local publication readiness also checks Git's configured tagger +identity. Native Git and SSH authentication remain in use; no conventional +private-key filename is required. + +To require a specific local input, list it in `readiness.required_files` in the +profile. Paths are literal repository-root-relative or absolute filenames. This +checks readability, not Git authentication. `--assets DIR` selects an existing +build receipt and artifacts for identity and digest checks; delivery must be +selected. Build outputs are otherwise not required to exist. Dependency-cache +completeness and actual build execution remain unchecked. + +JSON output is one document with `schema_version: 1`, `command: "validate"`, +the working-input scope, selected operations, context, safe credential sources, +destinations, and ordered check results. Check statuses are `passed`, `failed`, +`skipped`, and `unchecked`; reasons distinguish configuration, input, remote, +dependency, offline, and unexecuted evidence. A selected failed or incomplete +check makes the command unsuccessful; an offline omission alone does not. Status +2 reports usage, configuration, or required-input errors; status 1 reports +other failures, cancellation, or output failure. Actual CI secret injection +requires a job or rehearsal result and is not established by local readiness. + +The Go facade's `Validate` accepts explicit selections and tokens and returns a +`ValidationReport` with a `ReadinessError` when selected checks fail. The CLI +loads its own credentials; the library does not load ambient tokens. diff --git a/docs/internal/overview.md b/docs/internal/overview.md index 78f1e31..35b2705 100644 --- a/docs/internal/overview.md +++ b/docs/internal/overview.md @@ -3,14 +3,15 @@ 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 +- The root `releasekit` package is the orchestration facade. `Validate` inspects + working setup and read-only access, `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`, +- `cmd/releasekit` is the executable interface. Its `version`, `validate`, `check`, `publish`, `reconcile`, `publication-attempts`, `build`, `deliver`, and `ci-deliver` commands adapt profiles and command output to the supported library operations. @@ -20,7 +21,8 @@ See the [CLI contract](../cli.md), [configuration reference](../config.md), [source publication guide](../consumers/publish.md), [publication record format](../integrations/publication-records.md), [build guide](../consumers/build.md), -[delivery guide](../consumers/delivery.md), and +[delivery guide](../consumers/delivery.md), +[readiness guide](../consumers/readiness.md), and [runtime version guide](../consumers/runtime-version.md) for task-oriented use. Go declarations and GoDoc remain the owners of exact exported contracts. @@ -49,6 +51,7 @@ reports these implemented packages: | `internal/tempdir` | Disposable system temporary storage outside source worktrees. | | `internal/process` | Cancellable child-process execution, including owned stdin/stdout pipes for serialized exchanges, with per-command environment overlays and removals. | | `internal/preparation` | Coordination for expected-commit tag checkout and Go module dependency preparation. | +| `internal/readiness` | Working-input inspection and read-only setup observations for explicitly selected capabilities. | | `internal/releaseidentity` | Committed-object and working-tree module selection, declaration reading, and semantic-version-to-tag derivation. | | `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, pre-push evidence recording, saved-attempt discovery, later observation, and recovery state. | diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index c7808a4..edd2385 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -305,6 +305,13 @@ legacy migration errors, retained CI variable names, and secret-safe diagnostics ## Stage 7: Implement readiness validation and its CLI +**Completed:** The facade and `validate` command inspect working selections, +optional inputs, Go/build setup, credential contexts, retained artifacts, and +read-only publication/delivery access. Reports aggregate failures and identify +offline or unexecuted evidence. Focused CLI and facade tests, the offline +`go test ./...` suite, and `go run ./internal/apicheck` pass. Rehearsal profile +loading and Woodpecker observation are connected in the following stages. + **Work:** add internal readiness orchestration, a root `Validate` operation, facade-owned request/report types, and `releasekit validate`. diff --git a/internal/git/remote.go b/internal/git/remote.go index 86c1145..639326b 100644 --- a/internal/git/remote.go +++ b/internal/git/remote.go @@ -139,6 +139,30 @@ func (endpoint Endpoint) Recheck(ctx context.Context, repositoryDir string) erro return endpoint.verifyScopedURLs(ctx, repositoryDir) } +// QueryMain reads authoritative main without requiring a release tag or +// comparing the branch to a candidate commit. +func (endpoint Endpoint) QueryMain(ctx context.Context, repositoryDir string) (RemoteRef, error) { + const mainRef = "refs/heads/main" + output, err := run(ctx, repositoryDir, endpoint.scopedConfig(), "ls-remote", endpoint.ScopedName, mainRef) + if err != nil { + return RemoteRef{State: RefUnreadable}, fmt.Errorf("%w: query authoritative main at %s: %w", ErrRemoteStateUnreadable, DisplayURL(endpoint.PushURL), err) + } + main := 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 RemoteRef{State: RefUnreadable}, fmt.Errorf("%w: malformed ls-remote output %q", ErrRemoteStateUnreadable, displayDiagnostic(line)) + } + if name == mainRef { + main = mergeRef(main, object, false) + } + } + return main, nil +} + // Query reads exact main and tag refs. A command failure is unreadable, // never evidence that a ref is absent. func (endpoint Endpoint) Query(ctx context.Context, repositoryDir, tag string) (Snapshot, error) { diff --git a/internal/git/remote_test.go b/internal/git/remote_test.go index 831c3a1..0e5a536 100644 --- a/internal/git/remote_test.go +++ b/internal/git/remote_test.go @@ -10,6 +10,23 @@ import ( "testing" ) +func TestQueryMainDoesNotRequireAReleaseTag(t *testing.T) { + repo := newRemoteFixture(t) + endpoint, err := Resolve(context.Background(), repo.work, "origin") + if err != nil { + t.Fatal(err) + } + main, err := endpoint.QueryMain(context.Background(), repo.work) + if err != nil || main.State != RefPresent || main.Object != repo.commit { + t.Fatalf("main = %#v, error = %v", main, err) + } + gitRun(t, repo.bare, "update-ref", "-d", "refs/heads/main") + main, err = endpoint.QueryMain(context.Background(), repo.work) + if err != nil || main.State != RefAbsent { + t.Fatalf("missing main = %#v, error = %v", main, err) + } +} + 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") diff --git a/internal/git/source.go b/internal/git/source.go index 7639497..9d365db 100644 --- a/internal/git/source.go +++ b/internal/git/source.go @@ -47,6 +47,14 @@ func RepositoryRoot(ctx context.Context, directory string) (string, error) { return normalizeRepositoryRoot(root) } +// CheckTaggerIdentity checks Git's native committer identity without creating a tag. +func CheckTaggerIdentity(ctx context.Context, directory string) error { + if _, err := run(ctx, directory, nil, "var", "GIT_COMMITTER_IDENT"); err != nil { + return fmt.Errorf("resolve Git tagger identity: %w", err) + } + return nil +} + func normalizeRepositoryRoot(root string) (string, error) { root = strings.TrimSuffix(root, "\n") resolved, err := filepath.EvalSymlinks(root) diff --git a/internal/gitea/backend.go b/internal/gitea/backend.go index 9314510..0859027 100644 --- a/internal/gitea/backend.go +++ b/internal/gitea/backend.go @@ -44,14 +44,23 @@ type repositoryResponse struct { } `json:"owner"` } -func (b *Backend) Preflight(ctx context.Context) error { +// ValidateConfiguration checks the destination and token without network access. +func (b *Backend) ValidateConfiguration() error { if strings.TrimSpace(b.destination.Token) == "" { return &forge.PreflightFailure{Kind: forge.PreflightMissingCredential, Err: errors.New("Gitea token is required")} } - base, apiRoot, err := b.destinationAPI("preflight repository access") + _, _, err := b.destinationAPI("preflight repository access") if err != nil { return &forge.PreflightFailure{Kind: forge.PreflightInvalidDestination, Err: err} } + return nil +} + +func (b *Backend) Preflight(ctx context.Context) error { + if err := b.ValidateConfiguration(); err != nil { + return err + } + base, apiRoot, _ := b.destinationAPI("preflight repository access") client := b.client.httpClient() var resolved repositoryResponse endpoint := apiRoot diff --git a/internal/gotool/gotool.go b/internal/gotool/gotool.go index 910e624..b131fbd 100644 --- a/internal/gotool/gotool.go +++ b/internal/gotool/gotool.go @@ -48,6 +48,15 @@ var architectureFeatures = []string{ "GOAMD64", "GOARM", "GOARM64", "GO386", "GOMIPS", "GOMIPS64", "GOPPC64", "GORISCV64", "GOWASM", } +// LocalVersion identifies the selected local Go tool without downloading a toolchain. +func LocalVersion(ctx context.Context, directory string) (string, error) { + output, err := discover(ctx, directory, discoveryEnvironment(), "go", "version") + if err != nil { + return "", fmt.Errorf("identify local Go toolchain: %w", err) + } + return strings.TrimSpace(string(output)), nil +} + // 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 diff --git a/internal/readiness/readiness.go b/internal/readiness/readiness.go new file mode 100644 index 0000000..226329d --- /dev/null +++ b/internal/readiness/readiness.go @@ -0,0 +1,354 @@ +// Package readiness inspects working inputs and read-only access evidence. +package readiness + +import ( + "context" + "errors" + "fmt" + "go/version" + "os" + "path/filepath" + "strings" + + "go.maximumdirect.net/releasekit/internal/artifact" + "go.maximumdirect.net/releasekit/internal/git" + "go.maximumdirect.net/releasekit/internal/gotool" + "go.maximumdirect.net/releasekit/internal/releaseidentity" + "golang.org/x/mod/modfile" + "golang.org/x/mod/module" +) + +type Request struct { + RepositoryDir, ModuleDir, Product, Remote, ExpectedPushURL, Context string + Source *releaseidentity.SourceSpec + Operations []string + Offline bool + Build *artifact.Settings + HasDelivery, HasRehearsal bool + RequiredFiles []string + DeliveryConfig func() error + Credential func() error + Delivery func(context.Context) error + Prebuilt func(context.Context, releaseidentity.ResolvedSource) error +} + +type Check struct { + ID, Operation, Status, Reason, Message string + Cause error +} + +type Report struct { + RepositoryDir, GitDestination string + Operations []string + Checks []Check +} + +func (r *Report) record(id, operation, reason string, err error) bool { + check := Check{ID: id, Operation: operation, Status: "passed", Reason: reason, Message: "available"} + if err != nil { + check.Status = "failed" + check.Message = git.DisplayDiagnostic(err.Error()) + check.Cause = err + } + r.Checks = append(r.Checks, check) + return err == nil +} +func (r *Report) note(id, operation, status, reason, message string) { + r.Checks = append(r.Checks, Check{ID: id, Operation: operation, Status: status, Reason: reason, Message: message}) +} + +// Run collects independent working-input and read-only observations. Network +// effects are limited to selected publication reads and the supplied preflight. +func Run(ctx context.Context, request Request) Report { + report := Report{Operations: append([]string(nil), request.Operations...)} + selected := map[string]bool{} + for _, op := range report.Operations { + selected[op] = true + } + has := func(op string) bool { + return selected[op] || selected["rehearsal"] && (op == "publication" || op == "delivery") + } + if strings.TrimSpace(request.Product) == "" { + report.record("product", "configuration", "configuration", errors.New("product is required")) + } + if request.Context != "local" && request.Context != "ci" { + report.record("context", "configuration", "configuration", errors.New("context must be local or ci")) + } + for _, op := range report.Operations { + switch op { + case "publication", "go", "build", "delivery", "rehearsal": + default: + report.record("operation", op, "configuration", fmt.Errorf("unknown operation %q", op)) + } + } + repository, repoErr := git.RepositoryRoot(ctx, request.RepositoryDir) + report.record("repository", "configuration", "configuration", repoErr) + report.RepositoryDir = repository + var source releaseidentity.ResolvedSource + var sourceErr error + if repoErr == nil { + source, sourceErr = releaseidentity.LoadWorkingSource(ctx, repository, request.ModuleDir, request.Source) + if sourceErr == nil { + sourceErr = inspectSourceConfiguration(ctx, request, source) + } + report.record("source", "configuration", "configuration", sourceErr) + } else { + report.note("source", "configuration", "skipped", "dependency", "repository unavailable") + } + if selected["go"] && sourceErr == nil && repoErr == nil && !source.GoEnabled { + report.record("go-selection", "go", "configuration", errors.New("Go capability is not declared")) + } + if selected["build"] && (request.Build == nil || len(request.Build.Targets) == 0) { + report.record("build-selection", "build", "configuration", errors.New("build targets are not declared")) + } + if selected["build"] && repoErr == nil && sourceErr == nil && !source.GoEnabled { + report.record("build-capability", "build", "configuration", errors.New("build targets require Go capability")) + } + if has("delivery") && !request.HasDelivery { + report.record("delivery-selection", "delivery", "configuration", errors.New("delivery is not declared")) + } + if selected["rehearsal"] && !request.HasRehearsal { + report.record("rehearsal-selection", "rehearsal", "configuration", errors.New("rehearsal is not declared")) + } + for _, name := range request.RequiredFiles { + path := name + if !filepath.IsAbs(path) { + path = filepath.Join(repository, path) + } + var err error + if strings.TrimSpace(name) == "" { + err = errors.New("required file path is blank") + } else if !filepath.IsAbs(name) && (filepath.Clean(name) == ".." || strings.HasPrefix(filepath.Clean(name), ".."+string(filepath.Separator))) { + err = errors.New("relative required file path escapes the repository") + } else if repoErr != nil && !filepath.IsAbs(name) { + err = errors.New("repository unavailable for relative required file") + } else { + var info os.FileInfo + info, err = os.Stat(path) + if err == nil && !info.Mode().IsRegular() { + err = errors.New("required input is not a regular file") + } + if err == nil { + var file *os.File + file, err = os.Open(path) + if err == nil { + err = file.Close() + } + } + } + if err != nil { + err = fmt.Errorf("required file %q: %w", git.DisplayDiagnostic(name), err) + } + report.record("required-file", "configuration", "required_input", err) + } + if has("publication") { + if repoErr != nil { + report.note("git-identity", "publication", "skipped", "dependency", "repository unavailable") + report.note("git-main", "publication", "skipped", "dependency", "repository unavailable") + } else { + if request.Context == "local" { + report.record("git-identity", "publication", "configuration", git.CheckTaggerIdentity(ctx, repository)) + } + remote := request.Remote + if remote == "" { + remote = "origin" + } + endpoint, err := git.Resolve(ctx, repository, remote) + if err == nil { + report.GitDestination = git.DisplayURL(endpoint.PushURL) + if request.ExpectedPushURL != "" && request.ExpectedPushURL != endpoint.PushURL { + err = fmt.Errorf("effective push endpoint %q differs from expected %q", git.DisplayURL(endpoint.PushURL), git.DisplayURL(request.ExpectedPushURL)) + } + } + if report.record("git-endpoint", "publication", "configuration", err) { + if request.Offline { + report.note("git-main", "publication", "unchecked", "offline", "authoritative main not read in offline mode") + } else { + main, readErr := endpoint.QueryMain(ctx, repository) + if readErr == nil && main.State != git.RefPresent { + readErr = errors.New("authoritative main is absent or ambiguous") + } + report.record("git-main", "publication", "remote", readErr) + } + } else { + report.note("git-main", "publication", "skipped", "dependency", "publication endpoint unavailable") + } + } + } + buildNeeded := selected["build"] || selected["rehearsal"] && request.Build != nil && len(request.Build.Targets) > 0 + goNeeded := selected["go"] || buildNeeded || selected["rehearsal"] && source.GoEnabled + if goNeeded && repoErr == nil && sourceErr == nil && source.GoEnabled { + report.record("go-toolchain", "go", "required_input", inspectGo(ctx, source.ModuleDir)) + report.note("go-dependencies", "go", "unchecked", "not_executed", "dependency cache and build execution were not checked") + } else if goNeeded { + report.note("go-toolchain", "go", "skipped", "dependency", "selected Go source unavailable") + } + if buildNeeded && request.Build != nil && len(request.Build.Targets) > 0 { + if repoErr != nil || sourceErr != nil || !source.GoEnabled { + report.note("build-inputs", "build", "skipped", "dependency", "selected Go source unavailable") + } else { + if report.record("build-inputs", "build", "configuration", inspectBuild(source, *request.Build)) && !localMainPackage(source, request.Build.MainPackage) { + report.note("main-package", "build", "unchecked", "not_executed", "external package inputs require build execution") + } + } + } + if has("delivery") && request.HasDelivery { + var configErr, credentialErr error + if request.DeliveryConfig == nil { + configErr = errors.New("delivery settings unavailable") + } else { + configErr = request.DeliveryConfig() + } + if request.Credential == nil { + credentialErr = errors.New("delivery credential unavailable") + } else { + credentialErr = request.Credential() + } + configOK := report.record("delivery-inputs", "delivery", "configuration", configErr) + credentialOK := report.record("delivery-credential", "delivery", "configuration", credentialErr) + if !configOK || !credentialOK { + report.note("delivery-access", "delivery", "skipped", "dependency", "delivery settings or credential unavailable") + } else if request.Offline { + report.note("delivery-access", "delivery", "unchecked", "offline", "hosted access not checked in offline mode") + } else if request.Delivery == nil { + report.record("delivery-access", "delivery", "remote", errors.New("delivery observation unavailable")) + } else { + report.record("delivery-access", "delivery", "remote", request.Delivery(ctx)) + } + } + if request.Prebuilt != nil { + if !has("delivery") { + report.record("prebuilt", "delivery", "configuration", errors.New("prebuilt assets require delivery selection")) + } else if sourceErr != nil || repoErr != nil { + report.note("prebuilt", "delivery", "skipped", "dependency", "selected source unavailable") + } else { + report.record("prebuilt", "delivery", "required_input", request.Prebuilt(ctx, source)) + } + } + if selected["rehearsal"] { + report.note("ci-secret-injection", "rehearsal", "unchecked", "not_executed", "CI job secret injection requires job evidence") + if request.Offline { + report.note("woodpecker-access", "rehearsal", "unchecked", "offline", "Woodpecker access not checked in offline mode") + } else if request.HasRehearsal { + report.note("woodpecker-access", "rehearsal", "unchecked", "unavailable", "Woodpecker observation is unavailable") + } else { + report.note("woodpecker-access", "rehearsal", "skipped", "dependency", "rehearsal settings unavailable") + } + } + return report +} + +// inspectSourceConfiguration exercises the selected tag rules with a valid +// representative identifier. It neither selects nor requires a release version. +func inspectSourceConfiguration(ctx context.Context, request Request, source releaseidentity.ResolvedSource) error { + version := source.VersionPrefix + "1.0.0" + if source.Publication == "go-module" { + if source.VersionFormat != "semver" || source.VersionPrefix != "v" { + return errors.New("Go module publication requires prefixed semantic versions") + } + _, major, ok := module.SplitPathVersion(source.ModulePath) + if !ok { + return errors.New("invalid Go module path major") + } + if major != "" { + version = strings.TrimLeft(major, "/.") + ".0.0" + } + } else { + switch source.VersionFormat { + case "date": + version = source.VersionPrefix + "2000-01-01" + case "year-month": + version = source.VersionPrefix + "2000.01.0" + } + } + _, err := releaseidentity.FromWorkingSource(ctx, source.RepositoryDir, request.ModuleDir, version, request.Source) + return err +} + +func inspectGo(ctx context.Context, dir string) error { + data, err := os.ReadFile(filepath.Join(dir, "go.mod")) + if err != nil { + return err + } + declaration, err := modfile.Parse("go.mod", data, nil) + if err != nil { + return err + } + output, err := gotool.LocalVersion(ctx, dir) + if err != nil { + return err + } + fields := strings.Fields(output) + if len(fields) < 3 || !version.IsValid(fields[2]) { + return errors.New("Go returned an unrecognized version") + } + if declaration.Go != nil && version.Compare(fields[2], "go"+declaration.Go.Version) < 0 { + return fmt.Errorf("local %s is older than declared Go %s", fields[2], declaration.Go.Version) + } + return nil +} + +func inspectBuild(source releaseidentity.ResolvedSource, build artifact.Settings) error { + if strings.TrimSpace(build.MainPackage) == "" || !artifact.ValidComponent(build.BinaryName) { + return errors.New("build requires a main package and valid binary name") + } + for _, target := range build.Targets { + if !artifact.ValidComponent(target.OS) || !artifact.ValidComponent(target.Arch) { + return fmt.Errorf("invalid build target %q/%q", target.OS, target.Arch) + } + } + name := build.MainPackage + if name == source.ModulePath { + name = "." + } else if strings.HasPrefix(name, source.ModulePath+"/") { + name = "./" + strings.TrimPrefix(name, source.ModulePath+"/") + } + if name == "." || strings.HasPrefix(name, "./") { + path := filepath.Join(source.ModuleDir, filepath.FromSlash(name)) + info, err := os.Stat(path) + if err != nil { + return fmt.Errorf("inspect main package: %w", err) + } + if !info.IsDir() { + return errors.New("main package input is not a directory") + } + entries, err := os.ReadDir(path) + if err != nil { + return err + } + var inputErr error + for _, entry := range entries { + if !entry.IsDir() && strings.HasSuffix(entry.Name(), ".go") && !strings.HasSuffix(entry.Name(), "_test.go") { + filename := filepath.Join(path, entry.Name()) + info, err := os.Stat(filename) + if err != nil { + inputErr = err + continue + } + if !info.Mode().IsRegular() { + continue + } + file, err := os.Open(filename) + if err != nil { + inputErr = err + continue + } + closeErr := file.Close() + if closeErr != nil { + inputErr = closeErr + continue + } + return nil + } + } + if inputErr != nil { + return fmt.Errorf("read main package input: %w", inputErr) + } + return errors.New("main package directory contains no non-test Go source") + } + return nil +} + +func localMainPackage(source releaseidentity.ResolvedSource, name string) bool { + return name == "." || strings.HasPrefix(name, "./") || name == source.ModulePath || strings.HasPrefix(name, source.ModulePath+"/") +} diff --git a/readiness.go b/readiness.go new file mode 100644 index 0000000..d5a234c --- /dev/null +++ b/readiness.go @@ -0,0 +1,294 @@ +package releasekit + +import ( + "context" + "encoding/hex" + "errors" + "fmt" + "io" + "net/url" + "os" + "path/filepath" + "strings" + + "go.maximumdirect.net/releasekit/internal/artifact" + "go.maximumdirect.net/releasekit/internal/git" + "go.maximumdirect.net/releasekit/internal/readiness" + "go.maximumdirect.net/releasekit/internal/releaseidentity" +) + +// ReadinessOperation selects an independent readiness capability. +type ReadinessOperation string + +const ( + ReadinessPublication ReadinessOperation = "publication" + ReadinessGo ReadinessOperation = "go" + ReadinessBuild ReadinessOperation = "build" + ReadinessDelivery ReadinessOperation = "delivery" + ReadinessRehearsal ReadinessOperation = "rehearsal" +) + +// ReadinessStatus describes the evidence obtained for a check. +type ReadinessStatus string + +const ( + ReadinessPassed ReadinessStatus = "passed" + ReadinessFailed ReadinessStatus = "failed" + ReadinessSkipped ReadinessStatus = "skipped" + ReadinessUnchecked ReadinessStatus = "unchecked" +) + +// ReadinessCredential describes a credential source without exposing a token. +type ReadinessCredential struct { + Context string + Source string + Declared bool +} + +// WoodpeckerObservation identifies the selected CI repository and credential. +type WoodpeckerObservation struct { + BaseURL string + RepositoryID int64 + Workflow string + Step string + Token string +} + +// ValidateRequest supplies working inputs and explicit credentials for a +// read-only readiness inspection. It does not load ambient credentials. +type ValidateRequest struct { + RepositoryDir string + ModuleDir string + Source *SourceSpec + Product string + Remote string + ExpectedPushURL string + Operations []ReadinessOperation + Context string + Offline bool + Build *BuildSpec + Destination *DeliveryDestination + Credentials []ReadinessCredential + CredentialError error + Woodpecker *WoodpeckerObservation + RequiredFiles []string + Prebuilt *BuildResult + Output io.Writer +} + +// ReadinessError summarizes unsuccessful checks while preserving their causes. +type ReadinessError struct{ Causes []error } + +func (err *ReadinessError) Error() string { + return "readiness validation did not complete successfully" +} +func (err *ReadinessError) Unwrap() []error { return err.Causes } + +// Validate inspects working inputs and selected read-only access without +// building, publishing, checking out, or running product checks. +func Validate(ctx context.Context, request ValidateRequest) (ValidationReport, error) { + if request.Context == "" { + request.Context = "local" + } + operations := append([]ReadinessOperation(nil), request.Operations...) + if len(operations) == 0 { + operations = append(operations, ReadinessPublication) + selection, err := releaseidentity.NormalizeSource(request.ModuleDir, internalSourceSpec(request.Source)) + if err == nil && selection.GoEnabled { + operations = append(operations, ReadinessGo) + } + if request.Build != nil && len(request.Build.Targets) != 0 { + operations = append(operations, ReadinessBuild) + } + if request.Destination != nil { + operations = append(operations, ReadinessDelivery) + } + } + var operationNames []string + seen := map[ReadinessOperation]bool{} + unique := operations[:0] + for _, operation := range operations { + if !seen[operation] { + seen[operation] = true + unique = append(unique, operation) + operationNames = append(operationNames, string(operation)) + } + } + operations = unique + internalRequest := readiness.Request{ + RepositoryDir: request.RepositoryDir, ModuleDir: request.ModuleDir, Source: internalSourceSpec(request.Source), Product: request.Product, + Remote: request.Remote, ExpectedPushURL: request.ExpectedPushURL, Context: request.Context, Operations: operationNames, + Offline: request.Offline, HasDelivery: request.Destination != nil, HasRehearsal: request.Woodpecker != nil, RequiredFiles: request.RequiredFiles, + } + if request.Build != nil { + settings := *internalBuildSpec(request.Build) + internalRequest.Build = &settings + } + if request.Destination != nil { + internalRequest.DeliveryConfig = func() error { + destination := *request.Destination + destination.Token = "readiness-configuration" + backend, err := deliveryBackend(destination) + if err != nil { + return err + } + validator, ok := backend.(interface{ ValidateConfiguration() error }) + if !ok { + return errors.New("destination validation is unavailable") + } + return publicPreflightError(validator.ValidateConfiguration()) + } + internalRequest.Credential = func() error { + if request.CredentialError != nil { + return request.CredentialError + } + if strings.TrimSpace(request.Destination.Token) == "" { + return errors.New("delivery token is required") + } + return nil + } + internalRequest.Delivery = func(ctx context.Context) error { + return PreflightDelivery(ctx, *request.Destination) + } + } + if request.Prebuilt != nil { + internalRequest.Prebuilt = func(ctx context.Context, source releaseidentity.ResolvedSource) error { + return validateReadinessBuild(ctx, request, source) + } + } + internal := readiness.Run(ctx, internalRequest) + report := ValidationReport{InputSource: "working", RepositoryDir: internal.RepositoryDir, Operations: operations, Context: request.Context, Offline: request.Offline, GitDestination: internal.GitDestination, Credentials: append([]ReadinessCredential(nil), request.Credentials...)} + if request.Destination != nil { + report.DeliveryDestination = git.DisplayURL(request.Destination.BaseURL) + "/" + request.Destination.Owner + "/" + request.Destination.Repository + } + var causes []error + for _, check := range internal.Checks { + if check.ID == "delivery-access" && check.Cause != nil { + var failure *DeliveryPreflightError + if errors.As(check.Cause, &failure) && failure.Kind != DeliveryPreflightUnavailable && !errors.Is(check.Cause, context.Canceled) && !errors.Is(check.Cause, context.DeadlineExceeded) { + check.Reason = "configuration" + } + } + report.Checks = append(report.Checks, ReadinessResult{ID: check.ID, Operation: ReadinessOperation(check.Operation), Status: ReadinessStatus(check.Status), Reason: check.Reason, Message: check.Message, Cause: check.Cause}) + if check.Status == "failed" { + if check.Cause != nil { + causes = append(causes, check.Cause) + } else { + causes = append(causes, errors.New(check.Message)) + } + } + if check.Status == "unchecked" && check.Reason == "unavailable" { + causes = append(causes, errors.New(check.Message)) + } + } + for _, credential := range request.Credentials { + if !seen[ReadinessDelivery] && !seen[ReadinessRehearsal] { + break + } + if credential.Declared && strings.TrimSpace(credential.Source) == "" { + err := fmt.Errorf("%s credential source is blank", credential.Context) + report.Checks = append(report.Checks, ReadinessResult{ID: "credential-declaration", Operation: ReadinessDelivery, Status: ReadinessFailed, Reason: "configuration", Message: err.Error(), Cause: err}) + causes = append(causes, err) + } + } + if seen[ReadinessRehearsal] && request.Woodpecker != nil { + observation := request.Woodpecker + base, err := url.Parse(observation.BaseURL) + if err != nil || base == nil || (base.Scheme != "http" && base.Scheme != "https") || base.Host == "" || observation.RepositoryID <= 0 || strings.TrimSpace(observation.Workflow) == "" || strings.TrimSpace(observation.Step) == "" || strings.TrimSpace(observation.Token) == "" { + err := errors.New("rehearsal requires a valid Woodpecker URL, repository ID, workflow, step, and token") + report.Checks = append(report.Checks, ReadinessResult{ID: "woodpecker-settings", Operation: ReadinessRehearsal, Status: ReadinessFailed, Reason: "configuration", Message: err.Error(), Cause: err}) + causes = append(causes, err) + } + } + if request.Output != nil { + if _, err := fmt.Fprintf(request.Output, "readiness source=working context=%s offline=%t\n", request.Context, request.Offline); err != nil { + causes = append(causes, err) + } + } + if len(causes) != 0 { + return report, &ReadinessError{Causes: causes} + } + return report, nil +} + +func validateReadinessBuild(ctx context.Context, request ValidateRequest, source releaseidentity.ResolvedSource) error { + build := request.Prebuilt + if build.IdentityKind == "diagnostic" { + attempt := strings.TrimPrefix(build.Version, "releasekit-test-") + parts := strings.Split(build.Tag, "/") + if !strings.HasPrefix(build.Version, "releasekit-test-") || len(attempt) != 32 || strings.ToLower(attempt) != attempt || len(parts) != 3 || parts[0] != "releasekit-test" || parts[1] == "" || parts[2] != attempt { + return errors.New("invalid diagnostic build identity") + } + if _, err := hex.DecodeString(attempt); err != nil { + return errors.New("invalid diagnostic build identity") + } + if err := git.CheckTagRef(ctx, source.RepositoryDir, build.Tag); err != nil { + return err + } + } else { + identity, err := releaseidentity.FromWorkingSource(ctx, source.RepositoryDir, request.ModuleDir, build.Version, internalSourceSpec(request.Source)) + if err != nil { + return err + } + if build.IdentityKind != identity.Kind || build.Tag != identity.Tag { + return errors.New("prebuilt release identity does not match selected source") + } + } + commit, err := git.CaptureHead(ctx, source.RepositoryDir) + if err != nil { + return err + } + if build.RepositoryDir != source.RepositoryDir || build.SourceDir != source.ModuleDir || build.SourceSubdir != source.ModuleSubdir || build.GoEnabled != source.GoEnabled || string(build.Publication) != source.Publication || string(build.VersionFormat) != source.VersionFormat || build.VersionPrefix != source.VersionPrefix || build.CandidateCommit != commit || build.ModulePath != source.ModulePath || build.ModuleDir != source.ModuleDir { + return errors.New("prebuilt identity does not match the selected source and commit") + } + if request.Build == nil { + return errors.New("prebuilt assets require declared build settings") + } + if len(request.Build.Targets) != 0 && !build.SourceVerified { + return errors.New("prebuilt build source was not verified") + } + want := internalBuildSpec(request.Build) + if build.MainPackage != want.MainPackage || build.BinaryName != want.BinaryName { + return errors.New("prebuilt build settings do not match") + } + declarations := make([]artifact.Declaration, 0, len(build.Artifacts)) + assets := make([]artifact.ExpectedAsset, 0, len(build.Artifacts)) + for _, item := range build.Artifacts { + declarations = append(declarations, artifact.Declaration{Target: artifact.Target{OS: item.Target.OS, Arch: item.Target.Arch}, Filename: item.Filename}) + if !filepath.IsAbs(item.Path) || !filepath.IsAbs(build.OutputDir) || filepath.Clean(filepath.Dir(item.Path)) != filepath.Clean(build.OutputDir) { + return errors.New("prebuilt artifact path must be in the recorded output directory") + } + info, err := os.Stat(item.Path) + if err != nil { + return err + } + assets = append(assets, artifact.ExpectedAsset{Filename: item.Filename, Path: item.Path, SHA256: item.SHA256, Size: info.Size()}) + } + if err := artifact.ValidateDeclarations(build.BinaryName, build.Version, artifact.NormalizeTargets(want.Targets), declarations); err != nil { + return err + } + return artifact.VerifyLocalAssets(assets) +} + +// ReadinessResult records one check, its outcome, and an optional cause. +type ReadinessResult struct { + ID string + Operation ReadinessOperation + Status ReadinessStatus + Reason string + Message string + Cause error +} + +// ValidationReport records the scope and ordered findings of a readiness run. +type ValidationReport struct { + InputSource string + RepositoryDir string + Operations []ReadinessOperation + Context string + Offline bool + GitDestination string + DeliveryDestination string + Credentials []ReadinessCredential + Checks []ReadinessResult +} diff --git a/readiness_test.go b/readiness_test.go new file mode 100644 index 0000000..9df94ca --- /dev/null +++ b/readiness_test.go @@ -0,0 +1,19 @@ +package releasekit_test + +import ( + "context" + "errors" + "testing" + + releasekit "go.maximumdirect.net/releasekit" +) + +func TestValidatePreservesPartialReportAndCancellation(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + report, err := releasekit.Validate(ctx, releasekit.ValidateRequest{RepositoryDir: t.TempDir(), Product: "Example", Source: &releasekit.SourceSpec{}, Offline: true}) + var failure *releasekit.ReadinessError + if !errors.As(err, &failure) || !errors.Is(err, context.Canceled) || report.InputSource != "working" || len(report.Checks) == 0 { + t.Fatalf("report=%+v error=%v", report, err) + } +}