beads/cmd/bd/backup_export.go
Okano, Osamu ef6c6e3e48
Follow up remaining runtime .beads fallbacks after GH#3124 (#3183)
* 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
2026-04-10 21:23:14 -07:00

167 lines
4.8 KiB
Go

package main
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/config"
"github.com/steveyegge/beads/internal/debug"
"github.com/steveyegge/beads/internal/storage"
)
// backupState tracks watermarks for backup change detection.
type backupState struct {
LastDoltCommit string `json:"last_dolt_commit"`
Timestamp time.Time `json:"timestamp"`
}
// backupDir returns the backup directory path, creating it if needed.
// When backup.git-repo is set to a valid git repo, returns a backup/ subdirectory
// inside that repo. Otherwise it requires an active beads workspace and uses its
// backup/ subdirectory.
func backupDir() (string, error) {
gitRepo := config.GetString("backup.git-repo")
if gitRepo != "" {
if strings.HasPrefix(gitRepo, "~/") {
home, _ := os.UserHomeDir()
gitRepo = filepath.Join(home, gitRepo[2:])
}
if _, err := os.Stat(filepath.Join(gitRepo, ".git")); err != nil {
fmt.Fprintf(os.Stderr, "Warning: backup.git-repo %s is not a git repo, falling back to .beads/backup\n", gitRepo)
} else {
dir := filepath.Join(gitRepo, "backup")
if err := os.MkdirAll(dir, 0700); err != nil {
return "", fmt.Errorf("failed to create backup dir in git-repo: %w", err)
}
return dir, nil
}
}
beadsDir := beads.FindBeadsDir()
if beadsDir == "" {
return "", fmt.Errorf("%s; %s", activeWorkspaceNotFoundError(), diagHint())
}
dir := filepath.Join(beadsDir, "backup")
if err := os.MkdirAll(dir, 0700); err != nil {
return "", fmt.Errorf("failed to create backup directory: %w", err)
}
return dir, nil
}
// loadBackupState reads the backup state file, returning a zero state if missing.
func loadBackupState(dir string) (*backupState, error) {
path := filepath.Join(dir, "backup_state.json")
data, err := os.ReadFile(path) //nolint:gosec // path is constructed internally
if os.IsNotExist(err) {
return &backupState{}, nil
}
if err != nil {
return nil, fmt.Errorf("failed to read backup state: %w", err)
}
var state backupState
if err := json.Unmarshal(data, &state); err != nil {
return nil, fmt.Errorf("failed to parse backup state: %w", err)
}
return &state, nil
}
// saveBackupState writes the backup state file atomically.
func saveBackupState(dir string, state *backupState) error {
data, err := json.MarshalIndent(state, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal backup state: %w", err)
}
return atomicWriteFile(filepath.Join(dir, "backup_state.json"), data)
}
// atomicWriteFile writes data to a temp file and renames it into place (crash-safe).
func atomicWriteFile(path string, data []byte) error {
dir := filepath.Dir(path)
tmp, err := os.CreateTemp(dir, ".backup-tmp-*")
if err != nil {
return fmt.Errorf("failed to create temp file: %w", err)
}
tmpPath := tmp.Name()
if _, err := tmp.Write(data); err != nil {
_ = tmp.Close()
_ = os.Remove(tmpPath)
return fmt.Errorf("failed to write temp file: %w", err)
}
if err := tmp.Sync(); err != nil {
_ = tmp.Close()
_ = os.Remove(tmpPath)
return fmt.Errorf("failed to sync temp file: %w", err)
}
if err := tmp.Close(); err != nil {
_ = os.Remove(tmpPath)
return fmt.Errorf("failed to close temp file: %w", err)
}
if err := os.Rename(tmpPath, path); err != nil {
_ = os.Remove(tmpPath)
return fmt.Errorf("failed to rename temp file: %w", err)
}
return nil
}
// runBackupExport performs a Dolt-native backup to .beads/backup/.
// Returns the updated state.
func runBackupExport(ctx context.Context, force bool) (*backupState, error) {
dir, err := backupDir()
if err != nil {
return nil, err
}
state, err := loadBackupState(dir)
if err != nil {
return nil, err
}
// Change detection: skip if nothing changed (unless forced)
if !force {
currentCommit, err := store.GetCurrentCommit(ctx)
if err != nil {
return nil, fmt.Errorf("failed to get current commit: %w", err)
}
if currentCommit == state.LastDoltCommit && state.LastDoltCommit != "" {
debug.Logf("backup: no changes since last backup (commit %s)\n", truncateHash(currentCommit))
return state, nil
}
}
bs, ok := storage.UnwrapStore(store).(storage.BackupStore)
if !ok {
return nil, fmt.Errorf("storage backend does not support backup operations")
}
if err := bs.BackupDatabase(ctx, dir); err != nil {
return nil, err
}
// Update watermarks
currentCommit, err := store.GetCurrentCommit(ctx)
if err != nil {
return nil, fmt.Errorf("failed to get current commit for state: %w", err)
}
state.LastDoltCommit = currentCommit
state.Timestamp = time.Now().UTC()
if err := saveBackupState(dir, state); err != nil {
return nil, err
}
return state, nil
}
// truncateHash returns the first 8 characters of a hash, or the full string if shorter.
func truncateHash(h string) string {
if len(h) > 8 {
return h[:8]
}
return h
}