* Stabilize hook-related tests by forcing repo-local hooksPath * Implement hook migration apply mode and matrix execution (#2218)
This commit is contained in:
parent
6595087031
commit
e5179c719a
7 changed files with 933 additions and 57 deletions
|
|
@ -38,15 +38,15 @@ func DetectPendingMigrations(path string) []PendingMigration {
|
|||
description,
|
||||
hookPlan.BrokenMarkerCount,
|
||||
)
|
||||
// Phase 1 is planning-only. Keep this at warning level for now.
|
||||
// TODO(gh-1380): raise to critical when apply mode is implemented.
|
||||
// Keep warning level until doctor auto-fix wiring is implemented.
|
||||
// TODO(gh-2220): reevaluate severity once doctor --fix can invoke hook migration.
|
||||
priority = 2
|
||||
}
|
||||
|
||||
pending = append(pending, PendingMigration{
|
||||
Name: "hooks",
|
||||
Description: description,
|
||||
Command: "bd migrate hooks --dry-run",
|
||||
Command: "bd migrate hooks --apply",
|
||||
Priority: priority,
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,15 +27,15 @@ func TestDetectPendingMigrations_Hooks(t *testing.T) {
|
|||
if m.Name != "hooks" {
|
||||
t.Fatalf("expected migration name 'hooks', got %q", m.Name)
|
||||
}
|
||||
if m.Command != "bd migrate hooks --dry-run" {
|
||||
t.Fatalf("expected command 'bd migrate hooks --dry-run', got %q", m.Command)
|
||||
if m.Command != "bd migrate hooks --apply" {
|
||||
t.Fatalf("expected command 'bd migrate hooks --apply', got %q", m.Command)
|
||||
}
|
||||
if m.Priority != 2 {
|
||||
t.Fatalf("expected recommended priority 2, got %d", m.Priority)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDetectPendingMigrations_HooksBrokenMarkerIsWarningInPhase1(t *testing.T) {
|
||||
func TestDetectPendingMigrations_HooksBrokenMarkerIsWarningUntilDoctorFixIntegration(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
setupGitRepoInDir(t, tmpDir)
|
||||
forceRepoHooksPath(t, tmpDir)
|
||||
|
|
@ -52,11 +52,11 @@ func TestDetectPendingMigrations_HooksBrokenMarkerIsWarningInPhase1(t *testing.T
|
|||
t.Fatalf("expected 1 pending migration, got %d", len(pending))
|
||||
}
|
||||
if pending[0].Priority != 2 {
|
||||
t.Fatalf("expected warning priority 2 in phase 1, got %d", pending[0].Priority)
|
||||
t.Fatalf("expected warning priority 2 until doctor fix integration, got %d", pending[0].Priority)
|
||||
}
|
||||
|
||||
check := CheckPendingMigrations(tmpDir)
|
||||
if check.Status != StatusWarning {
|
||||
t.Fatalf("expected warning status for phase 1 planning-only migration, got %q", check.Status)
|
||||
t.Fatalf("expected warning status for migration until doctor fix integration, got %q", check.Status)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -772,6 +772,8 @@ func init() {
|
|||
migrateCmd.AddCommand(migrateSyncCmd)
|
||||
|
||||
migrateHooksCmd.Flags().Bool("dry-run", false, "Show what would be done without making changes")
|
||||
migrateHooksCmd.Flags().Bool("apply", false, "Apply planned hook migration changes")
|
||||
migrateHooksCmd.Flags().Bool("yes", false, "Skip confirmation prompt for --apply")
|
||||
migrateHooksCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
|
||||
migrateCmd.AddCommand(migrateHooksCmd)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,35 +1,45 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/steveyegge/beads/cmd/bd/doctor"
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
const hookMigrationApplyTrackingIssue = "https://github.com/steveyegge/beads/issues/2218"
|
||||
|
||||
var migrateHooksCmd = &cobra.Command{
|
||||
Use: "hooks [path]",
|
||||
Short: "Plan git hook migration to marker-managed format",
|
||||
Short: "Plan or apply git hook migration to marker-managed format",
|
||||
Long: `Analyze git hook files and sidecar artifacts for migration to marker-managed format.
|
||||
|
||||
This command is planning-only in phase 1. It does not modify hook files.
|
||||
Modes:
|
||||
--dry-run Preview migration operations without changing files
|
||||
--apply Apply migration operations
|
||||
|
||||
Examples:
|
||||
bd migrate hooks
|
||||
bd migrate hooks --dry-run
|
||||
bd migrate hooks --json`,
|
||||
bd migrate hooks --apply
|
||||
bd migrate hooks --apply --yes
|
||||
bd migrate hooks --dry-run --json`,
|
||||
Args: cobra.MaximumNArgs(1),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
requestedDryRun, _ := cmd.Flags().GetBool("dry-run")
|
||||
if err := validateHookMigrationDryRunRequested(requestedDryRun); err != nil {
|
||||
requestedApply, _ := cmd.Flags().GetBool("apply")
|
||||
requestedYes, _ := cmd.Flags().GetBool("yes")
|
||||
|
||||
mode, err := validateHookMigrationMode(requestedDryRun, requestedApply, requestedYes)
|
||||
if err != nil {
|
||||
FatalErrorRespectJSON("%v", err)
|
||||
}
|
||||
|
||||
if mode.RequestedApply {
|
||||
CheckReadonly("migrate hooks")
|
||||
}
|
||||
|
||||
targetPath := "."
|
||||
if len(args) == 1 {
|
||||
targetPath = args[0]
|
||||
|
|
@ -45,39 +55,112 @@ Examples:
|
|||
FatalErrorRespectJSON("building hook migration plan: %v", err)
|
||||
}
|
||||
|
||||
execPlan := buildHookMigrationExecutionPlan(plan)
|
||||
|
||||
if mode.RequestedApply {
|
||||
if len(execPlan.BlockingErrors) > 0 {
|
||||
FatalErrorRespectJSON("hook migration is blocked:\n- %s", strings.Join(execPlan.BlockingErrors, "\n- "))
|
||||
}
|
||||
if execPlan.operationCount() > 0 {
|
||||
if err := validateHookMigrationApplyConsent(mode.RequestedYes, term.IsTerminal(int(os.Stdin.Fd())), jsonOutput); err != nil {
|
||||
FatalErrorRespectJSON("%v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if jsonOutput {
|
||||
outputJSON(buildHookMigrationJSON(plan, requestedDryRun))
|
||||
if mode.RequestedApply {
|
||||
summary, applied, applyErr := maybeApplyHookMigration(execPlan, mode.RequestedYes)
|
||||
if applyErr != nil {
|
||||
FatalErrorRespectJSON("applying hook migration: %v", applyErr)
|
||||
}
|
||||
if !applied {
|
||||
summary.SkippedArtifacts = append(summary.SkippedArtifacts, "canceled")
|
||||
summary.SkippedCount = len(summary.SkippedArtifacts)
|
||||
}
|
||||
outputJSON(buildHookMigrationJSON(plan, mode, execPlan, &summary))
|
||||
return
|
||||
}
|
||||
outputJSON(buildHookMigrationJSON(plan, mode, execPlan, nil))
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Println(strings.Join(formatHookMigrationPlan(plan), "\n"))
|
||||
fmt.Println(strings.Join(formatHookMigrationPlan(plan, mode), "\n"))
|
||||
fmt.Println()
|
||||
fmt.Println(strings.Join(formatHookMigrationOperations(execPlan), "\n"))
|
||||
|
||||
if mode.RequestedDryRun {
|
||||
return
|
||||
}
|
||||
|
||||
summary, applied, applyErr := maybeApplyHookMigration(execPlan, mode.RequestedYes)
|
||||
if applyErr != nil {
|
||||
FatalErrorRespectJSON("applying hook migration: %v", applyErr)
|
||||
}
|
||||
if !applied {
|
||||
fmt.Println()
|
||||
fmt.Println("Migration canceled.")
|
||||
return
|
||||
}
|
||||
|
||||
for _, line := range formatHookMigrationApplySummary(summary) {
|
||||
fmt.Println(line)
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
func validateHookMigrationDryRunRequested(requestedDryRun bool) error {
|
||||
if requestedDryRun {
|
||||
return nil
|
||||
func maybeApplyHookMigration(execPlan hookMigrationExecutionPlan, autoYes bool) (hookMigrationApplySummary, bool, error) {
|
||||
if execPlan.operationCount() == 0 {
|
||||
return hookMigrationApplySummary{}, true, nil
|
||||
}
|
||||
return errors.New(
|
||||
"phase 1 is planning-only: --dry-run is required for 'bd migrate hooks'. " +
|
||||
"Apply mode is tracked in #2218 and will be enabled once the PR resolving #2218 is merged: " +
|
||||
hookMigrationApplyTrackingIssue,
|
||||
)
|
||||
|
||||
if !autoYes {
|
||||
confirmed, err := confirmHookMigrationApply(execPlan.operationCount())
|
||||
if err != nil {
|
||||
return hookMigrationApplySummary{}, false, err
|
||||
}
|
||||
if !confirmed {
|
||||
return hookMigrationApplySummary{}, false, nil
|
||||
}
|
||||
}
|
||||
|
||||
summary, err := applyHookMigrationExecution(execPlan)
|
||||
return summary, err == nil, err
|
||||
}
|
||||
|
||||
func buildHookMigrationJSON(plan doctor.HookMigrationPlan, requestedDryRun bool) map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"status": "planning_only",
|
||||
"planning_only": true,
|
||||
"requested_dry_run": requestedDryRun,
|
||||
"dry_run": true,
|
||||
"plan": plan,
|
||||
func buildHookMigrationJSON(plan doctor.HookMigrationPlan, mode hookMigrationMode, execPlan hookMigrationExecutionPlan, summary *hookMigrationApplySummary) map[string]interface{} {
|
||||
status := "preview"
|
||||
if mode.RequestedApply {
|
||||
status = "applied"
|
||||
}
|
||||
|
||||
output := map[string]interface{}{
|
||||
"status": status,
|
||||
"dry_run": mode.RequestedDryRun,
|
||||
"apply": mode.RequestedApply,
|
||||
"plan": plan,
|
||||
"operations": execPlan.outputOperations(),
|
||||
"operation_count": execPlan.operationCount(),
|
||||
"blocking_errors": execPlan.BlockingErrors,
|
||||
"blocking_error_count": len(execPlan.BlockingErrors),
|
||||
}
|
||||
|
||||
if summary != nil {
|
||||
output["result"] = summary
|
||||
}
|
||||
|
||||
return output
|
||||
}
|
||||
|
||||
func formatHookMigrationPlan(plan doctor.HookMigrationPlan) []string {
|
||||
func formatHookMigrationPlan(plan doctor.HookMigrationPlan, mode hookMigrationMode) []string {
|
||||
lines := []string{
|
||||
"Hook migration plan (planning only)",
|
||||
"Hook migration plan",
|
||||
}
|
||||
|
||||
if mode.RequestedDryRun {
|
||||
lines = append(lines, "Mode: dry-run")
|
||||
} else if mode.RequestedApply {
|
||||
lines = append(lines, "Mode: apply")
|
||||
}
|
||||
|
||||
if !plan.IsGitRepo {
|
||||
|
|
@ -112,10 +195,77 @@ func formatHookMigrationPlan(plan doctor.HookMigrationPlan) []string {
|
|||
}
|
||||
|
||||
if plan.NeedsMigrationCount > 0 {
|
||||
lines = append(lines, "Next: run 'bd migrate hooks --dry-run --json' for machine-readable planning output.")
|
||||
if mode.RequestedDryRun {
|
||||
lines = append(lines, "Next: run 'bd migrate hooks --apply' to execute this migration plan.")
|
||||
} else {
|
||||
lines = append(lines, "Applying migration operations...")
|
||||
}
|
||||
} else {
|
||||
lines = append(lines, "No hook migration is required.")
|
||||
}
|
||||
|
||||
return lines
|
||||
}
|
||||
|
||||
func formatHookMigrationOperations(execPlan hookMigrationExecutionPlan) []string {
|
||||
lines := []string{"Planned operations:"}
|
||||
if execPlan.operationCount() == 0 {
|
||||
lines = append(lines, "- none")
|
||||
return lines
|
||||
}
|
||||
|
||||
for _, op := range execPlan.outputOperations() {
|
||||
switch op.Action {
|
||||
case "write_hook":
|
||||
source := op.SourcePath
|
||||
if source == "" {
|
||||
source = "<template>"
|
||||
}
|
||||
lines = append(lines, fmt.Sprintf("- write %s: %s (source: %s)", op.HookName, op.Path, source))
|
||||
case "retire_sidecar":
|
||||
lines = append(lines, fmt.Sprintf("- retire %s: %s -> %s", op.HookName, op.SourcePath, op.Destination))
|
||||
}
|
||||
}
|
||||
|
||||
if len(execPlan.BlockingErrors) > 0 {
|
||||
lines = append(lines, "Blocking issues:")
|
||||
for _, blocking := range execPlan.BlockingErrors {
|
||||
lines = append(lines, "- "+blocking)
|
||||
}
|
||||
}
|
||||
|
||||
return lines
|
||||
}
|
||||
|
||||
func formatHookMigrationApplySummary(summary hookMigrationApplySummary) []string {
|
||||
lines := []string{
|
||||
"",
|
||||
"Hook migration apply summary",
|
||||
fmt.Sprintf("- hooks written: %d", summary.WrittenHookCount),
|
||||
fmt.Sprintf("- artifacts retired: %d", summary.RetiredCount),
|
||||
fmt.Sprintf("- artifacts skipped: %d", summary.SkippedCount),
|
||||
}
|
||||
|
||||
if summary.WrittenHookCount > 0 {
|
||||
lines = append(lines, "Written hooks:")
|
||||
for _, hook := range summary.WrittenHooks {
|
||||
lines = append(lines, "- "+hook)
|
||||
}
|
||||
}
|
||||
|
||||
if summary.RetiredCount > 0 {
|
||||
lines = append(lines, "Retired artifacts:")
|
||||
for _, retired := range summary.RetiredArtifacts {
|
||||
lines = append(lines, "- "+retired)
|
||||
}
|
||||
}
|
||||
|
||||
if summary.SkippedCount > 0 {
|
||||
lines = append(lines, "Skipped artifacts:")
|
||||
for _, skipped := range summary.SkippedArtifacts {
|
||||
lines = append(lines, "- "+skipped)
|
||||
}
|
||||
}
|
||||
|
||||
return lines
|
||||
}
|
||||
|
|
|
|||
425
cmd/bd/migrate_hooks_apply.go
Normal file
425
cmd/bd/migrate_hooks_apply.go
Normal file
|
|
@ -0,0 +1,425 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/steveyegge/beads/cmd/bd/doctor"
|
||||
)
|
||||
|
||||
type hookMigrationMode struct {
|
||||
RequestedDryRun bool
|
||||
RequestedApply bool
|
||||
RequestedYes bool
|
||||
}
|
||||
|
||||
func validateHookMigrationMode(requestedDryRun, requestedApply, requestedYes bool) (hookMigrationMode, error) {
|
||||
switch {
|
||||
case requestedDryRun && requestedApply:
|
||||
return hookMigrationMode{}, errors.New("cannot use --dry-run and --apply together")
|
||||
case requestedYes && !requestedApply:
|
||||
return hookMigrationMode{}, errors.New("--yes requires --apply")
|
||||
case !requestedDryRun && !requestedApply:
|
||||
return hookMigrationMode{}, errors.New("must specify exactly one mode: --dry-run or --apply")
|
||||
default:
|
||||
return hookMigrationMode{
|
||||
RequestedDryRun: requestedDryRun,
|
||||
RequestedApply: requestedApply,
|
||||
RequestedYes: requestedYes,
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
func validateHookMigrationApplyConsent(requestedYes, interactive, jsonRequested bool) error {
|
||||
if requestedYes {
|
||||
return nil
|
||||
}
|
||||
if jsonRequested {
|
||||
return errors.New("--json with --apply requires --yes")
|
||||
}
|
||||
if interactive {
|
||||
return nil
|
||||
}
|
||||
return errors.New("--apply requires confirmation; rerun with --yes in non-interactive mode")
|
||||
}
|
||||
|
||||
type hookMigrationWriteSource string
|
||||
|
||||
const (
|
||||
hookMigrationWriteFromTemplate hookMigrationWriteSource = "template"
|
||||
hookMigrationWriteFromHookFile hookMigrationWriteSource = "hook_file"
|
||||
hookMigrationWriteFromOld hookMigrationWriteSource = "old_sidecar"
|
||||
hookMigrationWriteFromBackup hookMigrationWriteSource = "backup_sidecar"
|
||||
)
|
||||
|
||||
type hookMigrationWriteOp struct {
|
||||
HookName string `json:"hook_name"`
|
||||
HookPath string `json:"hook_path"`
|
||||
State string `json:"state"`
|
||||
SourceKind hookMigrationWriteSource `json:"source_kind"`
|
||||
SourcePath string `json:"source_path,omitempty"`
|
||||
}
|
||||
|
||||
type hookMigrationRetireOp struct {
|
||||
HookName string `json:"hook_name"`
|
||||
SourcePath string `json:"source_path"`
|
||||
DestinationPath string `json:"destination_path"`
|
||||
}
|
||||
|
||||
type hookMigrationExecutionPlan struct {
|
||||
WriteOps []hookMigrationWriteOp `json:"write_ops"`
|
||||
RetireOps []hookMigrationRetireOp `json:"retire_ops"`
|
||||
NoopHooks []string `json:"noop_hooks"`
|
||||
BlockingErrors []string `json:"blocking_errors"`
|
||||
}
|
||||
|
||||
type hookMigrationOutputOperation struct {
|
||||
Action string `json:"action"`
|
||||
HookName string `json:"hook_name"`
|
||||
Path string `json:"path,omitempty"`
|
||||
SourcePath string `json:"source_path,omitempty"`
|
||||
Destination string `json:"destination_path,omitempty"`
|
||||
State string `json:"state,omitempty"`
|
||||
}
|
||||
|
||||
type hookMigrationApplySummary struct {
|
||||
WrittenHooks []string `json:"written_hooks"`
|
||||
RetiredArtifacts []string `json:"retired_artifacts"`
|
||||
SkippedArtifacts []string `json:"skipped_artifacts"`
|
||||
WrittenHookCount int `json:"written_hook_count"`
|
||||
RetiredCount int `json:"retired_count"`
|
||||
SkippedCount int `json:"skipped_count"`
|
||||
}
|
||||
|
||||
func (p hookMigrationExecutionPlan) operationCount() int {
|
||||
return len(p.WriteOps) + len(p.RetireOps)
|
||||
}
|
||||
|
||||
func (p hookMigrationExecutionPlan) outputOperations() []hookMigrationOutputOperation {
|
||||
ops := make([]hookMigrationOutputOperation, 0, p.operationCount())
|
||||
for _, write := range p.WriteOps {
|
||||
ops = append(ops, hookMigrationOutputOperation{
|
||||
Action: "write_hook",
|
||||
HookName: write.HookName,
|
||||
Path: write.HookPath,
|
||||
SourcePath: write.SourcePath,
|
||||
State: write.State,
|
||||
})
|
||||
}
|
||||
for _, retire := range p.RetireOps {
|
||||
ops = append(ops, hookMigrationOutputOperation{
|
||||
Action: "retire_sidecar",
|
||||
HookName: retire.HookName,
|
||||
Path: retire.SourcePath,
|
||||
SourcePath: retire.SourcePath,
|
||||
Destination: retire.DestinationPath,
|
||||
})
|
||||
}
|
||||
return ops
|
||||
}
|
||||
|
||||
func buildHookMigrationExecutionPlan(plan doctor.HookMigrationPlan) hookMigrationExecutionPlan {
|
||||
execPlan := hookMigrationExecutionPlan{
|
||||
WriteOps: make([]hookMigrationWriteOp, 0, plan.NeedsMigrationCount),
|
||||
RetireOps: make([]hookMigrationRetireOp, 0, plan.NeedsMigrationCount*2),
|
||||
NoopHooks: make([]string, 0, plan.TotalHooks),
|
||||
BlockingErrors: make([]string, 0),
|
||||
}
|
||||
|
||||
for _, hook := range plan.Hooks {
|
||||
switch hook.State {
|
||||
case "marker_managed", "unmanaged_custom", "missing_no_artifacts":
|
||||
execPlan.NoopHooks = append(execPlan.NoopHooks, hook.Name)
|
||||
continue
|
||||
case "marker_broken", "read_error":
|
||||
execPlan.BlockingErrors = append(execPlan.BlockingErrors, formatHookMigrationBlockingError(hook))
|
||||
continue
|
||||
}
|
||||
|
||||
sourceKind, sourcePath, err := chooseHookMigrationWriteSource(hook)
|
||||
if err != nil {
|
||||
execPlan.BlockingErrors = append(execPlan.BlockingErrors, err.Error())
|
||||
continue
|
||||
}
|
||||
|
||||
execPlan.WriteOps = append(execPlan.WriteOps, hookMigrationWriteOp{
|
||||
HookName: hook.Name,
|
||||
HookPath: hook.HookPath,
|
||||
State: hook.State,
|
||||
SourceKind: sourceKind,
|
||||
SourcePath: sourcePath,
|
||||
})
|
||||
|
||||
if hook.HasOldSidecar {
|
||||
execPlan.RetireOps = append(execPlan.RetireOps, hookMigrationRetireOp{
|
||||
HookName: hook.Name,
|
||||
SourcePath: hook.HookPath + ".old",
|
||||
DestinationPath: hook.HookPath + ".old.migrated",
|
||||
})
|
||||
}
|
||||
if hook.HasBackupSidecar {
|
||||
execPlan.RetireOps = append(execPlan.RetireOps, hookMigrationRetireOp{
|
||||
HookName: hook.Name,
|
||||
SourcePath: hook.HookPath + ".backup",
|
||||
DestinationPath: hook.HookPath + ".backup.migrated",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return execPlan
|
||||
}
|
||||
|
||||
func formatHookMigrationBlockingError(hook doctor.HookMigrationHookPlan) string {
|
||||
suggestion := strings.TrimSpace(hook.SuggestedAction)
|
||||
if suggestion == "" {
|
||||
suggestion = "Repair manually, then rerun migration"
|
||||
}
|
||||
if hook.ReadError != "" {
|
||||
return fmt.Sprintf("%s (%s): %s", hook.Name, hook.State, hook.ReadError)
|
||||
}
|
||||
return fmt.Sprintf("%s (%s): %s", hook.Name, hook.State, suggestion)
|
||||
}
|
||||
|
||||
func chooseHookMigrationWriteSource(hook doctor.HookMigrationHookPlan) (hookMigrationWriteSource, string, error) {
|
||||
switch hook.State {
|
||||
case "legacy_only":
|
||||
return hookMigrationWriteFromTemplate, "", nil
|
||||
case "legacy_with_old_sidecar", "legacy_with_both_sidecars", "missing_with_old_sidecar", "missing_with_both_sidecars":
|
||||
return hookMigrationWriteFromOld, hook.HookPath + ".old", nil
|
||||
case "legacy_with_backup_sidecar", "missing_with_backup_sidecar":
|
||||
return hookMigrationWriteFromBackup, hook.HookPath + ".backup", nil
|
||||
case "custom_with_sidecars":
|
||||
return hookMigrationWriteFromHookFile, hook.HookPath, nil
|
||||
default:
|
||||
if hook.NeedsMigration {
|
||||
return "", "", fmt.Errorf("%s has unsupported migration state %q", hook.Name, hook.State)
|
||||
}
|
||||
return "", "", fmt.Errorf("%s does not require migration", hook.Name)
|
||||
}
|
||||
}
|
||||
|
||||
type preparedHookWrite struct {
|
||||
HookName string
|
||||
Path string
|
||||
Content []byte
|
||||
}
|
||||
|
||||
func applyHookMigrationExecution(execPlan hookMigrationExecutionPlan) (hookMigrationApplySummary, error) {
|
||||
if len(execPlan.BlockingErrors) > 0 {
|
||||
return hookMigrationApplySummary{}, fmt.Errorf(
|
||||
"hook migration blocked by %d issue(s): %s",
|
||||
len(execPlan.BlockingErrors),
|
||||
strings.Join(execPlan.BlockingErrors, "; "),
|
||||
)
|
||||
}
|
||||
|
||||
preparedWrites, err := prepareHookMigrationWrites(execPlan.WriteOps)
|
||||
if err != nil {
|
||||
return hookMigrationApplySummary{}, err
|
||||
}
|
||||
|
||||
if err := validateRetireCollisionPolicy(execPlan.RetireOps); err != nil {
|
||||
return hookMigrationApplySummary{}, err
|
||||
}
|
||||
|
||||
summary := hookMigrationApplySummary{
|
||||
WrittenHooks: make([]string, 0, len(preparedWrites)),
|
||||
RetiredArtifacts: make([]string, 0, len(execPlan.RetireOps)),
|
||||
SkippedArtifacts: make([]string, 0),
|
||||
}
|
||||
|
||||
for _, write := range preparedWrites {
|
||||
// #nosec G306 -- git hooks must be executable for Git to run them
|
||||
if err := os.WriteFile(write.Path, write.Content, 0755); err != nil {
|
||||
return summary, fmt.Errorf("writing migrated hook %s: %w", write.Path, err)
|
||||
}
|
||||
summary.WrittenHooks = append(summary.WrittenHooks, write.HookName)
|
||||
}
|
||||
|
||||
for _, retire := range execPlan.RetireOps {
|
||||
retired, retiredErr := retireHookSidecar(retire)
|
||||
if retiredErr != nil {
|
||||
return summary, retiredErr
|
||||
}
|
||||
if retired == "" {
|
||||
summary.SkippedArtifacts = append(summary.SkippedArtifacts, retire.SourcePath)
|
||||
continue
|
||||
}
|
||||
summary.RetiredArtifacts = append(summary.RetiredArtifacts, retired)
|
||||
}
|
||||
|
||||
summary.WrittenHookCount = len(summary.WrittenHooks)
|
||||
summary.RetiredCount = len(summary.RetiredArtifacts)
|
||||
summary.SkippedCount = len(summary.SkippedArtifacts)
|
||||
|
||||
return summary, nil
|
||||
}
|
||||
|
||||
func prepareHookMigrationWrites(writeOps []hookMigrationWriteOp) ([]preparedHookWrite, error) {
|
||||
prepared := make([]preparedHookWrite, 0, len(writeOps))
|
||||
|
||||
for _, op := range writeOps {
|
||||
rendered, err := renderMigratedHookContent(op)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
prepared = append(prepared, preparedHookWrite{
|
||||
HookName: op.HookName,
|
||||
Path: op.HookPath,
|
||||
Content: rendered,
|
||||
})
|
||||
}
|
||||
|
||||
return prepared, nil
|
||||
}
|
||||
|
||||
func renderMigratedHookContent(op hookMigrationWriteOp) ([]byte, error) {
|
||||
var baseContent string
|
||||
|
||||
switch op.SourceKind {
|
||||
case hookMigrationWriteFromTemplate:
|
||||
baseContent = ""
|
||||
case hookMigrationWriteFromHookFile, hookMigrationWriteFromOld, hookMigrationWriteFromBackup:
|
||||
content, err := os.ReadFile(op.SourcePath) // #nosec G304 -- source paths come from migration planner + known sidecar suffixes
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reading source content for %s from %s: %w", op.HookName, op.SourcePath, err)
|
||||
}
|
||||
baseContent = string(content)
|
||||
default:
|
||||
return nil, fmt.Errorf("unknown source kind %q for %s", op.SourceKind, op.HookName)
|
||||
}
|
||||
|
||||
baseContent = strings.ReplaceAll(baseContent, "\r\n", "\n")
|
||||
baseContent = ensureHookShebang(baseContent)
|
||||
|
||||
content := injectHookSection(baseContent, generateHookSection(op.HookName))
|
||||
content = strings.ReplaceAll(content, "\r\n", "\n")
|
||||
if !strings.HasSuffix(content, "\n") {
|
||||
content += "\n"
|
||||
}
|
||||
|
||||
return []byte(content), nil
|
||||
}
|
||||
|
||||
func ensureHookShebang(content string) string {
|
||||
if strings.HasPrefix(content, "#!") {
|
||||
return content
|
||||
}
|
||||
|
||||
trimmedLeading := strings.TrimLeft(content, "\n")
|
||||
if trimmedLeading == "" {
|
||||
return "#!/usr/bin/env sh\n"
|
||||
}
|
||||
|
||||
return "#!/usr/bin/env sh\n" + trimmedLeading
|
||||
}
|
||||
|
||||
func validateRetireCollisionPolicy(retireOps []hookMigrationRetireOp) error {
|
||||
for _, op := range retireOps {
|
||||
sourceExists, err := pathExists(op.SourcePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("checking source sidecar %s: %w", op.SourcePath, err)
|
||||
}
|
||||
if !sourceExists {
|
||||
continue
|
||||
}
|
||||
|
||||
destinationExists, err := pathExists(op.DestinationPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("checking destination sidecar %s: %w", op.DestinationPath, err)
|
||||
}
|
||||
if !destinationExists {
|
||||
continue
|
||||
}
|
||||
|
||||
equal, err := filesEqual(op.SourcePath, op.DestinationPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("comparing sidecars %s and %s: %w", op.SourcePath, op.DestinationPath, err)
|
||||
}
|
||||
if !equal {
|
||||
return fmt.Errorf(
|
||||
"artifact collision for %s: %s already exists with different content",
|
||||
op.SourcePath,
|
||||
op.DestinationPath,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func retireHookSidecar(op hookMigrationRetireOp) (string, error) {
|
||||
sourceExists, err := pathExists(op.SourcePath)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("checking sidecar %s: %w", op.SourcePath, err)
|
||||
}
|
||||
if !sourceExists {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
destinationExists, err := pathExists(op.DestinationPath)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("checking sidecar destination %s: %w", op.DestinationPath, err)
|
||||
}
|
||||
|
||||
if destinationExists {
|
||||
equal, err := filesEqual(op.SourcePath, op.DestinationPath)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("comparing sidecar %s to %s: %w", op.SourcePath, op.DestinationPath, err)
|
||||
}
|
||||
if !equal {
|
||||
return "", fmt.Errorf("artifact collision for %s: %s already exists with different content", op.SourcePath, op.DestinationPath)
|
||||
}
|
||||
if err := os.Remove(op.SourcePath); err != nil {
|
||||
return "", fmt.Errorf("removing already-retired sidecar %s: %w", op.SourcePath, err)
|
||||
}
|
||||
return op.SourcePath + " -> " + op.DestinationPath + " (destination already existed)", nil
|
||||
}
|
||||
|
||||
if err := os.Rename(op.SourcePath, op.DestinationPath); err != nil {
|
||||
return "", fmt.Errorf("retiring sidecar %s -> %s: %w", op.SourcePath, op.DestinationPath, err)
|
||||
}
|
||||
|
||||
return op.SourcePath + " -> " + op.DestinationPath, nil
|
||||
}
|
||||
|
||||
func pathExists(path string) (bool, error) {
|
||||
_, err := os.Stat(path)
|
||||
if err == nil {
|
||||
return true, nil
|
||||
}
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
|
||||
func filesEqual(pathA, pathB string) (bool, error) {
|
||||
a, err := os.ReadFile(pathA) // #nosec G304 -- compared paths come from deterministic migration operations
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
b, err := os.ReadFile(pathB) // #nosec G304 -- compared paths come from deterministic migration operations
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return bytes.Equal(a, b), nil
|
||||
}
|
||||
|
||||
func confirmHookMigrationApply(totalOperations int) (bool, error) {
|
||||
fmt.Printf("\nThis will apply %d hook migration operation(s). Continue? (Y/n): ", totalOperations)
|
||||
reader := bufio.NewReader(os.Stdin)
|
||||
response, err := reader.ReadString('\n')
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("reading confirmation: %w", err)
|
||||
}
|
||||
response = strings.TrimSpace(strings.ToLower(response))
|
||||
if response == "" || response == "y" || response == "yes" {
|
||||
return true, nil
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
254
cmd/bd/migrate_hooks_apply_test.go
Normal file
254
cmd/bd/migrate_hooks_apply_test.go
Normal file
|
|
@ -0,0 +1,254 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/cmd/bd/doctor"
|
||||
"github.com/steveyegge/beads/internal/git"
|
||||
)
|
||||
|
||||
func TestApplyHookMigrationExecution_LegacyWithOldSidecar(t *testing.T) {
|
||||
repoDir, hooksDir := setupHookMigrationRepo(t)
|
||||
preCommitPath := filepath.Join(hooksDir, "pre-commit")
|
||||
|
||||
writeHookMigrationFile(t, preCommitPath, "#!/usr/bin/env sh\n# bd-shim v2\n# bd-hooks-version: 0.56.1\nexec bd hooks run pre-commit \"$@\"\n")
|
||||
writeHookMigrationFile(t, preCommitPath+".old", "#!/usr/bin/env sh\necho old-custom\n")
|
||||
|
||||
plan, err := doctor.PlanHookMigration(repoDir)
|
||||
if err != nil {
|
||||
t.Fatalf("PlanHookMigration failed: %v", err)
|
||||
}
|
||||
execPlan := buildHookMigrationExecutionPlan(plan)
|
||||
|
||||
summary, err := applyHookMigrationExecution(execPlan)
|
||||
if err != nil {
|
||||
t.Fatalf("applyHookMigrationExecution failed: %v", err)
|
||||
}
|
||||
if summary.WrittenHookCount != 1 {
|
||||
t.Fatalf("expected 1 written hook, got %d", summary.WrittenHookCount)
|
||||
}
|
||||
if summary.RetiredCount != 1 {
|
||||
t.Fatalf("expected 1 retired artifact, got %d", summary.RetiredCount)
|
||||
}
|
||||
|
||||
rendered := mustReadHookMigrationFile(t, preCommitPath)
|
||||
if !strings.Contains(rendered, "echo old-custom") {
|
||||
t.Fatalf("expected migrated hook to preserve .old body, got:\n%s", rendered)
|
||||
}
|
||||
if !strings.Contains(rendered, hookSectionBeginPrefix) || !strings.Contains(rendered, hookSectionEnd) {
|
||||
t.Fatalf("expected migrated hook to contain marker section, got:\n%s", rendered)
|
||||
}
|
||||
|
||||
assertMissingHookMigrationFile(t, preCommitPath+".old")
|
||||
assertExistsHookMigrationFile(t, preCommitPath+".old.migrated")
|
||||
}
|
||||
|
||||
func TestApplyHookMigrationExecution_LegacyWithBothSidecarsPrefersOld(t *testing.T) {
|
||||
repoDir, hooksDir := setupHookMigrationRepo(t)
|
||||
preCommitPath := filepath.Join(hooksDir, "pre-commit")
|
||||
|
||||
writeHookMigrationFile(t, preCommitPath, "#!/usr/bin/env sh\n# bd-shim v2\n# bd-hooks-version: 0.56.1\nexec bd hooks run pre-commit \"$@\"\n")
|
||||
writeHookMigrationFile(t, preCommitPath+".old", "#!/usr/bin/env sh\necho from-old\n")
|
||||
writeHookMigrationFile(t, preCommitPath+".backup", "#!/usr/bin/env sh\necho from-backup\n")
|
||||
|
||||
plan, err := doctor.PlanHookMigration(repoDir)
|
||||
if err != nil {
|
||||
t.Fatalf("PlanHookMigration failed: %v", err)
|
||||
}
|
||||
execPlan := buildHookMigrationExecutionPlan(plan)
|
||||
|
||||
if _, err := applyHookMigrationExecution(execPlan); err != nil {
|
||||
t.Fatalf("applyHookMigrationExecution failed: %v", err)
|
||||
}
|
||||
|
||||
rendered := mustReadHookMigrationFile(t, preCommitPath)
|
||||
if !strings.Contains(rendered, "echo from-old") {
|
||||
t.Fatalf("expected .old content to be preferred, got:\n%s", rendered)
|
||||
}
|
||||
if strings.Contains(rendered, "echo from-backup") {
|
||||
t.Fatalf("expected .backup content to be ignored, got:\n%s", rendered)
|
||||
}
|
||||
|
||||
assertExistsHookMigrationFile(t, preCommitPath+".old.migrated")
|
||||
assertExistsHookMigrationFile(t, preCommitPath+".backup.migrated")
|
||||
assertMissingHookMigrationFile(t, preCommitPath+".old")
|
||||
assertMissingHookMigrationFile(t, preCommitPath+".backup")
|
||||
}
|
||||
|
||||
func TestApplyHookMigrationExecution_CustomWithSidecarsPreservesHookBody(t *testing.T) {
|
||||
repoDir, hooksDir := setupHookMigrationRepo(t)
|
||||
preCommitPath := filepath.Join(hooksDir, "pre-commit")
|
||||
|
||||
writeHookMigrationFile(t, preCommitPath, "#!/usr/bin/env sh\necho custom-body\n")
|
||||
writeHookMigrationFile(t, preCommitPath+".old", "#!/usr/bin/env sh\necho stale-old\n")
|
||||
writeHookMigrationFile(t, preCommitPath+".backup", "#!/usr/bin/env sh\necho stale-backup\n")
|
||||
|
||||
plan, err := doctor.PlanHookMigration(repoDir)
|
||||
if err != nil {
|
||||
t.Fatalf("PlanHookMigration failed: %v", err)
|
||||
}
|
||||
execPlan := buildHookMigrationExecutionPlan(plan)
|
||||
|
||||
if _, err := applyHookMigrationExecution(execPlan); err != nil {
|
||||
t.Fatalf("applyHookMigrationExecution failed: %v", err)
|
||||
}
|
||||
|
||||
rendered := mustReadHookMigrationFile(t, preCommitPath)
|
||||
if !strings.Contains(rendered, "echo custom-body") {
|
||||
t.Fatalf("expected migrated hook to preserve custom body, got:\n%s", rendered)
|
||||
}
|
||||
if !strings.Contains(rendered, hookSectionBeginPrefix) || !strings.Contains(rendered, hookSectionEnd) {
|
||||
t.Fatalf("expected migrated hook to contain marker section, got:\n%s", rendered)
|
||||
}
|
||||
|
||||
assertExistsHookMigrationFile(t, preCommitPath+".old.migrated")
|
||||
assertExistsHookMigrationFile(t, preCommitPath+".backup.migrated")
|
||||
}
|
||||
|
||||
func TestApplyHookMigrationExecution_MarkerBrokenBlocksApply(t *testing.T) {
|
||||
repoDir, hooksDir := setupHookMigrationRepo(t)
|
||||
preCommitPath := filepath.Join(hooksDir, "pre-commit")
|
||||
|
||||
brokenContent := "#!/usr/bin/env sh\n# --- BEGIN BEADS INTEGRATION v0.57.0 ---\nbd hooks run pre-commit \"$@\"\n"
|
||||
writeHookMigrationFile(t, preCommitPath, brokenContent)
|
||||
|
||||
plan, err := doctor.PlanHookMigration(repoDir)
|
||||
if err != nil {
|
||||
t.Fatalf("PlanHookMigration failed: %v", err)
|
||||
}
|
||||
execPlan := buildHookMigrationExecutionPlan(plan)
|
||||
if len(execPlan.BlockingErrors) == 0 {
|
||||
t.Fatal("expected blocking errors for broken marker")
|
||||
}
|
||||
|
||||
if _, err := applyHookMigrationExecution(execPlan); err == nil {
|
||||
t.Fatal("expected apply to fail for broken marker state")
|
||||
}
|
||||
|
||||
rendered := mustReadHookMigrationFile(t, preCommitPath)
|
||||
if rendered != brokenContent {
|
||||
t.Fatalf("expected broken hook to remain unchanged after blocked apply")
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyHookMigrationExecution_Idempotent(t *testing.T) {
|
||||
repoDir, hooksDir := setupHookMigrationRepo(t)
|
||||
preCommitPath := filepath.Join(hooksDir, "pre-commit")
|
||||
|
||||
writeHookMigrationFile(t, preCommitPath, "#!/usr/bin/env sh\n# bd-shim v2\n# bd-hooks-version: 0.56.1\nexec bd hooks run pre-commit \"$@\"\n")
|
||||
writeHookMigrationFile(t, preCommitPath+".old", "#!/usr/bin/env sh\necho old-custom\n")
|
||||
|
||||
plan, err := doctor.PlanHookMigration(repoDir)
|
||||
if err != nil {
|
||||
t.Fatalf("PlanHookMigration failed: %v", err)
|
||||
}
|
||||
execPlan := buildHookMigrationExecutionPlan(plan)
|
||||
if _, err := applyHookMigrationExecution(execPlan); err != nil {
|
||||
t.Fatalf("first apply failed: %v", err)
|
||||
}
|
||||
|
||||
secondPlan, err := doctor.PlanHookMigration(repoDir)
|
||||
if err != nil {
|
||||
t.Fatalf("second PlanHookMigration failed: %v", err)
|
||||
}
|
||||
secondExec := buildHookMigrationExecutionPlan(secondPlan)
|
||||
if secondExec.operationCount() != 0 {
|
||||
t.Fatalf("expected second execution to be no-op, got %d operations", secondExec.operationCount())
|
||||
}
|
||||
|
||||
summary, err := applyHookMigrationExecution(secondExec)
|
||||
if err != nil {
|
||||
t.Fatalf("second apply should be no-op, got error: %v", err)
|
||||
}
|
||||
if summary.WrittenHookCount != 0 || summary.RetiredCount != 0 {
|
||||
t.Fatalf("expected no-op summary on second apply, got %+v", summary)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyHookMigrationExecution_RetireCollisionFailsBeforeWrites(t *testing.T) {
|
||||
repoDir, hooksDir := setupHookMigrationRepo(t)
|
||||
preCommitPath := filepath.Join(hooksDir, "pre-commit")
|
||||
|
||||
legacyHook := "#!/usr/bin/env sh\n# bd-shim v2\n# bd-hooks-version: 0.56.1\nexec bd hooks run pre-commit \"$@\"\n"
|
||||
writeHookMigrationFile(t, preCommitPath, legacyHook)
|
||||
writeHookMigrationFile(t, preCommitPath+".old", "#!/usr/bin/env sh\necho old-custom\n")
|
||||
writeHookMigrationFile(t, preCommitPath+".old.migrated", "#!/usr/bin/env sh\necho conflicting-content\n")
|
||||
|
||||
plan, err := doctor.PlanHookMigration(repoDir)
|
||||
if err != nil {
|
||||
t.Fatalf("PlanHookMigration failed: %v", err)
|
||||
}
|
||||
execPlan := buildHookMigrationExecutionPlan(plan)
|
||||
|
||||
if _, err := applyHookMigrationExecution(execPlan); err == nil {
|
||||
t.Fatal("expected retire collision to fail apply")
|
||||
} else if !strings.Contains(err.Error(), "artifact collision") {
|
||||
t.Fatalf("expected collision error, got: %v", err)
|
||||
}
|
||||
|
||||
rendered := mustReadHookMigrationFile(t, preCommitPath)
|
||||
if rendered != legacyHook {
|
||||
t.Fatalf("expected hook file to remain unchanged when collision blocks apply")
|
||||
}
|
||||
}
|
||||
|
||||
func setupHookMigrationRepo(t *testing.T) (repoDir string, hooksDir string) {
|
||||
t.Helper()
|
||||
repoDir = newGitRepo(t)
|
||||
|
||||
runInDir(t, repoDir, func() {
|
||||
cmd := exec.Command("git", "config", "core.hooksPath", ".git/hooks")
|
||||
if err := cmd.Run(); err != nil {
|
||||
t.Fatalf("failed to set core.hooksPath: %v", err)
|
||||
}
|
||||
|
||||
var err error
|
||||
hooksDir, err = git.GetGitHooksDir()
|
||||
if err != nil {
|
||||
t.Fatalf("failed to resolve hooks dir: %v", err)
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(hooksDir, 0o755); err != nil {
|
||||
t.Fatalf("failed to create hooks dir: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
return repoDir, hooksDir
|
||||
}
|
||||
|
||||
func writeHookMigrationFile(t *testing.T, path, content string) {
|
||||
t.Helper()
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
t.Fatalf("failed to create parent dir for %s: %v", path, err)
|
||||
}
|
||||
if err := os.WriteFile(path, []byte(content), 0o755); err != nil {
|
||||
t.Fatalf("failed to write %s: %v", path, err)
|
||||
}
|
||||
}
|
||||
|
||||
func mustReadHookMigrationFile(t *testing.T, path string) string {
|
||||
t.Helper()
|
||||
content, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to read %s: %v", path, err)
|
||||
}
|
||||
return string(content)
|
||||
}
|
||||
|
||||
func assertExistsHookMigrationFile(t *testing.T, path string) {
|
||||
t.Helper()
|
||||
if _, err := os.Stat(path); err != nil {
|
||||
t.Fatalf("expected %s to exist: %v", path, err)
|
||||
}
|
||||
}
|
||||
|
||||
func assertMissingHookMigrationFile(t *testing.T, path string) {
|
||||
t.Helper()
|
||||
if _, err := os.Stat(path); !os.IsNotExist(err) {
|
||||
t.Fatalf("expected %s to be missing, got err=%v", path, err)
|
||||
}
|
||||
}
|
||||
|
|
@ -14,37 +14,82 @@ func TestBuildHookMigrationJSON(t *testing.T) {
|
|||
NeedsMigrationCount: 2,
|
||||
TotalHooks: 5,
|
||||
}
|
||||
|
||||
out := buildHookMigrationJSON(plan, false)
|
||||
|
||||
if status, ok := out["status"].(string); !ok || status != "planning_only" {
|
||||
t.Fatalf("expected status planning_only, got %#v", out["status"])
|
||||
mode := hookMigrationMode{
|
||||
RequestedDryRun: true,
|
||||
}
|
||||
if planningOnly, ok := out["planning_only"].(bool); !ok || !planningOnly {
|
||||
t.Fatalf("expected planning_only=true, got %#v", out["planning_only"])
|
||||
execPlan := hookMigrationExecutionPlan{
|
||||
WriteOps: []hookMigrationWriteOp{
|
||||
{
|
||||
HookName: "pre-commit",
|
||||
HookPath: "/tmp/repo/.git/hooks/pre-commit",
|
||||
State: "legacy_only",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
out := buildHookMigrationJSON(plan, mode, execPlan, nil)
|
||||
|
||||
if status, ok := out["status"].(string); !ok || status != "preview" {
|
||||
t.Fatalf("expected status preview, got %#v", out["status"])
|
||||
}
|
||||
if dryRun, ok := out["dry_run"].(bool); !ok || !dryRun {
|
||||
t.Fatalf("expected dry_run=true, got %#v", out["dry_run"])
|
||||
}
|
||||
if opCount, ok := out["operation_count"].(int); !ok || opCount != 1 {
|
||||
t.Fatalf("expected operation_count=1, got %#v", out["operation_count"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateHookMigrationDryRunRequested(t *testing.T) {
|
||||
if err := validateHookMigrationDryRunRequested(true); err != nil {
|
||||
t.Fatalf("expected no error for dry-run mode, got %v", err)
|
||||
func TestValidateHookMigrationMode(t *testing.T) {
|
||||
mode, err := validateHookMigrationMode(true, false, false)
|
||||
if err != nil {
|
||||
t.Fatalf("expected no error for --dry-run mode, got %v", err)
|
||||
}
|
||||
if !mode.RequestedDryRun || mode.RequestedApply {
|
||||
t.Fatalf("unexpected mode for dry-run: %#v", mode)
|
||||
}
|
||||
|
||||
err := validateHookMigrationDryRunRequested(false)
|
||||
if err == nil {
|
||||
t.Fatalf("expected error when --dry-run is missing")
|
||||
mode, err = validateHookMigrationMode(false, true, true)
|
||||
if err != nil {
|
||||
t.Fatalf("expected no error for --apply --yes mode, got %v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "--dry-run is required") {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
if !mode.RequestedApply || !mode.RequestedYes || mode.RequestedDryRun {
|
||||
t.Fatalf("unexpected mode for apply: %#v", mode)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "#2218") {
|
||||
t.Fatalf("expected issue reference #2218, got: %v", err)
|
||||
|
||||
_, err = validateHookMigrationMode(true, true, false)
|
||||
if err == nil || !strings.Contains(err.Error(), "cannot use --dry-run and --apply together") {
|
||||
t.Fatalf("expected mutual-exclusion error, got: %v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "resolving #2218 is merged") {
|
||||
t.Fatalf("expected merge condition note, got: %v", err)
|
||||
|
||||
_, err = validateHookMigrationMode(false, false, false)
|
||||
if err == nil || !strings.Contains(err.Error(), "must specify exactly one mode") {
|
||||
t.Fatalf("expected mode-required error, got: %v", err)
|
||||
}
|
||||
|
||||
_, err = validateHookMigrationMode(false, false, true)
|
||||
if err == nil || !strings.Contains(err.Error(), "--yes requires --apply") {
|
||||
t.Fatalf("expected yes-without-apply error, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateHookMigrationApplyConsent(t *testing.T) {
|
||||
if err := validateHookMigrationApplyConsent(true, false, false); err != nil {
|
||||
t.Fatalf("expected --yes to bypass prompt checks, got: %v", err)
|
||||
}
|
||||
|
||||
if err := validateHookMigrationApplyConsent(false, true, false); err != nil {
|
||||
t.Fatalf("expected interactive mode to allow prompt, got: %v", err)
|
||||
}
|
||||
|
||||
err := validateHookMigrationApplyConsent(false, false, true)
|
||||
if err == nil || !strings.Contains(err.Error(), "--json with --apply requires --yes") {
|
||||
t.Fatalf("expected json+apply consent error, got: %v", err)
|
||||
}
|
||||
|
||||
err = validateHookMigrationApplyConsent(false, false, false)
|
||||
if err == nil || !strings.Contains(err.Error(), "requires confirmation") {
|
||||
t.Fatalf("expected non-interactive consent error, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -52,7 +97,7 @@ func TestFormatHookMigrationPlan_NotGitRepo(t *testing.T) {
|
|||
lines := formatHookMigrationPlan(doctor.HookMigrationPlan{
|
||||
Path: "/tmp/no-git",
|
||||
IsGitRepo: false,
|
||||
})
|
||||
}, hookMigrationMode{RequestedDryRun: true})
|
||||
|
||||
rendered := strings.Join(lines, "\n")
|
||||
if !strings.Contains(rendered, "not a git repository") {
|
||||
|
|
@ -77,7 +122,7 @@ func TestFormatHookMigrationPlan_WithMigrations(t *testing.T) {
|
|||
},
|
||||
}
|
||||
|
||||
lines := formatHookMigrationPlan(plan)
|
||||
lines := formatHookMigrationPlan(plan, hookMigrationMode{RequestedDryRun: true})
|
||||
rendered := strings.Join(lines, "\n")
|
||||
|
||||
if !strings.Contains(rendered, "Needs migration: 1/5") {
|
||||
|
|
@ -86,7 +131,7 @@ func TestFormatHookMigrationPlan_WithMigrations(t *testing.T) {
|
|||
if !strings.Contains(rendered, "- pre-commit: legacy_with_old_sidecar [migrate]") {
|
||||
t.Fatalf("expected hook entry, got: %s", rendered)
|
||||
}
|
||||
if !strings.Contains(rendered, "Next: run 'bd migrate hooks --dry-run --json'") {
|
||||
if !strings.Contains(rendered, "Next: run 'bd migrate hooks --apply'") {
|
||||
t.Fatalf("expected next-step hint, got: %s", rendered)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue