* test(cmd/bd): reset cobra flags between in-process runs; keep them out of parallel tests
runBDInProcess and runBDInProcessAllowError execute the package-level
rootCmd tree again and again in one process, and cobra never resets a
flag between Execute calls: a value one invocation parsed (create's
--title, --labels, list's --status, ...) and its Changed bit stayed on the
FlagSet, so the next invocation saw it, and a slice flag that had been
set appended to the stale value instead of replacing it. With a Dolt test
server (the only setup in which these tests run) that failed about 20
TestCLI_* tests depending on suite order.
TestMain now snapshots every flag of the tree (snapshotCommandFlags,
after all init()s registered them, before any test runs) and both runners
put the tree back before and after each run (resetCommandFlags): the
pointee of each flag.Value is restored (for pflag's scalar types that is
the bound variable; for slice types it also clears the internal "changed"
bit, so the next Set replaces), slice contents via SliceValue.Replace,
and Changed=false. TestResetCommandFlagsRestoresEveryFlag sets every flag
of the real tree and checks the reset. The ad-hoc --title reset in
TestCLI_CreateRejectsEmptyTitle_ProxiedServerMode is no longer needed.
Seven TestCLI_Comment* tests called t.Parallel() around the runners.
inProcessMutex serializes the runners only against each other, so their
chdir, stdio swap, env and config re-initialization raced every other
parallel test (data races on config globals; TestCobraParallelPolicyGuard
failing to read its own source files after a concurrent chdir). They run
serially now, and the guard treats the two runners like rootCmd.Execute.
Also two stale TestCLI_Create* cases: DryRunWithRigPrefix exercised a
create --prefix flag that no longer exists, and the flag-like-title cases
passed "--help" or "--foo-bar" where cobra parses them as flags; they now
pass the title after "--", the only way it reaches create's own guard.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(cmd/bd): fix the ADO round-trip and bulk-delete tests that rotted unseen
Both need the integration tag and a Dolt test server, which no CI lane
gave cmd/bd (BEADS_TEST_SKIP=dolt everywhere), so they failed unnoticed:
- TestADORoundTrip* stored ado.pat in the database. ado.pat is a secret
read only from config.yaml or AZURE_DEVOPS_PAT (config.IsYamlOnlyKey),
so the tracker found no PAT. The fixture sets AZURE_DEVOPS_PAT.
- TestBulkDeleteNoResurrection expected GetIssue to return (nil, nil) for
a deleted issue; the Dolt store reports storage.ErrNotFound.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(cmd/bd): fix parity, completion and notion tests that only fail with a Dolt server
These are Dolt-gated (integration tag + test server), so no CI lane ran
them and they rotted:
- TestParityCreate*/TestParityReopenErrorExits1Silently: bd create
auto-routes via routing.DetectUserRole("."), which warns "beads.role
not configured (GH#2950)" on stderr when the working directory's git
config has no beads.role. The suite pins the configured case, so the
parity env now sets beads.role=maintainer in a test-owned global git
config ($XDG_CONFIG_HOME/git/config; the role lookup scrubs every
GIT_CONFIG_* variable, so those cannot be used).
- TestIssueIDCompletion: issueIDCompletion resolves a database path
before looking at the open store and returns nothing when there is
none; the test now sets dbPath to its store's path.
- TestIssueIDCompletion_UsesWorktreeFallbackWhenStoreNil and
TestGetNotionConfigReadsDBPathWhenStoreUnset: the code under test
reopens the store from metadata.json, which names a database but not
the per-test branch of the shared database that newTestStore uses, so
the reopened store saw none of the test's rows. They now use their own
database (newTestStoreIsolatedDB).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(cmd/bd): fix stale doctor/e2e/autocommit/readonly Dolt-gated tests
These need the integration tag and a Dolt test server, which no CI lane
gave cmd/bd, so they rotted unseen:
- TestE2E_DoctorFixMetadataRoundtrip, TestE2E_MigrateDoltMetadata,
TestDoctorCheckHealthReportsVersionMismatchOnRepoLocalPort: bd init now
defaults to embedded mode, where `bd sql` and `bd dolt start` are
refused. Init with --server on a repo-local server of their own
(repoLocalServerEnv: the suite's shared-server port vars cleared, server
stopped at cleanup) and start it explicitly, since BEADS_TEST_MODE=1 never
auto-starts one. MigrateDoltMetadata's DELETE also needed `key` quoted.
- TestDoctor{Conventions,Pollution}MaxRows_EnvOnly_Exits2: bdRunRaw drops
every BEADS_* variable, so the subprocess hit dolt.New's test-database
firewall (exit 1) before the row cap; pass BEADS_TEST_SERVER=1.
- TestDoltAutoCommit_On_WritesAdvanceHead: the embedded engine keeps its
data under .beads/embeddeddolt, not .beads/dolt; findDoltRepoDir looks
in both.
- TestValidateCheck_AllClean: bd doctor validate runs five checks since
the cross-table duplicates check was added.
- TestConfigValidateReadOnlyIsHermetic: readonly commands take a shared
workspace gate, whose lock file (.beads/dolt.gate.lock) workspacegate
creates on first use by design; compare the .beads tree without gate
lock files.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(cmd/bd): undo each in-process execution's env and storage-mode leaks
Every in-process run of the bd command tree (runBDInProcess and the many
tests that call rootCmd.Execute directly) leaves process state behind:
PersistentPreRun exports the selected workspace as BEADS_DIR, loads its
.beads/.env, and records the workspace's mode in serverMode /
proxiedServerMode. With a Dolt test server, later tests in the same shard
then resolved a deleted fixture ("no active beads workspace found",
"migration sidecar is missing"), ran subprocess bd against the wrong
workspace ("recorded as proxied-server in .beads/metadata.json"), or took
the proxied path in RunE-level tests ("proxied-server UOW provider not
initialized", a nil-UOW panic in reopenProxiedResolve that killed a shard).
TestMain now registers a cobra initializer/finalizer pair
(installExecuteIsolation) that snapshots the environment and the two mode
globals when an execution starts and restores them when it ends; the
runners' restoreEnvSnapshot shares the helper. TestDoltConfigEnvironmentOverrides
used os.Setenv + defer os.Unsetenv, which deleted the suite's
BEADS_DOLT_SERVER_PORT (the test server's port) for every later test; it
uses t.Setenv now.
Full integration-tagged cmd/bd suite against a hermetic dolt (16 shards):
18 order-dependent failures and the shard panic gone; the 27 remaining
failures all fail alone too.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(init): keep --quiet quiet through the Claude/Codex/Cursor auto-setup
`bd init --quiet` ("Suppress output") still printed the project
integration installers' progress to stdout ("Installing Claude hooks for
this project...", "Claude Code integration installed", ...): the
installers write to os.Stdout unconditionally. Point stdout at the null
device around them while quiet; their failures keep going to stderr as
before. Found by TestInitCommand's quiet case, which asserts no output and
had not run in CI (Dolt-gated).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(init): bring the Dolt-gated init tests up to the current init contract
These tests need a Dolt test server, so no CI lane ran them and they
drifted from the product:
- Embedded is init's default mode, so the server-mode assertions
(.beads/dolt, opening the database on the test server, dolt_mode
"server" in metadata.json) now pass --server (TestInitCommand,
TestInitAlreadyInitialized, TestInitRedirect, TestInitBEADS_DIR,
TestInitDoltMetadata, TestInitDoltMetadataNoGit, TestInitDatabaseFlag's
metadata subtests). The in-process ones reset rootCmd's flags around
themselves so --server cannot leak into later in-process inits.
- Each server init gets its own --database: the suite shares one test
server, and a "test" database another test created belongs to another
project (init refuses: PROJECT IDENTITY MISMATCH).
- The marker tests seed a current-era version witness: the legacy-upgrade
guard refuses a non-empty .beads/dolt without one.
- The redirect test provisions the canonical target with config.yaml: bd
ignores a redirect to a directory with no project files (#4692).
- Shared-server inits get a free port of their own
(sharedServerTestEnv): the inherited BEADS_DOLT_SERVER_PORT is the
suite's test server, which a shared-server start refuses as another
project's, and the default shared port is 3308, a developer's live
server.
- --shared-server's config.yaml is now nested YAML (dolt: shared-server:
true); parse it instead of matching the old flat line.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(cmd/bd): run the Dolt-gated tests that skipped on a bare dolt.New
setupTestDB (config, kv and Linear round-trip tests), setupGatedTestDB
(mol ready --gated) and the rename-prefix and bd sql tests opened stores
with dolt.New(&dolt.Config{Path: ...}): no server port, no
CreateIfMissing, so against a running test server they got "database ...
not found" and skipped as "Dolt server not available". They now use the
suite's newTestStore helpers (skip only when no test server runs), and
what that exposed is fixed test-side:
- TestCustomStatusConfig: custom_statuses is read back ORDER BY name;
look statuses up by name / expect name order.
- TestLinearRoundTripCoreFields, TestLinearPullMilestonesCreatesEpicHierarchy:
linear.api_key is a yaml-only secret (LINEAR_API_KEY), push now needs an
explicit linear.state_map, and batch push uses TeamLabels and
issueBatchCreate, which the mock server now answers.
- TestSqlCommand: bd sql refuses in the default embedded mode; set
serverMode for the server-backed store, and stop discarding RunE errors.
- TestE2E_AutoStartedRepoLocalServerPersistsAcrossCommands skipped on
this process's embedded mode although every bd it runs is a subprocess
on a --server workspace; gate on the dolt binary instead and stop the
auto-started server at cleanup.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(cmd/bd): no fixed "unused" port, no swallowed JSON, no leaked front-door server
Three more things the Dolt-backed cmd/bd run exposed:
- TestTestServerConnection, TestSharedServerCfgNilHonorsSharedServer and
the two TestLegacyGuard* e2e tests pointed bd at 127.0.0.1:59999 as a
port nothing listens on. Any process on the host may hold it; a
listener that accepts and resets turns the expected "connection
refused" / "Dolt server unreachable" into another error. They take a
just-freed port from closedLoopbackPort (testutil.FindFreePort) now.
- TestDoltSetConfigJSONOutput and TestDoltSetConfigWithUpdateConfig
created .beads 0755, so bd's permissions warning landed in the JSON
under test and the tests skipped ("output not pure JSON") every run.
The fixture uses 0700, and non-JSON output fails instead of skipping.
- TestMigrateDoltModeFrontDoor's closing show/list auto-start a
repo-local server after the reverse migration; nothing stopped it, so
the suite's leak check failed (when the opt-in
BEADS_TEST_MIGRATION_FRONTDOOR suite runs). It stops it at cleanup.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* ci(bazel): advisory cmd/bd Dolt-server tier (bazel-cmd-dolt)
No CI lane ran cmd/bd's Dolt-gated tests (TestCLI_*, the init and
store-backed suites, the doctor/e2e tests): main.yml's integration shards,
nightly's Full Test Suite, and Bazel's --config=prcore/ci and
--config=integration all pass BEADS_TEST_SKIP=dolt, so cmd/bd's TestMain
never starts a test server and those tests skip; the proxied and embedded
tiers run only their manifests' tests. They rotted unseen.
//cmd/bd:bd_dolt_server_test (tag dolt-server-cmd) runs the whole
integration-tagged cmd/bd suite, the integration build's bd_test, against
a hermetic dolt sql-server: BEADS_TEST_DOLT_SERVER=local starts it from
the pinned dolt in the test wrapper's runfiles, and
BEADS_TEST_REQUIRE_DOLT_CONTAINER=1 fails the target instead of skipping
into a cached pass. No test selection: the Go binary shards itself over
every top-level test (32 shards), so each runs exactly once, and
check_testcases.py fails a shard that ran none. --config=doltserver-cmd
has exactly --config=integration's build flags, so the two lanes share
bd_test's compile; prcore/ci and integration exclude the tag.
bazel.yml's new bazel-cmd-dolt job runs it exactly where bazel-integration
runs (same if: remotely on the farm for same-repo PRs, fork-ro/fork-rw,
and locally with the read-only cache in mode cache for forks). It is
advisory: job-level continue-on-error keeps a failure out of the call's
aggregate (BAZEL), and pr.yml's ci-gate reads its result (BAZEL_CMD_DOLT)
but requires it only while the committed top-level flag
BAZEL_CMD_DOLT_REQUIRED is "true" (now "false"; flipping it is the one
change needed). bazel-gate.sh accepts its skip in modes skip and local.
Policy tests: a third lane category in TestBazelLaneIsGatedAlongsideLegacy
(bazelFlagGatedLanes: gate env wired, never statically required, added by
the run script exactly when the pinned flag is "true"), the gate
simulation over every mode with the flag off (advisory: nothing it
reports reddens the gate) and on (exactly a gated lane), the cache-mode
and execution-mode checks, the tag taxonomy and prcore/integration
exclusions, and TestBazelCmdDoltJob (job steps, timeouts, .bazelrc
config equal to integration's build with no dolt skip or test selection,
the target's dolt-server rules, and bd_test's env repeated).
Measured locally (all fixes in this series, 32 shards, 16 at a time on a
shared host): 3267 top-level tests, all shards pass, max shard 313s (one
5001-issue export test, 214s, sets it), mean 100s.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(init): hand the project installers a writer instead of swapping os.Stdout
The --quiet fix earlier in this series pointed the process-global
os.Stdout at the null device around the Claude/Codex/Cursor installers.
That works, but it mutates a global from inside a cobra Run: anything else
writing to stdout meanwhile (a goroutine, a future concurrent installer)
would vanish, and a concurrent read of os.Stdout is a data race.
The installers already write through env structs with stdout/stderr
fields. setup.ProjectInstallOutput carries the two writers, and
InstallClaudeProjectTo / InstallCodexProjectTo / InstallCursorProjectTo
use them (the old entry points keep the process streams). init passes
QuietProjectInstallOutput() under --quiet: progress discarded, error lines
still on stderr. The proxied-server init path (domain adapter
InstallClaudeProject now takes quiet) does the same, so its
"Installing Claude hooks..." is quiet too.
Consistent error policy under --quiet: errors still reach stderr. init's
own "Warning: failed to setup <installer>" lines were suppressed under
--quiet while the installers' "Error:" lines were not, and some installer
failures (Cursor rules) print nothing themselves; the warnings now print
whether or not quiet, like the installers' errors.
Coverage in required lanes: TestProjectInstallersReportToTheGivenOutput
(cmd/bd/setup) and TestEmbeddedInitA/basic, which now asserts that
`bd init --quiet` with agents enabled installs the Claude hooks and prints
none of the installers' progress (verified to fail with the quiet output
disabled).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(export): exercise the incremental-export fallback with a small threshold
TestTryIncrementalExport_ThresholdExceededFallsBack seeded
incrementalExportThreshold+1 = 5001 issues to cross the threshold. Batch
create is one transaction but still several statements per issue, so under
-race against the shared test server it took ~214 s, the longest test in
cmd/bd's Dolt-backed suite by far. The behaviour under test is only
"more changed issues than the threshold -> full export fallback".
incrementalExportThreshold becomes a var (same value), and the test, which
is not parallel, sets it to 20 and seeds 21 issues: 214 s -> 0.6 s.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(cmd/bd): tighten the flag-reset self-test, guards and canaries
Review follow-ups:
- TestResetCommandFlagsRestoresEveryFlag no longer skips a flag it cannot
set: a flag type without a sample value, a Set error, or a non-pointer
Value (which resetCommandFlags could not restore) is an error, so a new
flag type cannot go untested. resetCommandFlags documents that it also
resets flag-bound package globals.
- TestCobraParallelPolicyGuard treats .ExecuteC/.ExecuteContext/
.ExecuteContextC like .Execute (the per-execution isolation writes the
mode globals; a parallel execution would race).
- TestConfigValidateReadOnlyIsHermetic ignores only the gate a readonly
command takes (.beads/dolt.gate.lock and its .info sidecar), not any
"*.gate.lock*" file, so a new unexpected gate still trips the canary.
- TestCLI_CreateRejectsFlagLikeTitles: a bare `bd create --foo-bar` must
fail and create no issue (bd-2c0's intent), next to the "--" cases.
- TestCustomStatusConfig cites why statuses come back in name order: the
normalized custom_statuses table (#2961, 8537d943b) has no ordinal and is
read ORDER BY name, like custom_types; the test predates it.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* ci(bazel): run the cmd/bd Dolt-server tier in 16 shards
Each shard pays ~30-40 s of fixed cost (TestMain plus its own dolt
sql-server), so 32 shards spent roughly 40% of the lane's executor time on
setup and added 32 farm actions to every PR touching cmd/bd. With the
5001-issue export test cut to under a second, 16 shards measure (locally,
--nocache_test_results): max 186 s, mean 137 s, 2,187 executor-seconds
(vs ~2,800-3,200 at 32), all 3,267 top-level tests, every shard passing.
TestBazelCmdDoltJob pins the count; bazel.yml's timing comment is
restated (cache mode ~20-30 minutes).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2630 lines
82 KiB
Go
2630 lines
82 KiB
Go
//go:build cgo
|
|
|
|
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"runtime"
|
|
"strconv"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/steveyegge/beads/internal/beads"
|
|
"github.com/steveyegge/beads/internal/configfile"
|
|
"github.com/steveyegge/beads/internal/git"
|
|
"github.com/steveyegge/beads/internal/storage/dolt"
|
|
"github.com/steveyegge/beads/internal/testutil"
|
|
"github.com/steveyegge/beads/internal/utils"
|
|
"gopkg.in/yaml.v3"
|
|
)
|
|
|
|
// skipIfNoDolt skips the test when no Dolt server is available.
|
|
// Checks both binary availability and test server status.
|
|
func skipIfNoDolt(t *testing.T) {
|
|
t.Helper()
|
|
testutil.RequireDoltBinary(t)
|
|
if testDoltServerPort == 0 {
|
|
t.Skip("skipping: Dolt test server not running")
|
|
}
|
|
}
|
|
|
|
func TestInitCommand(t *testing.T) {
|
|
skipIfNoDolt(t)
|
|
resetInitFlagsForServerInit(t)
|
|
tests := []struct {
|
|
name string
|
|
prefix string
|
|
quiet bool
|
|
wantOutputText string
|
|
wantNoOutput bool
|
|
}{
|
|
{
|
|
name: "init with default prefix",
|
|
prefix: "",
|
|
quiet: false,
|
|
wantOutputText: "bd initialized successfully",
|
|
},
|
|
{
|
|
name: "init with custom prefix",
|
|
prefix: "myproject",
|
|
quiet: false,
|
|
wantOutputText: "myproject-<hash>",
|
|
},
|
|
{
|
|
name: "init with quiet flag",
|
|
prefix: "test",
|
|
quiet: true,
|
|
wantNoOutput: true,
|
|
},
|
|
{
|
|
name: "init with prefix ending in hyphen",
|
|
prefix: "test-",
|
|
quiet: false,
|
|
wantOutputText: "test-<hash>",
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
// Reset global state
|
|
origDBPath := dbPath
|
|
origStore := store
|
|
defer func() {
|
|
if store != nil && store != origStore {
|
|
store.Close()
|
|
}
|
|
store = origStore
|
|
dbPath = origDBPath
|
|
}()
|
|
dbPath = ""
|
|
store = nil
|
|
|
|
// Reset Cobra command state
|
|
rootCmd.SetArgs([]string{})
|
|
initCmd.Flags().Set("prefix", "")
|
|
initCmd.Flags().Set("quiet", "false")
|
|
|
|
tmpDir := t.TempDir()
|
|
t.Chdir(tmpDir)
|
|
|
|
// Capture output
|
|
var buf bytes.Buffer
|
|
oldStdout := os.Stdout
|
|
r, w, _ := os.Pipe()
|
|
os.Stdout = w
|
|
defer func() {
|
|
os.Stdout = oldStdout
|
|
}()
|
|
|
|
// Build command arguments
|
|
// A database of its own: the suite shares one test server.
|
|
args := []string{"init", "--server", "--database", uniqueTestDBName(t)}
|
|
if tt.prefix != "" {
|
|
args = append(args, "--prefix", tt.prefix)
|
|
}
|
|
if tt.quiet {
|
|
args = append(args, "--quiet")
|
|
}
|
|
|
|
rootCmd.SetArgs(args)
|
|
|
|
// Run command
|
|
var err error
|
|
err = rootCmd.Execute()
|
|
|
|
// Restore stdout and read output
|
|
w.Close()
|
|
buf.ReadFrom(r)
|
|
os.Stdout = oldStdout
|
|
output := buf.String()
|
|
|
|
if err != nil {
|
|
t.Fatalf("init command failed: %v", err)
|
|
}
|
|
|
|
// Check output
|
|
if tt.wantNoOutput {
|
|
if output != "" {
|
|
t.Errorf("Expected no output with --quiet, got: %s", output)
|
|
}
|
|
} else if tt.wantOutputText != "" {
|
|
if !strings.Contains(output, tt.wantOutputText) {
|
|
t.Errorf("Expected output to contain %q, got: %s", tt.wantOutputText, output)
|
|
}
|
|
}
|
|
|
|
// Verify .beads directory was created
|
|
beadsDir := filepath.Join(tmpDir, ".beads")
|
|
if _, err := os.Stat(beadsDir); os.IsNotExist(err) {
|
|
t.Error(".beads directory was not created")
|
|
}
|
|
|
|
// Verify .gitignore was created with proper content
|
|
gitignorePath := filepath.Join(beadsDir, ".gitignore")
|
|
gitignoreContent, err := os.ReadFile(gitignorePath)
|
|
if err != nil {
|
|
t.Errorf(".gitignore file was not created: %v", err)
|
|
} else {
|
|
// Check for essential patterns
|
|
gitignoreStr := string(gitignoreContent)
|
|
expectedPatterns := []string{
|
|
"*.db",
|
|
"*.db?*",
|
|
"*.db-journal",
|
|
"*.db-wal",
|
|
"*.db-shm",
|
|
"bd.sock",
|
|
"dolt/",
|
|
}
|
|
for _, pattern := range expectedPatterns {
|
|
if !strings.Contains(gitignoreStr, pattern) {
|
|
t.Errorf(".gitignore missing expected pattern: %s", pattern)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Verify Dolt database directory was created
|
|
doltPath := filepath.Join(beadsDir, "dolt")
|
|
if info, err := os.Stat(doltPath); os.IsNotExist(err) {
|
|
t.Errorf("Dolt database directory was not created at %s", doltPath)
|
|
} else if !info.IsDir() {
|
|
t.Errorf("Expected %s to be a directory", doltPath)
|
|
}
|
|
|
|
// Database content verification (prefix, metadata) is skipped here because
|
|
// embedded Dolt's Close() can timeout, leaving file locks held and preventing
|
|
// re-opening the DB in the same process. The init command's own internal logic
|
|
// verifies these writes succeed; prefix/metadata correctness is also covered
|
|
// by dedicated Dolt storage tests.
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestInitTargetsRequestedProjectBelowOSTempRoot(t *testing.T) {
|
|
sandbox := t.TempDir()
|
|
tempRoot := filepath.Join(sandbox, "tmp")
|
|
tempBeadsDir := filepath.Join(tempRoot, ".beads")
|
|
if err := os.MkdirAll(tempBeadsDir, 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(filepath.Join(tempBeadsDir, "metadata.json"), []byte("{}\n"), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
project := filepath.Join(tempRoot, "isolated", "project")
|
|
if err := os.MkdirAll(project, 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Chdir(project)
|
|
t.Setenv("TMPDIR", tempRoot)
|
|
t.Setenv("BEADS_DIR", "")
|
|
t.Setenv("BEADS_DB", "")
|
|
t.Setenv("BD_DB", "")
|
|
|
|
originalDBPath := dbPath
|
|
dbPath = ""
|
|
t.Cleanup(func() { dbPath = originalDBPath })
|
|
|
|
selected := selectedNoDBBeadsDir(initCmd)
|
|
if selected != "" {
|
|
t.Fatalf("selectedNoDBBeadsDir(init) = %q, want no inherited temp-root store", selected)
|
|
}
|
|
prepareSelectedNoDBContext(selected)
|
|
|
|
want := filepath.Join(project, ".beads")
|
|
if got := resolveInitBeadsDir(); !utils.PathsEqual(got, want) {
|
|
t.Fatalf("resolveInitBeadsDir() = %q, want requested project %q", got, want)
|
|
}
|
|
}
|
|
|
|
// Note: Error case testing is omitted because the init command calls os.Exit()
|
|
// on errors, which makes it difficult to test in a unit test context.
|
|
|
|
func TestInitAlreadyInitialized(t *testing.T) {
|
|
skipIfNoDolt(t)
|
|
resetInitFlagsForServerInit(t)
|
|
// Reset global state
|
|
origDBPath := dbPath
|
|
defer func() { dbPath = origDBPath }()
|
|
dbPath = ""
|
|
|
|
tmpDir := t.TempDir()
|
|
t.Chdir(tmpDir)
|
|
|
|
// Initialize once
|
|
// A database of its own: the suite shares one test server, where a
|
|
// "test" database another test created belongs to another project.
|
|
database := uniqueTestDBName(t)
|
|
rootCmd.SetArgs([]string{"init", "--server", "--database", database, "--prefix", "test", "--quiet"})
|
|
|
|
if err := rootCmd.Execute(); err != nil {
|
|
t.Fatalf("First init failed: %v", err)
|
|
}
|
|
|
|
// Initialize again with same prefix and --force flag (bd-emg: safety guard)
|
|
// Without --force, init should refuse when database already exists
|
|
rootCmd.SetArgs([]string{"init", "--server", "--database", database, "--prefix", "test", "--quiet", "--force"})
|
|
|
|
if err := rootCmd.Execute(); err != nil {
|
|
t.Fatalf("Second init with --force failed: %v", err)
|
|
}
|
|
|
|
// Verify database still works
|
|
dbPath := filepath.Join(tmpDir, ".beads", "dolt")
|
|
store, err := openExistingTestDB(t, dbPath)
|
|
if err != nil {
|
|
t.Fatalf("Failed to open database: %v", err)
|
|
}
|
|
defer store.Close()
|
|
|
|
ctx := context.Background()
|
|
prefix, err := store.GetConfig(ctx, "issue_prefix")
|
|
if err != nil {
|
|
t.Fatalf("Failed to get prefix after re-init: %v", err)
|
|
}
|
|
|
|
if prefix != "test" {
|
|
t.Errorf("Expected prefix 'test', got %q", prefix)
|
|
}
|
|
}
|
|
|
|
// GH#3490: `bd init --init-if-missing` makes init idempotent for scaffold
|
|
// scripts. When the workspace is already initialized, init must skip and
|
|
// return without error (exit 0), emitting a benign "Skipping init" message,
|
|
// instead of aborting via os.Exit(1). The default (no-flag) abort path calls
|
|
// os.Exit(1) and therefore cannot be exercised in-process (see the note above
|
|
// TestInitAlreadyInitialized); this test covers the new success path.
|
|
func TestInitIfMissing(t *testing.T) {
|
|
skipIfNoDolt(t)
|
|
// Reset global state
|
|
origDBPath := dbPath
|
|
|
|
// Cobra flag values persist across Execute() calls on the shared command
|
|
// tree (a sibling test may have left --force set, and our own first init
|
|
// sets --quiet). Normalize the flags this test depends on before each run,
|
|
// and restore defaults afterward so we neither inherit nor leak state.
|
|
resetInitFlags := func() {
|
|
_ = initCmd.Flags().Set("force", "false")
|
|
_ = initCmd.Flags().Set("reinit-local", "false")
|
|
_ = initCmd.Flags().Set("init-if-missing", "false")
|
|
_ = initCmd.Flags().Set("quiet", "false")
|
|
_ = initCmd.Flags().Set("prefix", "")
|
|
}
|
|
defer func() {
|
|
dbPath = origDBPath
|
|
resetInitFlags()
|
|
}()
|
|
dbPath = ""
|
|
resetInitFlags()
|
|
|
|
tmpDir := t.TempDir()
|
|
t.Chdir(tmpDir)
|
|
|
|
// First init creates the workspace.
|
|
rootCmd.SetArgs([]string{"init", "--prefix", "test", "--quiet"})
|
|
if err := rootCmd.Execute(); err != nil {
|
|
t.Fatalf("First init failed: %v", err)
|
|
}
|
|
|
|
// Re-running with --init-if-missing must be a benign no-op that exits 0:
|
|
// Execute() returns nil rather than the process aborting via os.Exit(1).
|
|
// Clear --quiet (set by the first run) so the skip message is emitted, and
|
|
// ensure no stale --force bypasses the already-initialized guard.
|
|
resetInitFlags()
|
|
|
|
oldStderr := os.Stderr
|
|
r, w, _ := os.Pipe()
|
|
os.Stderr = w
|
|
defer func() { os.Stderr = oldStderr }()
|
|
|
|
rootCmd.SetArgs([]string{"init", "--prefix", "test", "--init-if-missing"})
|
|
execErr := rootCmd.Execute()
|
|
|
|
w.Close()
|
|
var buf bytes.Buffer
|
|
buf.ReadFrom(r)
|
|
stderr := buf.String()
|
|
|
|
if execErr != nil {
|
|
t.Fatalf("init --init-if-missing on an initialized workspace should succeed, got: %v", execErr)
|
|
}
|
|
if !strings.Contains(stderr, "Skipping init: workspace already initialized") {
|
|
t.Errorf("expected a 'Skipping init: workspace already initialized' message on stderr, got:\n%s", stderr)
|
|
}
|
|
|
|
// The skip is a no-op: the existing workspace must remain in place (init
|
|
// returned before touching any data). We assert on the .beads directory
|
|
// rather than a specific backend layout so the test holds for both the
|
|
// embedded and server test modes.
|
|
beadsDir := filepath.Join(tmpDir, ".beads")
|
|
if info, err := os.Stat(beadsDir); err != nil || !info.IsDir() {
|
|
t.Fatalf("expected existing .beads workspace to remain at %s, stat err: %v", beadsDir, err)
|
|
}
|
|
}
|
|
|
|
// TestInitIfMissingPrefixMismatch covers the guard that keeps --init-if-missing
|
|
// from masking a genuine prefix mismatch (review follow-up on #4332/#3490): a
|
|
// re-init that explicitly requests a different prefix than the existing
|
|
// workspace must abort, while a matching prefix (after normalization) or an
|
|
// undeterminable existing name must fall through to the benign skip.
|
|
func TestInitIfMissingPrefixMismatch(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
existing string
|
|
requested string
|
|
want bool
|
|
}{
|
|
{name: "exact match", existing: "foo", requested: "foo", want: false},
|
|
{name: "case-insensitive match", existing: "Foo", requested: "foo", want: false},
|
|
{name: "hyphen normalizes to underscore", existing: "my_proj", requested: "my-proj", want: false},
|
|
{name: "trailing hyphen trimmed", existing: "foo", requested: "foo-", want: false},
|
|
{name: "leading-digit gets bd_ prefix", existing: "bd_001", requested: "001", want: false},
|
|
{name: "genuine mismatch aborts", existing: "foo", requested: "bar", want: true},
|
|
{name: "unknown existing falls through", existing: "", requested: "bar", want: false},
|
|
{name: "empty requested falls through", existing: "foo", requested: "", want: false},
|
|
}
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
if got := initIfMissingPrefixMismatch(tt.existing, tt.requested); got != tt.want {
|
|
t.Errorf("initIfMissingPrefixMismatch(%q, %q) = %v, want %v",
|
|
tt.existing, tt.requested, got, tt.want)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestInitIfMissingMatchingPrefixSkips verifies the mismatch guard does not
|
|
// regress the happy path: re-running with the SAME explicit --prefix as the
|
|
// existing workspace still skips cleanly (exit 0) rather than aborting.
|
|
func TestInitIfMissingMatchingPrefixSkips(t *testing.T) {
|
|
skipIfNoDolt(t)
|
|
origDBPath := dbPath
|
|
resetInitFlags := func() {
|
|
_ = initCmd.Flags().Set("force", "false")
|
|
_ = initCmd.Flags().Set("reinit-local", "false")
|
|
_ = initCmd.Flags().Set("init-if-missing", "false")
|
|
_ = initCmd.Flags().Set("quiet", "false")
|
|
_ = initCmd.Flags().Set("prefix", "")
|
|
}
|
|
defer func() {
|
|
dbPath = origDBPath
|
|
resetInitFlags()
|
|
}()
|
|
dbPath = ""
|
|
resetInitFlags()
|
|
|
|
tmpDir := t.TempDir()
|
|
t.Chdir(tmpDir)
|
|
|
|
rootCmd.SetArgs([]string{"init", "--prefix", "test", "--quiet"})
|
|
if err := rootCmd.Execute(); err != nil {
|
|
t.Fatalf("First init failed: %v", err)
|
|
}
|
|
|
|
resetInitFlags()
|
|
oldStderr := os.Stderr
|
|
r, w, _ := os.Pipe()
|
|
os.Stderr = w
|
|
defer func() { os.Stderr = oldStderr }()
|
|
|
|
// Same prefix as the existing workspace: must skip, not abort.
|
|
rootCmd.SetArgs([]string{"init", "--prefix", "test", "--init-if-missing"})
|
|
execErr := rootCmd.Execute()
|
|
|
|
w.Close()
|
|
var buf bytes.Buffer
|
|
buf.ReadFrom(r)
|
|
stderr := buf.String()
|
|
|
|
if execErr != nil {
|
|
t.Fatalf("init --init-if-missing with matching prefix should succeed, got: %v", execErr)
|
|
}
|
|
if !strings.Contains(stderr, "Skipping init: workspace already initialized") {
|
|
t.Errorf("expected benign skip message, got:\n%s", stderr)
|
|
}
|
|
}
|
|
|
|
func TestInitIfMissingDatabaseMismatch(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
existing string
|
|
requested string
|
|
want bool
|
|
}{
|
|
{name: "exact match", existing: "foo", requested: "foo", want: false},
|
|
{name: "case-insensitive match", existing: "Foo", requested: "foo", want: false},
|
|
{name: "genuine mismatch aborts", existing: "foo", requested: "bar", want: true},
|
|
{name: "unknown existing falls through", existing: "", requested: "bar", want: false},
|
|
{name: "empty requested falls through", existing: "foo", requested: "", want: false},
|
|
}
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
if got := initIfMissingDatabaseMismatch(tt.existing, tt.requested); got != tt.want {
|
|
t.Errorf("initIfMissingDatabaseMismatch(%q, %q) = %v, want %v",
|
|
tt.existing, tt.requested, got, tt.want)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestCheckExistingBeadsDataOperationalErrorNotMasked verifies the core of the
|
|
// --init-if-missing idempotency fix: only the benign "already initialized"
|
|
// outcome matches errWorkspaceAlreadyInitialized (and may be skipped), while an
|
|
// operational failure must NOT match it — otherwise --init-if-missing would mask
|
|
// a real error (e.g. an unreadable .beads/embeddeddolt) as a successful skip.
|
|
func TestCheckExistingBeadsDataOperationalErrorNotMasked(t *testing.T) {
|
|
saveEmbeddedConfig := func(t *testing.T, beadsDir string) {
|
|
t.Helper()
|
|
cfg := &configfile.Config{
|
|
Database: "dolt",
|
|
Backend: configfile.BackendDolt,
|
|
DoltMode: configfile.DoltModeEmbedded,
|
|
}
|
|
if err := cfg.Save(beadsDir); err != nil {
|
|
t.Fatalf("save config: %v", err)
|
|
}
|
|
}
|
|
|
|
t.Run("existing database matches sentinel", func(t *testing.T) {
|
|
beadsDir := t.TempDir()
|
|
saveEmbeddedConfig(t, beadsDir)
|
|
// A real embedded database lives at embeddeddolt/<db>/.dolt.
|
|
if err := os.MkdirAll(filepath.Join(beadsDir, "embeddeddolt", "mydb", ".dolt"), 0o750); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
err := checkExistingBeadsDataAt(beadsDir, "mydb")
|
|
if err == nil {
|
|
t.Fatal("expected already-initialized error, got nil")
|
|
}
|
|
if !errors.Is(err, errWorkspaceAlreadyInitialized) {
|
|
t.Errorf("existing-database error must match errWorkspaceAlreadyInitialized, got: %v", err)
|
|
}
|
|
})
|
|
|
|
t.Run("operational error not masked", func(t *testing.T) {
|
|
beadsDir := t.TempDir()
|
|
saveEmbeddedConfig(t, beadsDir)
|
|
// Make embeddeddolt a regular file so os.ReadDir fails with a
|
|
// non-IsNotExist (operational) error rather than "already initialized".
|
|
if err := os.WriteFile(filepath.Join(beadsDir, "embeddeddolt"), []byte("not a dir"), 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
err := checkExistingBeadsDataAt(beadsDir, "mydb")
|
|
if err == nil {
|
|
t.Fatal("expected operational error, got nil")
|
|
}
|
|
if errors.Is(err, errWorkspaceAlreadyInitialized) {
|
|
t.Errorf("operational error must NOT match errWorkspaceAlreadyInitialized (would be masked by --init-if-missing): %v", err)
|
|
}
|
|
})
|
|
}
|
|
|
|
func TestInitWithCustomDBPath(t *testing.T) {
|
|
t.Skip("BEADS_DB env var does not control Dolt store location; Dolt always uses .beads/dolt/")
|
|
// Save original state
|
|
origDBPath := dbPath
|
|
defer func() { dbPath = origDBPath }()
|
|
|
|
tmpDir := t.TempDir()
|
|
customDBDir := filepath.Join(tmpDir, "custom", "location")
|
|
|
|
// Change to a different directory to ensure --db flag is actually used
|
|
workDir := filepath.Join(tmpDir, "workdir")
|
|
if err := os.MkdirAll(workDir, 0750); err != nil {
|
|
t.Fatalf("Failed to create work directory: %v", err)
|
|
}
|
|
|
|
t.Chdir(workDir)
|
|
|
|
customDBPath := filepath.Join(customDBDir, "test.db")
|
|
|
|
// Test with BEADS_DB environment variable (replacing --db flag test)
|
|
t.Run("init with BEADS_DB pointing to custom path", func(t *testing.T) {
|
|
dbPath = "" // Reset global
|
|
os.Setenv("BEADS_DB", customDBPath)
|
|
defer os.Unsetenv("BEADS_DB")
|
|
|
|
rootCmd.SetArgs([]string{"init", "--prefix", "custom", "--quiet"})
|
|
|
|
if err := rootCmd.Execute(); err != nil {
|
|
t.Fatalf("Init with BEADS_DB failed: %v", err)
|
|
}
|
|
|
|
// Verify database was created at custom location
|
|
if _, err := os.Stat(customDBPath); os.IsNotExist(err) {
|
|
t.Errorf("Database was not created at custom path %s", customDBPath)
|
|
}
|
|
|
|
// Verify database works
|
|
store, err := openExistingTestDB(t, customDBPath)
|
|
if err != nil {
|
|
t.Fatalf("Failed to open database: %v", err)
|
|
}
|
|
defer store.Close()
|
|
|
|
ctx := context.Background()
|
|
prefix, err := store.GetConfig(ctx, "issue_prefix")
|
|
if err != nil {
|
|
t.Fatalf("Failed to get prefix: %v", err)
|
|
}
|
|
|
|
if prefix != "custom" {
|
|
t.Errorf("Expected prefix 'custom', got %q", prefix)
|
|
}
|
|
|
|
// Verify .beads/ directory was NOT created in work directory
|
|
if _, err := os.Stat(filepath.Join(workDir, ".beads")); err == nil {
|
|
t.Error(".beads/ directory should not be created when using BEADS_DB env var")
|
|
}
|
|
})
|
|
|
|
// Test with BEADS_DB env var
|
|
t.Run("init with BEADS_DB env var", func(t *testing.T) {
|
|
dbPath = "" // Reset global
|
|
envDBPath := filepath.Join(tmpDir, "env", "location", "env.db")
|
|
os.Setenv("BEADS_DB", envDBPath)
|
|
defer os.Unsetenv("BEADS_DB")
|
|
|
|
rootCmd.SetArgs([]string{"init", "--prefix", "envtest", "--quiet"})
|
|
|
|
if err := rootCmd.Execute(); err != nil {
|
|
t.Fatalf("Init with BEADS_DB failed: %v", err)
|
|
}
|
|
|
|
// Verify database was created at env location
|
|
if _, err := os.Stat(envDBPath); os.IsNotExist(err) {
|
|
t.Errorf("Database was not created at BEADS_DB path %s", envDBPath)
|
|
}
|
|
|
|
// Verify database works
|
|
store, err := openExistingTestDB(t, envDBPath)
|
|
if err != nil {
|
|
t.Fatalf("Failed to open database: %v", err)
|
|
}
|
|
defer store.Close()
|
|
|
|
ctx := context.Background()
|
|
prefix, err := store.GetConfig(ctx, "issue_prefix")
|
|
if err != nil {
|
|
t.Fatalf("Failed to get prefix: %v", err)
|
|
}
|
|
|
|
if prefix != "envtest" {
|
|
t.Errorf("Expected prefix 'envtest', got %q", prefix)
|
|
}
|
|
})
|
|
|
|
// Test that BEADS_DB path containing ".beads" doesn't create CWD/.beads
|
|
t.Run("init with BEADS_DB path containing .beads", func(t *testing.T) {
|
|
dbPath = "" // Reset global
|
|
// Path contains ".beads" but is outside work directory
|
|
customPath := filepath.Join(tmpDir, "storage", ".beads-backup", "test.db")
|
|
os.Setenv("BEADS_DB", customPath)
|
|
defer os.Unsetenv("BEADS_DB")
|
|
|
|
rootCmd.SetArgs([]string{"init", "--prefix", "beadstest", "--quiet"})
|
|
|
|
if err := rootCmd.Execute(); err != nil {
|
|
t.Fatalf("Init with custom .beads path failed: %v", err)
|
|
}
|
|
|
|
// Verify database was created at custom location
|
|
if _, err := os.Stat(customPath); os.IsNotExist(err) {
|
|
t.Errorf("Database was not created at custom path %s", customPath)
|
|
}
|
|
|
|
// Verify .beads/ directory was NOT created in work directory
|
|
if _, err := os.Stat(filepath.Join(workDir, ".beads")); err == nil {
|
|
t.Error(".beads/ directory should not be created in CWD when BEADS_DB path contains .beads")
|
|
}
|
|
})
|
|
|
|
// Test with multiple BEADS_DB variations
|
|
t.Run("BEADS_DB with subdirectories", func(t *testing.T) {
|
|
dbPath = "" // Reset global
|
|
envPath := filepath.Join(tmpDir, "env", "subdirs", "test.db")
|
|
|
|
os.Setenv("BEADS_DB", envPath)
|
|
defer os.Unsetenv("BEADS_DB")
|
|
|
|
rootCmd.SetArgs([]string{"init", "--prefix", "envtest2", "--quiet"})
|
|
|
|
if err := rootCmd.Execute(); err != nil {
|
|
t.Fatalf("Init with BEADS_DB subdirs failed: %v", err)
|
|
}
|
|
|
|
// Verify database was created at env location
|
|
if _, err := os.Stat(envPath); os.IsNotExist(err) {
|
|
t.Errorf("Database was not created at BEADS_DB path %s", envPath)
|
|
}
|
|
|
|
// Verify .beads/ directory was NOT created in work directory
|
|
if _, err := os.Stat(filepath.Join(workDir, ".beads")); err == nil {
|
|
t.Error(".beads/ directory should not be created in CWD when BEADS_DB is set")
|
|
}
|
|
})
|
|
}
|
|
|
|
// TestSetupClaudeSettings_InvalidJSON verifies that invalid JSON in existing
|
|
// settings.local.json returns an error instead of silently overwriting.
|
|
// This is a regression test for bd-5bj where user settings were lost.
|
|
func TestSetupClaudeSettings_InvalidJSON(t *testing.T) {
|
|
tmpDir := t.TempDir()
|
|
t.Chdir(tmpDir)
|
|
|
|
// Create .claude directory
|
|
claudeDir := filepath.Join(tmpDir, ".claude")
|
|
if err := os.MkdirAll(claudeDir, 0755); err != nil {
|
|
t.Fatalf("Failed to create .claude directory: %v", err)
|
|
}
|
|
|
|
// Create settings.local.json with invalid JSON (array syntax in object context)
|
|
// This is the exact pattern that caused the bug in the user's file
|
|
invalidJSON := `{
|
|
"permissions": {
|
|
"allow": [
|
|
"Bash(python3:*)"
|
|
],
|
|
"deny": [
|
|
"_comment": "Add commands to block here"
|
|
]
|
|
}
|
|
}`
|
|
settingsPath := filepath.Join(claudeDir, "settings.local.json")
|
|
if err := os.WriteFile(settingsPath, []byte(invalidJSON), 0644); err != nil {
|
|
t.Fatalf("Failed to write invalid settings: %v", err)
|
|
}
|
|
|
|
// Call setupClaudeSettings - should return an error
|
|
var err error
|
|
err = setupClaudeSettings(false)
|
|
if err == nil {
|
|
t.Fatal("Expected error for invalid JSON, got nil")
|
|
}
|
|
|
|
// Verify the error message mentions invalid JSON
|
|
if !strings.Contains(err.Error(), "invalid JSON") {
|
|
t.Errorf("Expected error to mention 'invalid JSON', got: %v", err)
|
|
}
|
|
|
|
// Verify the original file was NOT modified
|
|
content, err := os.ReadFile(settingsPath)
|
|
if err != nil {
|
|
t.Fatalf("Failed to read settings file: %v", err)
|
|
}
|
|
|
|
if !strings.Contains(string(content), "permissions") {
|
|
t.Error("Original file content should be preserved")
|
|
}
|
|
|
|
if strings.Contains(string(content), "bd prime") {
|
|
t.Error("File should NOT contain bd prime prompt after error")
|
|
}
|
|
}
|
|
|
|
// TestSetupClaudeSettings_ValidJSON verifies that valid JSON is properly updated
|
|
func TestSetupClaudeSettings_ValidJSON(t *testing.T) {
|
|
tmpDir := t.TempDir()
|
|
t.Chdir(tmpDir)
|
|
|
|
// Create .claude directory
|
|
claudeDir := filepath.Join(tmpDir, ".claude")
|
|
if err := os.MkdirAll(claudeDir, 0755); err != nil {
|
|
t.Fatalf("Failed to create .claude directory: %v", err)
|
|
}
|
|
|
|
// Create settings.local.json with valid JSON
|
|
validJSON := `{
|
|
"permissions": {
|
|
"allow": [
|
|
"Bash(python3:*)"
|
|
]
|
|
},
|
|
"hooks": {
|
|
"PreToolUse": []
|
|
}
|
|
}`
|
|
settingsPath := filepath.Join(claudeDir, "settings.local.json")
|
|
if err := os.WriteFile(settingsPath, []byte(validJSON), 0644); err != nil {
|
|
t.Fatalf("Failed to write valid settings: %v", err)
|
|
}
|
|
|
|
// Call setupClaudeSettings - should succeed
|
|
var err error
|
|
err = setupClaudeSettings(false)
|
|
if err != nil {
|
|
t.Fatalf("Expected no error for valid JSON, got: %v", err)
|
|
}
|
|
|
|
// Verify the file was updated with prompt AND preserved existing settings
|
|
content, err := os.ReadFile(settingsPath)
|
|
if err != nil {
|
|
t.Fatalf("Failed to read settings file: %v", err)
|
|
}
|
|
|
|
contentStr := string(content)
|
|
|
|
// Should contain the new prompt
|
|
if !strings.Contains(contentStr, "bd prime") {
|
|
t.Error("File should contain bd prime prompt")
|
|
}
|
|
|
|
// Should preserve existing permissions
|
|
if !strings.Contains(contentStr, "permissions") {
|
|
t.Error("File should preserve permissions section")
|
|
}
|
|
|
|
// Should preserve existing hooks
|
|
if !strings.Contains(contentStr, "hooks") {
|
|
t.Error("File should preserve hooks section")
|
|
}
|
|
|
|
if !strings.Contains(contentStr, "PreToolUse") {
|
|
t.Error("File should preserve PreToolUse hook")
|
|
}
|
|
}
|
|
|
|
// TestSetupClaudeSettings_NoExistingFile verifies behavior when no file exists
|
|
func TestSetupClaudeSettings_NoExistingFile(t *testing.T) {
|
|
tmpDir := t.TempDir()
|
|
t.Chdir(tmpDir)
|
|
|
|
// Don't create .claude directory - setupClaudeSettings should create it
|
|
|
|
// Call setupClaudeSettings - should succeed
|
|
var err error
|
|
err = setupClaudeSettings(false)
|
|
if err != nil {
|
|
t.Fatalf("Expected no error when no file exists, got: %v", err)
|
|
}
|
|
|
|
// Verify the file was created with prompt
|
|
settingsPath := filepath.Join(tmpDir, ".claude", "settings.local.json")
|
|
content, err := os.ReadFile(settingsPath)
|
|
if err != nil {
|
|
t.Fatalf("Failed to read settings file: %v", err)
|
|
}
|
|
|
|
if !strings.Contains(string(content), "bd prime") {
|
|
t.Error("File should contain bd prime prompt")
|
|
}
|
|
}
|
|
|
|
// TestInitPromptRoleConfig tests the beads.role git config read/write functions
|
|
func TestInitPromptRoleConfig(t *testing.T) {
|
|
t.Run("getBeadsRole returns empty when not configured", func(t *testing.T) {
|
|
tmpDir := newGitRepo(t)
|
|
t.Chdir(tmpDir)
|
|
|
|
role, hasRole := getBeadsRole()
|
|
if hasRole {
|
|
t.Errorf("Expected hasRole=false when not configured, got true with role=%q", role)
|
|
}
|
|
if role != "" {
|
|
t.Errorf("Expected empty role when not configured, got %q", role)
|
|
}
|
|
})
|
|
|
|
t.Run("setBeadsRole and getBeadsRole roundtrip", func(t *testing.T) {
|
|
tmpDir := newGitRepo(t)
|
|
t.Chdir(tmpDir)
|
|
|
|
// Set role to contributor
|
|
if err := setBeadsRole("contributor"); err != nil {
|
|
t.Fatalf("Failed to set beads.role: %v", err)
|
|
}
|
|
|
|
role, hasRole := getBeadsRole()
|
|
if !hasRole {
|
|
t.Error("Expected hasRole=true after setting role")
|
|
}
|
|
if role != "contributor" {
|
|
t.Errorf("Expected role 'contributor', got %q", role)
|
|
}
|
|
|
|
// Change to maintainer
|
|
if err := setBeadsRole("maintainer"); err != nil {
|
|
t.Fatalf("Failed to set beads.role: %v", err)
|
|
}
|
|
|
|
role, hasRole = getBeadsRole()
|
|
if !hasRole {
|
|
t.Error("Expected hasRole=true after setting role")
|
|
}
|
|
if role != "maintainer" {
|
|
t.Errorf("Expected role 'maintainer', got %q", role)
|
|
}
|
|
})
|
|
}
|
|
|
|
// TestInitPromptSkippedWithFlags verifies that --contributor and --team flags skip the prompt
|
|
func TestInitPromptSkippedWithFlags(t *testing.T) {
|
|
skipIfNoDolt(t)
|
|
t.Run("contributor flag skips prompt and runs wizard", func(t *testing.T) {
|
|
// Reset global state
|
|
origDBPath := dbPath
|
|
defer func() { dbPath = origDBPath }()
|
|
dbPath = ""
|
|
|
|
// Reset caches so RepoContext picks up new directory
|
|
beads.ResetCaches()
|
|
git.ResetCaches()
|
|
defer func() {
|
|
beads.ResetCaches()
|
|
git.ResetCaches()
|
|
}()
|
|
|
|
// Reset Cobra flags
|
|
initCmd.Flags().Set("contributor", "false")
|
|
|
|
tmpDir := newGitRepo(t)
|
|
t.Chdir(tmpDir)
|
|
|
|
// Verify no role is set initially
|
|
role, hasRole := getBeadsRole()
|
|
if hasRole {
|
|
t.Fatalf("Expected no role initially, got %q", role)
|
|
}
|
|
|
|
// Run bd init with --contributor flag (quiet to suppress wizard output)
|
|
// The wizard will fail because there's no planning repo, but that's OK
|
|
// We just want to verify the flag bypasses the prompt
|
|
rootCmd.SetArgs([]string{"init", "--prefix", "test", "--contributor", "--quiet"})
|
|
_ = rootCmd.Execute() // Ignore error - wizard may fail
|
|
|
|
// The --contributor flag should NOT set beads.role (that's done by prompt, not flag)
|
|
// The flag just triggers the wizard directly
|
|
})
|
|
|
|
t.Run("team flag skips prompt", func(t *testing.T) {
|
|
// Reset global state
|
|
origDBPath := dbPath
|
|
defer func() { dbPath = origDBPath }()
|
|
dbPath = ""
|
|
|
|
// Reset caches so RepoContext picks up new directory
|
|
beads.ResetCaches()
|
|
git.ResetCaches()
|
|
defer func() {
|
|
beads.ResetCaches()
|
|
git.ResetCaches()
|
|
}()
|
|
|
|
// Reset Cobra flags
|
|
initCmd.Flags().Set("team", "false")
|
|
|
|
tmpDir := newGitRepo(t)
|
|
t.Chdir(tmpDir)
|
|
|
|
// Verify no role is set initially
|
|
role, hasRole := getBeadsRole()
|
|
if hasRole {
|
|
t.Fatalf("Expected no role initially, got %q", role)
|
|
}
|
|
|
|
// Run bd init with --team flag
|
|
rootCmd.SetArgs([]string{"init", "--prefix", "test", "--team", "--quiet"})
|
|
_ = rootCmd.Execute() // Ignore error - wizard may fail
|
|
|
|
// The --team flag should not set beads.role
|
|
// (team wizard is separate from contributor/maintainer roles)
|
|
})
|
|
}
|
|
|
|
// TestInitPromptTTYDetection verifies shouldPromptForRole behavior
|
|
func TestInitPromptTTYDetection(t *testing.T) {
|
|
// Note: In test environment, stdin is typically NOT a TTY (it's a pipe)
|
|
// This test verifies the function works, not that we're in a TTY
|
|
|
|
t.Run("shouldPromptForRole returns false in test environment", func(t *testing.T) {
|
|
// In test environment, stdin is typically piped, not a TTY
|
|
result := shouldPromptForRole()
|
|
|
|
// We can't guarantee what the result will be in all test environments,
|
|
// but we can verify the function doesn't panic and returns a bool
|
|
if result {
|
|
t.Log("Test environment has TTY stdin (unusual but acceptable)")
|
|
} else {
|
|
t.Log("Test environment does not have TTY stdin (expected)")
|
|
}
|
|
})
|
|
}
|
|
|
|
// TestInitPromptNonGitRepo verifies prompt is skipped in non-git directories
|
|
func TestInitPromptNonGitRepo(t *testing.T) {
|
|
skipIfNoDolt(t)
|
|
// Reset global state
|
|
origDBPath := dbPath
|
|
defer func() { dbPath = origDBPath }()
|
|
dbPath = ""
|
|
|
|
// Reset caches so RepoContext picks up new directory
|
|
beads.ResetCaches()
|
|
git.ResetCaches()
|
|
defer func() {
|
|
beads.ResetCaches()
|
|
git.ResetCaches()
|
|
}()
|
|
|
|
// Reset Cobra flags that may be set from previous tests
|
|
initCmd.Flags().Set("contributor", "false")
|
|
initCmd.Flags().Set("team", "false")
|
|
|
|
tmpDir := t.TempDir()
|
|
t.Chdir(tmpDir)
|
|
|
|
// DON'T initialize git repo
|
|
|
|
// Run bd init - should succeed without prompting (no git repo)
|
|
rootCmd.SetArgs([]string{"init", "--prefix", "test", "--quiet"})
|
|
if err := rootCmd.Execute(); err != nil {
|
|
t.Fatalf("Init should succeed in non-git directory: %v", err)
|
|
}
|
|
|
|
// Verify .beads was created
|
|
beadsDir := filepath.Join(tmpDir, ".beads")
|
|
if _, err := os.Stat(beadsDir); os.IsNotExist(err) {
|
|
t.Error(".beads directory should be created even without git")
|
|
}
|
|
}
|
|
|
|
// TestInitPromptExistingRole verifies behavior when beads.role is already set
|
|
func TestInitPromptExistingRole(t *testing.T) {
|
|
skipIfNoDolt(t)
|
|
// Reinit publishes its selected workspace into the command environment.
|
|
t.Setenv("BEADS_DIR", "")
|
|
t.Run("existing role is preserved on reinit with --force", func(t *testing.T) {
|
|
// Reset global state
|
|
origDBPath := dbPath
|
|
defer func() { dbPath = origDBPath }()
|
|
dbPath = ""
|
|
|
|
// Reset caches so RepoContext picks up new directory
|
|
beads.ResetCaches()
|
|
git.ResetCaches()
|
|
defer func() {
|
|
beads.ResetCaches()
|
|
git.ResetCaches()
|
|
}()
|
|
|
|
// Reset Cobra flags that may be set from previous tests
|
|
initCmd.Flags().Set("contributor", "false")
|
|
initCmd.Flags().Set("team", "false")
|
|
initCmd.Flags().Set("force", "false")
|
|
|
|
tmpDir := newGitRepo(t)
|
|
t.Chdir(tmpDir)
|
|
|
|
// Set role before init
|
|
if err := setBeadsRole("contributor"); err != nil {
|
|
t.Fatalf("Failed to set beads.role: %v", err)
|
|
}
|
|
|
|
// Run bd init (non-interactive, so prompt is skipped)
|
|
rootCmd.SetArgs([]string{"init", "--prefix", "test", "--quiet"})
|
|
if err := rootCmd.Execute(); err != nil {
|
|
t.Fatalf("Init failed: %v", err)
|
|
}
|
|
|
|
// Verify role is still set
|
|
role, hasRole := getBeadsRole()
|
|
if !hasRole {
|
|
t.Error("Expected beads.role to still be set after init")
|
|
}
|
|
if role != "contributor" {
|
|
t.Errorf("Expected role 'contributor' to be preserved, got %q", role)
|
|
}
|
|
|
|
// Reset Cobra flags for reinit
|
|
initCmd.Flags().Set("force", "false")
|
|
|
|
// Reinit with --force (non-interactive)
|
|
rootCmd.SetArgs([]string{"init", "--prefix", "test", "--quiet", "--force"})
|
|
if err := rootCmd.Execute(); err != nil {
|
|
t.Fatalf("Reinit failed: %v", err)
|
|
}
|
|
|
|
// Verify role is still set (not cleared by reinit)
|
|
role, hasRole = getBeadsRole()
|
|
if !hasRole {
|
|
t.Error("Expected beads.role to still be set after reinit")
|
|
}
|
|
if role != "contributor" {
|
|
t.Errorf("Expected role 'contributor' to be preserved after reinit, got %q", role)
|
|
}
|
|
})
|
|
}
|
|
|
|
func TestInitContributorSetsBeadsRoleContributor(t *testing.T) {
|
|
skipIfNoDolt(t)
|
|
|
|
// Serial: this fixture owns command flags, stdin, cwd and process environment.
|
|
// Do not inherit another in-process command's selected workspace.
|
|
t.Setenv("BEADS_DIR", "")
|
|
// The pipe below supplies real wizard answers; explicitly allow interaction
|
|
// even when CI or terminal detection would normally suppress it.
|
|
t.Setenv("BD_NON_INTERACTIVE", "0")
|
|
for _, name := range []string{"contributor", "team", "force", "non-interactive", "role", "prefix", "quiet"} {
|
|
flag := initCmd.Flags().Lookup(name)
|
|
if flag == nil {
|
|
t.Fatalf("missing init flag --%s", name)
|
|
}
|
|
value, changed := flag.Value.String(), flag.Changed
|
|
t.Cleanup(func() {
|
|
if err := flag.Value.Set(value); err != nil {
|
|
t.Errorf("restore --%s: %v", name, err)
|
|
}
|
|
flag.Changed = changed
|
|
})
|
|
if err := flag.Value.Set(flag.DefValue); err != nil {
|
|
t.Fatalf("reset --%s: %v", name, err)
|
|
}
|
|
flag.Changed = false
|
|
}
|
|
|
|
origDBPath := dbPath
|
|
defer func() { dbPath = origDBPath }()
|
|
dbPath = ""
|
|
|
|
beads.ResetCaches()
|
|
git.ResetCaches()
|
|
defer func() {
|
|
beads.ResetCaches()
|
|
git.ResetCaches()
|
|
}()
|
|
|
|
// Keep test isolated from the real home/planning repo.
|
|
testHome := t.TempDir()
|
|
t.Setenv("HOME", testHome)
|
|
t.Setenv("USERPROFILE", testHome)
|
|
t.Setenv("XDG_CONFIG_HOME", filepath.Join(testHome, ".config"))
|
|
|
|
tmpDir := newGitRepo(t)
|
|
t.Chdir(tmpDir)
|
|
|
|
// Owned local remotes prevent network lookups during initialization.
|
|
cmd := exec.Command("git", "remote", "add", "origin", newGitRepo(t))
|
|
cmd.Dir = tmpDir
|
|
if err := cmd.Run(); err != nil {
|
|
t.Fatalf("failed to add origin remote: %v", err)
|
|
}
|
|
cmd = exec.Command("git", "remote", "add", "upstream", newGitRepo(t))
|
|
cmd.Dir = tmpDir
|
|
if err := cmd.Run(); err != nil {
|
|
t.Fatalf("failed to add upstream remote: %v", err)
|
|
}
|
|
|
|
// Wizard answers:
|
|
// 1) "Do you want to use a separate planning repo anyway? [Y/n]" -> Enter (default yes)
|
|
// 2) "Planning repo path [press Enter for default]" -> Enter (default ~/.beads-planning)
|
|
r, w, err := os.Pipe()
|
|
if err != nil {
|
|
t.Fatalf("failed to create stdin pipe: %v", err)
|
|
}
|
|
oldStdin := os.Stdin
|
|
os.Stdin = r
|
|
t.Cleanup(func() { os.Stdin = oldStdin })
|
|
t.Cleanup(func() { _ = r.Close() })
|
|
_, _ = w.WriteString("\n\n")
|
|
_ = w.Close()
|
|
|
|
rootCmd.SetArgs([]string{"init", "--prefix", "test", "--contributor", "--quiet"})
|
|
if err := rootCmd.Execute(); err != nil {
|
|
t.Fatalf("init --contributor failed: %v", err)
|
|
}
|
|
|
|
role, hasRole := getBeadsRole()
|
|
if !hasRole {
|
|
t.Fatal("expected beads.role to be configured")
|
|
}
|
|
if role != "contributor" {
|
|
t.Fatalf("beads.role = %q, want %q", role, "contributor")
|
|
}
|
|
}
|
|
|
|
// TestInitNonInteractiveAlwaysSetsRole verifies that bd init --non-interactive
|
|
// always leaves beads.role set, even when no --role flag is provided (GH#2950).
|
|
// This is the safety net for the init flow.
|
|
func TestInitNonInteractiveAlwaysSetsRole(t *testing.T) {
|
|
skipIfNoDolt(t)
|
|
|
|
origDBPath := dbPath
|
|
defer func() { dbPath = origDBPath }()
|
|
dbPath = ""
|
|
|
|
beads.ResetCaches()
|
|
git.ResetCaches()
|
|
defer func() {
|
|
beads.ResetCaches()
|
|
git.ResetCaches()
|
|
}()
|
|
|
|
initCmd.Flags().Set("contributor", "false")
|
|
initCmd.Flags().Set("team", "false")
|
|
initCmd.Flags().Set("force", "false")
|
|
initCmd.Flags().Set("role", "")
|
|
|
|
tmpDir := newGitRepo(t)
|
|
t.Chdir(tmpDir)
|
|
|
|
// Ensure no role is set before init
|
|
exec.Command("git", "config", "--unset", "beads.role").Run() //nolint:errcheck
|
|
|
|
rootCmd.SetArgs([]string{"init", "--prefix", "test", "--quiet", "--non-interactive"})
|
|
if err := rootCmd.Execute(); err != nil {
|
|
t.Fatalf("init --non-interactive failed: %v", err)
|
|
}
|
|
|
|
role, hasRole := getBeadsRole()
|
|
if !hasRole {
|
|
t.Fatal("expected beads.role to be configured after non-interactive init (GH#2950)")
|
|
}
|
|
if role != "maintainer" {
|
|
t.Fatalf("beads.role = %q, want %q (default for non-interactive)", role, "maintainer")
|
|
}
|
|
}
|
|
|
|
// TestInitWithRedirect verifies that bd init creates the database in the redirect target,
|
|
// not in the local .beads directory. (GH#bd-0qel)
|
|
// TestInitRedirect groups redirect-related init tests.
|
|
func TestInitRedirect(t *testing.T) {
|
|
skipIfNoDolt(t)
|
|
resetInitFlagsForServerInit(t)
|
|
resetRedirectState := func(t *testing.T) {
|
|
t.Helper()
|
|
origDBPath := dbPath
|
|
origBeadsDir := os.Getenv("BEADS_DIR")
|
|
t.Cleanup(func() {
|
|
dbPath = origDBPath
|
|
if origBeadsDir != "" {
|
|
os.Setenv("BEADS_DIR", origBeadsDir)
|
|
} else {
|
|
os.Unsetenv("BEADS_DIR")
|
|
}
|
|
})
|
|
dbPath = ""
|
|
os.Unsetenv("BEADS_DIR")
|
|
initCmd.Flags().Set("prefix", "")
|
|
initCmd.Flags().Set("quiet", "false")
|
|
initCmd.Flags().Set("force", "false")
|
|
}
|
|
|
|
t.Run("RedirectCreatesDBInTarget", func(t *testing.T) {
|
|
resetRedirectState(t)
|
|
|
|
tmpDir := t.TempDir()
|
|
|
|
projectDir := filepath.Join(tmpDir, "project")
|
|
if err := os.MkdirAll(projectDir, 0755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
localBeadsDir := filepath.Join(projectDir, ".beads")
|
|
if err := os.MkdirAll(localBeadsDir, 0755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
targetBeadsDir := filepath.Join(tmpDir, "canonical", ".beads")
|
|
if err := os.MkdirAll(targetBeadsDir, 0755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
// A provisioned canonical workspace (config.yaml, no database yet):
|
|
// bd follows a redirect only to a target that holds project files,
|
|
// and ignores one to a bare directory (gastownhall/beads#4692).
|
|
if err := os.WriteFile(filepath.Join(targetBeadsDir, "config.yaml"), []byte("# provisioned canonical workspace\n"), 0644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
redirectPath := filepath.Join(localBeadsDir, beads.RedirectFileName)
|
|
if err := os.WriteFile(redirectPath, []byte("../canonical/.beads\n"), 0644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
t.Chdir(projectDir)
|
|
|
|
rootCmd.SetArgs([]string{"init", "--server", "--database", uniqueTestDBName(t), "--prefix", "redirect-test", "--quiet"})
|
|
if err := rootCmd.Execute(); err != nil {
|
|
t.Fatalf("Init with redirect failed: %v", err)
|
|
}
|
|
|
|
targetDBPath := filepath.Join(targetBeadsDir, "dolt")
|
|
if _, err := os.Stat(targetDBPath); os.IsNotExist(err) {
|
|
t.Errorf("Dolt database was NOT created in redirect target: %s", targetDBPath)
|
|
}
|
|
|
|
localDBPath := filepath.Join(localBeadsDir, "dolt")
|
|
if _, err := os.Stat(localDBPath); err == nil {
|
|
t.Errorf("Database was incorrectly created in local .beads: %s (should be in redirect target)", localDBPath)
|
|
}
|
|
|
|
store, err := openExistingTestDB(t, targetDBPath)
|
|
if err != nil {
|
|
t.Fatalf("Failed to open database in redirect target: %v", err)
|
|
}
|
|
defer store.Close()
|
|
|
|
ctx := context.Background()
|
|
prefix, err := store.GetConfig(ctx, "issue_prefix")
|
|
if err != nil {
|
|
t.Fatalf("Failed to get issue prefix from database: %v", err)
|
|
}
|
|
if prefix != "redirect-test" {
|
|
t.Errorf("Expected prefix 'redirect-test', got %q", prefix)
|
|
}
|
|
})
|
|
|
|
// Verifies that bd init errors when the redirect target already has a database,
|
|
// preventing accidental overwrites. (GH#bd-0qel)
|
|
t.Run("ErrorWhenTargetHasExistingDB", func(t *testing.T) {
|
|
resetRedirectState(t)
|
|
|
|
tmpDir := t.TempDir()
|
|
|
|
canonicalDir := filepath.Join(tmpDir, "canonical")
|
|
canonicalBeadsDir := filepath.Join(canonicalDir, ".beads")
|
|
if err := os.MkdirAll(canonicalBeadsDir, 0755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
canonicalDBPath := filepath.Join(canonicalBeadsDir, "beads.db")
|
|
// Create the db file so checkExistingBeadsData detects it
|
|
if err := os.WriteFile(canonicalDBPath, []byte{}, 0644); err != nil {
|
|
t.Fatalf("Failed to create canonical db file: %v", err)
|
|
}
|
|
|
|
projectDir := filepath.Join(tmpDir, "project")
|
|
projectBeadsDir := filepath.Join(projectDir, ".beads")
|
|
if err := os.MkdirAll(projectBeadsDir, 0755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
redirectPath := filepath.Join(projectBeadsDir, beads.RedirectFileName)
|
|
if err := os.WriteFile(redirectPath, []byte("../canonical/.beads\n"), 0644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
// Use os.Chdir since checkExistingBeadsData reads CWD directly
|
|
origWd, _ := os.Getwd()
|
|
if err := os.Chdir(projectDir); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer os.Chdir(origWd)
|
|
|
|
err := checkExistingBeadsData("new-prefix")
|
|
if err == nil {
|
|
t.Fatal("Expected checkExistingBeadsData to return error when redirect target already has database")
|
|
}
|
|
|
|
errorMsg := err.Error()
|
|
if !strings.Contains(errorMsg, "redirect target already has database") {
|
|
t.Errorf("Expected error about redirect target having database, got: %s", errorMsg)
|
|
}
|
|
|
|
// Verify the canonical DB file still exists (wasn't deleted/overwritten)
|
|
if _, statErr := os.Stat(canonicalDBPath); os.IsNotExist(statErr) {
|
|
t.Error("Canonical database file should still exist after error")
|
|
}
|
|
})
|
|
}
|
|
|
|
// =============================================================================
|
|
// BEADS_DIR Tests
|
|
// =============================================================================
|
|
// These tests verify that bd init respects the BEADS_DIR environment variable
|
|
// for both safety checks and database creation.
|
|
|
|
// TestInitBEADS_DIR groups BEADS_DIR-related init tests.
|
|
// Tests requirements FR-001, FR-002, FR-004, NFR-001.
|
|
func TestInitBEADS_DIR(t *testing.T) {
|
|
skipIfNoDolt(t)
|
|
resetInitFlagsForServerInit(t)
|
|
// resetBeadsDirState resets global state and env vars for each subtest.
|
|
resetBeadsDirState := func(t *testing.T) {
|
|
t.Helper()
|
|
origDBPath := dbPath
|
|
t.Cleanup(func() {
|
|
dbPath = origDBPath
|
|
beads.ResetCaches()
|
|
git.ResetCaches()
|
|
})
|
|
dbPath = ""
|
|
beads.ResetCaches()
|
|
git.ResetCaches()
|
|
initCmd.Flags().Set("prefix", "")
|
|
initCmd.Flags().Set("quiet", "false")
|
|
initCmd.Flags().Set("backend", "")
|
|
}
|
|
|
|
// checkExistingBeadsData tests (FR-001, FR-004)
|
|
t.Run("CheckExisting_NoExistingDB", func(t *testing.T) {
|
|
resetBeadsDirState(t)
|
|
|
|
tmpDir := t.TempDir()
|
|
beadsDirPath := filepath.Join(tmpDir, "external", ".beads")
|
|
os.MkdirAll(beadsDirPath, 0755)
|
|
|
|
os.Setenv("BEADS_DIR", beadsDirPath)
|
|
t.Cleanup(func() { os.Unsetenv("BEADS_DIR") })
|
|
beads.ResetCaches()
|
|
|
|
err := checkExistingBeadsData("test")
|
|
if err != nil {
|
|
t.Errorf("Expected no error when BEADS_DIR has no database, got: %v", err)
|
|
}
|
|
})
|
|
|
|
t.Run("CheckExisting_CWDIgnoredWhenSet", func(t *testing.T) {
|
|
resetBeadsDirState(t)
|
|
|
|
tmpDir := t.TempDir()
|
|
|
|
// Create CWD with existing database (should be ignored)
|
|
cwdBeadsDir := filepath.Join(tmpDir, "cwd", ".beads")
|
|
os.MkdirAll(cwdBeadsDir, 0755)
|
|
cwdDBPath := filepath.Join(cwdBeadsDir, beads.CanonicalDatabaseName)
|
|
// Create the db file so checkExistingBeadsData detects it
|
|
if err := os.WriteFile(cwdDBPath, []byte{}, 0644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
// Create BEADS_DIR location (no database)
|
|
beadsDirPath := filepath.Join(tmpDir, "external", ".beads")
|
|
os.MkdirAll(beadsDirPath, 0755)
|
|
|
|
os.Setenv("BEADS_DIR", beadsDirPath)
|
|
t.Cleanup(func() { os.Unsetenv("BEADS_DIR") })
|
|
beads.ResetCaches()
|
|
|
|
origWd, _ := os.Getwd()
|
|
os.Chdir(filepath.Join(tmpDir, "cwd"))
|
|
defer os.Chdir(origWd)
|
|
|
|
err := checkExistingBeadsData("test")
|
|
if err != nil {
|
|
t.Errorf("Expected no error when BEADS_DIR has no database (CWD should be ignored), got: %v", err)
|
|
}
|
|
})
|
|
|
|
t.Run("CheckExisting_ErrorWhenDBExists", func(t *testing.T) {
|
|
resetBeadsDirState(t)
|
|
|
|
tmpDir := t.TempDir()
|
|
|
|
beadsDirPath := filepath.Join(tmpDir, "external", ".beads")
|
|
os.MkdirAll(beadsDirPath, 0755)
|
|
testDBPath := filepath.Join(beadsDirPath, beads.CanonicalDatabaseName)
|
|
// Create the db file so checkExistingBeadsData detects it
|
|
if err := os.WriteFile(testDBPath, []byte{}, 0644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
os.Setenv("BEADS_DIR", beadsDirPath)
|
|
t.Cleanup(func() { os.Unsetenv("BEADS_DIR") })
|
|
beads.ResetCaches()
|
|
|
|
err := checkExistingBeadsData("test")
|
|
if err == nil {
|
|
t.Error("Expected error when BEADS_DIR already has database")
|
|
}
|
|
if !strings.Contains(err.Error(), beadsDirPath) {
|
|
t.Errorf("Expected error to mention BEADS_DIR path %s, got: %v", beadsDirPath, err)
|
|
}
|
|
})
|
|
|
|
// FR-002: init creates database at BEADS_DIR
|
|
t.Run("InitCreatesDBAtBeadsDir", func(t *testing.T) {
|
|
if runtime.GOOS == "windows" {
|
|
t.Skip("Skipping BEADS_DIR test on Windows")
|
|
}
|
|
|
|
resetBeadsDirState(t)
|
|
|
|
tmpDir := t.TempDir()
|
|
|
|
beadsDirPath := filepath.Join(tmpDir, "external", ".beads")
|
|
os.MkdirAll(filepath.Dir(beadsDirPath), 0755)
|
|
|
|
os.Setenv("BEADS_DIR", beadsDirPath)
|
|
t.Cleanup(func() { os.Unsetenv("BEADS_DIR") })
|
|
beads.ResetCaches()
|
|
git.ResetCaches()
|
|
|
|
cwdPath := filepath.Join(tmpDir, "workdir")
|
|
os.MkdirAll(cwdPath, 0755)
|
|
t.Chdir(cwdPath)
|
|
|
|
rootCmd.SetArgs([]string{"init", "--server", "--database", uniqueTestDBName(t), "--prefix", "beadsdir-test", "--quiet"})
|
|
if err := rootCmd.Execute(); err != nil {
|
|
t.Fatalf("Init with BEADS_DIR failed: %v", err)
|
|
}
|
|
|
|
expectedDBPath := filepath.Join(beadsDirPath, "dolt")
|
|
if info, err := os.Stat(expectedDBPath); os.IsNotExist(err) {
|
|
t.Errorf("Dolt database was not created at BEADS_DIR path: %s", expectedDBPath)
|
|
} else if !info.IsDir() {
|
|
t.Errorf("Expected %s to be a directory", expectedDBPath)
|
|
}
|
|
|
|
cwdDBPath := filepath.Join(cwdPath, ".beads", "dolt")
|
|
if _, err := os.Stat(cwdDBPath); err == nil {
|
|
t.Errorf("Database should NOT have been created at CWD: %s", cwdDBPath)
|
|
}
|
|
|
|
store, err := openExistingTestDB(t, expectedDBPath)
|
|
if err != nil {
|
|
t.Fatalf("Failed to open database at BEADS_DIR: %v", err)
|
|
}
|
|
defer store.Close()
|
|
|
|
ctx := context.Background()
|
|
prefix, err := store.GetConfig(ctx, "issue_prefix")
|
|
if err != nil {
|
|
t.Fatalf("Failed to get prefix from database: %v", err)
|
|
}
|
|
if prefix != "beadsdir-test" {
|
|
t.Errorf("Expected prefix 'beadsdir-test', got %q", prefix)
|
|
}
|
|
})
|
|
|
|
// NFR-001: existing behavior unchanged when BEADS_DIR not set
|
|
t.Run("WithoutBeadsDirNoBehaviorChange", func(t *testing.T) {
|
|
resetBeadsDirState(t)
|
|
|
|
os.Unsetenv("BEADS_DIR")
|
|
beads.ResetCaches()
|
|
git.ResetCaches()
|
|
|
|
tmpDir := t.TempDir()
|
|
t.Chdir(tmpDir)
|
|
|
|
rootCmd.SetArgs([]string{"init", "--server", "--database", uniqueTestDBName(t), "--prefix", "no-beadsdir", "--quiet"})
|
|
if err := rootCmd.Execute(); err != nil {
|
|
t.Fatalf("Init without BEADS_DIR failed: %v", err)
|
|
}
|
|
|
|
expectedDBPath := filepath.Join(tmpDir, ".beads", "dolt")
|
|
if info, err := os.Stat(expectedDBPath); os.IsNotExist(err) {
|
|
t.Errorf("Dolt database was not created at default CWD/.beads path: %s", expectedDBPath)
|
|
} else if !info.IsDir() {
|
|
t.Errorf("Expected %s to be a directory", expectedDBPath)
|
|
}
|
|
|
|
store, err := openExistingTestDB(t, expectedDBPath)
|
|
if err != nil {
|
|
t.Fatalf("Failed to open database: %v", err)
|
|
}
|
|
defer store.Close()
|
|
|
|
ctx := context.Background()
|
|
prefix, err := store.GetConfig(ctx, "issue_prefix")
|
|
if err != nil {
|
|
t.Fatalf("Failed to get prefix from database: %v", err)
|
|
}
|
|
if prefix != "no-beadsdir" {
|
|
t.Errorf("Expected prefix 'no-beadsdir', got %q", prefix)
|
|
}
|
|
})
|
|
|
|
// Worktree bypass: BEADS_DIR skips the worktree guard and git init
|
|
t.Run("WorktreeBypassWhenBeadsDirSet", func(t *testing.T) {
|
|
if runtime.GOOS == "windows" {
|
|
t.Skip("Skipping worktree test on Windows")
|
|
}
|
|
|
|
resetBeadsDirState(t)
|
|
|
|
tmpDir := t.TempDir()
|
|
|
|
// Create a main git repo with an initial commit (required for worktrees)
|
|
mainRepo := filepath.Join(tmpDir, "main-repo")
|
|
if err := os.MkdirAll(mainRepo, 0755); err != nil {
|
|
t.Fatalf("Failed to create main repo dir: %v", err)
|
|
}
|
|
runGit := func(dir string, args ...string) {
|
|
t.Helper()
|
|
cmd := exec.Command("git", args...)
|
|
cmd.Dir = dir
|
|
out, err := cmd.CombinedOutput()
|
|
if err != nil {
|
|
t.Fatalf("git %v in %s failed: %v\n%s", args, dir, err, out)
|
|
}
|
|
}
|
|
runGit(mainRepo, "init")
|
|
runGit(mainRepo, "config", "user.email", "test@test.com")
|
|
runGit(mainRepo, "config", "user.name", "Test")
|
|
runGit(mainRepo, "commit", "--allow-empty", "-m", "initial")
|
|
|
|
// Create a worktree
|
|
worktreeDir := filepath.Join(tmpDir, "my-worktree")
|
|
runGit(mainRepo, "worktree", "add", worktreeDir, "-b", "test-wt")
|
|
|
|
// Set BEADS_DIR to a standalone location outside the repo
|
|
beadsDirPath := filepath.Join(tmpDir, "standalone", ".beads")
|
|
if err := os.MkdirAll(filepath.Dir(beadsDirPath), 0755); err != nil {
|
|
t.Fatalf("Failed to create standalone dir: %v", err)
|
|
}
|
|
os.Setenv("BEADS_DIR", beadsDirPath)
|
|
t.Cleanup(func() { os.Unsetenv("BEADS_DIR") })
|
|
beads.ResetCaches()
|
|
git.ResetCaches()
|
|
|
|
// cd into the worktree — without BEADS_DIR this would fail
|
|
t.Chdir(worktreeDir)
|
|
|
|
rootCmd.SetArgs([]string{"init", "--prefix", "wt-bypass", "--skip-hooks", "--quiet"})
|
|
err := rootCmd.Execute()
|
|
if err != nil {
|
|
t.Fatalf("Init with BEADS_DIR from worktree should succeed, got: %v", err)
|
|
}
|
|
|
|
// Verify database was created at BEADS_DIR, not in the worktree
|
|
expectedDBPath := filepath.Join(beadsDirPath, "dolt")
|
|
if _, statErr := os.Stat(expectedDBPath); os.IsNotExist(statErr) {
|
|
t.Errorf("Dolt database was not created at BEADS_DIR path: %s", expectedDBPath)
|
|
}
|
|
|
|
worktreeDBPath := filepath.Join(worktreeDir, ".beads", "dolt")
|
|
if _, statErr := os.Stat(worktreeDBPath); statErr == nil {
|
|
t.Errorf("Database should NOT have been created in worktree: %s", worktreeDBPath)
|
|
}
|
|
})
|
|
|
|
// Precedence: BEADS_DB > BEADS_DIR
|
|
t.Run("BEADS_DB_OverridesBeadsDir", func(t *testing.T) {
|
|
t.Skip("BEADS_DB env var does not control Dolt store location; Dolt always uses .beads/dolt/")
|
|
resetBeadsDirState(t)
|
|
|
|
beadsDirTarget := t.TempDir()
|
|
beadsDBTarget := t.TempDir()
|
|
|
|
beadsDirBeads := filepath.Join(beadsDirTarget, ".beads")
|
|
if err := os.MkdirAll(beadsDirBeads, 0750); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
beadsDBPath := filepath.Join(beadsDBTarget, "override.db")
|
|
|
|
t.Setenv("BEADS_DIR", beadsDirBeads)
|
|
t.Setenv("BEADS_DB", beadsDBPath)
|
|
|
|
tmpDir := t.TempDir()
|
|
t.Chdir(tmpDir)
|
|
|
|
rootCmd.SetArgs([]string{"init", "--prefix", "precedence", "--quiet"})
|
|
if err := rootCmd.Execute(); err != nil {
|
|
t.Fatalf("Init with BEADS_DB + BEADS_DIR failed: %v", err)
|
|
}
|
|
|
|
if _, err := os.Stat(beadsDBPath); os.IsNotExist(err) {
|
|
t.Errorf("Database was NOT created at BEADS_DB path: %s", beadsDBPath)
|
|
}
|
|
|
|
beadsDirDBPath := filepath.Join(beadsDirBeads, beads.CanonicalDatabaseName)
|
|
if _, err := os.Stat(beadsDirDBPath); err == nil {
|
|
t.Errorf("Database was incorrectly created at BEADS_DIR path: %s (BEADS_DB should override)", beadsDirDBPath)
|
|
}
|
|
|
|
store, err := openExistingTestDB(t, beadsDBPath)
|
|
if err != nil {
|
|
t.Fatalf("Failed to open database: %v", err)
|
|
}
|
|
defer store.Close()
|
|
|
|
ctx := context.Background()
|
|
prefix, err := store.GetConfig(ctx, "issue_prefix")
|
|
if err != nil {
|
|
t.Fatalf("Failed to get prefix from database: %v", err)
|
|
}
|
|
if prefix != "precedence" {
|
|
t.Errorf("Expected prefix 'precedence', got %q", prefix)
|
|
}
|
|
})
|
|
}
|
|
|
|
// TestInit_WithBEADS_DIR_DoltBackend verifies that bd init with Dolt backend
|
|
// creates the database at BEADS_DIR when the environment variable is set.
|
|
// This tests requirements FR-002 for Dolt backend.
|
|
func TestInit_WithBEADS_DIR_DoltBackend(t *testing.T) {
|
|
// Skip on Windows
|
|
if runtime.GOOS == "windows" {
|
|
t.Skip("Skipping BEADS_DIR Dolt test on Windows")
|
|
}
|
|
|
|
testutil.RequireDoltBinary(t)
|
|
|
|
// Reset global state
|
|
origDBPath := dbPath
|
|
defer func() { dbPath = origDBPath }()
|
|
dbPath = ""
|
|
|
|
// Save and restore BEADS_DIR
|
|
origBeadsDir := os.Getenv("BEADS_DIR")
|
|
defer func() {
|
|
if origBeadsDir != "" {
|
|
os.Setenv("BEADS_DIR", origBeadsDir)
|
|
} else {
|
|
os.Unsetenv("BEADS_DIR")
|
|
}
|
|
beads.ResetCaches()
|
|
git.ResetCaches()
|
|
}()
|
|
|
|
// Reset Cobra flags
|
|
initCmd.Flags().Set("prefix", "")
|
|
initCmd.Flags().Set("quiet", "false")
|
|
initCmd.Flags().Set("backend", "")
|
|
|
|
tmpDir := t.TempDir()
|
|
|
|
// Create external BEADS_DIR location
|
|
beadsDirPath := filepath.Join(tmpDir, "external", ".beads")
|
|
os.MkdirAll(filepath.Dir(beadsDirPath), 0755)
|
|
|
|
os.Setenv("BEADS_DIR", beadsDirPath)
|
|
beads.ResetCaches()
|
|
git.ResetCaches()
|
|
|
|
// Change to a different working directory
|
|
cwdPath := filepath.Join(tmpDir, "workdir")
|
|
os.MkdirAll(cwdPath, 0755)
|
|
t.Chdir(cwdPath)
|
|
|
|
// Run bd init with Dolt backend
|
|
rootCmd.SetArgs([]string{"init", "--prefix", "dolt-test", "--quiet"})
|
|
if err := rootCmd.Execute(); err != nil {
|
|
t.Fatalf("Init with BEADS_DIR and Dolt backend failed: %v", err)
|
|
}
|
|
|
|
// In embedded mode (default), the engine creates .beads/embeddeddolt/ —
|
|
// .beads/dolt/ should NOT be created (GH#2903).
|
|
unexpectedDoltPath := filepath.Join(beadsDirPath, "dolt")
|
|
if _, err := os.Stat(unexpectedDoltPath); err == nil {
|
|
t.Errorf("Empty .beads/dolt/ should not be created in embedded mode: %s", unexpectedDoltPath)
|
|
}
|
|
|
|
// Verify database was NOT created at CWD
|
|
cwdDoltPath := filepath.Join(cwdPath, ".beads", "dolt")
|
|
if _, err := os.Stat(cwdDoltPath); err == nil {
|
|
t.Errorf("Dolt database should NOT have been created at CWD: %s", cwdDoltPath)
|
|
}
|
|
}
|
|
|
|
// Note: TestInit_WithoutBEADS_DIR_NoBehaviorChange and TestInit_BEADS_DB_OverridesBEADS_DIR
|
|
// are now subtests of TestInitBEADS_DIR above.
|
|
|
|
// TestInitDoltMetadata verifies that bd init --backend dolt writes and persists
|
|
// all 3 tracking metadata fields (bd_version, repo_id, clone_id) via verifyMetadata.
|
|
// Covers FR-001, FR-002, FR-003, FR-004.
|
|
func TestInitDoltMetadata(t *testing.T) {
|
|
skipIfNoDolt(t)
|
|
resetInitFlagsForServerInit(t)
|
|
if runtime.GOOS == "windows" {
|
|
t.Skip("Skipping Dolt metadata test on Windows")
|
|
}
|
|
|
|
saveAndRestoreGlobals(t)
|
|
dbPath = ""
|
|
|
|
// Reset caches to avoid stale state
|
|
beads.ResetCaches()
|
|
git.ResetCaches()
|
|
t.Cleanup(func() {
|
|
beads.ResetCaches()
|
|
git.ResetCaches()
|
|
})
|
|
|
|
// Reset Cobra flags
|
|
initCmd.Flags().Set("prefix", "")
|
|
initCmd.Flags().Set("quiet", "false")
|
|
initCmd.Flags().Set("backend", "")
|
|
|
|
tmpDir := newGitRepo(t)
|
|
t.Chdir(tmpDir)
|
|
|
|
// Add remote.origin.url so ComputeRepoID succeeds
|
|
_ = runCommandInDir(tmpDir, "git", "config", "remote.origin.url", "https://github.com/test/repo.git")
|
|
|
|
database := uniqueTestDBName(t)
|
|
rootCmd.SetArgs([]string{"init", "--server", "--database", database, "--prefix", "test", "--quiet"})
|
|
if err := rootCmd.Execute(); err != nil {
|
|
t.Fatalf("init --backend dolt failed: %v", err)
|
|
}
|
|
|
|
// Open the dolt store to verify metadata was written
|
|
ctx := context.Background()
|
|
doltPath := filepath.Join(tmpDir, ".beads", "dolt")
|
|
doltStore, err := openDoltStoreForTest(t, ctx, doltPath, database)
|
|
if err != nil {
|
|
t.Fatalf("failed to open dolt store for verification: %v", err)
|
|
}
|
|
defer doltStore.Close()
|
|
|
|
// FR-001: bd_version must be written
|
|
bdVersion, err := doltStore.GetLocalMetadata(ctx, "bd_version")
|
|
if err != nil {
|
|
t.Fatalf("GetLocalMetadata(bd_version) failed: %v", err)
|
|
}
|
|
if bdVersion == "" {
|
|
t.Error("bd_version local metadata was not written")
|
|
}
|
|
|
|
// FR-002: repo_id must be written (git repo with remote configured)
|
|
repoID, err := doltStore.GetMetadata(ctx, "repo_id")
|
|
if err != nil {
|
|
t.Fatalf("GetMetadata(repo_id) failed: %v", err)
|
|
}
|
|
if repoID == "" {
|
|
t.Error("repo_id metadata was not written")
|
|
}
|
|
|
|
// FR-003: clone_id must be written
|
|
cloneID, err := doltStore.GetMetadata(ctx, "clone_id")
|
|
if err != nil {
|
|
t.Fatalf("GetMetadata(clone_id) failed: %v", err)
|
|
}
|
|
if cloneID == "" {
|
|
t.Error("clone_id metadata was not written")
|
|
}
|
|
}
|
|
|
|
// openDoltStoreForTest opens an existing Dolt store for read-only verification in tests.
|
|
func openDoltStoreForTest(t *testing.T, ctx context.Context, doltPath, dbName string) (*dolt.DoltStore, error) {
|
|
t.Helper()
|
|
return dolt.New(ctx, &dolt.Config{
|
|
Path: doltPath,
|
|
Database: dbName,
|
|
ReadOnly: true,
|
|
})
|
|
}
|
|
|
|
// TestVerifyMetadataSuccess verifies that verifyMetadata writes and reads back metadata.
|
|
// Note: Failure path tests (write errors, read-back mismatches) were removed because
|
|
// verifyMetadata now takes *dolt.DoltStore (concrete type), making interface-based
|
|
// mocking impossible. The failure paths are simple error-to-stderr logic.
|
|
func TestVerifyMetadataSuccess(t *testing.T) {
|
|
skipIfNoDolt(t)
|
|
ctx := context.Background()
|
|
|
|
tmpDir := t.TempDir()
|
|
testDB := filepath.Join(tmpDir, "test.db")
|
|
store := newTestStore(t, testDB)
|
|
defer store.Close()
|
|
|
|
ok := verifyMetadata(ctx, store, "test_key", "test_value")
|
|
if !ok {
|
|
t.Error("verifyMetadata should return true on success")
|
|
}
|
|
// Verify the value was actually written
|
|
val, err := store.GetMetadata(ctx, "test_key")
|
|
if err != nil {
|
|
t.Fatalf("GetMetadata failed: %v", err)
|
|
}
|
|
if val != "test_value" {
|
|
t.Errorf("expected 'test_value', got %q", val)
|
|
}
|
|
}
|
|
|
|
// TestInitDoltMetadataNoGit verifies that bd init outside a git repo gracefully
|
|
// skips repo_id while still writing bd_version and clone_id.
|
|
// Verifies warning output; actual metadata persistence checked by e2e tests.
|
|
// Covers FR-015 (skip repo_id outside git).
|
|
func TestInitDoltMetadataNoGit(t *testing.T) {
|
|
skipIfNoDolt(t)
|
|
resetInitFlagsForServerInit(t)
|
|
if runtime.GOOS == "windows" {
|
|
t.Skip("Skipping Dolt metadata test on Windows")
|
|
}
|
|
|
|
saveAndRestoreGlobals(t)
|
|
dbPath = ""
|
|
|
|
beads.ResetCaches()
|
|
git.ResetCaches()
|
|
t.Cleanup(func() {
|
|
beads.ResetCaches()
|
|
git.ResetCaches()
|
|
})
|
|
|
|
// Reset Cobra flags
|
|
initCmd.Flags().Set("prefix", "")
|
|
initCmd.Flags().Set("quiet", "false")
|
|
initCmd.Flags().Set("backend", "")
|
|
|
|
// Create temp dir WITHOUT git init — bd init will create one,
|
|
// but there will be no remote configured so upstream warning is expected.
|
|
tmpDir := t.TempDir()
|
|
t.Chdir(tmpDir)
|
|
|
|
// Run init in a non-git directory (bd init will create git repo internally)
|
|
rootCmd.SetArgs([]string{"init", "--server", "--database", uniqueTestDBName(t), "--prefix", "nogit"})
|
|
if err := rootCmd.Execute(); err != nil {
|
|
t.Fatalf("init --prefix nogit failed: %v", err)
|
|
}
|
|
|
|
// Note: no upstream/repository ID warning expected here because bd init
|
|
// creates a brand-new git repo with no remotes, and the upstream warning
|
|
// is intentionally skipped for repos with no remotes (not noise-worthy).
|
|
|
|
// Verify .beads/dolt directory was created (init succeeded)
|
|
doltPath := filepath.Join(tmpDir, ".beads", "dolt")
|
|
if info, err := os.Stat(doltPath); os.IsNotExist(err) {
|
|
t.Errorf("Dolt database directory was not created: %s", doltPath)
|
|
} else if !info.IsDir() {
|
|
t.Errorf("Expected Dolt path to be a directory: %s", doltPath)
|
|
}
|
|
|
|
// Verify no SQLite database was created (backend-specific)
|
|
sqlitePath := filepath.Join(tmpDir, ".beads", "beads.db")
|
|
if _, err := os.Stat(sqlitePath); err == nil {
|
|
t.Errorf("unexpected sqlite database created in dolt mode")
|
|
}
|
|
}
|
|
|
|
func TestInitServerModeWritesDoltCompatibilityMarker(t *testing.T) {
|
|
skipIfNoDolt(t)
|
|
saveAndRestoreGlobals(t)
|
|
ensureCleanGlobalState(t)
|
|
dbPath = ""
|
|
store = nil
|
|
|
|
tmpDir := t.TempDir()
|
|
t.Chdir(tmpDir)
|
|
|
|
beadsDir := filepath.Join(tmpDir, ".beads")
|
|
doltDir := filepath.Join(beadsDir, "dolt")
|
|
if err := os.MkdirAll(beadsDir, 0o700); err != nil {
|
|
t.Fatalf("creating beads dir: %v", err)
|
|
}
|
|
if err := os.MkdirAll(filepath.Join(doltDir, ".dolt"), 0o750); err != nil {
|
|
t.Fatalf("creating simulated server data dir: %v", err)
|
|
}
|
|
// A current-era version witness: without it the legacy-upgrade guard
|
|
// reads a non-empty .beads/dolt as a pre-1.0 workspace and refuses.
|
|
if err := writeLocalVersion(filepath.Join(beadsDir, localVersionFile), Version); err != nil {
|
|
t.Fatalf("writing version witness: %v", err)
|
|
}
|
|
|
|
database := uniqueTestDBName(t)
|
|
t.Cleanup(func() {
|
|
dropTestDatabase(database, testDoltServerPort)
|
|
})
|
|
|
|
rootCmd.SetArgs([]string{
|
|
"init",
|
|
"--server",
|
|
"--external",
|
|
"--server-host", "127.0.0.1",
|
|
"--server-port", fmt.Sprintf("%d", testDoltServerPort),
|
|
"--database", database,
|
|
"--prefix", "marker",
|
|
"--quiet",
|
|
"--skip-hooks",
|
|
"--skip-agents",
|
|
})
|
|
|
|
if err := rootCmd.Execute(); err != nil {
|
|
t.Fatalf("server init failed: %v", err)
|
|
}
|
|
|
|
markerPath := filepath.Join(doltDir, ".bd-dolt-ok")
|
|
if _, err := os.Stat(markerPath); err != nil {
|
|
t.Fatalf("expected server init to write %s: %v", markerPath, err)
|
|
}
|
|
}
|
|
|
|
func TestInitServerModeWarnsOnMarkerFailureInQuietMode(t *testing.T) {
|
|
skipIfNoDolt(t)
|
|
saveAndRestoreGlobals(t)
|
|
ensureCleanGlobalState(t)
|
|
dbPath = ""
|
|
store = nil
|
|
|
|
tmpDir := t.TempDir()
|
|
t.Chdir(tmpDir)
|
|
|
|
beadsDir := filepath.Join(tmpDir, ".beads")
|
|
doltDir := filepath.Join(beadsDir, "dolt")
|
|
if err := os.MkdirAll(doltDir, 0o700); err != nil {
|
|
t.Fatalf("creating dolt dir: %v", err)
|
|
}
|
|
if err := os.WriteFile(filepath.Join(doltDir, ".dolt"), []byte("not a dir"), 0o600); err != nil {
|
|
t.Fatalf("creating invalid dot-dolt marker: %v", err)
|
|
}
|
|
// As in TestInitServerModeWritesDoltCompatibilityMarker: a current-era
|
|
// witness keeps the legacy-upgrade guard from refusing the seeded root.
|
|
if err := writeLocalVersion(filepath.Join(beadsDir, localVersionFile), Version); err != nil {
|
|
t.Fatalf("writing version witness: %v", err)
|
|
}
|
|
|
|
database := uniqueTestDBName(t)
|
|
t.Cleanup(func() {
|
|
dropTestDatabase(database, testDoltServerPort)
|
|
})
|
|
|
|
oldStderr := os.Stderr
|
|
r, w, err := os.Pipe()
|
|
if err != nil {
|
|
t.Fatalf("pipe stderr: %v", err)
|
|
}
|
|
os.Stderr = w
|
|
defer func() {
|
|
os.Stderr = oldStderr
|
|
}()
|
|
|
|
rootCmd.SetArgs([]string{
|
|
"init",
|
|
"--server",
|
|
"--external",
|
|
"--server-host", "127.0.0.1",
|
|
"--server-port", fmt.Sprintf("%d", testDoltServerPort),
|
|
"--database", database,
|
|
"--prefix", "marker",
|
|
"--quiet",
|
|
"--skip-hooks",
|
|
"--skip-agents",
|
|
})
|
|
|
|
if err := rootCmd.Execute(); err != nil {
|
|
w.Close()
|
|
t.Fatalf("server init failed: %v", err)
|
|
}
|
|
|
|
if err := w.Close(); err != nil {
|
|
t.Fatalf("close stderr writer: %v", err)
|
|
}
|
|
var stderr bytes.Buffer
|
|
if _, err := stderr.ReadFrom(r); err != nil {
|
|
t.Fatalf("read stderr: %v", err)
|
|
}
|
|
|
|
if !strings.Contains(stderr.String(), "Warning: failed to write Dolt compatibility marker") {
|
|
t.Fatalf("expected marker warning in stderr, got:\n%s", stderr.String())
|
|
}
|
|
if !strings.Contains(stderr.String(), doltDir) {
|
|
t.Fatalf("expected marker warning to include dolt dir %s, got:\n%s", doltDir, stderr.String())
|
|
}
|
|
}
|
|
|
|
func setupBareParentInitWorktree(t *testing.T) (string, string) {
|
|
t.Helper()
|
|
|
|
tmpDir := t.TempDir()
|
|
bareDir := filepath.Join(tmpDir, "repo.git")
|
|
mainWorktreeDir := filepath.Join(tmpDir, "main")
|
|
featureWorktreeDir := filepath.Join(tmpDir, "feature")
|
|
|
|
runGit := func(dir string, args ...string) {
|
|
t.Helper()
|
|
cmd := exec.Command("git", args...)
|
|
cmd.Dir = dir
|
|
out, err := cmd.CombinedOutput()
|
|
if err != nil {
|
|
t.Fatalf("git %v in %s failed: %v\n%s", args, dir, err, out)
|
|
}
|
|
}
|
|
|
|
runGit(tmpDir, "init", "--bare", bareDir)
|
|
runGit(tmpDir, "--git-dir", bareDir, "symbolic-ref", "HEAD", "refs/heads/main")
|
|
runGit(tmpDir, "--git-dir", bareDir, "config", "user.email", "test@example.com")
|
|
runGit(tmpDir, "--git-dir", bareDir, "config", "user.name", "Test User")
|
|
emptyTreeCmd := exec.Command("git", "--git-dir", bareDir, "hash-object", "-t", "tree", "/dev/null")
|
|
emptyTreeCmd.Dir = tmpDir
|
|
emptyTreeOut, err := emptyTreeCmd.CombinedOutput()
|
|
if err != nil {
|
|
t.Fatalf("git hash-object failed: %v\n%s", err, emptyTreeOut)
|
|
}
|
|
emptyTree := strings.TrimSpace(string(emptyTreeOut))
|
|
commitCmd := exec.Command("git", "--git-dir", bareDir, "commit-tree", "-m", "Initial commit", emptyTree)
|
|
commitCmd.Dir = tmpDir
|
|
commitOut, err := commitCmd.CombinedOutput()
|
|
if err != nil {
|
|
t.Fatalf("git commit-tree failed: %v\n%s", err, commitOut)
|
|
}
|
|
initCommit := strings.TrimSpace(string(commitOut))
|
|
runGit(tmpDir, "--git-dir", bareDir, "update-ref", "HEAD", initCommit)
|
|
runGit(tmpDir, "--git-dir", bareDir, "worktree", "add", mainWorktreeDir, "main")
|
|
runGit(mainWorktreeDir, "branch", "feature")
|
|
runGit(tmpDir, "--git-dir", bareDir, "worktree", "add", featureWorktreeDir, "feature")
|
|
|
|
return bareDir, featureWorktreeDir
|
|
}
|
|
|
|
// TestInitDatabaseFlag tests the --database flag for bd init.
|
|
// Uses subprocess execution because:
|
|
// - init manipulates extensive Cobra global state that's difficult to reset
|
|
// - init validation paths call os.Exit(1), which kills in-process tests
|
|
//
|
|
// Each subtest runs bd init in a temp directory and verifies metadata.json.
|
|
func TestInitDatabaseFlag(t *testing.T) {
|
|
skipIfNoDolt(t)
|
|
bd := buildBDForInitTests(t)
|
|
|
|
t.Run("metadata_written", func(t *testing.T) {
|
|
tmpDir := t.TempDir()
|
|
|
|
// Run init with --database to specify a pre-existing database name
|
|
cmd := exec.Command(bd, "init", "--server", "--database", "myapp_production", "--quiet")
|
|
cmd.Dir = tmpDir
|
|
cmd.Env = os.Environ()
|
|
out, err := cmd.CombinedOutput()
|
|
if err != nil {
|
|
t.Fatalf("bd init --database failed: %v\n%s", err, out)
|
|
}
|
|
|
|
// Verify metadata.json contains the correct database name
|
|
beadsDir := filepath.Join(tmpDir, ".beads")
|
|
cfg, err := configfile.Load(beadsDir)
|
|
if err != nil {
|
|
t.Fatalf("Failed to load metadata.json: %v", err)
|
|
}
|
|
if cfg == nil {
|
|
t.Fatal("metadata.json not found")
|
|
}
|
|
|
|
if cfg.DoltDatabase != "myapp_production" {
|
|
t.Errorf("Expected DoltDatabase %q, got %q", "myapp_production", cfg.DoltDatabase)
|
|
}
|
|
if cfg.DoltMode != configfile.DoltModeServer {
|
|
t.Errorf("Expected DoltMode %q, got %q", configfile.DoltModeServer, cfg.DoltMode)
|
|
}
|
|
})
|
|
|
|
t.Run("BareParentWorktreeAutoInit", func(t *testing.T) {
|
|
skipIfNoDolt(t)
|
|
if runtime.GOOS == "windows" {
|
|
t.Skip("Skipping worktree test on Windows")
|
|
}
|
|
|
|
origDBPath := dbPath
|
|
t.Cleanup(func() {
|
|
dbPath = origDBPath
|
|
beads.ResetCaches()
|
|
git.ResetCaches()
|
|
})
|
|
dbPath = ""
|
|
beads.ResetCaches()
|
|
git.ResetCaches()
|
|
bd := buildBDForInitTests(t)
|
|
bareDir, worktreeDir := setupBareParentInitWorktree(t)
|
|
bareBeadsDir := filepath.Join(bareDir, ".beads")
|
|
|
|
// Shared-server init daemonizes a dolt sql-server that nothing here
|
|
// stopped; it outlived the suite whose temp HOME it served
|
|
// (wy-j2zc8q). Registered before the first subprocess so the
|
|
// t.Fatalf paths are covered too.
|
|
stopSharedServerCleanup(t)
|
|
|
|
// The shared server's own port: the inherited BEADS_DOLT_SERVER_PORT
|
|
// is the suite's test server, which a shared-server start refuses as
|
|
// another project's, and without one it would default to 3308.
|
|
sharedEnv := sharedServerTestEnv(t)
|
|
cmd := exec.Command(bd, "init", "--prefix", "bare-fallback", "--skip-hooks", "--quiet")
|
|
cmd.Dir = worktreeDir
|
|
cmd.Env = sharedEnv
|
|
out, err := cmd.CombinedOutput()
|
|
if err != nil {
|
|
t.Fatalf("bd init from bare-parent worktree failed: %v\n%s", err, out)
|
|
}
|
|
|
|
if _, err := os.Stat(filepath.Join(bareBeadsDir, "metadata.json")); err != nil {
|
|
t.Fatalf("expected bare parent metadata.json to exist: %v", err)
|
|
}
|
|
if _, err := os.Stat(filepath.Join(worktreeDir, ".beads")); !os.IsNotExist(err) {
|
|
t.Fatalf("worktree should not get a local .beads directory, stat err=%v", err)
|
|
}
|
|
|
|
retry := exec.Command(bd, "init", "--prefix", "bare-fallback", "--skip-hooks", "--quiet")
|
|
retry.Dir = worktreeDir
|
|
retry.Env = sharedEnv
|
|
retryOut, retryErr := retry.CombinedOutput()
|
|
if retryErr == nil {
|
|
t.Fatal("expected second bd init to fail against existing bare-parent .beads")
|
|
}
|
|
if !strings.Contains(string(retryOut), "already initialized") && !strings.Contains(string(retryOut), "already exists") {
|
|
t.Fatalf("expected existing-data guard on second init, got:\n%s", retryOut)
|
|
}
|
|
})
|
|
|
|
t.Run("with_prefix", func(t *testing.T) {
|
|
tmpDir := t.TempDir()
|
|
|
|
// Run init with both --database and --prefix
|
|
// --database should override prefix for DB name, but prefix still sets issue_prefix
|
|
cmd := exec.Command(bd, "init", "--server", "--database", "shared_db", "--prefix", "team-alpha", "--quiet")
|
|
cmd.Dir = tmpDir
|
|
cmd.Env = os.Environ()
|
|
out, err := cmd.CombinedOutput()
|
|
if err != nil {
|
|
t.Fatalf("bd init --database --prefix failed: %v\n%s", err, out)
|
|
}
|
|
|
|
// Verify metadata.json
|
|
beadsDir := filepath.Join(tmpDir, ".beads")
|
|
cfg, err := configfile.Load(beadsDir)
|
|
if err != nil {
|
|
t.Fatalf("Failed to load metadata.json: %v", err)
|
|
}
|
|
if cfg == nil {
|
|
t.Fatal("metadata.json not found")
|
|
}
|
|
|
|
// --database overrides the SQL database name
|
|
if cfg.DoltDatabase != "shared_db" {
|
|
t.Errorf("Expected DoltDatabase %q (from --database), got %q", "shared_db", cfg.DoltDatabase)
|
|
}
|
|
|
|
// Verify the database was opened and issue_prefix was set
|
|
// by reopening the store and checking config
|
|
dbPath := filepath.Join(beadsDir, "dolt")
|
|
s, err := openExistingTestDB(t, dbPath)
|
|
if err != nil {
|
|
t.Fatalf("Failed to reopen database: %v", err)
|
|
}
|
|
defer s.Close()
|
|
|
|
ctx := context.Background()
|
|
issuePrefix, err := s.GetConfig(ctx, "issue_prefix")
|
|
if err != nil {
|
|
t.Fatalf("Failed to get issue_prefix: %v", err)
|
|
}
|
|
if issuePrefix != "team-alpha" {
|
|
t.Errorf("Expected issue_prefix %q (from --prefix), got %q", "team-alpha", issuePrefix)
|
|
}
|
|
})
|
|
|
|
t.Run("server_config_in_metadata", func(t *testing.T) {
|
|
tmpDir := t.TempDir()
|
|
|
|
// Run init with --database
|
|
cmd := exec.Command(bd, "init", "--server", "--database", "test_server_cfg", "--quiet")
|
|
cmd.Dir = tmpDir
|
|
cmd.Env = os.Environ()
|
|
out, err := cmd.CombinedOutput()
|
|
if err != nil {
|
|
t.Fatalf("bd init --database failed: %v\n%s", err, out)
|
|
}
|
|
|
|
// Verify metadata.json has both dolt_database and dolt_mode: server
|
|
beadsDir := filepath.Join(tmpDir, ".beads")
|
|
cfg, err := configfile.Load(beadsDir)
|
|
if err != nil {
|
|
t.Fatalf("Failed to load metadata.json: %v", err)
|
|
}
|
|
if cfg == nil {
|
|
t.Fatal("metadata.json not found")
|
|
}
|
|
|
|
if cfg.DoltDatabase != "test_server_cfg" {
|
|
t.Errorf("Expected DoltDatabase %q, got %q", "test_server_cfg", cfg.DoltDatabase)
|
|
}
|
|
if cfg.DoltMode != configfile.DoltModeServer {
|
|
t.Errorf("Expected DoltMode %q, got %q", configfile.DoltModeServer, cfg.DoltMode)
|
|
}
|
|
if cfg.Backend != configfile.BackendDolt {
|
|
t.Errorf("Expected Backend %q, got %q", configfile.BackendDolt, cfg.Backend)
|
|
}
|
|
})
|
|
|
|
t.Run("shared_server_flag_selects_server_mode", func(t *testing.T) {
|
|
tmpDir := t.TempDir()
|
|
|
|
// --shared-server starts (daemonizes) the shared server: give it a
|
|
// free port of its own (see sharedServerTestEnv) and stop it after.
|
|
port, err := testutil.FindFreePort()
|
|
if err != nil {
|
|
t.Fatalf("find free port: %v", err)
|
|
}
|
|
stopSharedServerCleanup(t)
|
|
cmd := exec.Command(bd, "init", "--shared-server", "--prefix", "shared-mode-test", "--skip-hooks")
|
|
cmd.Dir = tmpDir
|
|
cmd.Env = append(os.Environ(), "BEADS_DOLT_SERVER_PORT="+strconv.Itoa(port))
|
|
out, err := cmd.CombinedOutput()
|
|
if err != nil {
|
|
t.Fatalf("bd init --shared-server failed: %v\n%s", err, out)
|
|
}
|
|
|
|
beadsDir := filepath.Join(tmpDir, ".beads")
|
|
cfg, err := configfile.Load(beadsDir)
|
|
if err != nil {
|
|
t.Fatalf("Failed to load metadata.json: %v", err)
|
|
}
|
|
if cfg == nil {
|
|
t.Fatal("metadata.json not found")
|
|
}
|
|
|
|
if cfg.DoltMode != configfile.DoltModeServer {
|
|
t.Errorf("Expected DoltMode %q, got %q", configfile.DoltModeServer, cfg.DoltMode)
|
|
}
|
|
|
|
configYAML, err := os.ReadFile(filepath.Join(beadsDir, "config.yaml"))
|
|
if err != nil {
|
|
t.Fatalf("Failed to read config.yaml: %v", err)
|
|
}
|
|
// SetYamlConfig writes dotted keys as nested YAML (dolt:
|
|
// shared-server: true); accept the old flat form as well.
|
|
var parsedYAML struct {
|
|
Dolt struct {
|
|
SharedServer bool `yaml:"shared-server"`
|
|
} `yaml:"dolt"`
|
|
Flat bool `yaml:"dolt.shared-server"`
|
|
}
|
|
if err := yaml.Unmarshal(configYAML, &parsedYAML); err != nil {
|
|
t.Fatalf("parse config.yaml: %v\n%s", err, configYAML)
|
|
}
|
|
if !parsedYAML.Dolt.SharedServer && !parsedYAML.Flat {
|
|
t.Fatalf("expected config.yaml to enable shared server, got:\n%s", configYAML)
|
|
}
|
|
|
|
outStr := string(out)
|
|
if !strings.Contains(outStr, "Shared server mode enabled") {
|
|
t.Fatalf("expected init output to mention shared server mode, got:\n%s", outStr)
|
|
}
|
|
if !strings.Contains(outStr, "Mode: server") {
|
|
t.Fatalf("expected init output to report server mode, got:\n%s", outStr)
|
|
}
|
|
if strings.Contains(outStr, "Mode: embedded") {
|
|
t.Fatalf("init output should not report embedded mode when --shared-server is set:\n%s", outStr)
|
|
}
|
|
})
|
|
|
|
t.Run("validation_invalid_name", func(t *testing.T) {
|
|
tmpDir := t.TempDir()
|
|
|
|
// Run init with an invalid database name (contains semicolon = SQL injection)
|
|
cmd := exec.Command(bd, "init", "--database", "bad;name", "--quiet")
|
|
cmd.Dir = tmpDir
|
|
cmd.Env = os.Environ()
|
|
out, err := cmd.CombinedOutput()
|
|
if err == nil {
|
|
t.Fatal("Expected error for invalid database name, but command succeeded")
|
|
}
|
|
|
|
outStr := string(out)
|
|
if !strings.Contains(outStr, "invalid database name") {
|
|
t.Errorf("Expected error to mention 'invalid database name', got: %s", outStr)
|
|
}
|
|
|
|
// Verify no .beads directory was created (early validation prevents side effects)
|
|
beadsDir := filepath.Join(tmpDir, ".beads")
|
|
if _, err := os.Stat(beadsDir); err == nil {
|
|
t.Error(".beads directory should not be created when validation fails")
|
|
}
|
|
})
|
|
|
|
t.Run("validation_name_with_spaces", func(t *testing.T) {
|
|
tmpDir := t.TempDir()
|
|
|
|
// Database name with spaces should fail validation
|
|
cmd := exec.Command(bd, "init", "--database", "my database", "--quiet")
|
|
cmd.Dir = tmpDir
|
|
cmd.Env = os.Environ()
|
|
out, err := cmd.CombinedOutput()
|
|
if err == nil {
|
|
t.Fatal("Expected error for database name with spaces, but command succeeded")
|
|
}
|
|
|
|
outStr := string(out)
|
|
if !strings.Contains(outStr, "invalid database name") {
|
|
t.Errorf("Expected error to mention 'invalid database name', got: %s", outStr)
|
|
}
|
|
})
|
|
|
|
t.Run("validation_name_with_backtick", func(t *testing.T) {
|
|
tmpDir := t.TempDir()
|
|
|
|
// Database name with backtick injection should fail validation
|
|
cmd := exec.Command(bd, "init", "--database", "db`; DROP DATABASE x; --", "--quiet")
|
|
cmd.Dir = tmpDir
|
|
cmd.Env = os.Environ()
|
|
out, err := cmd.CombinedOutput()
|
|
if err == nil {
|
|
t.Fatal("Expected error for database name with backtick injection, but command succeeded")
|
|
}
|
|
|
|
outStr := string(out)
|
|
if !strings.Contains(outStr, "invalid database name") {
|
|
t.Errorf("Expected error to mention 'invalid database name', got: %s", outStr)
|
|
}
|
|
})
|
|
}
|
|
|
|
func TestBareParentWorktreeCoreCommandsWithoutRedirect(t *testing.T) {
|
|
skipIfNoDolt(t)
|
|
if runtime.GOOS == "windows" {
|
|
t.Skip("Skipping worktree test on Windows")
|
|
}
|
|
|
|
bd := buildBDForInitTests(t)
|
|
bareDir, worktreeDir := setupBareParentInitWorktree(t)
|
|
bareBeadsDir := filepath.Join(bareDir, ".beads")
|
|
// See TestInitDatabaseFlag/BareParentWorktreeAutoInit.
|
|
sharedEnv := sharedServerTestEnv(t)
|
|
|
|
// Same daemonized shared server, same missing stop (wy-j2zc8q).
|
|
stopSharedServerCleanup(t)
|
|
|
|
initCmd := exec.Command(bd, "init", "--prefix", "bare-core", "--skip-hooks", "--quiet")
|
|
initCmd.Dir = worktreeDir
|
|
initCmd.Env = sharedEnv
|
|
if out, err := initCmd.CombinedOutput(); err != nil {
|
|
t.Fatalf("bd init from bare-parent worktree failed: %v\n%s", err, out)
|
|
}
|
|
|
|
if _, err := os.Stat(filepath.Join(bareBeadsDir, "metadata.json")); err != nil {
|
|
t.Fatalf("expected bare parent metadata.json to exist: %v", err)
|
|
}
|
|
|
|
createCmd := exec.Command(bd, "create", "bare fallback issue", "--description", "regression", "--json")
|
|
createCmd.Dir = worktreeDir
|
|
createCmd.Env = sharedEnv
|
|
createOut, err := createCmd.CombinedOutput()
|
|
if err != nil {
|
|
t.Fatalf("bd create from bare-parent worktree failed: %v\n%s", err, createOut)
|
|
}
|
|
if !strings.Contains(string(createOut), "bare fallback issue") {
|
|
t.Fatalf("bd create output did not include created title:\n%s", createOut)
|
|
}
|
|
|
|
listCmd := exec.Command(bd, "list", "--json")
|
|
listCmd.Dir = worktreeDir
|
|
listCmd.Env = sharedEnv
|
|
listOut, err := listCmd.CombinedOutput()
|
|
if err != nil {
|
|
t.Fatalf("bd list from bare-parent worktree failed: %v\n%s", err, listOut)
|
|
}
|
|
if !strings.Contains(string(listOut), "bare fallback issue") {
|
|
t.Fatalf("bd list output did not include created issue:\n%s", listOut)
|
|
}
|
|
}
|
|
|
|
// initBackendTestEnv returns the process environment with all beads-specific
|
|
// variables (BEADS_*, BD_*) removed and BEADS_DIR pinned to beadsDir. Pinning
|
|
// BEADS_DIR isolates each subtest's workspace and stops bd from walking up into
|
|
// an ambient .beads left by another test or tool; HOME is preserved so bd init's
|
|
// git bootstrap still works.
|
|
func initBackendTestEnv(beadsDir string) []string {
|
|
var env []string
|
|
for _, e := range os.Environ() {
|
|
if strings.HasPrefix(e, "BEADS_") || strings.HasPrefix(e, "BD_") {
|
|
continue
|
|
}
|
|
env = append(env, e)
|
|
}
|
|
return append(env, "BEADS_DIR="+beadsDir)
|
|
}
|
|
|
|
func TestInitBackendFlag(t *testing.T) {
|
|
bd := buildBDForInitTests(t)
|
|
|
|
// The SQLite backend was rolled back with the other alternative backends:
|
|
// init fails closed with migration guidance and writes no workspace state.
|
|
t.Run("sqlite_is_no_longer_supported", func(t *testing.T) {
|
|
tmpDir := t.TempDir()
|
|
beadsDir := filepath.Join(tmpDir, ".beads")
|
|
|
|
cmd := exec.Command(bd, "init", "--backend", "sqlite", "--quiet")
|
|
cmd.Dir = tmpDir
|
|
cmd.Env = initBackendTestEnv(beadsDir)
|
|
out, err := cmd.CombinedOutput()
|
|
if err == nil {
|
|
t.Fatalf("Expected non-zero exit for --backend=sqlite:\n%s", out)
|
|
}
|
|
outStr := string(out)
|
|
if !strings.Contains(outStr, "no longer supported") || !strings.Contains(outStr, "single engine") {
|
|
t.Errorf("Expected rollback guidance for sqlite, got: %s", outStr)
|
|
}
|
|
if _, statErr := os.Stat(beadsDir); !os.IsNotExist(statErr) {
|
|
t.Fatalf("rejected sqlite init created workspace state (stat error: %v)", statErr)
|
|
}
|
|
})
|
|
|
|
for _, backend := range []string{"postgres", "mysql"} {
|
|
t.Run(backend+"_is_no_longer_supported", func(t *testing.T) {
|
|
tmpDir := t.TempDir()
|
|
beadsDir := filepath.Join(tmpDir, ".beads")
|
|
|
|
cmd := exec.Command(bd, "init", "--backend", backend, "--quiet")
|
|
cmd.Dir = tmpDir
|
|
cmd.Env = initBackendTestEnv(beadsDir)
|
|
out, err := cmd.CombinedOutput()
|
|
if err == nil {
|
|
t.Fatalf("Expected non-zero exit for --backend=%s", backend)
|
|
}
|
|
|
|
outStr := string(out)
|
|
if !strings.Contains(outStr, "no longer supported") {
|
|
t.Errorf("Expected rollback guidance for %s, got: %s", backend, outStr)
|
|
}
|
|
if !strings.Contains(outStr, `"dolt"`) {
|
|
t.Errorf("Expected supported backend guidance for %s, got: %s", backend, outStr)
|
|
}
|
|
})
|
|
}
|
|
|
|
// A genuinely unsupported backend value is still rejected up front.
|
|
t.Run("unknown_backend_errors", func(t *testing.T) {
|
|
tmpDir := t.TempDir()
|
|
beadsDir := filepath.Join(tmpDir, ".beads")
|
|
|
|
cmd := exec.Command(bd, "init", "--backend", "mongodb", "--quiet")
|
|
cmd.Dir = tmpDir
|
|
cmd.Env = initBackendTestEnv(beadsDir)
|
|
out, err := cmd.CombinedOutput()
|
|
if err == nil {
|
|
t.Fatal("Expected non-zero exit for a genuinely unknown backend")
|
|
}
|
|
|
|
outStr := string(out)
|
|
if !strings.Contains(outStr, "unknown backend") {
|
|
t.Errorf("Expected 'unknown backend' error, got: %s", outStr)
|
|
}
|
|
})
|
|
|
|
t.Run("dolt_backend_succeeds", func(t *testing.T) {
|
|
skipIfNoDolt(t)
|
|
tmpDir := t.TempDir()
|
|
beadsDir := filepath.Join(tmpDir, ".beads")
|
|
|
|
cmd := exec.Command(bd, "init", "--backend", "dolt", "--quiet")
|
|
cmd.Dir = tmpDir
|
|
cmd.Env = initBackendTestEnv(beadsDir)
|
|
out, err := cmd.CombinedOutput()
|
|
if err != nil {
|
|
t.Fatalf("bd init --backend=dolt should succeed: %v\n%s", err, out)
|
|
}
|
|
})
|
|
|
|
t.Run("default_backend_is_dolt", func(t *testing.T) {
|
|
skipIfNoDolt(t)
|
|
tmpDir := t.TempDir()
|
|
beadsDir := filepath.Join(tmpDir, ".beads")
|
|
|
|
cmd := exec.Command(bd, "init", "--quiet")
|
|
cmd.Dir = tmpDir
|
|
cmd.Env = initBackendTestEnv(beadsDir)
|
|
out, err := cmd.CombinedOutput()
|
|
if err != nil {
|
|
t.Fatalf("bd init should default to dolt: %v\n%s", err, out)
|
|
}
|
|
|
|
// Verify metadata.json has backend: dolt
|
|
cfg, err := configfile.Load(beadsDir)
|
|
if err != nil {
|
|
t.Fatalf("Failed to load metadata.json: %v", err)
|
|
}
|
|
if cfg == nil {
|
|
t.Fatal("metadata.json not found")
|
|
}
|
|
if cfg.Backend != configfile.BackendDolt {
|
|
t.Errorf("Expected backend %q, got %q", configfile.BackendDolt, cfg.Backend)
|
|
}
|
|
})
|
|
}
|
|
|
|
// TestInitDatabaseAdoptsExistingProjectID verifies that bd init --database adopts
|
|
// the _project_id from an existing server database instead of generating a new one.
|
|
// This prevents PROJECT IDENTITY MISMATCH errors when multiple users connect to
|
|
// a shared remote Dolt server. (GH#2922)
|
|
func TestInitDatabaseAdoptsExistingProjectID(t *testing.T) {
|
|
skipIfNoDolt(t)
|
|
|
|
// Reset global state
|
|
origDBPath := dbPath
|
|
origStore := store
|
|
defer func() {
|
|
if store != nil && store != origStore {
|
|
store.Close()
|
|
}
|
|
store = origStore
|
|
dbPath = origDBPath
|
|
}()
|
|
dbPath = ""
|
|
store = nil
|
|
|
|
ctx := context.Background()
|
|
|
|
// Create a database with a known _project_id (simulates first user's init)
|
|
database := uniqueTestDBName(t)
|
|
firstBeadsDir := filepath.Join(t.TempDir(), ".beads")
|
|
if err := os.MkdirAll(firstBeadsDir, 0o755); err != nil {
|
|
t.Fatalf("mkdir: %v", err)
|
|
}
|
|
|
|
doltNewMutex.Lock()
|
|
firstStore, err := dolt.New(ctx, &dolt.Config{
|
|
Path: filepath.Join(firstBeadsDir, "dolt"),
|
|
BeadsDir: firstBeadsDir,
|
|
ServerHost: "127.0.0.1",
|
|
ServerPort: testDoltServerPort,
|
|
Database: database,
|
|
CreateIfMissing: true,
|
|
})
|
|
doltNewMutex.Unlock()
|
|
if err != nil {
|
|
t.Fatalf("create first store: %v", err)
|
|
}
|
|
|
|
knownProjectID := "test-known-project-id-gh2922"
|
|
if err := firstStore.SetMetadata(ctx, "_project_id", knownProjectID); err != nil {
|
|
t.Fatalf("set _project_id: %v", err)
|
|
}
|
|
if err := firstStore.SetConfig(ctx, "issue_prefix", "test"); err != nil {
|
|
t.Fatalf("set issue_prefix: %v", err)
|
|
}
|
|
firstStore.Close()
|
|
|
|
t.Cleanup(func() {
|
|
dropTestDatabase(database, testDoltServerPort)
|
|
})
|
|
|
|
// Simulate second user — init with --database pointing at the existing DB
|
|
secondDir := t.TempDir()
|
|
t.Chdir(secondDir)
|
|
|
|
// Set up minimal git repo (init expects it for repo_id)
|
|
if err := exec.Command("git", "-C", secondDir, "init").Run(); err != nil {
|
|
t.Fatalf("git init: %v", err)
|
|
}
|
|
_ = exec.Command("git", "-C", secondDir, "config", "user.email", "test@test.com").Run()
|
|
_ = exec.Command("git", "-C", secondDir, "config", "user.name", "Test").Run()
|
|
|
|
rootCmd.SetArgs([]string{
|
|
"init",
|
|
"--server",
|
|
"--server-host", "127.0.0.1",
|
|
"--server-port", fmt.Sprintf("%d", testDoltServerPort),
|
|
"--database", database,
|
|
"--prefix", "second",
|
|
"--quiet",
|
|
"--skip-hooks",
|
|
"--skip-agents",
|
|
})
|
|
|
|
if err := rootCmd.Execute(); err != nil {
|
|
t.Fatalf("second init failed: %v", err)
|
|
}
|
|
|
|
// Verify the second user's metadata.json adopted the existing project_id
|
|
secondBeadsDir := filepath.Join(secondDir, ".beads")
|
|
cfg, err := configfile.Load(secondBeadsDir)
|
|
if err != nil {
|
|
t.Fatalf("load metadata.json: %v", err)
|
|
}
|
|
|
|
if cfg.ProjectID != knownProjectID {
|
|
t.Errorf("ProjectID = %q, want %q (should adopt existing project_id from server)", cfg.ProjectID, knownProjectID)
|
|
}
|
|
}
|
|
|
|
// resetInitFlagsForServerInit puts every rootCmd flag back to its registered
|
|
// default before and after a test that executes `bd init --server ...`
|
|
// in-process: embedded is init's default mode, so the Dolt-server-gated init
|
|
// tests pass --server, and cobra would otherwise carry that (and any other
|
|
// parsed flag) into the next in-process init.
|
|
func resetInitFlagsForServerInit(t *testing.T) {
|
|
t.Helper()
|
|
resetCommandFlags(rootCmd)
|
|
t.Cleanup(func() { resetCommandFlags(rootCmd) })
|
|
}
|
|
|
|
// sharedServerTestEnv is os.Environ() in shared-server mode with a free port
|
|
// of its own for the shared server (as dolt_worktree_remote_test.go does):
|
|
// the inherited BEADS_DOLT_SERVER_PORT names this suite's test server, which
|
|
// a shared-server start refuses as another project's, and the shared
|
|
// server's default port (3308) may be a developer's live server.
|
|
func sharedServerTestEnv(t *testing.T) []string {
|
|
t.Helper()
|
|
port, err := testutil.FindFreePort()
|
|
if err != nil {
|
|
t.Fatalf("find free port: %v", err)
|
|
}
|
|
return append(os.Environ(),
|
|
"BEADS_DOLT_SHARED_SERVER=1",
|
|
"BEADS_DOLT_SERVER_PORT="+strconv.Itoa(port),
|
|
)
|
|
}
|