1272 lines
44 KiB
Go
1272 lines
44 KiB
Go
//go:build cgo
|
|
|
|
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"runtime"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/steveyegge/beads/internal/configfile"
|
|
"github.com/steveyegge/beads/internal/storage/embeddeddolt"
|
|
"github.com/steveyegge/beads/internal/types"
|
|
)
|
|
|
|
var (
|
|
embeddedBDOnce sync.Once
|
|
embeddedBD string
|
|
embeddedBDErr error
|
|
)
|
|
|
|
// buildEmbeddedBD returns the path to an embedded bd binary for subprocess tests.
|
|
// If BEADS_TEST_BD_BINARY is set, uses that pre-built binary (skipping the ~45s build).
|
|
// CI can pre-build once and pass the path to all test invocations.
|
|
func buildEmbeddedBD(t *testing.T) string {
|
|
t.Helper()
|
|
embeddedBDOnce.Do(func() {
|
|
if prebuilt := os.Getenv("BEADS_TEST_BD_BINARY"); prebuilt != "" {
|
|
if _, err := os.Stat(prebuilt); err != nil {
|
|
embeddedBDErr = fmt.Errorf("BEADS_TEST_BD_BINARY=%q not found: %w", prebuilt, err)
|
|
return
|
|
}
|
|
embeddedBD = prebuilt
|
|
return
|
|
}
|
|
tmpDir, err := os.MkdirTemp("", "bd-embedded-init-test-*")
|
|
if err != nil {
|
|
embeddedBDErr = fmt.Errorf("failed to create temp dir: %w", err)
|
|
return
|
|
}
|
|
name := "bd"
|
|
if runtime.GOOS == "windows" {
|
|
name = "bd.exe"
|
|
}
|
|
embeddedBD = filepath.Join(tmpDir, name)
|
|
cmd := exec.Command("go", "build", "-tags", "gms_pure_go", "-o", embeddedBD, ".")
|
|
if out, err := cmd.CombinedOutput(); err != nil {
|
|
embeddedBDErr = fmt.Errorf("go build failed: %v\n%s", err, out)
|
|
}
|
|
})
|
|
if embeddedBDErr != nil {
|
|
t.Fatalf("Failed to build embedded bd binary: %v", embeddedBDErr)
|
|
}
|
|
return embeddedBD
|
|
}
|
|
|
|
func initGitRepoAt(t *testing.T, dir string) {
|
|
t.Helper()
|
|
for _, args := range [][]string{
|
|
{"init"},
|
|
{"config", "user.email", "test@test.com"},
|
|
{"config", "user.name", "Test"},
|
|
// Force repo-local hooks so tests ignore any global hooksPath override.
|
|
{"config", "core.hooksPath", ".git/hooks"},
|
|
} {
|
|
cmd := exec.Command("git", args...)
|
|
cmd.Dir = dir
|
|
if out, err := cmd.CombinedOutput(); err != nil {
|
|
t.Fatalf("git %s failed: %v\n%s", args[0], err, out)
|
|
}
|
|
}
|
|
}
|
|
|
|
func bdEnv(dir string) []string {
|
|
var env []string
|
|
for _, e := range os.Environ() {
|
|
if strings.HasPrefix(e, "BEADS_") {
|
|
continue
|
|
}
|
|
env = append(env, e)
|
|
}
|
|
return append(env, "HOME="+dir, "BEADS_DOLT_AUTO_START=0", "BEADS_NO_DAEMON=1")
|
|
}
|
|
|
|
func isEmbeddedLockOutput(out string) bool {
|
|
out = strings.ToLower(out)
|
|
return strings.Contains(out, "one writer at a time") ||
|
|
strings.Contains(out, "database is locked") ||
|
|
strings.Contains(out, "locked by another dolt process")
|
|
}
|
|
|
|
func runCommandBuffers(t *testing.T, cmd *exec.Cmd) (stdout, stderr bytes.Buffer, err error) {
|
|
t.Helper()
|
|
cmd.Stdout = &stdout
|
|
cmd.Stderr = &stderr
|
|
err = cmd.Run()
|
|
return stdout, stderr, err
|
|
}
|
|
|
|
// bdRunWithFlockRetry runs a bd command with retry on flock contention.
|
|
// Returns stdout and nil on success, or combined stdout/stderr and the last
|
|
// error after retries are exhausted or a non-flock error occurs.
|
|
func bdRunWithFlockRetry(t *testing.T, bd, dir string, args ...string) ([]byte, error) {
|
|
t.Helper()
|
|
var out []byte
|
|
var err error
|
|
for attempt := 0; attempt < 10; attempt++ {
|
|
cmd := exec.Command(bd, args...)
|
|
cmd.Dir = dir
|
|
cmd.Env = bdEnv(dir)
|
|
var stdout, stderr bytes.Buffer
|
|
cmd.Stdout = &stdout
|
|
cmd.Stderr = &stderr
|
|
err = cmd.Run()
|
|
if err == nil {
|
|
return stdout.Bytes(), nil
|
|
}
|
|
out = append(stdout.Bytes(), stderr.Bytes()...)
|
|
if !isEmbeddedLockOutput(string(out)) {
|
|
return out, err
|
|
}
|
|
t.Logf("bd %s: flock contention (attempt %d/10), retrying...", args[0], attempt+1)
|
|
time.Sleep(time.Duration(500*(1<<min(attempt, 4))) * time.Millisecond)
|
|
}
|
|
return out, err
|
|
}
|
|
|
|
// bdInit creates a temp dir with a git repo, runs bd init --quiet with the
|
|
// given extra args, and returns (dir, beadsDir, combined output).
|
|
// Fatals if bd init fails.
|
|
func bdInit(t *testing.T, bd string, extraArgs ...string) (dir, beadsDir string, out string) {
|
|
t.Helper()
|
|
dir = t.TempDir()
|
|
initGitRepoAt(t, dir)
|
|
out = runBDInit(t, bd, dir, extraArgs...)
|
|
beadsDir = filepath.Join(dir, ".beads")
|
|
return
|
|
}
|
|
|
|
// bdInitInDir runs bd init --quiet in an existing dir. Fatals on failure.
|
|
func runBDInit(t *testing.T, bd, dir string, extraArgs ...string) string {
|
|
t.Helper()
|
|
args := append([]string{"init", "--quiet"}, extraArgs...)
|
|
cmd := exec.Command(bd, args...)
|
|
cmd.Dir = dir
|
|
cmd.Env = bdEnv(dir)
|
|
stdout, stderr, err := runCommandBuffers(t, cmd)
|
|
if err != nil {
|
|
t.Fatalf("bd init %s failed: %v\nstdout:\n%s\nstderr:\n%s", strings.Join(extraArgs, " "), err, stdout.String(), stderr.String())
|
|
}
|
|
return stdout.String()
|
|
}
|
|
|
|
// bdInitFail runs bd init --quiet expecting failure. Returns combined output.
|
|
func bdInitFail(t *testing.T, bd string, extraArgs ...string) string {
|
|
t.Helper()
|
|
dir := t.TempDir()
|
|
initGitRepoAt(t, dir)
|
|
args := append([]string{"init", "--quiet"}, extraArgs...)
|
|
cmd := exec.Command(bd, args...)
|
|
cmd.Dir = dir
|
|
cmd.Env = bdEnv(dir)
|
|
out, err := cmd.CombinedOutput()
|
|
if err == nil {
|
|
t.Fatal("bd init should have failed")
|
|
}
|
|
return string(out)
|
|
}
|
|
|
|
func readBack(t *testing.T, beadsDir, database, key string, metadata bool) string {
|
|
t.Helper()
|
|
|
|
// The embedded dolt driver holds a process-level lock, so concurrent
|
|
// test functions in the same shard can transiently block each other.
|
|
// Retry a few times before giving up.
|
|
const maxAttempts = 5
|
|
var lastErr error
|
|
for attempt := 0; attempt < maxAttempts; attempt++ {
|
|
if attempt > 0 {
|
|
time.Sleep(time.Duration(attempt) * 500 * time.Millisecond)
|
|
}
|
|
val, err := readBackOnce(t, beadsDir, database, key, metadata)
|
|
if err == nil {
|
|
return val
|
|
}
|
|
lastErr = err
|
|
if !strings.Contains(err.Error(), "locked") {
|
|
break // non-lock error, don't retry
|
|
}
|
|
t.Logf("readBack: attempt %d/%d got lock error, retrying: %v", attempt+1, maxAttempts, err)
|
|
}
|
|
t.Fatalf("readBack: %v", lastErr)
|
|
return "" // unreachable
|
|
}
|
|
|
|
func readBackOnce(t *testing.T, beadsDir, database, key string, metadata bool) (string, error) {
|
|
t.Helper()
|
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
defer cancel()
|
|
store, err := embeddeddolt.Open(ctx, beadsDir, database, "main")
|
|
if err != nil {
|
|
return "", fmt.Errorf("New failed: %w", err)
|
|
}
|
|
defer store.Close()
|
|
if metadata {
|
|
val, err := store.GetMetadata(ctx, key)
|
|
if err != nil {
|
|
return "", fmt.Errorf("GetMetadata(%q) failed: %w", key, err)
|
|
}
|
|
return val, nil
|
|
}
|
|
val, err := store.GetConfig(ctx, key)
|
|
if err != nil {
|
|
return "", fmt.Errorf("GetConfig(%q) failed: %w", key, err)
|
|
}
|
|
return val, nil
|
|
}
|
|
|
|
func stripANSI(s string) string {
|
|
var out strings.Builder
|
|
for i := 0; i < len(s); i++ {
|
|
if s[i] == '\033' && i+1 < len(s) && s[i+1] == '[' {
|
|
for i += 2; i < len(s); i++ {
|
|
if (s[i] >= 'A' && s[i] <= 'Z') || (s[i] >= 'a' && s[i] <= 'z') {
|
|
break
|
|
}
|
|
}
|
|
continue
|
|
}
|
|
out.WriteByte(s[i])
|
|
}
|
|
return out.String()
|
|
}
|
|
|
|
func runDolt(t *testing.T, doltBin, dir string, args ...string) string {
|
|
t.Helper()
|
|
cmd := exec.Command(doltBin, args...)
|
|
cmd.Dir = dir
|
|
out, err := cmd.Output()
|
|
if err != nil {
|
|
t.Fatalf("dolt %s failed: %v", strings.Join(args, " "), err)
|
|
}
|
|
return stripANSI(string(out))
|
|
}
|
|
|
|
func doltHeadHash(t *testing.T, doltBin, dir string) string {
|
|
t.Helper()
|
|
line := strings.TrimSpace(runDolt(t, doltBin, dir, "log", "-n", "1", "--oneline"))
|
|
if idx := strings.IndexByte(line, ' '); idx > 0 {
|
|
return line[:idx]
|
|
}
|
|
t.Fatalf("unexpected dolt log --oneline output: %q", line)
|
|
return ""
|
|
}
|
|
|
|
func requireFile(t *testing.T, path string) {
|
|
t.Helper()
|
|
if _, err := os.Stat(path); os.IsNotExist(err) {
|
|
t.Errorf("expected file to exist: %s", path)
|
|
}
|
|
}
|
|
|
|
func requireNoFile(t *testing.T, path string) {
|
|
t.Helper()
|
|
if _, err := os.Stat(path); err == nil {
|
|
t.Errorf("expected file not to exist: %s", path)
|
|
}
|
|
}
|
|
|
|
func TestEmbeddedInit(t *testing.T) {
|
|
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
|
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt init tests")
|
|
}
|
|
t.Parallel()
|
|
|
|
bd := buildEmbeddedBD(t)
|
|
|
|
t.Run("basic", func(t *testing.T) {
|
|
dir, beadsDir, _ := bdInit(t, bd, "--prefix", "basic")
|
|
embeddedDir := filepath.Join(beadsDir, "embeddeddolt")
|
|
requireFile(t, beadsDir)
|
|
requireFile(t, embeddedDir)
|
|
requireFile(t, filepath.Join(embeddedDir, "basic", ".dolt"))
|
|
|
|
if doltBin, err := exec.LookPath("dolt"); err == nil {
|
|
dbDir := filepath.Join(embeddedDir, "basic")
|
|
statusOut := runDolt(t, doltBin, dbDir, "status")
|
|
if !strings.Contains(statusOut, "nothing to commit") {
|
|
t.Errorf("expected clean working set, got:\n%s", statusOut)
|
|
}
|
|
logOut := runDolt(t, doltBin, dbDir, "log", "--oneline")
|
|
for _, want := range []string{"schema: apply migrations", "bd init"} {
|
|
if !strings.Contains(logOut, want) {
|
|
t.Errorf("dolt log missing %q commit:\n%s", want, logOut)
|
|
}
|
|
}
|
|
}
|
|
_ = dir
|
|
})
|
|
|
|
t.Run("prefix", func(t *testing.T) {
|
|
_, beadsDir, _ := bdInit(t, bd, "--prefix", "myproj")
|
|
if val := readBack(t, beadsDir, "myproj", "issue_prefix", false); val != "myproj" {
|
|
t.Errorf("issue_prefix: got %q, want %q", val, "myproj")
|
|
}
|
|
})
|
|
|
|
t.Run("prefix_trailing_hyphen", func(t *testing.T) {
|
|
_, beadsDir, _ := bdInit(t, bd, "--prefix", "test-")
|
|
if val := readBack(t, beadsDir, "test", "issue_prefix", false); val != "test" {
|
|
t.Errorf("issue_prefix: got %q, want %q", val, "test")
|
|
}
|
|
})
|
|
|
|
t.Run("quiet", func(t *testing.T) {
|
|
_, _, out := bdInit(t, bd, "--prefix", "qt")
|
|
if strings.Contains(out, "bd initialized") {
|
|
t.Error("--quiet should suppress success message")
|
|
}
|
|
})
|
|
|
|
t.Run("not_quiet", func(t *testing.T) {
|
|
dir := t.TempDir()
|
|
initGitRepoAt(t, dir)
|
|
cmd := exec.Command(bd, "init", "--prefix", "nq")
|
|
cmd.Dir = dir
|
|
cmd.Env = bdEnv(dir)
|
|
stdout, stderr, err := runCommandBuffers(t, cmd)
|
|
if err != nil {
|
|
t.Fatalf("bd init failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
|
|
}
|
|
if !strings.Contains(stdout.String(), "bd initialized successfully") {
|
|
t.Errorf("expected success message, got: %s", stdout.String())
|
|
}
|
|
})
|
|
|
|
t.Run("git_origin_registered_as_dolt_remote", func(t *testing.T) {
|
|
bareDir := filepath.Join(t.TempDir(), "plain.git")
|
|
runGitForBootstrapTest(t, "", "init", "--bare", "-b", "main", bareDir)
|
|
|
|
seedDir := t.TempDir()
|
|
initGitRepoAt(t, seedDir)
|
|
runGitForBootstrapTest(t, seedDir, "branch", "-M", "main")
|
|
runGitForBootstrapTest(t, seedDir, "commit", "--allow-empty", "-m", "init")
|
|
runGitForBootstrapTest(t, seedDir, "remote", "add", "origin", "file://"+bareDir)
|
|
runGitForBootstrapTest(t, seedDir, "push", "-u", "origin", "main")
|
|
|
|
dir := t.TempDir()
|
|
initGitRepoAt(t, dir)
|
|
remoteURL := "file://" + bareDir
|
|
runGitForBootstrapTest(t, dir, "remote", "add", "origin", remoteURL)
|
|
|
|
runBDInit(t, bd, dir, "--prefix", "pg", "--skip-hooks", "--skip-agents")
|
|
|
|
out := bdDolt(t, bd, dir, "remote", "list")
|
|
if !strings.Contains(out, "origin") || !strings.Contains(out, remoteURL) {
|
|
t.Fatalf("git origin should be registered as a Dolt remote %q; remote list:\n%s", remoteURL, out)
|
|
}
|
|
|
|
configYAML, err := os.ReadFile(filepath.Join(dir, ".beads", "config.yaml"))
|
|
if err != nil {
|
|
t.Fatalf("read config.yaml: %v", err)
|
|
}
|
|
if !strings.Contains(string(configYAML), remoteURL) {
|
|
t.Fatalf("git origin should be persisted as sync.remote; config.yaml:\n%s", configYAML)
|
|
}
|
|
|
|
bdDolt(t, bd, dir, "push")
|
|
ls := exec.Command("git", "ls-remote", remoteURL, "refs/dolt/data")
|
|
lsOut, err := ls.CombinedOutput()
|
|
if err != nil {
|
|
t.Fatalf("git ls-remote refs/dolt/data failed: %v\n%s", err, lsOut)
|
|
}
|
|
if !strings.Contains(string(lsOut), "refs/dolt/data") {
|
|
t.Fatalf("bd dolt push did not publish refs/dolt/data:\n%s", lsOut)
|
|
}
|
|
})
|
|
|
|
t.Run("no_git_origin_stays_local", func(t *testing.T) {
|
|
dir := t.TempDir()
|
|
initGitRepoAt(t, dir)
|
|
|
|
runBDInit(t, bd, dir, "--prefix", "local", "--skip-hooks", "--skip-agents")
|
|
|
|
out := bdDolt(t, bd, dir, "remote", "list")
|
|
if strings.Contains(out, "origin") {
|
|
t.Fatalf("init without git origin should not configure a Dolt remote; remote list:\n%s", out)
|
|
}
|
|
|
|
configYAML, err := os.ReadFile(filepath.Join(dir, ".beads", "config.yaml"))
|
|
if err != nil {
|
|
t.Fatalf("read config.yaml: %v", err)
|
|
}
|
|
if strings.Contains(string(configYAML), "sync.remote:") || strings.Contains(string(configYAML), "sync-remote:") {
|
|
t.Fatalf("init without git origin should not persist sync.remote; config.yaml:\n%s", configYAML)
|
|
}
|
|
})
|
|
|
|
t.Run("dolt_push_lazily_adopts_later_git_origin", func(t *testing.T) {
|
|
bareDir := filepath.Join(t.TempDir(), "later-origin.git")
|
|
runGitForBootstrapTest(t, "", "init", "--bare", "-b", "main", bareDir)
|
|
remoteURL := "file://" + bareDir
|
|
|
|
dir := t.TempDir()
|
|
initGitRepoAt(t, dir)
|
|
runGitForBootstrapTest(t, dir, "branch", "-M", "main")
|
|
runGitForBootstrapTest(t, dir, "commit", "--allow-empty", "-m", "init")
|
|
runBDInit(t, bd, dir, "--prefix", "late", "--skip-hooks", "--skip-agents")
|
|
bdCreate(t, bd, dir, "Lazy remote adoption", "--type", "task")
|
|
|
|
runGitForBootstrapTest(t, dir, "remote", "add", "origin", remoteURL)
|
|
runGitForBootstrapTest(t, dir, "push", "-u", "origin", "main")
|
|
|
|
bdDolt(t, bd, dir, "push")
|
|
|
|
out := bdDolt(t, bd, dir, "remote", "list")
|
|
if !strings.Contains(out, "origin") || !strings.Contains(out, remoteURL) {
|
|
t.Fatalf("bd dolt push should adopt later git origin %q; remote list:\n%s", remoteURL, out)
|
|
}
|
|
|
|
configYAML, err := os.ReadFile(filepath.Join(dir, ".beads", "config.yaml"))
|
|
if err != nil {
|
|
t.Fatalf("read config.yaml: %v", err)
|
|
}
|
|
if !strings.Contains(string(configYAML), remoteURL) {
|
|
t.Fatalf("bd dolt push should persist sync.remote; config.yaml:\n%s", configYAML)
|
|
}
|
|
|
|
ls := exec.Command("git", "ls-remote", remoteURL, "refs/dolt/data")
|
|
lsOut, err := ls.CombinedOutput()
|
|
if err != nil {
|
|
t.Fatalf("git ls-remote refs/dolt/data failed: %v\n%s", err, lsOut)
|
|
}
|
|
if !strings.Contains(string(lsOut), "refs/dolt/data") {
|
|
t.Fatalf("bd dolt push did not publish refs/dolt/data:\n%s", lsOut)
|
|
}
|
|
})
|
|
|
|
t.Run("dolt_push_adopts_target_origin_with_dash_c", func(t *testing.T) {
|
|
targetBare := filepath.Join(t.TempDir(), "target-origin.git")
|
|
ambientBare := filepath.Join(t.TempDir(), "ambient-origin.git")
|
|
runGitForBootstrapTest(t, "", "init", "--bare", "-b", "main", targetBare)
|
|
runGitForBootstrapTest(t, "", "init", "--bare", "-b", "main", ambientBare)
|
|
targetURL := "file://" + targetBare
|
|
ambientURL := "file://" + ambientBare
|
|
|
|
targetDir := t.TempDir()
|
|
initGitRepoAt(t, targetDir)
|
|
runGitForBootstrapTest(t, targetDir, "branch", "-M", "main")
|
|
runGitForBootstrapTest(t, targetDir, "commit", "--allow-empty", "-m", "init")
|
|
runBDInit(t, bd, targetDir, "--prefix", "dc", "--skip-hooks", "--skip-agents")
|
|
bdCreate(t, bd, targetDir, "Dash C remote adoption", "--type", "task")
|
|
runGitForBootstrapTest(t, targetDir, "remote", "add", "origin", targetURL)
|
|
runGitForBootstrapTest(t, targetDir, "push", "-u", "origin", "main")
|
|
|
|
ambientDir := t.TempDir()
|
|
initGitRepoAt(t, ambientDir)
|
|
runGitForBootstrapTest(t, ambientDir, "remote", "add", "origin", ambientURL)
|
|
|
|
cmd := exec.Command(bd, "-C", targetDir, "dolt", "push")
|
|
cmd.Dir = ambientDir
|
|
cmd.Env = bdEnv(ambientDir)
|
|
if out, err := cmd.CombinedOutput(); err != nil {
|
|
t.Fatalf("bd -C target dolt push failed: %v\n%s", err, out)
|
|
}
|
|
|
|
out := bdDolt(t, bd, targetDir, "remote", "list")
|
|
if !strings.Contains(out, "origin") || !strings.Contains(out, targetURL) {
|
|
t.Fatalf("bd -C target dolt push should adopt target origin %q; remote list:\n%s", targetURL, out)
|
|
}
|
|
if strings.Contains(out, ambientURL) {
|
|
t.Fatalf("bd -C target dolt push adopted ambient origin %q; remote list:\n%s", ambientURL, out)
|
|
}
|
|
})
|
|
|
|
t.Run("stealth_skips_git_origin_remote_synthesis", func(t *testing.T) {
|
|
bareDir := filepath.Join(t.TempDir(), "stealth.git")
|
|
runGitForBootstrapTest(t, "", "init", "--bare", "-b", "main", bareDir)
|
|
|
|
dir := t.TempDir()
|
|
initGitRepoAt(t, dir)
|
|
runGitForBootstrapTest(t, dir, "remote", "add", "origin", "file://"+bareDir)
|
|
|
|
runBDInit(t, bd, dir, "--prefix", "st", "--stealth", "--skip-agents")
|
|
|
|
out := bdDolt(t, bd, dir, "remote", "list")
|
|
if strings.Contains(out, "origin") {
|
|
t.Fatalf("stealth init should not synthesize a Dolt remote; remote list:\n%s", out)
|
|
}
|
|
|
|
configYAML, err := os.ReadFile(filepath.Join(dir, ".beads", "config.yaml"))
|
|
if err != nil {
|
|
t.Fatalf("read config.yaml: %v", err)
|
|
}
|
|
if strings.Contains(string(configYAML), "sync.remote:") || strings.Contains(string(configYAML), "sync-remote:") {
|
|
t.Fatalf("stealth init should not persist sync.remote; config.yaml:\n%s", configYAML)
|
|
}
|
|
})
|
|
|
|
t.Run("remote_bootstraps_existing_dolt_data", func(t *testing.T) {
|
|
if runtime.GOOS == "windows" {
|
|
t.Skip("uses os.Symlink to mask dolt off PATH; symlink semantics differ on Windows")
|
|
}
|
|
remoteDir := filepath.Join(t.TempDir(), "remote")
|
|
remoteURL := "file://" + remoteDir
|
|
|
|
sourceDir, _, _ := bdInit(t, bd, "--prefix", "src", "--skip-hooks", "--skip-agents")
|
|
sourceCfg, err := configfile.Load(filepath.Join(sourceDir, ".beads"))
|
|
if err != nil {
|
|
t.Fatalf("load source metadata.json: %v", err)
|
|
}
|
|
if sourceCfg.ProjectID == "" {
|
|
t.Fatal("source project ID is empty")
|
|
}
|
|
|
|
cmd := exec.Command(bd, "create", "Remote issue", "--type", "task")
|
|
cmd.Dir = sourceDir
|
|
cmd.Env = bdEnv(sourceDir)
|
|
if out, err := cmd.CombinedOutput(); err != nil {
|
|
t.Fatalf("bd create failed: %v\n%s", err, out)
|
|
}
|
|
bdDolt(t, bd, sourceDir, "commit")
|
|
bdDolt(t, bd, sourceDir, "remote", "add", "origin", remoteURL)
|
|
bdDolt(t, bd, sourceDir, "push", "--force")
|
|
|
|
cloneDir := t.TempDir()
|
|
initGitRepoAt(t, cloneDir)
|
|
gitBin, err := exec.LookPath("git")
|
|
if err != nil {
|
|
t.Fatalf("git not found: %v", err)
|
|
}
|
|
pathDir := filepath.Join(t.TempDir(), "path")
|
|
if err := os.MkdirAll(pathDir, 0o750); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.Symlink(gitBin, filepath.Join(pathDir, "git")); err != nil {
|
|
t.Fatalf("symlink git into PATH: %v", err)
|
|
}
|
|
noDoltEnv := bdEnv(cloneDir)
|
|
replacedPath := false
|
|
for i, entry := range noDoltEnv {
|
|
if strings.HasPrefix(entry, "PATH=") {
|
|
noDoltEnv[i] = "PATH=" + pathDir
|
|
replacedPath = true
|
|
break
|
|
}
|
|
}
|
|
if !replacedPath {
|
|
noDoltEnv = append(noDoltEnv, "PATH="+pathDir)
|
|
}
|
|
cmd = exec.Command(bd, "init", "--quiet", "--prefix", "clone", "--remote", remoteURL, "--skip-hooks", "--skip-agents")
|
|
cmd.Dir = cloneDir
|
|
cmd.Env = noDoltEnv
|
|
if out, err := cmd.CombinedOutput(); err != nil {
|
|
t.Fatalf("bd init --remote without dolt CLI failed: %v\n%s", err, out)
|
|
}
|
|
|
|
cloneCfg, err := configfile.Load(filepath.Join(cloneDir, ".beads"))
|
|
if err != nil {
|
|
t.Fatalf("load clone metadata.json: %v", err)
|
|
}
|
|
if cloneCfg.ProjectID != sourceCfg.ProjectID {
|
|
t.Fatalf("clone ProjectID = %q, want source ProjectID %q", cloneCfg.ProjectID, sourceCfg.ProjectID)
|
|
}
|
|
if val := readBack(t, filepath.Join(cloneDir, ".beads"), "clone", "_project_id", true); val != sourceCfg.ProjectID {
|
|
t.Fatalf("clone database _project_id = %q, want source ProjectID %q", val, sourceCfg.ProjectID)
|
|
}
|
|
|
|
cmd = exec.Command(bd, "list")
|
|
cmd.Dir = cloneDir
|
|
cmd.Env = bdEnv(cloneDir)
|
|
stdout, stderr, err := runCommandBuffers(t, cmd)
|
|
if err != nil {
|
|
t.Fatalf("bd list failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
|
|
}
|
|
if !strings.Contains(stdout.String(), "Remote issue") {
|
|
t.Fatalf("cloned database missing remote issue:\n%s", stdout.String())
|
|
}
|
|
|
|
cloneBeadsDir := filepath.Join(cloneDir, ".beads")
|
|
out := bdDolt(t, bd, cloneDir, "remote", "list")
|
|
if !strings.Contains(out, "origin") || !strings.Contains(out, remoteURL) {
|
|
t.Fatalf("expected origin remote %q in remote list:\n%s", remoteURL, out)
|
|
}
|
|
|
|
configYAML, err := os.ReadFile(filepath.Join(cloneBeadsDir, "config.yaml"))
|
|
if err != nil {
|
|
t.Fatalf("read config.yaml: %v", err)
|
|
}
|
|
if !strings.Contains(string(configYAML), remoteURL) {
|
|
t.Fatalf("config.yaml should persist --remote URL %q:\n%s", remoteURL, configYAML)
|
|
}
|
|
})
|
|
|
|
t.Run("remote_empty_initializes_fresh_and_wires_origin", func(t *testing.T) {
|
|
remoteDir := filepath.Join(t.TempDir(), "empty-remote")
|
|
if err := os.MkdirAll(remoteDir, 0o750); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
remoteURL := "file://" + remoteDir
|
|
|
|
dir := t.TempDir()
|
|
initGitRepoAt(t, dir)
|
|
runBDInit(t, bd, dir, "--prefix", "fresh", "--remote", remoteURL, "--skip-hooks", "--skip-agents")
|
|
|
|
beadsDir := filepath.Join(dir, ".beads")
|
|
if val := readBack(t, beadsDir, "fresh", "issue_prefix", false); val != "fresh" {
|
|
t.Fatalf("fresh issue_prefix = %q, want %q", val, "fresh")
|
|
}
|
|
|
|
out := bdDolt(t, bd, dir, "remote", "list")
|
|
if !strings.Contains(out, "origin") || !strings.Contains(out, remoteURL) {
|
|
t.Fatalf("expected origin remote %q in remote list:\n%s", remoteURL, out)
|
|
}
|
|
|
|
configYAML, err := os.ReadFile(filepath.Join(beadsDir, "config.yaml"))
|
|
if err != nil {
|
|
t.Fatalf("read config.yaml: %v", err)
|
|
}
|
|
if !strings.Contains(string(configYAML), remoteURL) {
|
|
t.Fatalf("config.yaml should persist --remote URL %q:\n%s", remoteURL, configYAML)
|
|
}
|
|
})
|
|
|
|
t.Run("remote_clone_failure_emits_url_and_hint", func(t *testing.T) {
|
|
// remotesapi:// is rejected by dolt as an unknown scheme almost
|
|
// instantly, so this exercises the non-empty-remote clone failure
|
|
// path without depending on TCP timeouts. Verifies (a) init exits
|
|
// non-zero rather than silently bootstrapping fresh, (b) the wrap
|
|
// from cmd/bd/init.go echoes the URL the user typed in %q form,
|
|
// and (c) the Hint: line is present.
|
|
remoteURL := "remotesapi://127.0.0.1:1/no-such-db"
|
|
dir := t.TempDir()
|
|
initGitRepoAt(t, dir)
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
|
defer cancel()
|
|
cmd := exec.CommandContext(ctx, bd, "init", "--quiet", "--prefix", "fail", "--remote", remoteURL, "--skip-hooks", "--skip-agents")
|
|
cmd.Dir = dir
|
|
cmd.Env = bdEnv(dir)
|
|
out, err := cmd.CombinedOutput()
|
|
if err == nil {
|
|
t.Fatalf("expected bd init --remote with bogus URL to fail; got success:\n%s", out)
|
|
}
|
|
wantWrap := fmt.Sprintf("failed to clone remote %q", remoteURL)
|
|
if !strings.Contains(string(out), wantWrap) {
|
|
t.Fatalf("expected init.go wrap %q in output; got:\n%s", wantWrap, out)
|
|
}
|
|
if !strings.Contains(string(out), "Hint:") {
|
|
t.Fatalf("expected error output to include a Hint: about reachability/credentials; got:\n%s", out)
|
|
}
|
|
if _, statErr := os.Stat(filepath.Join(dir, ".beads", "config.yaml")); statErr == nil {
|
|
t.Fatalf(".beads/config.yaml should not exist after a failed clone; init must not silently fall through to fresh init")
|
|
}
|
|
})
|
|
|
|
t.Run("remote_http_url_preserved_verbatim", func(t *testing.T) {
|
|
// Explicit --remote http:// URL pointed at a refused TCP port:
|
|
// asserts the URL flows through to the clone call unchanged
|
|
// (no normalization to git+http://), per GH#3339. The 30s context
|
|
// caps gRPC dial backoff in case a CI runner ever stalls.
|
|
remoteURL := "http://127.0.0.1:1/no-such-db"
|
|
dir := t.TempDir()
|
|
initGitRepoAt(t, dir)
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
|
defer cancel()
|
|
cmd := exec.CommandContext(ctx, bd, "init", "--quiet", "--prefix", "fail2", "--remote", remoteURL, "--skip-hooks", "--skip-agents")
|
|
cmd.Dir = dir
|
|
cmd.Env = bdEnv(dir)
|
|
out, err := cmd.CombinedOutput()
|
|
if err == nil {
|
|
t.Fatalf("expected bd init --remote with unreachable http URL to fail; got success:\n%s", out)
|
|
}
|
|
// Match the %q-quoted form init.go writes ("http://...") so this
|
|
// can't accidentally pass against an output that contains the
|
|
// rewritten "git+http://..." substring.
|
|
wantWrap := fmt.Sprintf("failed to clone remote %q", remoteURL)
|
|
if !strings.Contains(string(out), wantWrap) {
|
|
t.Fatalf("expected init.go wrap %q in output (proves no git+http:// rewrite); got:\n%s", wantWrap, out)
|
|
}
|
|
if strings.Contains(string(out), "git+http://127.0.0.1:1") {
|
|
t.Fatalf("explicit --remote http:// must not be normalized to git+http://; got:\n%s", out)
|
|
}
|
|
})
|
|
|
|
t.Run("database", func(t *testing.T) {
|
|
_, beadsDir, _ := bdInit(t, bd, "--database", "custom_db")
|
|
cfg, err := configfile.Load(beadsDir)
|
|
if err != nil {
|
|
t.Fatalf("failed to load metadata.json: %v", err)
|
|
}
|
|
if cfg.DoltDatabase != "custom_db" {
|
|
t.Errorf("DoltDatabase: got %q, want %q", cfg.DoltDatabase, "custom_db")
|
|
}
|
|
requireFile(t, filepath.Join(beadsDir, "embeddeddolt", "custom_db", ".dolt"))
|
|
if val := readBack(t, beadsDir, "custom_db", "issue_prefix", false); val == "" {
|
|
t.Error("issue_prefix not set in custom_db")
|
|
}
|
|
})
|
|
|
|
t.Run("database_with_prefix", func(t *testing.T) {
|
|
_, beadsDir, _ := bdInit(t, bd, "--database", "shared_db", "--prefix", "alpha")
|
|
cfg, err := configfile.Load(beadsDir)
|
|
if err != nil {
|
|
t.Fatalf("failed to load metadata.json: %v", err)
|
|
}
|
|
if cfg.DoltDatabase != "shared_db" {
|
|
t.Errorf("DoltDatabase: got %q, want %q", cfg.DoltDatabase, "shared_db")
|
|
}
|
|
if val := readBack(t, beadsDir, "shared_db", "issue_prefix", false); val != "alpha" {
|
|
t.Errorf("issue_prefix: got %q, want %q", val, "alpha")
|
|
}
|
|
})
|
|
|
|
t.Run("skip_hooks", func(t *testing.T) {
|
|
_, beadsDir, _ := bdInit(t, bd, "--prefix", "sh", "--skip-hooks")
|
|
requireNoFile(t, filepath.Join(beadsDir, "hooks"))
|
|
})
|
|
|
|
t.Run("stealth", func(t *testing.T) {
|
|
dir, _, _ := bdInit(t, bd, "--prefix", "st", "--stealth")
|
|
requireNoFile(t, filepath.Join(dir, "AGENTS.md"))
|
|
})
|
|
|
|
t.Run("force_reinit", func(t *testing.T) {
|
|
doltBin, err := exec.LookPath("dolt")
|
|
if err != nil {
|
|
t.Skip("dolt CLI not on PATH")
|
|
}
|
|
|
|
dir, beadsDir, _ := bdInit(t, bd, "--prefix", "fi")
|
|
dbDir := filepath.Join(beadsDir, "embeddeddolt", "fi")
|
|
|
|
statusOut := runDolt(t, doltBin, dbDir, "status")
|
|
if !strings.Contains(statusOut, "nothing to commit") {
|
|
t.Errorf("after first init: expected clean working set, got:\n%s", statusOut)
|
|
}
|
|
logOut1 := runDolt(t, doltBin, dbDir, "log", "--oneline")
|
|
for _, want := range []string{"schema: apply migrations", "bd init"} {
|
|
if !strings.Contains(logOut1, want) {
|
|
t.Errorf("after first init: missing %q commit:\n%s", want, logOut1)
|
|
}
|
|
}
|
|
headAfterFirst := doltHeadHash(t, doltBin, dbDir)
|
|
t.Logf("HEAD after first init: %s", headAfterFirst)
|
|
t.Logf("log after first init:\n%s", logOut1)
|
|
|
|
// Second init with --force
|
|
runBDInit(t, bd, dir, "--prefix", "fi", "--force")
|
|
|
|
statusOut = runDolt(t, doltBin, dbDir, "status")
|
|
if !strings.Contains(statusOut, "nothing to commit") {
|
|
t.Errorf("after force reinit: expected clean working set, got:\n%s", statusOut)
|
|
}
|
|
logOut2 := runDolt(t, doltBin, dbDir, "log", "--oneline")
|
|
t.Logf("HEAD after force reinit: %s", doltHeadHash(t, doltBin, dbDir))
|
|
t.Logf("log after force reinit:\n%s", logOut2)
|
|
|
|
for _, want := range []string{"schema: apply migrations", "bd init"} {
|
|
if !strings.Contains(logOut2, want) {
|
|
t.Errorf("after force reinit: missing %q commit:\n%s", want, logOut2)
|
|
}
|
|
}
|
|
|
|
commitCount1 := strings.Count(strings.TrimSpace(logOut1), "\n") + 1
|
|
commitCount2 := strings.Count(strings.TrimSpace(logOut2), "\n") + 1
|
|
if commitCount2 < commitCount1 {
|
|
t.Errorf("commit count decreased after force reinit: before=%d after=%d", commitCount1, commitCount2)
|
|
}
|
|
if val := readBack(t, beadsDir, "fi", "issue_prefix", false); val != "fi" {
|
|
t.Errorf("issue_prefix after --force: got %q, want %q", val, "fi")
|
|
}
|
|
})
|
|
|
|
t.Run("setup_exclude", func(t *testing.T) {
|
|
dir, _, _ := bdInit(t, bd, "--prefix", "se", "--setup-exclude")
|
|
content, err := os.ReadFile(filepath.Join(dir, ".git", "info", "exclude"))
|
|
if err != nil {
|
|
t.Fatalf("failed to read .git/info/exclude: %v", err)
|
|
}
|
|
if !strings.Contains(string(content), ".beads") {
|
|
t.Error("--setup-exclude should add .beads to .git/info/exclude")
|
|
}
|
|
})
|
|
|
|
t.Run("auto_commit_bypasses_hooks", func(t *testing.T) {
|
|
dir := t.TempDir()
|
|
initGitRepoAt(t, dir)
|
|
preCommitPath := filepath.Join(dir, ".git", "hooks", "pre-commit")
|
|
preCommit := "#!/bin/sh\necho hook-fired >> .hook-ran\nexit 1\n"
|
|
if err := os.WriteFile(preCommitPath, []byte(preCommit), 0755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
unsetHooksPath := exec.Command("git", "config", "--unset", "core.hooksPath")
|
|
unsetHooksPath.Dir = dir
|
|
if out, err := unsetHooksPath.CombinedOutput(); err != nil {
|
|
t.Fatalf("git config --unset core.hooksPath failed: %v\n%s", err, out)
|
|
}
|
|
|
|
runBDInit(t, bd, dir, "--prefix", "hook")
|
|
|
|
if _, err := os.Stat(filepath.Join(dir, ".hook-ran")); err == nil {
|
|
t.Fatal("expected init auto-commit to bypass git hooks")
|
|
}
|
|
logCmd := exec.Command("git", "log", "--oneline", "-n", "1")
|
|
logCmd.Dir = dir
|
|
stdout, stderr, err := runCommandBuffers(t, logCmd)
|
|
if err != nil {
|
|
t.Fatalf("git log failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
|
|
}
|
|
if !strings.Contains(stdout.String(), "bd init: initialize beads issue tracking") {
|
|
t.Fatalf("expected init commit to succeed, got log: %s", stdout.String())
|
|
}
|
|
})
|
|
|
|
t.Run("from_jsonl", func(t *testing.T) {
|
|
dir := t.TempDir()
|
|
initGitRepoAt(t, dir)
|
|
beadsDir := filepath.Join(dir, ".beads")
|
|
if err := os.MkdirAll(beadsDir, 0750); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
issues := []types.Issue{
|
|
{ID: "jl-abc123", Title: "One", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, CreatedAt: time.Now(), UpdatedAt: time.Now()},
|
|
{ID: "jl-def456", Title: "Two", Status: types.StatusOpen, Priority: 1, IssueType: types.TypeBug, CreatedAt: time.Now(), UpdatedAt: time.Now()},
|
|
}
|
|
var lines []string
|
|
for _, issue := range issues {
|
|
b, _ := json.Marshal(issue)
|
|
lines = append(lines, string(b))
|
|
}
|
|
if err := os.WriteFile(filepath.Join(beadsDir, "issues.jsonl"), []byte(strings.Join(lines, "\n")+"\n"), 0644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
preCommitPath := filepath.Join(dir, ".git", "hooks", "pre-commit")
|
|
preCommit := "#!/bin/sh\necho hook-fired >> .hook-ran\nexit 1\n"
|
|
if err := os.WriteFile(preCommitPath, []byte(preCommit), 0755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
unsetHooksPath := exec.Command("git", "config", "--unset", "core.hooksPath")
|
|
unsetHooksPath.Dir = dir
|
|
if out, err := unsetHooksPath.CombinedOutput(); err != nil {
|
|
t.Fatalf("git config --unset core.hooksPath failed: %v\n%s", err, out)
|
|
}
|
|
|
|
cmd := exec.Command(bd, "init", "--prefix", "jl", "--from-jsonl", "--quiet")
|
|
cmd.Dir = dir
|
|
cmd.Env = bdEnv(dir)
|
|
stdout, stderr, err := runCommandBuffers(t, cmd)
|
|
if err != nil {
|
|
t.Fatalf("--from-jsonl should succeed now that CreateIssuesWithFullOptions is implemented: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
|
|
}
|
|
if _, err := os.Stat(filepath.Join(dir, ".hook-ran")); err == nil {
|
|
t.Fatal("expected --from-jsonl auto-commit to bypass git hooks")
|
|
}
|
|
logCmd := exec.Command("git", "log", "--oneline", "-n", "1")
|
|
logCmd.Dir = dir
|
|
stdout.Reset()
|
|
stderr.Reset()
|
|
logCmd.Stdout = &stdout
|
|
logCmd.Stderr = &stderr
|
|
if err := logCmd.Run(); err != nil {
|
|
t.Fatalf("git log failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
|
|
}
|
|
if !strings.Contains(stdout.String(), "bd init: initialize beads issue tracking") {
|
|
t.Fatalf("expected init commit to succeed, got log: %s", stdout.String())
|
|
}
|
|
})
|
|
|
|
t.Run("from_jsonl_uses_import_path", func(t *testing.T) {
|
|
dir := t.TempDir()
|
|
initGitRepoAt(t, dir)
|
|
beadsDir := filepath.Join(dir, ".beads")
|
|
if err := os.MkdirAll(beadsDir, 0750); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(filepath.Join(beadsDir, "config.yaml"), []byte("import:\n path: beads.jsonl\n"), 0600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
issue := types.Issue{
|
|
ID: "jlcfg-abc123",
|
|
Title: "Configured JSONL",
|
|
Status: types.StatusOpen,
|
|
Priority: 2,
|
|
IssueType: types.TypeTask,
|
|
CreatedAt: time.Now(),
|
|
UpdatedAt: time.Now(),
|
|
}
|
|
line, _ := json.Marshal(issue)
|
|
if err := os.WriteFile(filepath.Join(beadsDir, "beads.jsonl"), append(line, '\n'), 0644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
cmd := exec.Command(bd, "init", "--prefix", "jlcfg", "--from-jsonl", "--quiet")
|
|
cmd.Dir = dir
|
|
cmd.Env = bdEnv(dir)
|
|
stdout, stderr, err := runCommandBuffers(t, cmd)
|
|
if err != nil {
|
|
t.Fatalf("--from-jsonl with import.path failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
|
|
}
|
|
|
|
showCmd := exec.Command(bd, "show", "jlcfg-abc123", "--json")
|
|
showCmd.Dir = dir
|
|
showCmd.Env = bdEnv(dir)
|
|
if out, err := showCmd.CombinedOutput(); err != nil {
|
|
t.Fatalf("imported issue not found: %v\n%s", err, out)
|
|
}
|
|
})
|
|
|
|
t.Run("backend_dolt", func(t *testing.T) {
|
|
_, beadsDir, _ := bdInit(t, bd, "--prefix", "bdolt", "--backend", "dolt")
|
|
embeddedDir := filepath.Join(beadsDir, "embeddeddolt")
|
|
requireFile(t, embeddedDir)
|
|
requireFile(t, filepath.Join(embeddedDir, "bdolt", ".dolt"))
|
|
})
|
|
|
|
t.Run("rejected_backends", func(t *testing.T) {
|
|
for _, tc := range []struct {
|
|
backend, wantErr string
|
|
}{
|
|
{"sqlite", "DEPRECATED"},
|
|
{"postgres", "unknown backend"},
|
|
} {
|
|
out := bdInitFail(t, bd, "--backend", tc.backend)
|
|
if !strings.Contains(out, tc.wantErr) {
|
|
t.Errorf("--backend %s: expected %q, got: %s", tc.backend, tc.wantErr, out)
|
|
}
|
|
}
|
|
})
|
|
|
|
t.Run("server_flags_ignored", func(t *testing.T) {
|
|
_, beadsDir, _ := bdInit(t, bd, "--prefix", "sv",
|
|
"--server-host", "10.0.0.1", "--server-port", "4444", "--server-user", "alice")
|
|
cfg, err := configfile.Load(beadsDir)
|
|
if err != nil {
|
|
t.Fatalf("failed to load metadata.json: %v", err)
|
|
}
|
|
if cfg.DoltServerHost != "10.0.0.1" {
|
|
t.Errorf("DoltServerHost: got %q, want %q", cfg.DoltServerHost, "10.0.0.1")
|
|
}
|
|
if cfg.DoltServerPort != 4444 {
|
|
t.Errorf("DoltServerPort: got %d, want %d", cfg.DoltServerPort, 4444)
|
|
}
|
|
if cfg.DoltServerUser != "alice" {
|
|
t.Errorf("DoltServerUser: got %q, want %q", cfg.DoltServerUser, "alice")
|
|
}
|
|
})
|
|
|
|
t.Run("metadata_written", func(t *testing.T) {
|
|
_, beadsDir, _ := bdInit(t, bd, "--prefix", "meta")
|
|
// bd_version is in local_metadata (dolt-ignored), not metadata
|
|
func() {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
defer cancel()
|
|
store, err := embeddeddolt.Open(ctx, beadsDir, "meta", "main")
|
|
if err != nil {
|
|
t.Fatalf("failed to open store for bd_version check: %v", err)
|
|
}
|
|
defer store.Close()
|
|
if val, err := store.GetLocalMetadata(ctx, "bd_version"); err != nil || val == "" {
|
|
t.Error("bd_version local metadata not set")
|
|
}
|
|
}()
|
|
importTime := readBack(t, beadsDir, "meta", "last_import_time", true)
|
|
if importTime == "" {
|
|
t.Error("last_import_time metadata not set")
|
|
}
|
|
if _, err := time.Parse(time.RFC3339, importTime); err != nil {
|
|
t.Errorf("last_import_time not valid RFC3339: %q", importTime)
|
|
}
|
|
})
|
|
|
|
t.Run("metadata_json", func(t *testing.T) {
|
|
_, beadsDir, _ := bdInit(t, bd, "--prefix", "mj")
|
|
cfg, err := configfile.Load(beadsDir)
|
|
if err != nil {
|
|
t.Fatalf("failed to load metadata.json: %v", err)
|
|
}
|
|
if cfg.Backend != configfile.BackendDolt {
|
|
t.Errorf("Backend: got %q, want %q", cfg.Backend, configfile.BackendDolt)
|
|
}
|
|
if cfg.ProjectID == "" {
|
|
t.Error("ProjectID should be set")
|
|
}
|
|
})
|
|
|
|
t.Run("files_created", func(t *testing.T) {
|
|
dir, beadsDir, _ := bdInit(t, bd, "--prefix", "fc", "--skip-hooks")
|
|
requireFile(t, filepath.Join(beadsDir, "config.yaml"))
|
|
requireFile(t, filepath.Join(beadsDir, "interactions.jsonl"))
|
|
requireFile(t, filepath.Join(dir, "AGENTS.md"))
|
|
|
|
content, err := os.ReadFile(filepath.Join(beadsDir, ".gitignore"))
|
|
if err != nil {
|
|
t.Fatalf("failed to read .beads/.gitignore: %v", err)
|
|
}
|
|
for _, pattern := range []string{"*.db", "dolt/", "bd.sock"} {
|
|
if !strings.Contains(string(content), pattern) {
|
|
t.Errorf(".gitignore missing pattern: %s", pattern)
|
|
}
|
|
}
|
|
})
|
|
|
|
t.Run("agents_template", func(t *testing.T) {
|
|
dir := t.TempDir()
|
|
initGitRepoAt(t, dir)
|
|
templatePath := filepath.Join(dir, "custom-agents.md")
|
|
if err := os.WriteFile(templatePath, []byte("# Custom Agents\nThis is custom.\n"), 0644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
runBDInit(t, bd, dir, "--prefix", "at", "--agents-template", templatePath, "--skip-hooks")
|
|
content, err := os.ReadFile(filepath.Join(dir, "AGENTS.md"))
|
|
if err != nil {
|
|
t.Fatalf("failed to read AGENTS.md: %v", err)
|
|
}
|
|
if !strings.Contains(string(content), "Custom Agents") {
|
|
t.Error("AGENTS.md should contain custom template content")
|
|
}
|
|
})
|
|
|
|
t.Run("no_git_repo", func(t *testing.T) {
|
|
dir := t.TempDir()
|
|
// Don't init git — bd init should create one
|
|
args := []string{"init", "--prefix", "ng", "--quiet"}
|
|
cmd := exec.Command(bd, args...)
|
|
cmd.Dir = dir
|
|
cmd.Env = bdEnv(dir)
|
|
if out, err := cmd.CombinedOutput(); err != nil {
|
|
t.Fatalf("bd init (no git) failed: %v\n%s", err, out)
|
|
}
|
|
requireFile(t, filepath.Join(dir, ".git"))
|
|
})
|
|
|
|
t.Run("database_name_validation", func(t *testing.T) {
|
|
out := bdInitFail(t, bd, "--database", "has spaces!")
|
|
if !strings.Contains(out, "invalid database name") {
|
|
t.Errorf("expected 'invalid database name' error, got: %s", out)
|
|
}
|
|
})
|
|
|
|
t.Run("prefix_auto_detect_from_dirname", func(t *testing.T) {
|
|
parent := t.TempDir()
|
|
dir := filepath.Join(parent, "myproject")
|
|
if err := os.MkdirAll(dir, 0750); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
initGitRepoAt(t, dir)
|
|
runBDInit(t, bd, dir)
|
|
if val := readBack(t, filepath.Join(dir, ".beads"), "myproject", "issue_prefix", false); val != "myproject" {
|
|
t.Errorf("auto-detected issue_prefix: got %q, want %q", val, "myproject")
|
|
}
|
|
})
|
|
|
|
t.Run("auto_detect_dotted_dirname", func(t *testing.T) {
|
|
// bd init in a directory named like "MyPkg.jl" (common in Julia repos)
|
|
// must sanitize the dot when auto-detecting the prefix: metadata.json
|
|
// DoltDatabase must match the actual Dolt database name so that reopens
|
|
// succeed and bd list works immediately after init.
|
|
parent := t.TempDir()
|
|
dir := filepath.Join(parent, "MyPkg.jl")
|
|
if err := os.MkdirAll(dir, 0750); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
initGitRepoAt(t, dir)
|
|
runBDInit(t, bd, dir)
|
|
|
|
beadsDir := filepath.Join(dir, ".beads")
|
|
cfg, err := configfile.Load(beadsDir)
|
|
if err != nil {
|
|
t.Fatalf("failed to load metadata.json: %v", err)
|
|
}
|
|
const want = "MyPkg_jl"
|
|
if cfg.DoltDatabase != want {
|
|
t.Errorf("DoltDatabase: got %q, want %q (dot must be sanitized)", cfg.DoltDatabase, want)
|
|
}
|
|
if val := readBack(t, beadsDir, want, "issue_prefix", false); val != want {
|
|
t.Errorf("issue_prefix: got %q, want %q", val, want)
|
|
}
|
|
|
|
// Verify bd list succeeds — confirms the database name in metadata.json
|
|
// matches the actual Dolt database created during init.
|
|
listCmd := exec.Command(bd, "list", "--json")
|
|
listCmd.Dir = dir
|
|
listCmd.Env = bdEnv(dir)
|
|
if out, err := listCmd.CombinedOutput(); err != nil {
|
|
t.Fatalf("bd list failed after init in dotted dirname: %v\n%s", err, out)
|
|
}
|
|
})
|
|
|
|
t.Run("prefix_numeric_sanitized", func(t *testing.T) {
|
|
parent := t.TempDir()
|
|
dir := filepath.Join(parent, "001")
|
|
if err := os.MkdirAll(dir, 0750); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
initGitRepoAt(t, dir)
|
|
runBDInit(t, bd, dir)
|
|
if val := readBack(t, filepath.Join(dir, ".beads"), "bd_001", "issue_prefix", false); val != "bd_001" {
|
|
t.Errorf("sanitized issue_prefix: got %q, want %q", val, "bd_001")
|
|
}
|
|
})
|
|
|
|
t.Run("invalid_dirname_errors_early", func(t *testing.T) {
|
|
// A directory name like "my project" (space) survives hyphen/dot sanitization
|
|
// and produces an invalid Dolt database name. The init command should exit
|
|
// non-zero with a human-readable error rather than a cryptic storage failure.
|
|
parent := t.TempDir()
|
|
dir := filepath.Join(parent, "my project")
|
|
if err := os.MkdirAll(dir, 0750); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
initGitRepoAt(t, dir)
|
|
cmd := exec.Command(bd, "init", "--quiet")
|
|
cmd.Dir = dir
|
|
cmd.Env = bdEnv(dir)
|
|
out, err := cmd.CombinedOutput()
|
|
if err == nil {
|
|
t.Fatal("bd init should have failed for directory with invalid name")
|
|
}
|
|
outStr := string(out)
|
|
if !strings.Contains(outStr, "invalid database name") && !strings.Contains(outStr, "produces an invalid") {
|
|
t.Errorf("expected actionable error message, got: %s", outStr)
|
|
}
|
|
})
|
|
|
|
t.Run("prefix_dot_sanitized", func(t *testing.T) {
|
|
// A Julia package repo like GPUPolynomials.jl passes --prefix GPUPolynomials.jl.
|
|
// The dot must be replaced with underscore in both the Dolt database name and
|
|
// metadata.json DoltDatabase, otherwise reopens fail with a name mismatch.
|
|
_, beadsDir, _ := bdInit(t, bd, "--prefix", "GPUPolynomials.jl")
|
|
cfg, err := configfile.Load(beadsDir)
|
|
if err != nil {
|
|
t.Fatalf("failed to load metadata.json: %v", err)
|
|
}
|
|
const want = "GPUPolynomials_jl"
|
|
if cfg.DoltDatabase != want {
|
|
t.Errorf("DoltDatabase: got %q, want %q", cfg.DoltDatabase, want)
|
|
}
|
|
if val := readBack(t, beadsDir, want, "issue_prefix", false); val != "GPUPolynomials_jl" {
|
|
t.Errorf("issue_prefix: got %q, want %q", val, "GPUPolynomials_jl")
|
|
}
|
|
})
|
|
|
|
t.Run("config_dot_prefix_sanitized", func(t *testing.T) {
|
|
dir := t.TempDir()
|
|
initGitRepoAt(t, dir)
|
|
beadsDir := filepath.Join(dir, ".beads")
|
|
if err := os.MkdirAll(beadsDir, 0o750); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(filepath.Join(beadsDir, "config.yaml"), []byte("issue-prefix: GPUPolynomials.jl\n"), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
runBDInit(t, bd, dir)
|
|
|
|
cfg, err := configfile.Load(beadsDir)
|
|
if err != nil {
|
|
t.Fatalf("failed to load metadata.json: %v", err)
|
|
}
|
|
const want = "GPUPolynomials_jl"
|
|
if cfg.DoltDatabase != want {
|
|
t.Errorf("DoltDatabase: got %q, want %q", cfg.DoltDatabase, want)
|
|
}
|
|
if val := readBack(t, beadsDir, want, "issue_prefix", false); val != want {
|
|
t.Errorf("issue_prefix: got %q, want %q", val, want)
|
|
}
|
|
})
|
|
}
|
|
|
|
// TestEmbeddedInitConcurrent verifies the exclusive flock prevents concurrent
|
|
// writers. Exactly one process should succeed; the rest get the lock error.
|
|
func TestEmbeddedInitConcurrent(t *testing.T) {
|
|
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
|
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt init tests")
|
|
}
|
|
t.Parallel()
|
|
|
|
bd := buildEmbeddedBD(t)
|
|
dir := t.TempDir()
|
|
initGitRepoAt(t, dir)
|
|
|
|
const N = 10
|
|
env := bdEnv(dir)
|
|
|
|
type result struct {
|
|
idx int
|
|
out string
|
|
err error
|
|
timedOut bool
|
|
}
|
|
results := make([]result, N)
|
|
var wg sync.WaitGroup
|
|
wg.Add(N)
|
|
for i := 0; i < N; i++ {
|
|
go func(idx int) {
|
|
defer wg.Done()
|
|
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
|
|
defer cancel()
|
|
|
|
cmd := exec.CommandContext(ctx, bd, "init", "--prefix", "conc", "--force", "--quiet", "--skip-agents")
|
|
cmd.Dir = dir
|
|
cmd.Env = env
|
|
out, err := cmd.CombinedOutput()
|
|
results[idx] = result{idx: idx, out: string(out), err: err, timedOut: ctx.Err() == context.DeadlineExceeded}
|
|
}(i)
|
|
}
|
|
wg.Wait()
|
|
|
|
successes, lockErrors := 0, 0
|
|
for _, r := range results {
|
|
if r.timedOut {
|
|
t.Errorf("process %d timed out after 45s running concurrent bd init: %v\n%s", r.idx, r.err, r.out)
|
|
continue
|
|
}
|
|
if strings.Contains(r.out, "panic") {
|
|
t.Errorf("process %d panicked:\n%s", r.idx, r.out)
|
|
}
|
|
if r.err == nil {
|
|
successes++
|
|
} else if isEmbeddedLockOutput(r.out) {
|
|
lockErrors++
|
|
} else {
|
|
t.Errorf("process %d failed with unexpected error: %v\n%s", r.idx, r.err, r.out)
|
|
}
|
|
}
|
|
if successes < 1 {
|
|
t.Errorf("expected at least 1 success, got %d", successes)
|
|
}
|
|
if successes+lockErrors != N {
|
|
t.Errorf("expected successes (%d) + lock errors (%d) = %d, got %d", successes, lockErrors, N, successes+lockErrors)
|
|
}
|
|
t.Logf("%d/%d succeeded, %d/%d got lock error", successes, N, lockErrors, N)
|
|
|
|
beadsDir := filepath.Join(dir, ".beads")
|
|
embeddedDir := filepath.Join(beadsDir, "embeddeddolt")
|
|
requireFile(t, embeddedDir)
|
|
requireFile(t, filepath.Join(embeddedDir, "conc", ".dolt"))
|
|
|
|
if val := readBack(t, beadsDir, "conc", "issue_prefix", false); val != "conc" {
|
|
t.Errorf("issue_prefix: got %q, want %q", val, "conc")
|
|
}
|
|
|
|
cfg, err := configfile.Load(beadsDir)
|
|
if err != nil {
|
|
t.Fatalf("failed to load metadata.json: %v", err)
|
|
}
|
|
if cfg.Backend != configfile.BackendDolt {
|
|
t.Errorf("Backend: got %q, want %q", cfg.Backend, configfile.BackendDolt)
|
|
}
|
|
|
|
if doltBin, err := exec.LookPath("dolt"); err == nil {
|
|
dbDir := filepath.Join(embeddedDir, "conc")
|
|
statusOut := runDolt(t, doltBin, dbDir, "status")
|
|
if !strings.Contains(statusOut, "nothing to commit") {
|
|
t.Errorf("expected clean working set after concurrent init, got:\n%s", statusOut)
|
|
}
|
|
logOut := runDolt(t, doltBin, dbDir, "log", "--oneline")
|
|
if !strings.Contains(logOut, "schema: apply migrations") {
|
|
t.Errorf("missing 'schema: apply migrations' commit:\n%s", logOut)
|
|
}
|
|
}
|
|
}
|