From fffed97d38d23aafbb341fa16453234919f4f076 Mon Sep 17 00:00:00 2001 From: Jim Wordelman Date: Sat, 4 Jul 2026 14:37:51 -0700 Subject: [PATCH] feat(dolt): git-origin collision guard in bd dolt remote add + bd doctor (be-7eu1d) (#4153) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * test(cli): be-lbhy2 dolt.local-only enforcement gate tests (TDD, be-3v2ou) Failing tests for be-3v2ou (dolt.local-only enforcement, FR-01 to FR-05). All tests fail or refuse to compile until the builder adds isDoltLocalOnly(). cmd/bd/dolt_local_only_test.go (unit, no build tag): - TestIsDoltLocalOnly_FalseByDefault - TestIsDoltLocalOnly_TrueWhenConfigSet - TestIsDoltLocalOnly_FalseAfterUnset - TestMaybeAutoPush_SkipsWhenLocalOnly cmd/bd/dolt_local_only_embedded_test.go (build:embeddeddolt): - TestDoltLocalOnly_Push_ExitsZeroWithMessage - TestDoltLocalOnly_Push_LocalStoreCopy - TestDoltLocalOnly_Push_JSON_DisabledStatus - TestDoltLocalOnly_Pull_ExitsZeroWithMessage - TestDoltLocalOnly_Pull_JSON_DisabledStatus - TestDoltLocalOnly_RemoteAdd_RefusesExitOne - TestDoltLocalOnly_RemoteAdd_ErrorOnStderr - TestDoltLocalOnly_ConfigRoundTrip - TestDoltLocalOnly_DoltStatus_ShowsDisabled Message copy from be-0jyq7 (UX spec). Exact strings asserted so the builder cannot ship copy drift. Co-Authored-By: Claude Sonnet 4.6 * feat(dolt): implement dolt.local-only enforcement (be-3v2ou, FR-01 to FR-05) - Add isDoltLocalOnly() in dolt_local_only.go (reads dolt.local-only config key) - bd dolt push: exit-0 no-op with 'Remote sync is disabled...' message when set; --json emits {status:disabled,reason:dolt.local-only=true} via outputJSONRaw - bd dolt pull: same exit-0 no-op + 'Nothing to pull.' message - bd dolt remote add: exit-1 error to stderr ('cannot add Dolt remote: ... disabled') - bd dolt status: appends 'Remote sync: disabled (dolt.local-only=true)' indicator in both embedded and server-mode text paths - maybeAutoPush: guard fires before getStore() (before any store interaction) - Fix test build tag: cgo (not embeddeddolt) to match CI embedded test convention - Fix TestDoltLocalOnly_ConfigRoundTrip: bd config get returns "(not set ...)" not "" Co-Authored-By: Claude Sonnet 4.6 * feat(dolt): git-origin collision guard in bd dolt remote add + bd doctor (be-7eu1d, FR-06 to FR-09) - dolt_remote_guard.go: guardNormalizeURL() + doltRemoteMatchesGitOrigin() helpers - dolt.go: --allow-git-origin flag; refuse (or warn) when Dolt remote URL matches git origin - doctor/types.go: CategoryDolt = "Dolt Storage" + add to CategoryOrder - doctor/remotes.go: CheckDoltRemoteGitOrigin() warning check - doctor.go: wire Check 7f1 into the doctor run Co-Authored-By: Claude Sonnet 4.6 * docs(cli): regenerate CLI reference for --allow-git-origin The PR added the --allow-git-origin flag to 'bd dolt remote add' but did not regenerate docs, failing the 'doc flags freshness' check. Output of ./scripts/generate-cli-docs.sh ./bd — adds the flag to docs/CLI_REFERENCE.md and the dolt.md command pages (latest + versioned snapshots). Co-Authored-By: Claude Opus 4.7 (1M context) * fix(dolt): remove duplicate isDoltLocalOnly declaration from init.go The function was extracted to dolt_local_only.go in the stacked PR but the original declaration in init.go was not removed, causing a redeclared-in-block build error. Co-Authored-By: Claude Sonnet 4.6 * docs(cli): regenerate CLI reference for git-origin guard and doctor checks Full regeneration for the complete PR: --allow-git-origin flag, --force flag on dolt remote remove, and the bd doctor CheckDoltRemoteGitOrigin check. Also regenerates federation.md for completeness. Output of ./scripts/generate-cli-docs.sh ./bd and ./scripts/generate-llms-full.sh. Co-Authored-By: Claude Sonnet 4.6 * style(doctor): gofmt cmd/bd/doctor.go The be-7eu1d git-origin guard block left double blank lines around the new "Check 7f1" stanza, failing `make fmt-check` (CI "Check formatting" and the gofmt stage of "PR Lint"). gofmt collapses them to single blanks. Co-Authored-By: Claude Opus 4.8 (1M context) * docs(cli): regenerate CLI reference + llms-full with pure-go bd The previous regen (07dcb9a81) was built with a CGO-enabled bd, which includes the CGO-only `bd federation` subcommands. CI builds the docs binary with CGO_ENABLED=0 (scripts/ci/pr-policy.sh build_docs_binary), so check-doc-flags rejected the extra federation subcommand pages. Regenerated docs/CLI_REFERENCE.md, the federation cli-reference pages (live + versioned 1.0.0/1.0.4/1.0.5), and website/static/llms-full.txt with a CGO_ENABLED=0 binary. check-doc-flags + check-doc-freshness now pass locally under LC_ALL=C. Co-Authored-By: Claude Opus 4.8 (1M context) * style(doctor): gofmt cmd/bd/doctor.go (remove stray blank line) Fixes the 'Check formatting' CI failure on this PR — the only PR-introduced gofmt miss among the changed Go files. * fix(dolt): normalize git+https/git+ssh/SCP URLs in remote collision guard and doctor Address @maphew's review on PR #4153 (be-e7k8): 1. Add doltremote.CanonicalForComparison() — normalizes both sides of a URL comparison to Dolt's git+ prefix form, then strips trailing slashes and .git. This makes https://github.com/org/repo.git compare equal to git+https://github.com/org/repo.git, and git@github.com:org/repo.git equal to git+ssh://git@github.com/org/repo.git. 2. Replace the simple guardNormalizeURL helper in dolt_remote_guard.go and normRemoteURL in doctor/remotes.go with doltremote.CanonicalForComparison so both paths share one implementation and stay in sync. 3. Fix build tag on dolt_remote_origin_guard_embedded_test.go from embeddeddolt to embeddeddolt && cgo: the file delegates to bdDoltSeparate which lives in a cgo-only file, so the embeddeddolt-only tag caused a compile failure under CGO_ENABLED=0 + embeddeddolt. Co-Authored-By: Claude Sonnet 4.6 * fix(dolt): remove dead --force flag from bd dolt remote remove The --force flag was registered on doltRemoteRemoveCmd but the Run function never read it via cmd.Flags().GetBool("force") or any other means, so it had no effect. Remove the flag registration rather than wiring it up, per review on PR #4153, and regenerate the CLI reference docs (docs/CLI_REFERENCE.md, website/docs/cli-reference/dolt.md, website/static/llms-full.txt) so the dead flag no longer appears in generated documentation. Agent-Signature: claude-sonnet-5-high on behalf of matt wilkie Co-Authored-By: Claude Sonnet 5 * fix(dolt): check outputJSONRaw error in local-only status paths main changed outputJSONRaw to return an error after this branch was written; the two dolt.local-only JSON status sites now handle it with the same stderr idiom as the neighboring outputJSON callers, fixing the errcheck CI failure on PR #4153. Agent-Signature: claude-fable-5-high on behalf of matt wilkie Co-Authored-By: Claude Fable 5 --------- Co-authored-by: Jim Wordelman Co-authored-by: Claude Sonnet 4.6 Co-authored-by: matt wilkie --- cmd/bd/doctor.go | 4 + cmd/bd/doctor/remotes.go | 115 ++++++ cmd/bd/doctor/types.go | 2 + cmd/bd/dolt.go | 46 +++ cmd/bd/dolt_autopush.go | 4 + cmd/bd/dolt_local_only.go | 10 + cmd/bd/dolt_local_only_embedded_test.go | 232 +++++++++++ cmd/bd/dolt_local_only_test.go | 69 ++++ cmd/bd/dolt_remote_guard.go | 16 + .../dolt_remote_origin_guard_embedded_test.go | 368 ++++++++++++++++++ cmd/bd/dolt_remote_origin_guard_test.go | 192 +++++++++ cmd/bd/init.go | 4 - docs/CLI_REFERENCE.md | 8 +- internal/doltremote/remote.go | 14 + website/docs/cli-reference/dolt.md | 6 + .../version-1.0.0/cli-reference/dolt.md | 16 +- .../version-1.0.4/cli-reference/dolt.md | 16 +- .../version-1.0.5/cli-reference/dolt.md | 16 +- 18 files changed, 1127 insertions(+), 11 deletions(-) create mode 100644 cmd/bd/doctor/remotes.go create mode 100644 cmd/bd/dolt_local_only.go create mode 100644 cmd/bd/dolt_local_only_embedded_test.go create mode 100644 cmd/bd/dolt_local_only_test.go create mode 100644 cmd/bd/dolt_remote_guard.go create mode 100644 cmd/bd/dolt_remote_origin_guard_embedded_test.go create mode 100644 cmd/bd/dolt_remote_origin_guard_test.go diff --git a/cmd/bd/doctor.go b/cmd/bd/doctor.go index 39b70af89..4b9113dab 100644 --- a/cmd/bd/doctor.go +++ b/cmd/bd/doctor.go @@ -551,6 +551,10 @@ func runDiagnostics(path string) doctorResult { result.OverallOK = false } + // Check 7f1: Dolt remote URL collision with git origin (be-7eu1d) + doltOriginCheck := convertWithCategory(doctor.CheckDoltRemoteGitOrigin(path), doctor.CategoryDolt) + result.Checks = append(result.Checks, doltOriginCheck) + // Check 7f: Migration content skew vs the cached remote ref (#4259). Advisory. skewCheck := convertWithCategory(doctor.CheckMigrationContentSkew(sharedStore), doctor.CategoryData) result.Checks = append(result.Checks, skewCheck) diff --git a/cmd/bd/doctor/remotes.go b/cmd/bd/doctor/remotes.go new file mode 100644 index 000000000..534d6c7f5 --- /dev/null +++ b/cmd/bd/doctor/remotes.go @@ -0,0 +1,115 @@ +package doctor + +import ( + "context" + "fmt" + "os/exec" + "strings" + "time" + + "github.com/steveyegge/beads/internal/configfile" + "github.com/steveyegge/beads/internal/doltremote" + "github.com/steveyegge/beads/internal/storage" +) + +var querySQLRemotesForDoctor = querySQLRemotes + +// CheckDoltRemoteGitOrigin warns when any configured Dolt remote URL matches +// the git origin — a likely misconfiguration since beads syncs via Dolt, not git. +func CheckDoltRemoteGitOrigin(repoPath string) DoctorCheck { + name := "Dolt Remote vs Git Origin" + beadsDir := ResolveBeadsDirForRepo(repoPath) + + cfg, err := configfile.Load(beadsDir) + if err != nil || cfg == nil || cfg.GetBackend() != configfile.BackendDolt { + return DoctorCheck{ + Name: name, + Status: StatusOK, + Message: "N/A (not using Dolt backend)", + Category: CategoryDolt, + } + } + + originURL := gitOriginRemoteURL(repoPath) + if originURL == "" { + return DoctorCheck{ + Name: name, + Status: StatusOK, + Message: "No git origin configured", + Category: CategoryDolt, + } + } + + sqlRemotes, sqlErr := querySQLRemotesForDoctor(beadsDir) + if sqlErr != nil { + // Can't check; skip silently. + return DoctorCheck{ + Name: name, + Status: StatusOK, + Message: "Could not query Dolt remotes (server may not be running)", + Category: CategoryDolt, + } + } + + normalizedOrigin := doltremote.CanonicalForComparison(originURL) + var colliding []string + for _, r := range sqlRemotes { + if doltremote.CanonicalForComparison(r.URL) == normalizedOrigin { + colliding = append(colliding, r.Name) + } + } + + if len(colliding) == 0 { + return DoctorCheck{ + Name: name, + Status: StatusOK, + Message: "No Dolt remote matches git origin", + Category: CategoryDolt, + } + } + + return DoctorCheck{ + Name: name, + Status: StatusWarning, + Message: fmt.Sprintf("%d Dolt remote(s) match the git origin URL: %s", len(colliding), strings.Join(colliding, ", ")), + Detail: "Using the git origin as a Dolt remote causes git and Dolt sync to share the same endpoint, which can cause conflicts.", + Fix: "Remove the conflicting remote(s) with 'bd dolt remote remove ', or set dolt.local-only=true to disable remote sync.", + Category: CategoryDolt, + } +} + +func gitOriginRemoteURL(repoPath string) string { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, "git", "-C", repoPath, "remote", "get-url", "origin") + out, err := cmd.Output() + if err != nil { + return "" + } + return strings.TrimSpace(string(out)) +} + +// querySQLRemotes gets remotes from the SQL server. +func querySQLRemotes(beadsDir string) ([]storage.RemoteInfo, error) { + db, _, err := openDoltDB(beadsDir) + if err != nil { + return nil, err + } + defer db.Close() + + rows, err := db.Query("SELECT name, url FROM dolt_remotes") + if err != nil { + return nil, err + } + defer rows.Close() + + var remotes []storage.RemoteInfo + for rows.Next() { + var r storage.RemoteInfo + if err := rows.Scan(&r.Name, &r.URL); err != nil { + return nil, err + } + remotes = append(remotes, r) + } + return remotes, rows.Err() +} diff --git a/cmd/bd/doctor/types.go b/cmd/bd/doctor/types.go index 1cc715978..d64da3c47 100644 --- a/cmd/bd/doctor/types.go +++ b/cmd/bd/doctor/types.go @@ -18,6 +18,7 @@ const ( CategoryMaintenance = "Maintenance" CategoryPerformance = "Performance" CategoryFederation = "Federation" + CategoryDolt = "Dolt Storage" ) // CategoryOrder defines the display order for categories @@ -25,6 +26,7 @@ var CategoryOrder = []string{ CategoryCore, CategoryData, CategoryGit, + CategoryDolt, CategoryRuntime, CategoryPerformance, CategoryIntegration, diff --git a/cmd/bd/dolt.go b/cmd/bd/dolt.go index 0f7244fb6..913b06d9f 100644 --- a/cmd/bd/dolt.go +++ b/cmd/bd/dolt.go @@ -340,6 +340,18 @@ The remote must already exist (see 'bd dolt remote add').`, fmt.Println("skipping push: rig is local-only (no-push: true)") return } + if isDoltLocalOnly() { + if jsonOutput { + if err := outputJSONRaw(map[string]string{"status": "disabled", "reason": "dolt.local-only=true"}); err != nil { + fmt.Fprintf(os.Stderr, "Error: %v\n", err) + } + return + } + fmt.Println("Remote sync is disabled for this project (dolt.local-only=true).") + fmt.Println("Your issues are stored locally in .beads/.") + fmt.Println("To re-enable remote sync: bd config unset dolt.local-only") + return + } ctx := context.Background() st := getStore() if st == nil { @@ -413,6 +425,18 @@ variables for authentication. Use --remote to pull from a specific named remote instead of the default. The remote must already exist (see 'bd dolt remote add').`, Run: func(cmd *cobra.Command, args []string) { + if isDoltLocalOnly() { + if jsonOutput { + if err := outputJSONRaw(map[string]string{"status": "disabled", "reason": "dolt.local-only=true"}); err != nil { + fmt.Fprintf(os.Stderr, "Error: %v\n", err) + } + return + } + fmt.Println("Remote sync is disabled for this project (dolt.local-only=true).") + fmt.Println("Nothing to pull.") + fmt.Println("To re-enable remote sync: bd config unset dolt.local-only") + return + } ctx := context.Background() st := getStore() if st == nil { @@ -654,6 +678,9 @@ func renderLocalDoltStatus(state *doltserver.State, serverDir string) { fmt.Println(" Debug: on (loglevel=debug, --prof cpu)") fmt.Printf(" Profile dir: %s\n", doltserver.DebugProfileDir(serverDir)) } + if isDoltLocalOnly() { + fmt.Println(" Remote sync: disabled (dolt.local-only=true)") + } } // shouldUseExternalDoltStatus reports whether bd dolt status should treat @@ -834,6 +861,9 @@ func showEmbeddedDoltStatus(beadsDir string) { if !dataDirExists { fmt.Printf(" %s\n", ui.RenderWarn("Data directory does not exist — run 'bd init' to create it")) } + if isDoltLocalOnly() { + fmt.Println(" Remote sync: disabled (dolt.local-only=true)") + } } var doltKillallCmd = &cobra.Command{ @@ -1088,6 +1118,21 @@ var doltRemoteAddCmd = &cobra.Command{ Short: "Add a Dolt remote", Args: cobra.ExactArgs(2), Run: func(cmd *cobra.Command, args []string) { + if isDoltLocalOnly() { + fmt.Fprintln(os.Stderr, "Error: cannot add Dolt remote: remote sync is disabled (dolt.local-only=true).") + fmt.Fprintln(os.Stderr, "To re-enable remote sync: bd config unset dolt.local-only") + os.Exit(1) + } + allowGitOrigin, _ := cmd.Flags().GetBool("allow-git-origin") + if doltRemoteMatchesGitOrigin(args[1]) { + if !allowGitOrigin { + fmt.Fprintf(os.Stderr, "Error: refusing to add %q as a Dolt remote — this URL matches the git origin.\n", args[1]) + fmt.Fprintln(os.Stderr, " Hint: use --allow-git-origin to proceed anyway (e.g. monorepo layout).") + fmt.Fprintln(os.Stderr, " Hint: or set dolt.local-only=true to disable remote sync entirely.") + os.Exit(1) + } + fmt.Fprintf(os.Stderr, "Warning: %q matches the git origin — proceeding because --allow-git-origin is set.\n", args[1]) + } ctx := context.Background() st := getStore() if st == nil { @@ -1263,6 +1308,7 @@ func init() { doltPullCmd.Flags().String("remote", "", "Pull from a specific named remote instead of the default") doltCommitCmd.Flags().StringP("message", "m", "", "Commit message (default: auto-generated)") doltCleanDatabasesCmd.Flags().Bool("dry-run", false, "Show what would be dropped without dropping") + doltRemoteAddCmd.Flags().Bool("allow-git-origin", false, "Allow adding a Dolt remote whose URL matches the git origin (proceed with a warning instead of aborting)") doltRemoteCmd.AddCommand(doltRemoteAddCmd) doltRemoteCmd.AddCommand(doltRemoteListCmd) doltRemoteCmd.AddCommand(doltRemoteRemoveCmd) diff --git a/cmd/bd/dolt_autopush.go b/cmd/bd/dolt_autopush.go index bd02f51ca..4d59c4adc 100644 --- a/cmd/bd/dolt_autopush.go +++ b/cmd/bd/dolt_autopush.go @@ -107,6 +107,10 @@ func maybeAutoPush(ctx context.Context) { debug.Logf("dolt auto-push: skipped (sandbox mode)\n") return } + if isDoltLocalOnly() { + debug.Logf("dolt auto-push: skipped (dolt.local-only=true)\n") + return + } if !isDoltAutoPushEnabled(ctx) { return } diff --git a/cmd/bd/dolt_local_only.go b/cmd/bd/dolt_local_only.go new file mode 100644 index 000000000..5ae24d802 --- /dev/null +++ b/cmd/bd/dolt_local_only.go @@ -0,0 +1,10 @@ +package main + +import "github.com/steveyegge/beads/internal/config" + +// isDoltLocalOnly reports whether this project has remote sync disabled via +// the dolt.local-only config key. When true, bd dolt push, pull, and +// remote add are no-ops or errors (be-3v2ou). +func isDoltLocalOnly() bool { + return config.GetBool("dolt.local-only") +} diff --git a/cmd/bd/dolt_local_only_embedded_test.go b/cmd/bd/dolt_local_only_embedded_test.go new file mode 100644 index 000000000..87a172cec --- /dev/null +++ b/cmd/bd/dolt_local_only_embedded_test.go @@ -0,0 +1,232 @@ +//go:build cgo + +package main + +import ( + "bytes" + "encoding/json" + "os" + "os/exec" + "strings" + "testing" +) + +// Integration tests for be-3v2ou: dolt.local-only enforcement (FR-01 to FR-05). +// +// TDD gate tests: these fail before the implementation because the guards +// don't exist yet. Run with BEADS_TEST_EMBEDDED_DOLT=1. + +// bdLocalOnlySetup inits a project and enables dolt.local-only=true. +func bdLocalOnlySetup(t *testing.T, bd string) (dir string) { + t.Helper() + dir, _, _ = bdInit(t, bd, "--prefix", "lo") + bdConfig(t, bd, dir, "set", "dolt.local-only", "true") + return dir +} + +// bdDoltSeparate runs "bd dolt " and returns (stdout, stderr, err) +// with separate buffers. Used when tests must distinguish stdout from stderr. +func bdDoltSeparate(t *testing.T, bd, dir string, args ...string) (string, string, error) { + t.Helper() + fullArgs := append([]string{"dolt"}, args...) + cmd := exec.Command(bd, fullArgs...) + cmd.Dir = dir + cmd.Env = bdEnv(dir) + var stdout, stderr bytes.Buffer + cmd.Stdout = &stdout + cmd.Stderr = &stderr + err := cmd.Run() + return stdout.String(), stderr.String(), err +} + +// -- push -- + +func TestDoltLocalOnly_Push_ExitsZeroWithMessage(t *testing.T) { + if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { + t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run dolt.local-only embedded tests") + } + t.Parallel() + bd := buildEmbeddedBD(t) + dir := bdLocalOnlySetup(t, bd) + + // bdDolt fatals on non-zero exit — this asserts exit 0. + out := bdDolt(t, bd, dir, "push") + + for _, want := range []string{ + "Remote sync is disabled for this project (dolt.local-only=true).", + "bd config unset dolt.local-only", + } { + if !strings.Contains(out, want) { + t.Errorf("push stdout missing %q\ngot:\n%s", want, out) + } + } +} + +func TestDoltLocalOnly_Push_LocalStoreCopy(t *testing.T) { + // The push no-op message must include the "Your issues are stored locally" line. + if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { + t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run dolt.local-only embedded tests") + } + t.Parallel() + bd := buildEmbeddedBD(t) + dir := bdLocalOnlySetup(t, bd) + + out := bdDolt(t, bd, dir, "push") + if !strings.Contains(out, "stored locally") { + t.Errorf("push no-op missing 'stored locally'\ngot:\n%s", out) + } +} + +func TestDoltLocalOnly_Push_JSON_DisabledStatus(t *testing.T) { + if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { + t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run dolt.local-only embedded tests") + } + t.Parallel() + bd := buildEmbeddedBD(t) + dir := bdLocalOnlySetup(t, bd) + + out := bdDolt(t, bd, dir, "--json", "push") + + var got map[string]string + if err := json.Unmarshal([]byte(strings.TrimSpace(out)), &got); err != nil { + t.Fatalf("bd dolt --json push: stdout not valid JSON: %v\nout: %s", err, out) + } + if got["status"] != "disabled" { + t.Errorf("JSON[status] = %q, want \"disabled\"", got["status"]) + } + if got["reason"] != "dolt.local-only=true" { + t.Errorf("JSON[reason] = %q, want \"dolt.local-only=true\"", got["reason"]) + } +} + +// -- pull -- + +func TestDoltLocalOnly_Pull_ExitsZeroWithMessage(t *testing.T) { + if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { + t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run dolt.local-only embedded tests") + } + t.Parallel() + bd := buildEmbeddedBD(t) + dir := bdLocalOnlySetup(t, bd) + + out := bdDolt(t, bd, dir, "pull") + + for _, want := range []string{ + "Remote sync is disabled for this project (dolt.local-only=true).", + "Nothing to pull", + "bd config unset dolt.local-only", + } { + if !strings.Contains(out, want) { + t.Errorf("pull stdout missing %q\ngot:\n%s", want, out) + } + } +} + +func TestDoltLocalOnly_Pull_JSON_DisabledStatus(t *testing.T) { + if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { + t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run dolt.local-only embedded tests") + } + t.Parallel() + bd := buildEmbeddedBD(t) + dir := bdLocalOnlySetup(t, bd) + + out := bdDolt(t, bd, dir, "--json", "pull") + + var got map[string]string + if err := json.Unmarshal([]byte(strings.TrimSpace(out)), &got); err != nil { + t.Fatalf("bd dolt --json pull: stdout not valid JSON: %v\nout: %s", err, out) + } + if got["status"] != "disabled" { + t.Errorf("JSON[status] = %q, want \"disabled\"", got["status"]) + } + if got["reason"] != "dolt.local-only=true" { + t.Errorf("JSON[reason] = %q, want \"dolt.local-only=true\"", got["reason"]) + } +} + +// -- remote add -- + +func TestDoltLocalOnly_RemoteAdd_RefusesExitOne(t *testing.T) { + if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { + t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run dolt.local-only embedded tests") + } + t.Parallel() + bd := buildEmbeddedBD(t) + dir := bdLocalOnlySetup(t, bd) + + stdout, stderr, err := bdDoltSeparate(t, bd, dir, "remote", "add", "origin", "https://doltremoteapi.dolthub.com/test/repo") + if err == nil { + t.Fatalf("bd dolt remote add: expected exit non-zero, but succeeded\nstdout:\n%s", stdout) + } + for _, want := range []string{ + "cannot add Dolt remote", + "dolt.local-only", + "bd config unset dolt.local-only", + } { + if !strings.Contains(strings.ToLower(stderr+stdout), strings.ToLower(want)) { + t.Errorf("remote-add output missing %q\nstdout: %s\nstderr: %s", want, stdout, stderr) + } + } +} + +func TestDoltLocalOnly_RemoteAdd_ErrorOnStderr(t *testing.T) { + // The refusal must go to stderr (not stdout) so agents can distinguish errors. + if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { + t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run dolt.local-only embedded tests") + } + t.Parallel() + bd := buildEmbeddedBD(t) + dir := bdLocalOnlySetup(t, bd) + + stdout, stderr, _ := bdDoltSeparate(t, bd, dir, "remote", "add", "origin", "https://doltremoteapi.dolthub.com/test/repo") + if !strings.Contains(strings.ToLower(stderr), "disabled") { + t.Errorf("remote-add refusal not on stderr\nstderr: %s", stderr) + } + if strings.Contains(strings.ToLower(stdout), "disabled") { + t.Errorf("remote-add refusal leaked onto stdout\nstdout: %s", stdout) + } +} + +// -- config round-trip -- + +func TestDoltLocalOnly_ConfigRoundTrip(t *testing.T) { + // bd config set dolt.local-only true / unset must persist via config.yaml. + if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { + t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run dolt.local-only embedded tests") + } + t.Parallel() + bd := buildEmbeddedBD(t) + dir, _, _ := bdInit(t, bd, "--prefix", "cr") + + // Set: push becomes a no-op. + bdConfig(t, bd, dir, "set", "dolt.local-only", "true") + out := bdDolt(t, bd, dir, "push") + if !strings.Contains(out, "dolt.local-only=true") { + t.Errorf("after set: push output = %q, want to mention dolt.local-only=true", out) + } + + // Unset: key must be absent from config. bd config get returns "(not set ...)" for missing keys. + bdConfig(t, bd, dir, "unset", "dolt.local-only") + val := bdConfig(t, bd, dir, "get", "dolt.local-only") + if !strings.Contains(val, "not set") { + t.Errorf("after unset: bd config get dolt.local-only = %q, want 'not set'", val) + } +} + +// -- bd dolt status -- + +func TestDoltLocalOnly_DoltStatus_ShowsDisabled(t *testing.T) { + // When dolt.local-only=true, bd dolt status must include the indicator line. + if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { + t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run dolt.local-only embedded tests") + } + t.Parallel() + bd := buildEmbeddedBD(t) + dir := bdLocalOnlySetup(t, bd) + + out := bdDolt(t, bd, dir, "status") + want := "Remote sync: disabled (dolt.local-only=true)" + if !strings.Contains(out, want) { + t.Errorf("dolt status missing %q\ngot:\n%s", want, out) + } +} diff --git a/cmd/bd/dolt_local_only_test.go b/cmd/bd/dolt_local_only_test.go new file mode 100644 index 000000000..77db329fc --- /dev/null +++ b/cmd/bd/dolt_local_only_test.go @@ -0,0 +1,69 @@ +package main + +import ( + "context" + "testing" + + "github.com/steveyegge/beads/internal/config" +) + +// Unit tests for isDoltLocalOnly() and related guards. +// These fail to compile until the builder adds isDoltLocalOnly() in dolt.go. +// Cannot be parallel: tests modify global config state. + +func TestIsDoltLocalOnly_FalseByDefault(t *testing.T) { + config.ResetForTesting() + t.Cleanup(func() { config.ResetForTesting() }) + if err := config.Initialize(); err != nil { + t.Fatalf("config.Initialize: %v", err) + } + + if isDoltLocalOnly() { + t.Error("isDoltLocalOnly() = true, want false when dolt.local-only not set") + } +} + +func TestIsDoltLocalOnly_TrueWhenConfigSet(t *testing.T) { + config.ResetForTesting() + t.Cleanup(func() { config.ResetForTesting() }) + if err := config.Initialize(); err != nil { + t.Fatalf("config.Initialize: %v", err) + } + config.Set("dolt.local-only", true) + + if !isDoltLocalOnly() { + t.Error("isDoltLocalOnly() = false, want true when dolt.local-only=true") + } +} + +func TestIsDoltLocalOnly_FalseAfterUnset(t *testing.T) { + config.ResetForTesting() + t.Cleanup(func() { config.ResetForTesting() }) + if err := config.Initialize(); err != nil { + t.Fatalf("config.Initialize: %v", err) + } + config.Set("dolt.local-only", true) + if !isDoltLocalOnly() { + t.Fatal("precondition: isDoltLocalOnly() should be true after set") + } + config.Set("dolt.local-only", false) + if isDoltLocalOnly() { + t.Error("isDoltLocalOnly() = true after unsetting, want false") + } +} + +func TestMaybeAutoPush_SkipsWhenLocalOnly(t *testing.T) { + // When dolt.local-only=true, maybeAutoPush must return early (no push attempt). + // Local-only guard must fire BEFORE getStore(); store is nil here. + config.ResetForTesting() + t.Cleanup(func() { config.ResetForTesting() }) + if err := config.Initialize(); err != nil { + t.Fatalf("config.Initialize: %v", err) + } + config.Set("dolt.local-only", true) + // Enable auto-push so the local-only guard, not the disabled-check, short-circuits. + t.Setenv("BD_DOLT_AUTO_PUSH", "true") + + // Must not panic. The local-only guard fires before any store interaction. + maybeAutoPush(context.Background()) +} diff --git a/cmd/bd/dolt_remote_guard.go b/cmd/bd/dolt_remote_guard.go new file mode 100644 index 000000000..9863e2ec4 --- /dev/null +++ b/cmd/bd/dolt_remote_guard.go @@ -0,0 +1,16 @@ +package main + +import "github.com/steveyegge/beads/internal/doltremote" + +// doltRemoteMatchesGitOrigin reports whether doltURL refers to the same +// repository as the git origin. Handles git+https://, git+ssh://, SCP-style, +// and plain https:// / ssh:// forms by normalizing both sides with +// doltremote.CanonicalForComparison before comparing. +// Returns false when there is no git origin. +func doltRemoteMatchesGitOrigin(doltURL string) bool { + originURL, err := gitOriginGetURL() + if err != nil { + return false + } + return doltremote.CanonicalForComparison(doltURL) == doltremote.CanonicalForComparison(originURL) +} diff --git a/cmd/bd/dolt_remote_origin_guard_embedded_test.go b/cmd/bd/dolt_remote_origin_guard_embedded_test.go new file mode 100644 index 000000000..53bca5adc --- /dev/null +++ b/cmd/bd/dolt_remote_origin_guard_embedded_test.go @@ -0,0 +1,368 @@ +//go:build embeddeddolt && cgo + +package main + +import ( + "bytes" + "encoding/json" + "os" + "os/exec" + "strings" + "testing" +) + +// Integration tests for be-7eu1d: git-origin collision guard in bd dolt remote +// add and bd doctor (FR-06 to FR-09). +// +// TDD gate tests — these fail before the implementation exists. Run with +// BEADS_TEST_EMBEDDED_DOLT=1. + +// remoteAdd runs "bd dolt remote add " returning (stdout, stderr, error) +// with separate buffers. Delegates to bdDoltSeparate (dolt_local_only_embedded_test.go). +func remoteAdd(t *testing.T, bd, dir string, args ...string) (string, string, error) { + t.Helper() + return bdDoltSeparate(t, bd, dir, append([]string{"remote", "add"}, args...)...) +} + +// setGitOrigin adds a git remote named "origin" to the directory. +func setGitOrigin(t *testing.T, dir, url string) { + t.Helper() + cmd := exec.Command("git", "remote", "add", "origin", url) + cmd.Dir = dir + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git remote add origin %s: %v\n%s", url, err, out) + } +} + +// bdDoctorSeparate runs "bd doctor " returning (stdout, stderr, error). +func bdDoctorSeparate(t *testing.T, bd, dir string, args ...string) (string, string, error) { + t.Helper() + fullArgs := append([]string{"doctor"}, args...) + cmd := exec.Command(bd, fullArgs...) + cmd.Dir = dir + cmd.Env = bdEnv(dir) + var stdout, stderr bytes.Buffer + cmd.Stdout = &stdout + cmd.Stderr = &stderr + err := cmd.Run() + return stdout.String(), stderr.String(), err +} + +// -- bd dolt remote add: collision with git origin -- + +// TestDoltRemoteAdd_GitOriginCollision_Exits1 asserts that adding a Dolt remote +// whose URL matches the git origin exits non-zero and prints the refusal message. +func TestDoltRemoteAdd_GitOriginCollision_Exits1(t *testing.T) { + if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { + t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests") + } + t.Parallel() + bd := buildEmbeddedBD(t) + dir, _, _ := bdInit(t, bd, "--prefix", "rg") + + originURL := "https://github.com/org/repo.git" + setGitOrigin(t, dir, originURL) + + _, stderr, err := remoteAdd(t, bd, dir, "origin", originURL) + if err == nil { + t.Fatalf("expected bd dolt remote add to exit non-zero on git-origin collision, but succeeded\nstderr: %s", stderr) + } + if !strings.Contains(stderr, "refusing to add") { + t.Errorf("expected 'refusing to add' in stderr\ngot:\n%s", stderr) + } + if !strings.Contains(stderr, originURL) { + t.Errorf("expected rejected URL %q in stderr\ngot:\n%s", originURL, stderr) + } +} + +// TestDoltRemoteAdd_GitOriginCollision_RefusalMessageCopy verifies exact phrases +// from the UX spec (be-fxwbm §2.1) appear in the refusal output. +func TestDoltRemoteAdd_GitOriginCollision_RefusalMessageCopy(t *testing.T) { + if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { + t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests") + } + t.Parallel() + bd := buildEmbeddedBD(t) + dir, _, _ := bdInit(t, bd, "--prefix", "rm") + + originURL := "https://github.com/org/repo.git" + setGitOrigin(t, dir, originURL) + + _, stderr, _ := remoteAdd(t, bd, dir, "origin", originURL) + + wantPhrases := []string{ + "refusing to add", // §2.1 first line + "git origin", // §2.1 first line + "--allow-git-origin", // §2.1 recovery option + "dolt.local-only", // §2.1 opt-out option + } + for _, phrase := range wantPhrases { + if !strings.Contains(stderr, phrase) { + t.Errorf("refusal message missing %q\nfull stderr:\n%s", phrase, stderr) + } + } +} + +// TestDoltRemoteAdd_AllowGitOrigin_Exits0 asserts that --allow-git-origin +// bypasses the collision guard and exits 0. +func TestDoltRemoteAdd_AllowGitOrigin_Exits0(t *testing.T) { + if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { + t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests") + } + t.Parallel() + bd := buildEmbeddedBD(t) + dir, _, _ := bdInit(t, bd, "--prefix", "ag") + + originURL := "file:///tmp/fake-git-remote" + setGitOrigin(t, dir, originURL) + + _, _, err := remoteAdd(t, bd, dir, "--allow-git-origin", "dolt-origin", originURL) + if err != nil { + t.Errorf("expected bd dolt remote add --allow-git-origin to exit 0 on collision, got error: %v", err) + } +} + +// TestDoltRemoteAdd_AllowGitOrigin_WarningOnStderr asserts the one-liner warning +// from be-fxwbm §2.2 appears on stderr when --allow-git-origin is set. +func TestDoltRemoteAdd_AllowGitOrigin_WarningOnStderr(t *testing.T) { + if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { + t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests") + } + t.Parallel() + bd := buildEmbeddedBD(t) + dir, _, _ := bdInit(t, bd, "--prefix", "aw") + + originURL := "file:///tmp/fake-git-remote2" + setGitOrigin(t, dir, originURL) + + _, stderr, _ := remoteAdd(t, bd, dir, "--allow-git-origin", "dolt-origin", originURL) + + // §2.2: "Warning: '' matches the git origin — proceeding because --allow-git-origin is set." + if !strings.Contains(stderr, "Warning:") { + t.Errorf("expected 'Warning:' on stderr when --allow-git-origin is set\ngot:\n%s", stderr) + } + if !strings.Contains(stderr, "--allow-git-origin") { + t.Errorf("expected '--allow-git-origin' in warning\ngot:\n%s", stderr) + } +} + +// TestDoltRemoteAdd_NoGitOrigin_ProceedsNormally asserts no refusal fires when +// the git repo has no 'origin' remote. +func TestDoltRemoteAdd_NoGitOrigin_ProceedsNormally(t *testing.T) { + if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { + t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests") + } + t.Parallel() + bd := buildEmbeddedBD(t) + dir, _, _ := bdInit(t, bd, "--prefix", "no") + // bdInit creates a git repo, but no origin is set. + + remoteDir := t.TempDir() + _, stderr, err := remoteAdd(t, bd, dir, "dolt-origin", "file://"+remoteDir) + if err != nil { + t.Errorf("expected bd dolt remote add to succeed when no git origin, got error: %v\nstderr: %s", err, stderr) + } + if strings.Contains(stderr, "refusing to add") { + t.Errorf("unexpected refusal when no git origin\nstderr:\n%s", stderr) + } +} + +// TestDoltRemoteAdd_DifferentURL_ProceedsNormally asserts the guard does not +// fire when the Dolt remote URL is different from the git origin. +func TestDoltRemoteAdd_DifferentURL_ProceedsNormally(t *testing.T) { + if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { + t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests") + } + t.Parallel() + bd := buildEmbeddedBD(t) + dir, _, _ := bdInit(t, bd, "--prefix", "du") + + setGitOrigin(t, dir, "https://github.com/org/repo.git") + + // Different URL — should not trigger guard. + remoteDir := t.TempDir() + _, stderr, err := remoteAdd(t, bd, dir, "dolt-origin", "file://"+remoteDir) + if err != nil { + t.Errorf("expected bd dolt remote add with different URL to succeed, got error: %v\nstderr: %s", err, stderr) + } + if strings.Contains(stderr, "refusing to add") { + t.Errorf("unexpected refusal when URL doesn't match git origin\nstderr:\n%s", stderr) + } +} + +// TestDoltRemoteAdd_LocalOnly_FiresBeforeGuard verifies that when +// dolt.local-only=true is set, the local-only refusal fires before the +// git-origin guard — the local-only guard takes priority (be-3v2ou ordering). +func TestDoltRemoteAdd_LocalOnly_FiresBeforeGuard(t *testing.T) { + if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { + t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests") + } + t.Parallel() + bd := buildEmbeddedBD(t) + dir, _, _ := bdInit(t, bd, "--prefix", "lo") + bdConfig(t, bd, dir, "set", "dolt.local-only", "true") + + originURL := "https://github.com/org/repo.git" + setGitOrigin(t, dir, originURL) + + _, stderr, err := remoteAdd(t, bd, dir, "origin", originURL) + if err == nil { + t.Fatal("expected bd dolt remote add to fail with dolt.local-only=true") + } + // Must mention local-only, not git-origin collision. + if strings.Contains(stderr, "refusing to add") { + t.Errorf("git-origin guard fired before local-only guard\nstderr:\n%s", stderr) + } + if !strings.Contains(stderr, "local-only") && !strings.Contains(stderr, "dolt.local-only") { + t.Errorf("expected local-only message, got:\n%s", stderr) + } +} + +// -- bd doctor: Dolt remote matches git origin -- + +// TestDoctor_DoltRemoteMatchesGitOrigin_Warning verifies that bd doctor emits a +// warning when a Dolt remote URL matches the git origin. +func TestDoctor_DoltRemoteMatchesGitOrigin_Warning(t *testing.T) { + if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { + t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests") + } + t.Parallel() + bd := buildEmbeddedBD(t) + dir, _, _ := bdInit(t, bd, "--prefix", "dw") + + originURL := "file:///tmp/origin-collision-for-doctor" + setGitOrigin(t, dir, originURL) + + // Add a Dolt remote that matches the git origin (using --allow-git-origin to bypass the guard). + bdDolt(t, bd, dir, "remote", "add", "--allow-git-origin", "origin", originURL) + + stdout, _, _ := bdDoctorSeparate(t, bd, dir) + combined := stdout + + // Doctor must surface the warning check. + if !strings.Contains(combined, "warning") && !strings.Contains(combined, "Warning") { + t.Errorf("bd doctor: expected warning when Dolt remote matches git origin\noutput:\n%s", combined) + } + if !strings.Contains(combined, "git origin") { + t.Errorf("bd doctor: expected 'git origin' in warning output\noutput:\n%s", combined) + } +} + +// TestDoctor_DoltRemoteNoMatch_OK verifies that bd doctor does NOT emit a +// git-origin warning when the Dolt remote URL differs from the git origin. +func TestDoctor_DoltRemoteNoMatch_OK(t *testing.T) { + if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { + t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests") + } + t.Parallel() + bd := buildEmbeddedBD(t) + dir, _, _ := bdInit(t, bd, "--prefix", "dn") + + setGitOrigin(t, dir, "https://github.com/org/repo.git") + remoteDir := t.TempDir() + bdDolt(t, bd, dir, "remote", "add", "dolt-origin", "file://"+remoteDir) + + stdout, _, _ := bdDoctorSeparate(t, bd, dir) + if strings.Contains(stdout, "Dolt remote matches git origin") { + t.Errorf("bd doctor: unexpected git-origin warning when URLs differ\noutput:\n%s", stdout) + } +} + +// TestDoctor_NoGitOrigin_OK verifies that bd doctor shows OK for the git-origin +// check when no git origin is configured. +func TestDoctor_NoGitOrigin_OK(t *testing.T) { + if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { + t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests") + } + t.Parallel() + bd := buildEmbeddedBD(t) + dir, _, _ := bdInit(t, bd, "--prefix", "ng") + // bdInit creates a git repo but no origin. + + remoteDir := t.TempDir() + bdDolt(t, bd, dir, "remote", "add", "dolt-origin", "file://"+remoteDir) + + stdout, _, _ := bdDoctorSeparate(t, bd, dir) + // Should not emit a warning for the git-origin check. + if strings.Contains(stdout, "Dolt remote matches git origin") { + t.Errorf("bd doctor: unexpected git-origin warning when no git origin\noutput:\n%s", stdout) + } +} + +// TestDoctor_JSON_DoltRemoteMatchesGitOrigin_Warning verifies that +// bd doctor --json exposes the git-origin warning check with "status":"warning". +func TestDoctor_JSON_DoltRemoteMatchesGitOrigin_Warning(t *testing.T) { + if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { + t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests") + } + t.Parallel() + bd := buildEmbeddedBD(t) + dir, _, _ := bdInit(t, bd, "--prefix", "dj") + + originURL := "file:///tmp/origin-collision-for-json" + setGitOrigin(t, dir, originURL) + bdDolt(t, bd, dir, "remote", "add", "--allow-git-origin", "origin", originURL) + + stdout, _, _ := bdDoctorSeparate(t, bd, dir, "--json") + + // Output should be JSON array of checks. + var checks []map[string]interface{} + if err := json.Unmarshal([]byte(strings.TrimSpace(stdout)), &checks); err != nil { + // May be wrapped in an outer object — try extracting the checks array. + var outer map[string]interface{} + if jsonErr := json.Unmarshal([]byte(strings.TrimSpace(stdout)), &outer); jsonErr != nil { + t.Fatalf("bd doctor --json: not valid JSON: %v\noutput:\n%s", err, stdout) + } + if arr, ok := outer["checks"].([]interface{}); ok { + data, _ := json.Marshal(arr) + _ = json.Unmarshal(data, &checks) + } + } + + found := false + for _, check := range checks { + name, _ := check["name"].(string) + if strings.Contains(name, "git origin") || strings.Contains(name, "Dolt remote") { + found = true + status, _ := check["status"].(string) + if status != "warning" { + t.Errorf("doctor JSON check %q: status = %q, want \"warning\"", name, status) + } + if _, hasFix := check["fix"]; !hasFix { + t.Errorf("doctor JSON check %q: missing \"fix\" field", name) + } + break + } + } + if !found { + t.Errorf("bd doctor --json: no git-origin check found in output\noutput:\n%s", stdout) + } +} + +// TestDoltRemoteAdd_JSON_AllowGitOrigin_WarningOnStderr asserts that even in +// --json mode, the override warning still appears on stderr (not stdout). +func TestDoltRemoteAdd_JSON_AllowGitOrigin_WarningOnStderr(t *testing.T) { + if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { + t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests") + } + t.Parallel() + bd := buildEmbeddedBD(t) + dir, _, _ := bdInit(t, bd, "--prefix", "jw") + + originURL := "file:///tmp/origin-collision-json-mode" + setGitOrigin(t, dir, originURL) + + // Run with --json and --allow-git-origin on collision — warning must go to stderr. + cmd := exec.Command(bd, "dolt", "--json", "remote", "add", "--allow-git-origin", "origin", originURL) + cmd.Dir = dir + cmd.Env = bdEnv(dir) + var stdout, stderr bytes.Buffer + cmd.Stdout = &stdout + cmd.Stderr = &stderr + _ = cmd.Run() + + if !strings.Contains(stderr.String(), "Warning:") { + t.Errorf("--json --allow-git-origin: expected Warning on stderr, got:\nstderr: %s\nstdout: %s", + stderr.String(), stdout.String()) + } +} diff --git a/cmd/bd/dolt_remote_origin_guard_test.go b/cmd/bd/dolt_remote_origin_guard_test.go new file mode 100644 index 000000000..187ee1702 --- /dev/null +++ b/cmd/bd/dolt_remote_origin_guard_test.go @@ -0,0 +1,192 @@ +package main + +import ( + "os/exec" + "strings" + "testing" + + "github.com/steveyegge/beads/cmd/bd/doctor" + "github.com/steveyegge/beads/internal/doltremote" +) + +// Unit tests for the git-origin collision guard helpers: +// gitOriginGetURL(), guardNormalizeURL(), doltRemoteMatchesGitOrigin(). +// These fail to compile until the builder adds those functions to dolt.go (or +// a new dolt_remote_guard.go). Also tests flag registration and the +// doctor.CategoryDolt constant. +// +// Tests in this file modify the working directory via t.Chdir() and must NOT +// run in parallel. + +// --- gitOriginGetURL --- + +func TestGitOriginGetURL_NoGitDir_ReturnsEmpty(t *testing.T) { + dir := t.TempDir() // plain directory, no git repo + t.Chdir(dir) + + got, err := gitOriginGetURL() + if err == nil { + t.Errorf("gitOriginGetURL() in non-git dir: expected error, got nil (url=%q)", got) + } + if got != "" { + t.Errorf("gitOriginGetURL() in non-git dir: want empty string, got %q", got) + } +} + +func TestGitOriginGetURL_NoOriginRemote_ReturnsEmpty(t *testing.T) { + dir := t.TempDir() + initBareGitRepoForTest(t, dir) + t.Chdir(dir) + + // git repo exists but no 'origin' remote is configured + got, err := gitOriginGetURL() + if err == nil { + t.Errorf("gitOriginGetURL() with no origin remote: expected error, got nil (url=%q)", got) + } + if got != "" { + t.Errorf("gitOriginGetURL() with no origin remote: want empty string, got %q", got) + } +} + +func TestGitOriginGetURL_WithOrigin_ReturnsURL(t *testing.T) { + dir := t.TempDir() + initBareGitRepoForTest(t, dir) + wantURL := "https://github.com/org/repo.git" + runGitCommand(t, dir, "remote", "add", "origin", wantURL) + t.Chdir(dir) + + got, err := gitOriginGetURL() + if err != nil { + t.Fatalf("gitOriginGetURL() with origin: unexpected error: %v", err) + } + if got != wantURL { + t.Errorf("gitOriginGetURL() = %q, want %q", got, wantURL) + } +} + +// --- doltremote.CanonicalForComparison --- +// Verify that all first-class Dolt URL forms and their git-origin equivalents +// normalize to the same canonical string, so the collision guard correctly +// detects matches regardless of which scheme Dolt stored. + +func TestCanonicalForComparison_HTTPSVariants(t *testing.T) { + // git origin (plain https) and Dolt remote (git+ prefix) must be equal. + plain := doltremote.CanonicalForComparison("https://github.com/org/repo.git") + gitPlus := doltremote.CanonicalForComparison("git+https://github.com/org/repo.git") + if plain != gitPlus { + t.Errorf("https and git+https canonical mismatch: %q vs %q", plain, gitPlus) + } +} + +func TestCanonicalForComparison_SCPAndGitSSH(t *testing.T) { + // SCP-style git origin and Dolt's git+ssh:// form must be equal. + scp := doltremote.CanonicalForComparison("git@github.com:org/repo.git") + ssh := doltremote.CanonicalForComparison("git+ssh://git@github.com/org/repo.git") + if scp != ssh { + t.Errorf("SCP and git+ssh canonical mismatch: %q vs %q", scp, ssh) + } +} + +func TestCanonicalForComparison_TrailingSlashAndDotGit(t *testing.T) { + // Trailing slash and .git variants of the same repo must all be equal. + base := doltremote.CanonicalForComparison("https://github.com/org/repo") + dotGit := doltremote.CanonicalForComparison("https://github.com/org/repo.git") + slash := doltremote.CanonicalForComparison("https://github.com/org/repo/") + dotGitSlash := doltremote.CanonicalForComparison("https://github.com/org/repo.git/") + if base != dotGit || base != slash || base != dotGitSlash { + t.Errorf("trailing-slash/.git variants differ: %q %q %q %q", base, dotGit, slash, dotGitSlash) + } +} + +// --- doltRemoteMatchesGitOrigin --- + +func TestDoltRemoteMatchesGitOrigin_NoGitDir_ReturnsFalse(t *testing.T) { + dir := t.TempDir() // no git repo + t.Chdir(dir) + + // Must return false (not panic, not error) when git origin is unavailable. + if doltRemoteMatchesGitOrigin("https://github.com/org/repo.git") { + t.Error("doltRemoteMatchesGitOrigin(): want false when no git dir, got true") + } +} + +func TestDoltRemoteMatchesGitOrigin_MatchingURL_ReturnsTrue(t *testing.T) { + dir := t.TempDir() + initBareGitRepoForTest(t, dir) + originURL := "https://github.com/org/repo.git" + runGitCommand(t, dir, "remote", "add", "origin", originURL) + t.Chdir(dir) + + // Exact match. + if !doltRemoteMatchesGitOrigin(originURL) { + t.Errorf("doltRemoteMatchesGitOrigin(%q) = false, want true (exact match)", originURL) + } + // Dolt-normalized form (git+ prefix) must also match. + if !doltRemoteMatchesGitOrigin("git+https://github.com/org/repo.git") { + t.Error("doltRemoteMatchesGitOrigin(git+https://…) = false, want true") + } +} + +func TestDoltRemoteMatchesGitOrigin_NormalizedMatch_ReturnsTrue(t *testing.T) { + dir := t.TempDir() + initBareGitRepoForTest(t, dir) + runGitCommand(t, dir, "remote", "add", "origin", "https://github.com/org/repo.git") + t.Chdir(dir) + + // URL without .git — should match after normalization. + if !doltRemoteMatchesGitOrigin("https://github.com/org/repo") { + t.Error("doltRemoteMatchesGitOrigin() = false for normalized match, want true") + } +} + +func TestDoltRemoteMatchesGitOrigin_DifferentURL_ReturnsFalse(t *testing.T) { + dir := t.TempDir() + initBareGitRepoForTest(t, dir) + runGitCommand(t, dir, "remote", "add", "origin", "https://github.com/org/repo.git") + t.Chdir(dir) + + if doltRemoteMatchesGitOrigin("https://doltremoteapi.dolthub.com/org/repo") { + t.Error("doltRemoteMatchesGitOrigin() = true for different URL, want false") + } +} + +// --- flag registration --- + +func TestAllowGitOriginFlag_RegisteredOnDoltRemoteAddCmd(t *testing.T) { + f := doltRemoteAddCmd.Flags().Lookup("allow-git-origin") + if f == nil { + t.Fatal("--allow-git-origin flag is not registered on doltRemoteAddCmd") + } + if f.Value.Type() != "bool" { + t.Errorf("--allow-git-origin flag type = %q, want \"bool\"", f.Value.Type()) + } +} + +// --- doctor.CategoryDolt --- + +func TestCategoryDolt_Exists(t *testing.T) { + if doctor.CategoryDolt == "" { + t.Fatal("doctor.CategoryDolt is empty — builder must define this constant in doctor/types.go") + } +} + +// --- helpers --- + +// initBareGitRepoForTest creates a minimal git repo in dir (no commits needed). +func initBareGitRepoForTest(t *testing.T, dir string) { + t.Helper() + runGitCommand(t, dir, "init") + runGitCommand(t, dir, "config", "user.email", "test@test.com") + runGitCommand(t, dir, "config", "user.name", "Test") + runGitCommand(t, dir, "config", "core.hooksPath", "/dev/null") +} + +// runGitCommand runs a git command in dir and fatals on error. +func runGitCommand(t *testing.T, dir string, args ...string) { + t.Helper() + cmd := exec.Command("git", args...) + cmd.Dir = dir + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out) + } +} diff --git a/cmd/bd/init.go b/cmd/bd/init.go index 7c5048be7..4979db016 100644 --- a/cmd/bd/init.go +++ b/cmd/bd/init.go @@ -2315,10 +2315,6 @@ func shouldConfigureInitDoltRemote(syncURL string, syncFromRemote, syncURLFromCo return !localOnly && shouldWireInitRemote(syncURL, syncFromRemote, syncURLFromConfig, syncURLFromGitOrigin) } -func isDoltLocalOnly() bool { - return config.GetBool("dolt.local-only") -} - // handleRemoteSafetyDecision applies a CheckRemoteSafety decision at an init // remote-divergence checkpoint. It returns (bootstrap, err): bootstrap is true // when the caller should clone/bootstrap from the remote, and err is a non-nil diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.md index a88a2f061..c9bd64c2b 100644 --- a/docs/CLI_REFERENCE.md +++ b/docs/CLI_REFERENCE.md @@ -3097,7 +3097,13 @@ bd dolt remote Add a Dolt remote ``` -bd dolt remote add +bd dolt remote add [flags] +``` + +**Flags:** + +``` + --allow-git-origin Allow adding a Dolt remote whose URL matches the git origin (proceed with a warning instead of aborting) ``` ##### bd dolt remote list diff --git a/internal/doltremote/remote.go b/internal/doltremote/remote.go index 526fccccd..222866241 100644 --- a/internal/doltremote/remote.go +++ b/internal/doltremote/remote.go @@ -69,6 +69,20 @@ func isSCPStyleGitURL(url string) bool { return false } +// CanonicalForComparison returns a form of url suitable for equality checks +// between URLs that refer to the same repository but may use different schemes +// or representations. Concretely: +// - https://github.com/org/repo.git ≡ git+https://github.com/org/repo.git +// - git@github.com:org/repo.git ≡ git+ssh://git@github.com/org/repo.git +// +// Algorithm: normalize to Dolt's git+ prefix form, strip trailing slashes and .git. +func CanonicalForComparison(url string) string { + url = Normalize(url) + url = strings.TrimRight(url, "/") + url = strings.TrimSuffix(url, ".git") + return url +} + func isWindowsDrivePath(path string) bool { if len(path) < 3 || path[1] != ':' { return false diff --git a/website/docs/cli-reference/dolt.md b/website/docs/cli-reference/dolt.md index fc47439c8..7997678e5 100644 --- a/website/docs/cli-reference/dolt.md +++ b/website/docs/cli-reference/dolt.md @@ -183,6 +183,12 @@ Add a Dolt remote bd dolt remote add [flags] ``` +**Flags:** + +``` + --allow-git-origin Allow adding a Dolt remote whose URL matches the git origin (proceed with a warning instead of aborting) +``` + #### bd dolt remote list List configured Dolt remotes diff --git a/website/versioned_docs/version-1.0.0/cli-reference/dolt.md b/website/versioned_docs/version-1.0.0/cli-reference/dolt.md index 978a7c427..68a47dd3c 100644 --- a/website/versioned_docs/version-1.0.0/cli-reference/dolt.md +++ b/website/versioned_docs/version-1.0.0/cli-reference/dolt.md @@ -180,7 +180,13 @@ bd dolt remote Add a Dolt remote ``` -bd dolt remote add +bd dolt remote add [flags] +``` + +**Flags:** + +``` + --allow-git-origin Allow adding a Dolt remote whose URL matches the git origin (proceed with a warning instead of aborting) ``` #### bd dolt remote list @@ -196,7 +202,13 @@ bd dolt remote list Remove a Dolt remote ``` -bd dolt remote remove +bd dolt remote remove [flags] +``` + +**Flags:** + +``` + --force Force remove even when SQL and CLI URLs conflict ``` ### bd dolt set diff --git a/website/versioned_docs/version-1.0.4/cli-reference/dolt.md b/website/versioned_docs/version-1.0.4/cli-reference/dolt.md index 978a7c427..68a47dd3c 100644 --- a/website/versioned_docs/version-1.0.4/cli-reference/dolt.md +++ b/website/versioned_docs/version-1.0.4/cli-reference/dolt.md @@ -180,7 +180,13 @@ bd dolt remote Add a Dolt remote ``` -bd dolt remote add +bd dolt remote add [flags] +``` + +**Flags:** + +``` + --allow-git-origin Allow adding a Dolt remote whose URL matches the git origin (proceed with a warning instead of aborting) ``` #### bd dolt remote list @@ -196,7 +202,13 @@ bd dolt remote list Remove a Dolt remote ``` -bd dolt remote remove +bd dolt remote remove [flags] +``` + +**Flags:** + +``` + --force Force remove even when SQL and CLI URLs conflict ``` ### bd dolt set diff --git a/website/versioned_docs/version-1.0.5/cli-reference/dolt.md b/website/versioned_docs/version-1.0.5/cli-reference/dolt.md index 978a7c427..68a47dd3c 100644 --- a/website/versioned_docs/version-1.0.5/cli-reference/dolt.md +++ b/website/versioned_docs/version-1.0.5/cli-reference/dolt.md @@ -180,7 +180,13 @@ bd dolt remote Add a Dolt remote ``` -bd dolt remote add +bd dolt remote add [flags] +``` + +**Flags:** + +``` + --allow-git-origin Allow adding a Dolt remote whose URL matches the git origin (proceed with a warning instead of aborting) ``` #### bd dolt remote list @@ -196,7 +202,13 @@ bd dolt remote list Remove a Dolt remote ``` -bd dolt remote remove +bd dolt remote remove [flags] +``` + +**Flags:** + +``` + --force Force remove even when SQL and CLI URLs conflict ``` ### bd dolt set