Wire rehearsal commands and tagged workflows
This commit is contained in:
@@ -4,6 +4,7 @@ import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
|
||||
@@ -143,3 +144,31 @@ func main(){ if len(os.Args)==2 && os.Args[1]=="version" {fmt.Println("fixture",
|
||||
t.Fatalf("result=%+v error=%v", result, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCIDiagnosticRejectsProfileSelectorMismatch(t *testing.T) {
|
||||
repo := newCLIRepository(t)
|
||||
writeRepositoryFile(t, repo, "releasekit.json", `{"product":"Example","source":{},"rehearsal":{"selector":"root"}}`)
|
||||
cliGitRun(t, repo, "add", "releasekit.json")
|
||||
cliGitRun(t, repo, "commit", "-m", "capture profile")
|
||||
captured, err := cli.CaptureCommittedProfile(t.Context(), repo, "HEAD", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
source, err := releaseidentity.LoadCommittedSource(t.Context(), repo, "", captured.Commit, captured.Settings.SourceSpec())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
identity, id, err := releaseidentity.NewDiagnostic(t.Context(), source, "other", captured.Commit)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
manifest := rehearsal.NewManifest(identity, id, "other", captured.Path, captured.Bytes)
|
||||
if _, err := rehearsal.CreateDiagnosticTag(t.Context(), repo, manifest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var output, diagnostics bytes.Buffer
|
||||
status := run(t.Context(), []string{"ci-deliver", "--repo", repo, "--prepared", "--commit", identity.Commit, identity.Tag}, &output, &diagnostics)
|
||||
if status == 0 || !strings.Contains(diagnostics.String(), "does not select diagnostic selector") {
|
||||
t.Fatalf("status=%d output=%s diagnostics=%s", status, &output, &diagnostics)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,12 +13,13 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"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]"
|
||||
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 test [--repo DIR] [--config FILE] [--ref REF] [--record-dir DIR] [--timeout DURATION] [--cleanup-timeout DURATION] [--json]\n releasekit test-resume --record FILE [--token-file FILE] [--woodpecker-token-file FILE] [--timeout DURATION] [--cleanup-timeout DURATION] [--json]\n releasekit test-cleanup --record FILE [--token-file FILE] [--woodpecker-token-file FILE] [--cleanup-timeout DURATION] [--json]\n releasekit reconcile --record FILE [--json]\n releasekit publication-attempts [--repo DIR] [--record-dir DIR] [--json]"
|
||||
|
||||
type Command string
|
||||
|
||||
@@ -32,28 +33,36 @@ const (
|
||||
CIDeliveryAction Command = "ci-deliver"
|
||||
ReconcileAction Command = "reconcile"
|
||||
PublicationAttemptsAction Command = "publication-attempts"
|
||||
TestAction Command = "test"
|
||||
TestResumeAction Command = "test-resume"
|
||||
TestCleanupAction Command = "test-cleanup"
|
||||
)
|
||||
|
||||
// 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
|
||||
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
|
||||
Ref string
|
||||
TokenFile string
|
||||
WoodpeckerTokenFile string
|
||||
Timeout time.Duration
|
||||
CleanupTimeout time.Duration
|
||||
}
|
||||
|
||||
type operationFlags []string
|
||||
@@ -80,6 +89,42 @@ func Parse(args []string) (Invocation, error) {
|
||||
return Invocation{}, errors.New("a command is required")
|
||||
}
|
||||
switch args[0] {
|
||||
case string(TestAction), string(TestResumeAction), string(TestCleanupAction):
|
||||
action := Command(args[0])
|
||||
flags := flag.NewFlagSet(string(action), flag.ContinueOnError)
|
||||
flags.SetOutput(io.Discard)
|
||||
invocation := Invocation{Command: action, Timeout: 30 * time.Minute, CleanupTimeout: 2 * time.Minute}
|
||||
if action == TestAction {
|
||||
flags.StringVar(&invocation.Repository, "repo", ".", "repository directory")
|
||||
flags.StringVar(&invocation.ConfigPath, "config", "", "committed profile path")
|
||||
flags.StringVar(&invocation.Ref, "ref", "", "source commit")
|
||||
flags.StringVar(&invocation.RecordDir, "record-dir", "", "attempt record directory")
|
||||
} else {
|
||||
flags.StringVar(&invocation.RecordPath, "record", "", "attempt record file")
|
||||
flags.StringVar(&invocation.TokenFile, "token-file", "", "delivery token file override")
|
||||
flags.StringVar(&invocation.WoodpeckerTokenFile, "woodpecker-token-file", "", "Woodpecker token file override")
|
||||
}
|
||||
if action != TestCleanupAction {
|
||||
flags.DurationVar(&invocation.Timeout, "timeout", 30*time.Minute, "CI observation timeout")
|
||||
}
|
||||
flags.DurationVar(&invocation.CleanupTimeout, "cleanup-timeout", 2*time.Minute, "cleanup timeout")
|
||||
flags.BoolVar(&invocation.JSON, "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 != TestAction && strings.TrimSpace(invocation.RecordPath) == "" {
|
||||
return Invocation{}, fmt.Errorf("%s requires --record FILE", action)
|
||||
}
|
||||
if invocation.Timeout < 0 {
|
||||
return Invocation{}, errors.New("--timeout must not be negative")
|
||||
}
|
||||
if invocation.CleanupTimeout <= 0 {
|
||||
return Invocation{}, errors.New("--cleanup-timeout must be positive")
|
||||
}
|
||||
return invocation, nil
|
||||
case string(ValidateAction):
|
||||
flags := flag.NewFlagSet(string(ValidateAction), flag.ContinueOnError)
|
||||
flags.SetOutput(io.Discard)
|
||||
|
||||
@@ -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.TestAction || invocation.Command == cli.TestResumeAction || invocation.Command == cli.TestCleanupAction {
|
||||
return runRehearsal(ctx, invocation, stdout, stderr)
|
||||
}
|
||||
if invocation.Command == cli.ValidateAction {
|
||||
return runValidate(ctx, invocation, stdout)
|
||||
}
|
||||
|
||||
@@ -27,6 +27,9 @@ func TestMultiModuleSelectorMapsSelectorsAndTags(t *testing.T) {
|
||||
{mode: "tag", value: "integrations/ckconfig/v1.2.3", want: "ckconfig\tintegrations/ckconfig/v*\tintegrations/ckconfig\treleasekit-ckconfig.json"},
|
||||
{mode: "tag", value: "integrations/core/v2.3.4", want: "core-v2\tintegrations/core/v2.*\tintegrations/core/v2\treleasekit-core-v2.json"},
|
||||
{mode: "tag", value: "v1.2.3", want: "root\tv[01].*\t.\treleasekit-root.json"},
|
||||
{mode: "tag", value: "configuration/2026-12-05", want: "config\tconfiguration/20*\t-\treleasekit-config.json"},
|
||||
{mode: "tag", value: "releasekit-test/ckconfig/" + strings.Repeat("a", 32), want: "ckconfig\tintegrations/ckconfig/v*\tintegrations/ckconfig\treleasekit-ckconfig.json"},
|
||||
{mode: "tag", value: "releasekit-test/config/" + strings.Repeat("b", 32), want: "config\tconfiguration/20*\t-\treleasekit-config.json"},
|
||||
} {
|
||||
t.Run(test.mode+" "+test.value, func(t *testing.T) {
|
||||
got := runModuleSelector(t, helper, test.mode, test.value, "")
|
||||
@@ -46,6 +49,9 @@ func TestMultiModuleSelectorMapsSelectorsAndTags(t *testing.T) {
|
||||
if output := runModuleSelectorError(t, helper, "tag", "feature/v1.2.3", mapPath); !strings.Contains(output, "ambiguous") {
|
||||
t.Fatalf("ambiguous event error = %q", output)
|
||||
}
|
||||
if output := runModuleSelectorError(t, helper, "tag", "releasekit-test/ckconfig/invalid", ""); !strings.Contains(output, "invalid diagnostic") {
|
||||
t.Fatalf("malformed diagnostic error=%q", output)
|
||||
}
|
||||
|
||||
if err := os.WriteFile(mapPath, []byte("space\tfeature/*\tintegrations/ck config\tprofiles/core release.json\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -19,6 +19,8 @@ import (
|
||||
"testing"
|
||||
|
||||
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
|
||||
"go.maximumdirect.net/releasekit/internal/rehearsal"
|
||||
"go.maximumdirect.net/releasekit/internal/releaseidentity"
|
||||
)
|
||||
|
||||
func TestMultiModuleWoodpeckerDelivery(t *testing.T) {
|
||||
@@ -33,7 +35,7 @@ func TestMultiModuleWoodpeckerDelivery(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
command := strings.ReplaceAll(block, "$${", "${")
|
||||
for _, eventTag := range []string{"refs/tags/v[01].*", "refs/tags/integrations/ckconfig/v*", "refs/tags/integrations/core/v2.*"} {
|
||||
for _, eventTag := range []string{"refs/tags/v[01].*", "refs/tags/integrations/ckconfig/v*", "refs/tags/integrations/core/v2.*", "refs/tags/configuration/20*", "refs/tags/releasekit-test/*/*"} {
|
||||
if !strings.Contains(string(contents), eventTag) {
|
||||
t.Errorf("workflow tag filters omit %q", eventTag)
|
||||
}
|
||||
@@ -41,6 +43,83 @@ func TestMultiModuleWoodpeckerDelivery(t *testing.T) {
|
||||
toolBinary := buildWorkflowCLI(t, root)
|
||||
proxy := writeWorkflowToolProxy(t)
|
||||
|
||||
t.Run("diagnostic tag selects the committed module and profile", func(t *testing.T) {
|
||||
attemptID := strings.Repeat("a", 32)
|
||||
tag := "releasekit-test/ckconfig/" + attemptID
|
||||
delivery := newMappedDeliveryFixture(t, tag)
|
||||
repository := newWorkflowRepository(t, example)
|
||||
writeMappedProfile(t, repository, "releasekit-ckconfig.json", cli.Settings{Product: "Example Consumer Integration", ModuleDir: "integrations/ckconfig", Delivery: workflowDeliverySettings(delivery.snapshot().URL), Rehearsal: &cli.RehearsalSettings{Selector: "ckconfig"}})
|
||||
cliGitRun(t, repository, "add", "--all")
|
||||
cliGitRun(t, repository, "commit", "-m", "capture diagnostic selection")
|
||||
captured, err := cli.CaptureCommittedProfile(t.Context(), repository, "HEAD", "releasekit-ckconfig.json")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
source, err := releaseidentity.LoadCommittedSource(t.Context(), repository, captured.Settings.ModuleDir, captured.Commit, captured.Settings.SourceSpec())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
identity, err := releaseidentity.DiagnosticFromAttempt(t.Context(), source, "ckconfig", captured.Commit, attemptID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
manifest := rehearsal.NewManifest(identity, attemptID, "ckconfig", captured.Path, captured.Bytes)
|
||||
if _, err := rehearsal.CreateDiagnosticTag(t.Context(), repository, manifest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
remote := filepath.Join(filepath.Dir(repository), "origin.git")
|
||||
cliGitRun(t, repository, "init", "--bare", remote)
|
||||
cliGitRun(t, repository, "remote", "add", "origin", remote)
|
||||
cliGitRun(t, repository, "push", "origin", "HEAD:refs/heads/main", "refs/tags/"+tag)
|
||||
delivery.update(func(data *mappedDeliveryData) { data.commit = captured.Commit })
|
||||
env := multiModuleWorkflowEnvironment(t, repository, captured.Commit, tag, toolBinary, proxy)
|
||||
output := runWoodpeckerBlock(t, command, repository, env)
|
||||
result, err := rehearsal.ReadResult(strings.NewReader(output), manifest)
|
||||
if err != nil || result.Verification != "complete" || result.PageID != 10 || delivery.snapshot().creates != 1 {
|
||||
t.Fatalf("result=%+v error=%v output=%s", result, err, output)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("source-only row installs the pinned tool", func(t *testing.T) {
|
||||
const tag = "configuration/2026-12-05"
|
||||
delivery := newMappedDeliveryFixture(t, tag)
|
||||
repository := newWorkflowRepository(t, example)
|
||||
writeRepositoryFile(t, repository, ".releasekit-version", "v0.2.197\n")
|
||||
writeMappedProfile(t, repository, "releasekit-config.json", cli.Settings{Product: "Example Configuration", Source: &cli.SourceSettings{Dir: "configuration"}, Version: &cli.VersionSettings{Format: "date"}, Delivery: workflowDeliverySettings(delivery.snapshot().URL), Rehearsal: &cli.RehearsalSettings{Selector: "config"}})
|
||||
commit := tagAndPushWorkflowRepository(t, repository, tag)
|
||||
delivery.update(func(data *mappedDeliveryData) { data.commit = commit })
|
||||
env := multiModuleWorkflowEnvironment(t, repository, commit, tag, toolBinary, proxy)
|
||||
output := runWoodpeckerBlock(t, command, repository, env)
|
||||
if !strings.Contains(output, "state complete") || !strings.Contains(output, "tool-version=v0.2.197") || delivery.snapshot().creates != 1 {
|
||||
t.Fatalf("output=%s delivery=%+v", output, delivery.snapshot())
|
||||
}
|
||||
captured, err := cli.CaptureCommittedProfile(t.Context(), repository, commit, "releasekit-config.json")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
source, err := releaseidentity.LoadCommittedSource(t.Context(), repository, captured.Settings.ModuleDir, commit, captured.Settings.SourceSpec())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
attemptID := strings.Repeat("b", 32)
|
||||
identity, err := releaseidentity.DiagnosticFromAttempt(t.Context(), source, "config", commit, attemptID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
manifest := rehearsal.NewManifest(identity, attemptID, "config", captured.Path, captured.Bytes)
|
||||
if _, err := rehearsal.CreateDiagnosticTag(t.Context(), repository, manifest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cliGitRun(t, repository, "push", "origin", "refs/tags/"+identity.Tag)
|
||||
delivery.update(func(data *mappedDeliveryData) { data.tag = identity.Tag; data.page = false; data.creates = 0 })
|
||||
env["CI_COMMIT_TAG"] = identity.Tag
|
||||
output = runWoodpeckerBlock(t, command, repository, env)
|
||||
result, err := rehearsal.ReadResult(strings.NewReader(output), manifest)
|
||||
if err != nil || result.Verification != "complete" || result.PageID != 10 || delivery.snapshot().creates != 1 {
|
||||
t.Fatalf("diagnostic result=%+v error=%v output=%s", result, err, output)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("nested page delivery retries from tagged mapping", func(t *testing.T) {
|
||||
const tag = "integrations/ckconfig/v1.2.3"
|
||||
delivery := newMappedDeliveryFixture(t, tag)
|
||||
@@ -220,6 +299,7 @@ func newMappedDeliveryFixture(t *testing.T, tag string) *mappedDeliveryFixture {
|
||||
state.mu.Lock()
|
||||
defer state.mu.Unlock()
|
||||
data.requests++
|
||||
tag := data.tag
|
||||
if r.Header.Get("Authorization") != "token fixture-token" {
|
||||
t.Errorf("delivery authorization = %q", r.Header.Get("Authorization"))
|
||||
}
|
||||
|
||||
236
cmd/releasekit/rehearsal.go
Normal file
236
cmd/releasekit/rehearsal.go
Normal file
@@ -0,0 +1,236 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"go.maximumdirect.net/releasekit"
|
||||
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
|
||||
"go.maximumdirect.net/releasekit/internal/forge"
|
||||
"go.maximumdirect.net/releasekit/internal/git"
|
||||
"go.maximumdirect.net/releasekit/internal/rehearsal"
|
||||
"go.maximumdirect.net/releasekit/internal/woodpecker"
|
||||
)
|
||||
|
||||
type rehearsalDocument struct {
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
Command string `json:"command"`
|
||||
AttemptID string `json:"attempt_id,omitempty"`
|
||||
Tag string `json:"tag,omitempty"`
|
||||
Commit string `json:"commit,omitempty"`
|
||||
ProfilePath string `json:"profile_path,omitempty"`
|
||||
ProfileSHA256 string `json:"profile_sha256,omitempty"`
|
||||
Selector string `json:"selector,omitempty"`
|
||||
SourceDir string `json:"source_dir,omitempty"`
|
||||
DiagnosticVersion string `json:"diagnostic_version,omitempty"`
|
||||
Scope string `json:"scope,omitempty"`
|
||||
RecordPath string `json:"record_path,omitempty"`
|
||||
TagObject string `json:"tag_object,omitempty"`
|
||||
Workflow string `json:"workflow"`
|
||||
Build string `json:"build"`
|
||||
Verification string `json:"verification"`
|
||||
Cleanup string `json:"cleanup"`
|
||||
PageID int64 `json:"page_id,omitempty"`
|
||||
PageURL string `json:"page_url,omitempty"`
|
||||
PipelineURLs []string `json:"pipeline_urls,omitempty"`
|
||||
Jobs []rehearsalJobDocument `json:"jobs,omitempty"`
|
||||
Workflows []rehearsalWorkflowDocument `json:"workflows,omitempty"`
|
||||
Artifacts []rehearsalArtifactDocument `json:"artifacts"`
|
||||
Remaining []string `json:"remaining,omitempty"`
|
||||
Diagnostics []string `json:"diagnostics,omitempty"`
|
||||
}
|
||||
type rehearsalJobDocument struct {
|
||||
PipelineID int64 `json:"pipeline_id"`
|
||||
PipelineNumber int64 `json:"pipeline_number"`
|
||||
WorkflowID int64 `json:"workflow_id"`
|
||||
StepID int64 `json:"step_id"`
|
||||
PipelineStatus string `json:"pipeline_status"`
|
||||
WorkflowState string `json:"workflow_state"`
|
||||
StepState string `json:"step_state"`
|
||||
}
|
||||
type rehearsalWorkflowDocument struct {
|
||||
PipelineID int64 `json:"pipeline_id"`
|
||||
PipelineNumber int64 `json:"pipeline_number"`
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
State string `json:"state"`
|
||||
}
|
||||
type rehearsalArtifactDocument struct {
|
||||
Name string `json:"name"`
|
||||
Size int64 `json:"size"`
|
||||
SHA256 string `json:"sha256"`
|
||||
}
|
||||
|
||||
type rehearsalInputError struct{ err error }
|
||||
|
||||
func (err *rehearsalInputError) Error() string { return err.err.Error() }
|
||||
func (err *rehearsalInputError) Unwrap() error { return err.err }
|
||||
|
||||
func runRehearsal(ctx context.Context, invocation cli.Invocation, stdout, stderr io.Writer) int {
|
||||
var result releasekit.RehearsalResult
|
||||
var err error
|
||||
if invocation.Command == cli.TestAction {
|
||||
result, err = startRehearsal(ctx, invocation, stderr)
|
||||
} else {
|
||||
result, err = recoverRecordedRehearsal(ctx, invocation, stderr)
|
||||
}
|
||||
status := rehearsalExitStatus(invocation.Command, result, err)
|
||||
if writeErr := writeRehearsalReport(stdout, invocation, result, err); writeErr != nil {
|
||||
fmt.Fprintf(stderr, "write rehearsal report: %v\n", git.DisplayError(writeErr))
|
||||
return 1
|
||||
}
|
||||
return status
|
||||
}
|
||||
func startRehearsal(ctx context.Context, invocation cli.Invocation, progress io.Writer) (releasekit.RehearsalResult, error) {
|
||||
captured, err := cli.CaptureCommittedProfile(ctx, invocation.Repository, invocation.Ref, invocation.ConfigPath)
|
||||
if err != nil {
|
||||
return releasekit.RehearsalResult{}, err
|
||||
}
|
||||
settings := captured.Settings
|
||||
if settings.Rehearsal == nil || settings.Rehearsal.Woodpecker == nil {
|
||||
return releasekit.RehearsalResult{}, errors.New("rehearsal.woodpecker settings are required")
|
||||
}
|
||||
if settings.Delivery == nil {
|
||||
return releasekit.RehearsalResult{}, errors.New("delivery settings are required")
|
||||
}
|
||||
forgeToken, _, err := cli.ResolveDeliveryCredential(captured.RepositoryDir, settings.Delivery.Credentials, cli.LocalCredentials)
|
||||
if err != nil {
|
||||
return releasekit.RehearsalResult{}, err
|
||||
}
|
||||
ciToken, _, err := cli.ResolveWoodpeckerCredential(captured.RepositoryDir, settings.Rehearsal.Woodpecker)
|
||||
if err != nil {
|
||||
return releasekit.RehearsalResult{}, err
|
||||
}
|
||||
configured := settings.Delivery.Credentials != nil && settings.Delivery.Credentials.CI != nil
|
||||
wood := settings.Rehearsal.Woodpecker
|
||||
request := releasekit.RehearsalRequest{RepositoryDir: captured.RepositoryDir, Ref: captured.Commit, ProfilePath: captured.Path, ModuleDir: settings.ModuleDir, Source: sourceSpec(settings), Product: settings.Product, Selector: settings.Rehearsal.RehearsalSelector(), Remote: settings.Remote, ExpectedPushURL: settings.ExpectedPushURL, Build: configuredBuildSpec(settings.Build), Destination: releasekit.DeliveryDestination{Forge: releasekit.Forge(settings.Delivery.Forge), BaseURL: settings.Delivery.BaseURL, Owner: settings.Delivery.Owner, Repository: settings.Delivery.Repository, Token: forgeToken}, Woodpecker: releasekit.WoodpeckerObservation{BaseURL: wood.BaseURL, RepositoryID: wood.RepositoryID, Workflow: wood.Workflow, Step: wood.Step, Token: ciToken}, CIConfigured: configured, RecordDir: invocation.RecordDir, ObservationTimeout: releasekit.RehearsalTimeout(invocation.Timeout), CleanupTimeout: releasekit.RehearsalTimeout(invocation.CleanupTimeout), Output: progress}
|
||||
if settings.Readiness != nil {
|
||||
request.RequiredFiles = append([]string(nil), settings.Readiness.RequiredFiles...)
|
||||
}
|
||||
return releasekit.Rehearse(ctx, request)
|
||||
}
|
||||
func recoverRecordedRehearsal(ctx context.Context, invocation cli.Invocation, progress io.Writer) (releasekit.RehearsalResult, error) {
|
||||
attempt, err := rehearsal.LoadAttempt(invocation.RecordPath)
|
||||
if err != nil {
|
||||
return releasekit.RehearsalResult{RecordPath: invocation.RecordPath}, err
|
||||
}
|
||||
summary := releasekit.RehearsalResult{RecordPath: invocation.RecordPath, AttemptID: attempt.Manifest.AttemptID, Tag: attempt.Manifest.Tag, Commit: attempt.Manifest.Commit, ProfilePath: attempt.Manifest.ProfilePath, ProfileSHA256: attempt.Manifest.ProfileSHA256, Selector: attempt.Manifest.Selector, SourceDir: attempt.Manifest.SourceDir, DiagnosticVersion: attempt.Manifest.DiagnosticVersion, TagObject: attempt.TagObject, Workflow: attempt.Outcomes["workflow"], Build: attempt.Outcomes["build"], Verification: attempt.Outcomes["verification"], Cleanup: attempt.Outcomes["cleanup"]}
|
||||
summary.Scope = "page"
|
||||
if len(attempt.PlannedAssets) > 0 {
|
||||
summary.Scope = "page-and-assets"
|
||||
}
|
||||
var token, woodToken string
|
||||
remoteDone := attempt.Outcomes["cleanup-page"] == "complete" && attempt.Outcomes["cleanup-remote-tag"] == "complete"
|
||||
if attempt.Outcomes["cleanup"] != "complete" && attempt.Outcomes["push"] != "not_attempted" && !remoteDone {
|
||||
token, woodToken, err = cli.ResolveRehearsalRecoveryCredentials(ctx, attempt.RepositoryDir, attempt.Manifest.Commit, attempt.Manifest.ProfilePath, attempt.Manifest.ProfileSHA256, invocation.TokenFile, invocation.WoodpeckerTokenFile)
|
||||
if err != nil {
|
||||
return summary, &rehearsalInputError{err: err}
|
||||
}
|
||||
}
|
||||
request := releasekit.RehearsalRecoveryRequest{RecordPath: invocation.RecordPath, DeliveryToken: token, WoodpeckerToken: woodToken, ObservationTimeout: releasekit.RehearsalTimeout(invocation.Timeout), CleanupTimeout: releasekit.RehearsalTimeout(invocation.CleanupTimeout), Output: progress}
|
||||
if invocation.Command == cli.TestResumeAction {
|
||||
return releasekit.ResumeRehearsal(ctx, request)
|
||||
}
|
||||
return releasekit.CleanupRehearsal(ctx, request)
|
||||
}
|
||||
func rehearsalExitStatus(command cli.Command, result releasekit.RehearsalResult, err error) int {
|
||||
if err == nil {
|
||||
if command == cli.TestCleanupAction && result.Cleanup == "complete" {
|
||||
return 0
|
||||
}
|
||||
if result.Verification == "complete" && result.Cleanup == "complete" {
|
||||
return 0
|
||||
}
|
||||
return 1
|
||||
}
|
||||
var inputErr *rehearsalInputError
|
||||
if errors.As(err, &inputErr) {
|
||||
return 2
|
||||
}
|
||||
if result.Cleanup == "conflict" {
|
||||
return 1
|
||||
}
|
||||
if result.RecordPath != "" && (result.Cleanup == "pending" || result.Cleanup == "unknown" || result.Workflow == "unknown" || result.Workflow == "waiting") {
|
||||
return 3
|
||||
}
|
||||
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
|
||||
return 1
|
||||
}
|
||||
var preflight *forge.PreflightFailure
|
||||
if errors.As(err, &preflight) && preflight.Kind == forge.PreflightUnavailable {
|
||||
return 1
|
||||
}
|
||||
var ciErr *woodpecker.Error
|
||||
if errors.As(err, &ciErr) && (ciErr.Status == 0 || ciErr.Status >= http.StatusInternalServerError) {
|
||||
return 1
|
||||
}
|
||||
if errors.Is(err, git.ErrRemoteStateUnreadable) {
|
||||
return 1
|
||||
}
|
||||
if result.RecordPath == "" || result.AttemptID == "" {
|
||||
return 2
|
||||
}
|
||||
return 1
|
||||
}
|
||||
func writeRehearsalReport(output io.Writer, invocation cli.Invocation, result releasekit.RehearsalResult, err error) error {
|
||||
doc := rehearsalDocument{SchemaVersion: 1, Command: string(invocation.Command), AttemptID: git.DisplayDiagnostic(result.AttemptID), Tag: git.DisplayDiagnostic(result.Tag), Commit: git.DisplayDiagnostic(result.Commit), ProfilePath: git.DisplayDiagnostic(result.ProfilePath), ProfileSHA256: git.DisplayDiagnostic(result.ProfileSHA256), Selector: git.DisplayDiagnostic(result.Selector), SourceDir: git.DisplayDiagnostic(result.SourceDir), DiagnosticVersion: git.DisplayDiagnostic(result.DiagnosticVersion), Scope: git.DisplayDiagnostic(result.Scope), RecordPath: git.DisplayDiagnostic(result.RecordPath), TagObject: git.DisplayDiagnostic(result.TagObject), Workflow: result.Workflow, Build: result.Build, Verification: result.Verification, Cleanup: result.Cleanup, PageID: result.PageID, PageURL: git.DisplayURL(result.PageURL), Artifacts: []rehearsalArtifactDocument{}}
|
||||
for _, link := range result.PipelineURLs {
|
||||
doc.PipelineURLs = append(doc.PipelineURLs, git.DisplayURL(link))
|
||||
}
|
||||
for _, j := range result.Jobs {
|
||||
doc.Jobs = append(doc.Jobs, rehearsalJobDocument{PipelineID: j.PipelineID, PipelineNumber: j.PipelineNumber, WorkflowID: j.WorkflowID, StepID: j.StepID, PipelineStatus: git.DisplayDiagnostic(j.PipelineStatus), WorkflowState: git.DisplayDiagnostic(j.WorkflowState), StepState: git.DisplayDiagnostic(j.StepState)})
|
||||
}
|
||||
for _, w := range result.Workflows {
|
||||
doc.Workflows = append(doc.Workflows, rehearsalWorkflowDocument{PipelineID: w.PipelineID, PipelineNumber: w.PipelineNumber, ID: w.ID, Name: git.DisplayDiagnostic(w.Name), State: git.DisplayDiagnostic(w.State)})
|
||||
}
|
||||
for _, a := range result.Artifacts {
|
||||
doc.Artifacts = append(doc.Artifacts, rehearsalArtifactDocument{Name: git.DisplayDiagnostic(a.Name), Size: a.Size, SHA256: git.DisplayDiagnostic(a.SHA256)})
|
||||
}
|
||||
for _, s := range result.Remaining {
|
||||
doc.Remaining = append(doc.Remaining, git.DisplayDiagnostic(s))
|
||||
}
|
||||
for _, s := range result.Diagnostics {
|
||||
doc.Diagnostics = append(doc.Diagnostics, git.DisplayDiagnostic(s))
|
||||
}
|
||||
if err != nil {
|
||||
doc.Diagnostics = append(doc.Diagnostics, git.DisplayError(err).Error())
|
||||
}
|
||||
if invocation.JSON {
|
||||
return json.NewEncoder(output).Encode(doc)
|
||||
}
|
||||
if _, writeErr := fmt.Fprintf(output, "rehearsal %s tag=%s commit=%s\nworkflow=%s build=%s verification=%s cleanup=%s\n", doc.AttemptID, doc.Tag, doc.Commit, doc.Workflow, doc.Build, doc.Verification, doc.Cleanup); writeErr != nil {
|
||||
return writeErr
|
||||
}
|
||||
for _, message := range doc.Diagnostics {
|
||||
if _, err := fmt.Fprintf(output, "diagnostic: %s\n", message); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, resource := range doc.Remaining {
|
||||
if _, err := fmt.Fprintf(output, "remaining: %s\n", resource); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, link := range doc.PipelineURLs {
|
||||
if _, err := fmt.Fprintf(output, "pipeline: %s\n", link); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if doc.PageURL != "" {
|
||||
if _, err := fmt.Fprintf(output, "release: %s\n", doc.PageURL); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if doc.RecordPath != "" {
|
||||
quoted := "'" + strings.ReplaceAll(doc.RecordPath, "'", `'\''`) + "'"
|
||||
if _, err := fmt.Fprintf(output, "record: %s\nresume: releasekit test-resume --record %s\ncleanup: releasekit test-cleanup --record %s\n", doc.RecordPath, quoted, quoted); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
106
cmd/releasekit/rehearsal_test.go
Normal file
106
cmd/releasekit/rehearsal_test.go
Normal file
@@ -0,0 +1,106 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
releasekit "go.maximumdirect.net/releasekit"
|
||||
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
|
||||
"go.maximumdirect.net/releasekit/internal/rehearsal"
|
||||
"go.maximumdirect.net/releasekit/internal/releaseidentity"
|
||||
)
|
||||
|
||||
func TestRehearsalArgumentsAndDefaults(t *testing.T) {
|
||||
parsed, err := cli.Parse([]string{"test", "--ref", "HEAD~1", "--timeout", "0", "--json"})
|
||||
if err != nil || parsed.Ref != "HEAD~1" || parsed.Timeout != 0 || parsed.CleanupTimeout != 2*time.Minute || !parsed.JSON {
|
||||
t.Fatalf("parsed=%+v error=%v", parsed, err)
|
||||
}
|
||||
parsed, err = cli.Parse([]string{"test-resume", "--record", "attempt.json", "--token-file", "forge", "--woodpecker-token-file", "ci"})
|
||||
if err != nil || parsed.RecordPath != "attempt.json" || parsed.Timeout != 30*time.Minute || parsed.TokenFile != "forge" || parsed.WoodpeckerTokenFile != "ci" {
|
||||
t.Fatalf("parsed=%+v error=%v", parsed, err)
|
||||
}
|
||||
for _, args := range [][]string{{"test-resume"}, {"test-cleanup", "--record", "x", "--cleanup-timeout", "0"}, {"test", "--timeout", "-1s"}, {"test", "v1.0.0"}, {"test-cleanup", "--record", "x", "--timeout", "1s"}} {
|
||||
if _, err := cli.Parse(args); err == nil {
|
||||
t.Fatalf("accepted %v", args)
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestRehearsalJSONReportsInputFailure(t *testing.T) {
|
||||
var output, diagnostics bytes.Buffer
|
||||
status := run(t.Context(), []string{"test", "--repo", t.TempDir(), "--json"}, &output, &diagnostics)
|
||||
var doc rehearsalDocument
|
||||
if err := json.Unmarshal(output.Bytes(), &doc); err != nil || status != 2 || doc.Command != "test" || doc.SchemaVersion != 1 || len(doc.Diagnostics) == 0 {
|
||||
t.Fatalf("status=%d output=%s diagnostics=%s error=%v", status, &output, &diagnostics, err)
|
||||
}
|
||||
}
|
||||
func TestCleanupCommandSelectsExplicitRecordAndReportsSeparateOutcome(t *testing.T) {
|
||||
repo := newCLIRepository(t)
|
||||
writeRepositoryFile(t, repo, "releasekit.json", `{"product":"Example","source":{},"rehearsal":{}}`)
|
||||
cliGitRun(t, repo, "add", "releasekit.json")
|
||||
cliGitRun(t, repo, "commit", "-m", "capture profile")
|
||||
captured, err := cli.CaptureCommittedProfile(t.Context(), repo, "HEAD", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
source, err := releaseidentity.LoadCommittedSource(t.Context(), repo, "", captured.Commit, captured.Settings.SourceSpec())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
identity, id, err := releaseidentity.NewDiagnostic(t.Context(), source, "root", captured.Commit)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
manifest := rehearsal.NewManifest(identity, id, "root", captured.Path, captured.Bytes)
|
||||
object, err := rehearsal.CreateDiagnosticTag(t.Context(), repo, manifest)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
record := rehearsal.Attempt{Manifest: manifest, RepositoryDir: repo, TagObject: object, Outcomes: map[string]string{"tag": "created", "push": "not_attempted", "workflow": "failed", "verification": "incomplete", "cleanup": "pending"}}
|
||||
store, err := rehearsal.CreateAttempt(t.Context(), repo, "", record)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var output, diagnostics bytes.Buffer
|
||||
status := run(t.Context(), []string{"test-cleanup", "--record", store.Path, "--json"}, &output, &diagnostics)
|
||||
var doc rehearsalDocument
|
||||
if err := json.Unmarshal(output.Bytes(), &doc); err != nil || status != 0 || doc.Cleanup != "complete" || doc.Verification != "incomplete" || doc.RecordPath != store.Path {
|
||||
t.Fatalf("status=%d output=%s diagnostics=%s error=%v", status, &output, &diagnostics, err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(repo, ".git", "refs", "tags", filepath.FromSlash(identity.Tag))); !os.IsNotExist(err) {
|
||||
t.Fatalf("local tag remains: %v", err)
|
||||
}
|
||||
output.Reset()
|
||||
diagnostics.Reset()
|
||||
status = run(t.Context(), []string{"test-resume", "--record", store.Path, "--json"}, &output, &diagnostics)
|
||||
if status != 1 || !strings.Contains(output.String(), `"cleanup":"complete"`) {
|
||||
t.Fatalf("resume status=%d output=%s diagnostics=%s", status, &output, &diagnostics)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRehearsalExitStatusPreservesObservedOutcomes(t *testing.T) {
|
||||
failure := errors.New("incomplete")
|
||||
for _, test := range []struct {
|
||||
command cli.Command
|
||||
result releasekit.RehearsalResult
|
||||
err error
|
||||
want int
|
||||
}{
|
||||
{cli.TestAction, releasekit.RehearsalResult{Verification: "complete", Cleanup: "complete"}, nil, 0},
|
||||
{cli.TestCleanupAction, releasekit.RehearsalResult{Verification: "failed", Cleanup: "complete"}, nil, 0},
|
||||
{cli.TestResumeAction, releasekit.RehearsalResult{Verification: "failed", Cleanup: "complete", RecordPath: "record", AttemptID: "attempt"}, failure, 1},
|
||||
{cli.TestAction, releasekit.RehearsalResult{Workflow: "waiting", Cleanup: "pending", RecordPath: "record"}, failure, 3},
|
||||
{cli.TestAction, releasekit.RehearsalResult{Cleanup: "conflict", RecordPath: "record"}, failure, 1},
|
||||
{cli.TestAction, releasekit.RehearsalResult{}, failure, 2},
|
||||
{cli.TestCleanupAction, releasekit.RehearsalResult{Cleanup: "pending", RecordPath: "record"}, &rehearsalInputError{err: failure}, 2},
|
||||
} {
|
||||
if got := rehearsalExitStatus(test.command, test.result, test.err); got != test.want {
|
||||
t.Fatalf("command=%s result=%+v got=%d want=%d", test.command, test.result, got, test.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -36,7 +36,7 @@ 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.
|
||||
files := []string{"cmd/releasekit/main.go", "cmd/releasekit/readiness.go", "cmd/releasekit/diagnostic.go", "cmd/releasekit/internal/cli/config.go", "cmd/releasekit/internal/cli/credentials.go", "readiness.go", "internal/readiness/readiness.go", "internal/readiness/committed.go", "internal/woodpecker/client.go", "internal/git/remote.go", "internal/git/source.go", "internal/gitea/backend.go", "internal/gotool/gotool.go", "internal/build/build.go", "internal/delivery/delivery.go", "internal/delivery/diagnostic.go", "internal/rehearsal/manifest.go", "internal/rehearsal/result.go", "internal/releaseidentity/diagnostic.go"}
|
||||
files := []string{"cmd/releasekit/main.go", "cmd/releasekit/readiness.go", "cmd/releasekit/diagnostic.go", "cmd/releasekit/rehearsal.go", "cmd/releasekit/internal/cli/config.go", "cmd/releasekit/internal/cli/credentials.go", "readiness.go", "rehearsal.go", "internal/readiness/readiness.go", "internal/readiness/committed.go", "internal/woodpecker/client.go", "internal/git/remote.go", "internal/git/source.go", "internal/gitea/backend.go", "internal/gotool/gotool.go", "internal/build/build.go", "internal/delivery/delivery.go", "internal/delivery/diagnostic.go", "internal/rehearsal/manifest.go", "internal/rehearsal/result.go", "internal/rehearsal/cleanup.go", "internal/releaseidentity/diagnostic.go"}
|
||||
for _, name := range files {
|
||||
contents, err := os.ReadFile(filepath.Join(root, filepath.FromSlash(name)))
|
||||
if err != nil {
|
||||
|
||||
Reference in New Issue
Block a user