75 lines
2.5 KiB
Go
75 lines
2.5 KiB
Go
package versioncontrolops
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
)
|
|
|
|
// Compact squashes old Dolt commits into a single base commit while preserving
|
|
// recent commits via cherry-pick. The recipe:
|
|
// 1. Create temp branch at the boundary commit (last old commit)
|
|
// 2. Checkout temp branch
|
|
// 3. Soft-reset to initial commit (collapses old history into working set)
|
|
// 4. Commit as single squashed base
|
|
// 5. Cherry-pick each recent commit on top
|
|
// 6. Checkout main, hard-reset to temp branch
|
|
// 7. Delete temp branch
|
|
//
|
|
// Callers should run DoltGC afterward to reclaim disk space.
|
|
//
|
|
// conn must be a single database connection (not a pooled *sql.DB) since the
|
|
// stored procedures rely on session-scoped state (current branch, working set).
|
|
func Compact(ctx context.Context, conn DBConn, initialHash, boundaryHash string, oldCommits int, recentHashes []string) (retErr error) {
|
|
branchCreated := false
|
|
|
|
// Best-effort cleanup: if any step fails after creating the temp branch,
|
|
// try to return to main and delete the temp branch so future compactions
|
|
// aren't blocked by a leftover branch.
|
|
defer func() {
|
|
if retErr != nil && branchCreated {
|
|
_, _ = conn.ExecContext(ctx, "CALL DOLT_CHECKOUT('main')")
|
|
_, _ = conn.ExecContext(ctx, "CALL DOLT_BRANCH('-D', 'compact-tmp')")
|
|
}
|
|
}()
|
|
|
|
execSQL := func(name, query string, args ...interface{}) error {
|
|
if _, err := conn.ExecContext(ctx, query, args...); err != nil {
|
|
return fmt.Errorf("compact step %q: %w", name, err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
if err := execSQL("create temp branch", "CALL DOLT_BRANCH('compact-tmp', ?)", boundaryHash); err != nil {
|
|
return err
|
|
}
|
|
branchCreated = true
|
|
|
|
if err := execSQL("checkout temp", "CALL DOLT_CHECKOUT('compact-tmp')"); err != nil {
|
|
return err
|
|
}
|
|
if err := execSQL("soft reset to initial", "CALL DOLT_RESET('--soft', ?)", initialHash); err != nil {
|
|
return err
|
|
}
|
|
msg := fmt.Sprintf("compact: squash %d commits into base snapshot", oldCommits)
|
|
if err := execSQL("commit squashed base", "CALL DOLT_COMMIT('-Am', ?)", msg); err != nil {
|
|
return err
|
|
}
|
|
|
|
for _, hash := range recentHashes {
|
|
if err := execSQL(fmt.Sprintf("cherry-pick %s", hash[:min(8, len(hash))]), "CALL DOLT_CHERRY_PICK(?)", hash); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
if err := execSQL("checkout main", "CALL DOLT_CHECKOUT('main')"); err != nil {
|
|
return err
|
|
}
|
|
if err := execSQL("reset main to compacted", "CALL DOLT_RESET('--hard', 'compact-tmp')"); err != nil {
|
|
return err
|
|
}
|
|
if err := execSQL("delete temp branch", "CALL DOLT_BRANCH('-D', 'compact-tmp')"); err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|