* fix(workspace): align resolved workspace messaging and config lookup intent(workspace): pure worktrees and external BEADS_DIR setups should work without implying a local .beads directory is required decision(config): derive config repo roots from FindBeadsDir-backed workspace resolution instead of a local-only .beads walk constraint(workspace-detection): keep FindBeadsDir ordering and storage behavior unchanged while making bd where the primary diagnostic hint learned(testing): shared-server env and global .beads ignore rules can distort CGO suites, so regression coverage now normalizes those test paths * fix(bootstrap): align no-workspace JSON wording intent(bootstrap): machine-readable no-workspace output should match the resolved-workspace guidance used elsewhere on this branch decision(bootstrap-json): reuse the shared workspace error helpers through a dedicated payload builder so tests can lock the JSON contract constraint(review-loop): keep the bootstrap CLI flow unchanged outside the no-workspace JSON branch while adding a focused regression test * fix(where): allow no-workspace diagnostics without db (beads-9f74-5l1) intent(where): no-workspace guidance should point to a command that actually runs when workspace resolution fails decision(startup): treat top-level where as a no-db command so it reaches its own handler before database preflight constraint(where-tests): subprocess mode can change the exact hint text, so the regression test locks the JSON contract and stable guidance fragments instead * fix(bootstrap): restore bd where guidance for no-workspace output (beads-9f74-3c3) intent(bootstrap): no-workspace bootstrap guidance should match the resolved-workspace diagnostics introduced on this branch decision(no-workspace-hints): reuse the shared hint that mentions bd where instead of the bootstrap-specific fallback text constraint(bootstrap-tests): cover both the payload helper and subprocess CLI path so wording regressions are caught before release * fix(workspace): remove no-workspace .beads fallbacks (beads-9f74-gr1) intent(workspace-resolution): finish the GH#3124 follow-up for runtime paths that still fabricated local .beads state rejected(no-workspace-fallback): inventing ./ .beads paths outside an active workspace hid shared-worktree resolution and created stray files decision(setup-recipes): keep built-in bd setup recipes usable without a workspace but require an active workspace for custom recipe state constraint(worktree-support): completion and backup helpers still need to resolve shared main-repo workspaces from a git worktree * fix(config): skip no-workspace store init for store-free commands intent(config): review-fix-loop found no-workspace config commands should reach their own graceful paths instead of failing in PersistentPreRun decision(config-preflight): detect store-free config subcommands before DB synthesis so config.yaml, git-backed, and diagnostic flows can run without an opened store constraint(json-contract): keep bd config validate --json machine-readable on stdout once pre-run stops short-circuiting into low-level DB errors learned(config-preflight): the parent config command not being in noDbCommands leaked store init into show, validate, drift, apply, and yaml-only config helpers * fix(ci): restore init prefix normalization and formatting intent(ci): clear the current PR failures instead of leaving the branch blocked behind known red checks decision(init-prefix): normalize dotted prefixes before persisting issue_prefix so config, metadata.json, and Dolt database naming stay aligned for Julia-style repos constraint(fmt-check): CI runs gofmt over the whole repo, so the existing spacing drift in internal/jira/tracker_test.go had to be cleaned up on this branch to get a green run learned(ci): the latest main CI was already red on the same formatting file and the same embedded shard, so rebasing surfaced pre-existing blockers rather than introducing a new shard-only regression
151 lines
4.3 KiB
Go
151 lines
4.3 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"os"
|
|
"strings"
|
|
|
|
"github.com/spf13/cobra"
|
|
"github.com/steveyegge/beads/internal/beads"
|
|
"github.com/steveyegge/beads/internal/configfile"
|
|
"github.com/steveyegge/beads/internal/storage"
|
|
"github.com/steveyegge/beads/internal/ui"
|
|
)
|
|
|
|
var backupRestoreCmd = &cobra.Command{
|
|
Use: "restore [path]",
|
|
Short: "Restore database from a Dolt backup",
|
|
Long: `Restore the beads database from a Dolt-native backup.
|
|
|
|
By default, reads from .beads/backup/ (or the configured backup directory).
|
|
Optionally specify a path to a directory containing a Dolt backup.
|
|
|
|
Use --force to overwrite an existing database with the backup contents.
|
|
|
|
The database must already be initialized (run 'bd init' first if needed).
|
|
To initialize and restore in one step, use: bd init && bd backup restore`,
|
|
Args: cobra.MaximumNArgs(1),
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
ctx := rootCtx
|
|
|
|
var dir string
|
|
if len(args) > 0 {
|
|
dir = args[0]
|
|
} else {
|
|
var err error
|
|
dir, err = backupDir()
|
|
if err != nil {
|
|
return fmt.Errorf("failed to find backup directory: %w", err)
|
|
}
|
|
}
|
|
|
|
if err := validateBackupRestoreDir(dir); err != nil {
|
|
return err
|
|
}
|
|
|
|
force, _ := cmd.Flags().GetBool("force")
|
|
|
|
if err := runBackupRestore(ctx, store, dir, force); err != nil {
|
|
return err
|
|
}
|
|
|
|
if !jsonOutput {
|
|
fmt.Printf("%s Restore complete\n", ui.RenderPass("✓"))
|
|
}
|
|
|
|
return nil
|
|
},
|
|
}
|
|
|
|
func init() {
|
|
backupRestoreCmd.Flags().Bool("force", false, "Overwrite existing database with backup contents")
|
|
backupCmd.AddCommand(backupRestoreCmd)
|
|
}
|
|
|
|
// runBackupRestore restores the database from a Dolt-native backup.
|
|
func runBackupRestore(ctx context.Context, s storage.DoltStorage, dir string, force bool) error {
|
|
if s == nil {
|
|
return fmt.Errorf("database is not initialized. Run 'bd init' first")
|
|
}
|
|
|
|
bs, ok := storage.UnwrapStore(s).(storage.BackupStore)
|
|
if !ok {
|
|
return fmt.Errorf("storage backend does not support backup operations")
|
|
}
|
|
|
|
if err := bs.RestoreDatabase(ctx, dir, force); err != nil {
|
|
return err
|
|
}
|
|
|
|
// After a force restore, the database's _project_id may differ from
|
|
// metadata.json (the backup came from a different project). Sync
|
|
// metadata.json to match the restored database so the identity check
|
|
// doesn't reject subsequent connections.
|
|
if force {
|
|
if err := syncProjectIDFromDB(ctx, s); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to sync project ID after restore: %v\n", err)
|
|
}
|
|
}
|
|
|
|
// Register the restore source as the backup destination so
|
|
// `bd backup sync` works immediately without a separate `bd backup add`.
|
|
registerBackupRemote(ctx, bs, dir)
|
|
|
|
if err := s.Commit(ctx, "bd backup restore"); err != nil {
|
|
if !strings.Contains(err.Error(), "nothing to commit") {
|
|
return fmt.Errorf("failed to commit restore: %w", err)
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// registerBackupRemote registers dir as the default backup remote and saves
|
|
// the local backup config. Errors are non-fatal warnings.
|
|
func registerBackupRemote(ctx context.Context, bs storage.BackupStore, dir string) {
|
|
backupURL := resolveDoltBackupURL(dir)
|
|
|
|
// Remove + re-add to handle the case where a remote already exists.
|
|
_ = bs.BackupRemove(ctx, defaultDoltBackupName)
|
|
if err := bs.BackupAdd(ctx, defaultDoltBackupName, backupURL); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to register backup remote: %v\n", err)
|
|
return
|
|
}
|
|
if err := saveDoltBackupConfig(backupURL); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: backup registered but failed to save config: %v\n", err)
|
|
}
|
|
}
|
|
|
|
// syncProjectIDFromDB reads _project_id from the restored database and
|
|
// updates metadata.json to match, preventing identity mismatch errors.
|
|
func syncProjectIDFromDB(ctx context.Context, s storage.DoltStorage) error {
|
|
dbID, err := s.GetMetadata(ctx, "_project_id")
|
|
if err != nil || dbID == "" {
|
|
return err
|
|
}
|
|
|
|
beadsDir := beads.FindBeadsDir()
|
|
if beadsDir == "" {
|
|
return fmt.Errorf("%s; %s", activeWorkspaceNotFoundError(), diagHint())
|
|
}
|
|
|
|
cfg, err := configfile.Load(beadsDir)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if cfg.ProjectID == dbID {
|
|
return nil // already in sync
|
|
}
|
|
|
|
cfg.ProjectID = dbID
|
|
return cfg.Save(beadsDir)
|
|
}
|
|
|
|
func validateBackupRestoreDir(dir string) error {
|
|
if _, err := os.Stat(dir); os.IsNotExist(err) {
|
|
return fmt.Errorf("backup directory not found: %s\nRun 'bd backup' first to create a backup", dir)
|
|
}
|
|
return nil
|
|
}
|