* fix(dolt): honor dolt.auto-commit=batch/off on the proxied-server write path (#4995)
In proxied-server mode every write minted a Dolt history commit whatever
dolt.auto-commit said. Two causes:
- cmd/bd/main.go never applied issueOpsContext(rootCtx) in the
proxiedServerMode branch of the root pre-run, so the context carried no
deferred-commit marker.
- internal/storage/uow/doltserver_tx.go: doltServerTx.Commit ignored
issueops.VersionCommitDeferred(ctx) and ran CALL DOLT_COMMIT('-Am', ?)
whenever a message was supplied.
Apply issueOpsContext to rootCtx in the proxied setup, and have
doltServerTx.Commit blank its message under a deferred context so the existing
plain-COMMIT branch persists the write to the working set without advancing
Dolt history. dolt.auto-commit=on is unchanged.
This commit alone strands batch/off writes in the working set; the explicit
flush point (`bd dolt commit`) follows in the later commits of this series.
(Originally recorded as "witness: salvage uncommitted work (ocb-ani)"; the
change itself is unmodified.)
* test(uow,cmd/bd): add regression tests for proxied dolt.auto-commit batch/off (#4995)
Add focused regression tests verifying that proxied dolt.auto-commit batch/off
defer Dolt version commits:
- cmd/bd: TestIssueOpsContextDefersByModeInProxiedServerMode verifies that
issueOpsContext defers version commits in proxied-server mode when
dolt.auto-commit is batch or off.
- internal/storage/uow: TestDoltServerTxCommitDefersDoltCommitUnderDeferredContext
and TestDoltServerTxRunTxWithDeferredContextSkipsDoltCommit verify that
doltServerTx.Commit blanks the commit message under a deferred context,
bypassing DOLT_COMMIT and status checks, and executing plain COMMIT to
persist writes into the working set without advancing Dolt history.
* fix(dolt): add the proxied flush point dolt.auto-commit=batch/off defers to (#4995)
The deferral half of this PR makes dolt.auto-commit=batch/off actually take
effect on the proxied-server write path. On its own that turns batch/off into
"never commit": proxied mode returns from the root pre-run before newDoltStore
runs, so getStore() is nil and `bd dolt commit` has no store to commit
through. Writes pile up in the sql-server working set where `dolt log`,
`dolt push` and backups never see them.
Add the missing half. cmd/bd/dolt_commit_proxied_server.go is the proxied dual
of `bd dolt commit`: it takes the uow.MaintenanceProvider route (RunNonTx) and
runs CALL DOLT_COMMIT('-Am', ?) on a pinned connection, gated on
issueops.HasPendingChanges. It deliberately does not go through
doltServerTx.Commit, which blanks its own message under the deferred context;
routing the flush through the deferral it exists to discharge would make the
flush a no-op. doltCommitCmd dispatches to it on usesProxiedServer(); the
message is built before the branch so both routes name the same default, and
the "Committed." / "Nothing to commit." contract is unchanged.
--dolt-auto-commit's help no longer claims proxied-server routes are
unaffected: it names the proxied flush point and keeps the SIGTERM/SIGHUP
flush marked embedded-only. docs/reference/configuration.md says the same.
`bd vc commit`'s proxied refusal now points at `bd dolt commit`.
Tests:
- cmd/bd/dolt_commit_proxied_integration_test.go: three batch writes leave
dolt_log unchanged and stay readable, `bd dolt commit` advances it by
exactly one, a second `bd dolt commit` reports "Nothing to commit." with
dolt_log unchanged, and one write under --dolt-auto-commit on advances it
by one. On the PR's original base it failed at the `bd dolt commit` step
with "no store available". On current main the front door refuses the
command before that code is reached, so this test is only green together
with the next commit, which moves `dolt commit` to supported in the proxy
capability registry.
- TestIssueOpsContextDefersByModeInProxiedServerMode renamed to
TestIssueOpsContextDefersByModePolicyTable and the proxiedServerMode
assignment dropped: issueOpsContext branches only on writesCommitNow(),
never on the storage mode, so the old name over-promised.
- doltserver_tx_test.go: "bd: update bd-4995" -> "bd: update GH#4995", which
no longer reads as a bead id.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(proxy): move `dolt commit` from refused to supported in the capability registry
Main's proxy capability registry (added by #6269, 24a9da6cc) declares
`dolt commit` direct-only: it has a "proxy.dolt_commit.unsupported" refusal
in proxyMaintenanceRefusals (cmd/bd/proxy_capability.go) and is classed
HistoryDirectOnly in historyCapabilityMatrix (cmd/bd/history_capability.go).
The front door therefore refuses `bd dolt commit` in proxied-server mode
before dispatch, so the proxied dual added earlier in this series is
unreachable, and dolt.auto-commit=batch/off has no way to flush.
the history/VC front-door contract, and neither the registry, its tests nor
the docs explain why `dolt commit` was listed. Nothing on main implemented
`dolt commit` for the proxied route at the time, which is consistent with the
entry being a statement of what existed rather than a design decision.
This flips a capability main had declared unsupported, deliberately: the
proxied route now has an implementation (runDoltCommitProxiedServer), and
batch/off need it as their flush point (GH#4995).
Declared the same way as the other proxied-supported command,
`dolt remote remove`: HistoryProxySupported in the history matrix, and no row
in proxyMaintenanceRefusals.
Tests follow: history_capability_test.go moves `dolt commit` from the
direct-only assertions and refusal contract to the proxy-supported ones
(including the nested front-door pass-through), and
history_remote_frontdoor_matrix_test.go drops the refusal row and adds a
`dolt commit` pass-through check to TestHistoryRemoteSupportedFrontDoorParity.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(proxy): exempt explicit commit points from the proxied deferral (#4995)
Maintainer review fixup for PR #6499, adopt-pr iterations 1-2.
Major (Contract & Interface Fidelity). The deferral is applied once, to
rootCtx, so it blanketed BOTH commit classes the direct route distinguishes by
which wrapper a verb picks: policy-honoring writes (transactHonoringAutoCommit,
per-verb issueOpsContext) and explicit commit points (transact, which passes
the caller's message whatever the policy says). Under dolt.auto-commit=batch a
proxied `bd batch -m "release batch"` therefore persisted the rows, discarded
the message and minted nothing, while the identical command and config on the
direct route committed it — and batch_proxied_server.go's own contract comment
rejects exactly that ("would persist these writes while silently bypassing
Dolt history"), as does batch.go's "the contract is the same on both backends".
issueops.WithImmediateVersionCommit clears the marker and cmd/bd's
explicitCommitPointContext applies it in the duals whose direct twin calls
transact. Scope is the intersection of the transact call sites with
proxyPermittedPaths: batch, mol bond/pour/squash, mol wisp create, and the
WISP half of mol burn (cook and migrate issues also call transact but are
refused in proxied mode, so they have no dual to exempt). The review sized the
radius at batch + 4 mol verbs; mol wisp create is the same class — its direct
twin reaches cloneSubgraph's transact through spawnMoleculeWithOptions — so it
is exempted with them.
Membership is per commit site, not per command (iteration 2). `bd mol burn` is
two classes on the direct route: wisps go through burnWisps -> transact, while
persistent molecules go through deleteBatch -> issueOpsContext ->
dolt/deleter.go, which returns before DOLT_COMMIT when the context defers.
Exempting the whole command minted one Dolt commit per persistent molecule
under batch/off — on a destructive verb, where the identical direct-route
command defers them all to `bd dolt commit`. runMolBurnProxiedServer now
applies the exemption to the wisp RunTxResult only, and the flag help,
configuration.md and the helper's own radius comment say so.
Minors:
- The flush passes '--author' like DoltStorage.CommitAll, so the one commit
batch mode keeps is attributed to the bd actor rather than the SQL session
user (without it dolt_log reads `root <root@localhost>`).
- runDoltCommitProxiedServer calls the shared runProxiedNonTx instead of
re-implementing its provider checks, so `bd --json dolt commit` keeps the
JSON error envelope; `dolt commit`'s RunE no longer re-wraps an
already-reported failure, and runProxiedNonTx's message gains the provider
%T the open-coded version had.
- The flag help and configuration.md drop two false claims: that the deferral
covers "every write" in proxied mode (the bd serve plane over the same
provider never touches rootCtx, so daemon writes still commit per write) and
that the SIGTERM/SIGHUP flush is "embedded-only" (flushBatchCommitOnShutdown
gates on an open store, which direct SQL-server mode has; only proxied mode
lacks one). Both surfaces now name the explicit-commit-point exemption.
- Both user-facing enumerations of that exemption are now derived from the
explicitCommitPointContext call sites rather than restated (iteration 2):
they had omitted mol wisp create, listed mol burn wholesale, and implied a
message-less `bd batch` defers when batch.go synthesizes a default message
and the dual exempts unconditionally, so every proxied batch commits.
- doltserver_tx.go's ephemeral-form comment names its second entry point —
RunTx/RunTxResult under a deferred context — where its
ONLY-dolt_ignored-state rationale stops applying.
Not done: regenerating docs/CLI_REFERENCE.md. Its --dolt-auto-commit drift is
base-preexisting, and the generated CLI docs are built from the release tag
pinned in docs/cli-docs.pin, not from this source, so touching them converts
the drift gate's inherited-drift warn-pass into a failure.
Tests. The uow blanking table gains the immediate-commit arm (tagless, so it
runs in every lane); the proxied integration test gains an explicit-batch-commit
step with a deferred plain create as its control, plus the flush attribution
assertions. Mutation-proved: reverting explicitCommitPointContext to a no-op
reds the new step (dolt_log 80 -> 80, no commit minted), and dropping
'--author' reds the attribution assertion with committer=root.
Iteration 2 adds the WIRING pin those left open — the mechanism was covered,
but deleting `ctx = explicitCommitPointContext(ctx)` from a dual was green in
every lane, which is why the mol burn over-application above was invisible.
dolt_autocommit_exemption_wiring_test.go is tagless and needs no server: a
uow.UnitOfWorkProvider that records the context RunTxResult hands NewUOW and
then refuses observes exactly the context each dual gives its transaction.
Mutation-proved per arm: neutering the exemption at batch/bond/squash reds
those three rows and only those; dropping it from the wisp RunTxResult reds
the wisp arm alone; and restoring the command-wide reassignment reds the
persistent arm alone, reproducing the defect this iteration fixes.
Validation: go build ./..., go vet (cgo and CGO_ENABLED=0), gofmt clean;
internal/storage/issueops; internal/storage/uow -run TestDoltServerTx; the
cmd/bd registry / history / policy / batch / mol / wisp / errors battery; and
the gated real-server lane BEADS_TEST_PROXIED_SERVER=1 green for both
TestProxiedServerBatchDefersThenDoltCommitAdvancesHeadOnce (41s) and
TestProxiedServerMolBurn (33s, all four subtests including the mixed
wisp+persistent burn this iteration changed).
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
380 lines
15 KiB
Go
380 lines
15 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
|
|
"github.com/spf13/cobra"
|
|
|
|
"github.com/steveyegge/beads/internal/beads"
|
|
"github.com/steveyegge/beads/internal/metrics"
|
|
"github.com/steveyegge/beads/internal/migration"
|
|
"github.com/steveyegge/beads/internal/ui"
|
|
)
|
|
|
|
type exitError struct {
|
|
Code int
|
|
}
|
|
|
|
func (e *exitError) Error() string {
|
|
return fmt.Sprintf("exit code %d", e.Code)
|
|
}
|
|
|
|
func exitCodeFromError(err error) (int, bool) {
|
|
var ee *exitError
|
|
if errors.As(err, &ee) {
|
|
return ee.Code, true
|
|
}
|
|
return 0, false
|
|
}
|
|
|
|
// isReportedExit reports whether err is an already-rendered failure — the
|
|
// *exitError every Handle*Error returns after writing the message (or the JSON
|
|
// error envelope) itself. A caller that re-wraps one prints a second Error line
|
|
// and, in --json mode, a plain line after the envelope.
|
|
func isReportedExit(err error) bool {
|
|
_, reported := exitCodeFromError(err)
|
|
return reported
|
|
}
|
|
|
|
func activeWorkspaceNotFoundError() string {
|
|
return "no active beads workspace found"
|
|
}
|
|
|
|
func activeWorkspaceNotFoundMessage() string {
|
|
return "No active beads workspace found."
|
|
}
|
|
|
|
func diagHint() string {
|
|
return workspaceDiagHint(true)
|
|
}
|
|
|
|
func whereDiagHint() string {
|
|
return workspaceDiagHint(false)
|
|
}
|
|
|
|
func workspaceDiagHint(includeWhere bool) string {
|
|
if includeWhere {
|
|
if !usesSQLServer() {
|
|
return "run 'bd where' to inspect the resolved workspace, or 'bd init' to create a new database"
|
|
}
|
|
return "run 'bd where' to inspect the resolved workspace, run 'bd doctor' to diagnose, or 'bd init' to create a new database"
|
|
}
|
|
if !usesSQLServer() {
|
|
return "check BEADS_DIR/worktree setup, or run 'bd init' to create a new database"
|
|
}
|
|
return "check BEADS_DIR/worktree setup, run 'bd doctor' to diagnose, or run 'bd init' to create a new database"
|
|
}
|
|
|
|
func buildJSONError(message, hint string) interface{} {
|
|
inner := map[string]interface{}{
|
|
"error": message,
|
|
}
|
|
if hint != "" {
|
|
inner["hint"] = hint
|
|
}
|
|
if jsonEnvelopeEnabled() {
|
|
return map[string]interface{}{
|
|
"schema_version": JSONSchemaVersion,
|
|
"data": inner,
|
|
}
|
|
}
|
|
inner["schema_version"] = JSONSchemaVersion
|
|
return inner
|
|
}
|
|
|
|
// buildJSONCapabilityError renders a typed refusal. {code, error, mutates} is a
|
|
// frozen contract that downstream consumers parse; `reason` is additive and
|
|
// appears only on refusals that came from the capability registry, which is why
|
|
// it is omitted rather than emitted empty — a consumer that keys on its presence
|
|
// must not be told "" by a runtime state error that has no policy reason.
|
|
func buildJSONCapabilityError(e *ProxyCapabilityError) interface{} {
|
|
inner := map[string]interface{}{"error": e.Message, "code": e.Code, "mutates": e.Mutates}
|
|
if e.Reason != "" {
|
|
inner["reason"] = string(e.Reason)
|
|
}
|
|
if jsonEnvelopeEnabled() {
|
|
return map[string]interface{}{"schema_version": JSONSchemaVersion, "data": inner}
|
|
}
|
|
inner["schema_version"] = JSONSchemaVersion
|
|
return inner
|
|
}
|
|
|
|
// HandleProxyCapabilityError renders a stable capability refusal while
|
|
// preserving the normal text/JSON front-door conventions.
|
|
//
|
|
// The allow path of every AssertProxy*Capability returns nil, and this wraps
|
|
// that return value directly, so nil must pass through: without the fast path
|
|
// errors.As(nil, ...) is false and an allowed capability would render as
|
|
// "Error: <nil>" with exit 1 at a front door nothing downstream catches.
|
|
func HandleProxyCapabilityError(err error) error {
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
var capErr *ProxyCapabilityError
|
|
if !errors.As(err, &capErr) {
|
|
return HandleErrorRespectJSON("%v", err)
|
|
}
|
|
code := capErr.ExitCode
|
|
if code == 0 {
|
|
code = 1
|
|
}
|
|
if jsonOutput {
|
|
enc := json.NewEncoder(os.Stdout)
|
|
enc.SetIndent("", " ")
|
|
_ = enc.Encode(buildJSONCapabilityError(capErr))
|
|
} else {
|
|
fmt.Fprintf(os.Stderr, "Error: %s\n", capErr.Message)
|
|
}
|
|
return &exitError{Code: code}
|
|
}
|
|
|
|
func jsonStderrError(message, hint string) {
|
|
encoder := json.NewEncoder(os.Stderr)
|
|
encoder.SetIndent("", " ")
|
|
_ = encoder.Encode(buildJSONError(message, hint))
|
|
}
|
|
|
|
func jsonStdoutError(message, hint string) {
|
|
encoder := json.NewEncoder(os.Stdout)
|
|
encoder.SetIndent("", " ")
|
|
_ = encoder.Encode(buildJSONError(message, hint))
|
|
}
|
|
|
|
func HandleError(format string, args ...interface{}) error {
|
|
fmt.Fprintf(os.Stderr, "Error: "+format+"\n", args...)
|
|
return &exitError{Code: 1}
|
|
}
|
|
|
|
func HandleErrorRespectJSON(format string, args ...interface{}) error {
|
|
if jsonOutput {
|
|
jsonStdoutError(fmt.Sprintf(format, args...), "")
|
|
return &exitError{Code: 1}
|
|
}
|
|
return HandleError(format, args...)
|
|
}
|
|
|
|
func HandleErrorWithHint(message, hint string) error {
|
|
if jsonOutput {
|
|
jsonStderrError(message, hint)
|
|
} else {
|
|
fmt.Fprintf(os.Stderr, "Error: %s\n", message) //nolint:gosec // G705: stderr, not a browser context
|
|
fmt.Fprintf(os.Stderr, "Hint: %s\n", hint) //nolint:gosec // G705: stderr, not a browser context
|
|
}
|
|
return &exitError{Code: 1}
|
|
}
|
|
|
|
func HandleErrorWithHintRespectJSON(message, hint string) error {
|
|
if jsonOutput {
|
|
jsonStdoutError(message, hint)
|
|
} else {
|
|
fmt.Fprintf(os.Stderr, "Error: %s\n", message)
|
|
fmt.Fprintf(os.Stderr, "Hint: %s\n", hint)
|
|
}
|
|
return &exitError{Code: 1}
|
|
}
|
|
|
|
func SilentExit() error {
|
|
return &exitError{Code: 1}
|
|
}
|
|
|
|
func WarnError(format string, args ...interface{}) {
|
|
fmt.Fprintf(os.Stderr, "Warning: "+format+"\n", args...)
|
|
}
|
|
|
|
// ExitMigrationFrozen is the exit code for a write refused because a
|
|
// migration freeze marker is active (dc-6jaq). Stable value so scripts can
|
|
// branch on "someone is migrating this workspace, come back later" without
|
|
// grep'ing stderr, instead of reading it as a generic failure (1) worth
|
|
// retrying immediately.
|
|
const ExitMigrationFrozen = 14
|
|
|
|
// CheckReadonly aborts the command when bd is running in read-only mode (the
|
|
// worker-sandbox posture, see readonlyMode), or when a migration freeze
|
|
// marker is active (dc-6jaq, folded in here rather than requiring every write
|
|
// command to remember a second call — see migrationFreezeError below). This
|
|
// is the chokepoint essentially every write command already calls first, so
|
|
// folding the freeze check in here covers the whole write surface at once,
|
|
// including commands added after this comment is written — not just a
|
|
// hand-picked list that rots (one concrete instance the hand-picked list
|
|
// missed: "bd q", cmd/bd/quick.go, the create alias). It exits via os.Exit
|
|
// and so cannot run the per-command deferred CloseEventAndAdd — a command
|
|
// blocked here records no cli_command event of its own (it never actually
|
|
// ran). It does flush metrics first, so events already queued earlier in this
|
|
// run are still written and scheduled for upload rather than stranded until
|
|
// the next clean exit. Callers that CAN return an error (the root
|
|
// PersistentPreRunE, runImport) call migrationFreezeError directly instead,
|
|
// so their deferred cleanup still runs.
|
|
func CheckReadonly(operation string) {
|
|
if readonlyMode {
|
|
fmt.Fprintf(os.Stderr, "Error: operation '%s' is not allowed in read-only mode\n", operation)
|
|
metrics.CloseAndFlush()
|
|
os.Exit(1)
|
|
}
|
|
if err := migrationFreezeError(operation); err != nil {
|
|
metrics.CloseAndFlush()
|
|
os.Exit(ExitMigrationFrozen)
|
|
}
|
|
}
|
|
|
|
// freezeSearchRoots returns the directories whose ancestry the freeze lookup
|
|
// must cover in addition to the working directory: the resolved workspace, so
|
|
// the gate keys on the store being written rather than on the caller's shell.
|
|
// Without it, `BEADS_DIR=/work/repo/.beads bd create` run from $HOME, `bd -C
|
|
// /work/repo create` (which sets BEADS_DIR and never chdirs), and any daemon
|
|
// or cron job with an unrelated cwd all walk the wrong tree and write straight
|
|
// through a freeze.
|
|
//
|
|
// PersistentPreRunE exports BEADS_DIR as part of selecting the workspace
|
|
// (prepareSelectedCommandContext), so by the time a command's RunE reaches
|
|
// CheckReadonly this is a cheap env read. The FindBeadsDir fallback covers the
|
|
// callers that run before that — and returns "" rather than erroring when
|
|
// there is no workspace at all, which Find skips.
|
|
func freezeSearchRoots() []string {
|
|
if dir := os.Getenv("BEADS_DIR"); dir != "" {
|
|
return []string{dir}
|
|
}
|
|
if dir := beads.FindBeadsDir(); dir != "" {
|
|
return []string{dir}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// migrationFreezeError reports the active migration freeze, if any: it
|
|
// returns nil when writes are not frozen, and otherwise prints the refusal to
|
|
// stderr and returns an ExitMigrationFrozen exit error. The refusal names the
|
|
// marker's own path, so the recovery instruction ("remove that file") is
|
|
// always actionable without knowing what created it.
|
|
//
|
|
// Three callers, each closing a different hole:
|
|
// 1. CheckReadonly above — the per-command chokepoint covering the write
|
|
// surface at large (create/update/close/... and everything that calls
|
|
// CheckReadonly, ~120 sites). Only that caller turns this error into an
|
|
// os.Exit, because its void signature leaves it nothing else to do.
|
|
// 2. The root PersistentPreRunE in main.go, before autoMigrateOnVersionBump
|
|
// and maybeAutoImportJSONL — those run as store-open side effects
|
|
// *before* any RunE, so waiting for a write command's own CheckReadonly
|
|
// call would let a version-bump migration or a JSONL auto-import slip
|
|
// through a freeze first (the most dangerous writes here, since they
|
|
// run against the very store the freeze protects).
|
|
// 3. import.go directly — bd import (runImport) is not gated by
|
|
// CheckReadonly at all today (a pre-existing, separate gap: readonlyMode
|
|
// doesn't block it either), so it cannot inherit the freeze check from
|
|
// caller 1 and needs its own explicit call.
|
|
func migrationFreezeError(operation string) error {
|
|
return migrationFreezeRefusal(operation, migration.Find(freezeSearchRoots()...))
|
|
}
|
|
|
|
// migrationFreezeRefusal renders an already-resolved lookup. Callers that
|
|
// need the same Result for more than the refusal — PersistentPreRunE, which
|
|
// also derives frozenForMaintenance from it — resolve once and pass it here,
|
|
// so a single walk answers the whole invocation and the two readings cannot
|
|
// disagree about a marker that appeared or vanished between them.
|
|
func migrationFreezeRefusal(operation string, res migration.Result) error {
|
|
if !res.Frozen() {
|
|
return nil
|
|
}
|
|
|
|
if res.Err != nil {
|
|
// Fail closed: bd could not tell whether a marker is present (a
|
|
// permission error on the marker or a directory above it). An
|
|
// undeterminable gate is not an open gate, and saying so beats
|
|
// writing into a workspace that may be mid-migration.
|
|
fmt.Fprint(os.Stderr, "⛔ ERROR: cannot determine whether this workspace is frozen for migration.\n")
|
|
fmt.Fprintf(os.Stderr, " %s\n", ui.SanitizeForTerminal(res.Err.Error()))
|
|
fmt.Fprintf(os.Stderr, " bd %s is blocked until the marker can be read.\n", operation)
|
|
fmt.Fprintf(os.Stderr, " Fix the permissions, or set %s to a path bd can stat.\n", migration.EnvFreezeFile)
|
|
return &exitError{Code: ExitMigrationFrozen}
|
|
}
|
|
|
|
// The marker can live in a directory bd does not control, so its payload
|
|
// is untrusted input on its way to a terminal. parse already keeps it to
|
|
// one line; sanitizing strips ANSI and control bytes on top of that.
|
|
operator := ""
|
|
reason := ""
|
|
if info := migration.ReadFile(res.Path); info != nil {
|
|
operator = ui.SanitizeForTerminal(info.Operator)
|
|
reason = ui.SanitizeForTerminal(info.Reason)
|
|
}
|
|
|
|
if operator != "" {
|
|
fmt.Fprintf(os.Stderr, "⛔ ERROR: workspace is frozen for migration (by %s).\n", operator)
|
|
} else {
|
|
// An empty or unparseable marker (a bare `touch`) records no
|
|
// operator; say nothing rather than printing "(by )".
|
|
fmt.Fprint(os.Stderr, "⛔ ERROR: workspace is frozen for migration.\n")
|
|
}
|
|
if reason != "" {
|
|
fmt.Fprintf(os.Stderr, " Reason: %s\n", reason)
|
|
}
|
|
fmt.Fprintf(os.Stderr, " bd %s is blocked by the freeze marker at %s.\n", operation, res.Path)
|
|
if res.FromEnv {
|
|
fmt.Fprintf(os.Stderr, " To resume writes, remove that file or unset %s.\n", migration.EnvFreezeFile)
|
|
} else {
|
|
// Name the variable on this path too: when the marker sits in a
|
|
// directory the caller cannot write to, pointing the variable
|
|
// elsewhere is the only recovery available to them.
|
|
fmt.Fprint(os.Stderr, " To resume writes, remove that file.\n")
|
|
fmt.Fprintf(os.Stderr, " If you cannot remove it, set %s to a path bd should check instead.\n", migration.EnvFreezeFile)
|
|
}
|
|
return &exitError{Code: ExitMigrationFrozen}
|
|
}
|
|
|
|
// migrationFreezeGate is the RunE-side entry point: it renders the refusal and,
|
|
// because the refusal has already said everything worth saying, suppresses
|
|
// cobra's own error and usage rendering for this invocation.
|
|
//
|
|
// Without the suppression a freeze refusal on any command that does not set
|
|
// SilenceErrors/SilenceUsage statically — duplicate, supersede, dep
|
|
// relate/unrelate, backup init/sync/remove/restore, ado sync, migrate-personal,
|
|
// batch — is followed by "Error: exit code 14" (exitError's placeholder text)
|
|
// and a full usage dump, so a clean refusal reads like a syntax error. Setting
|
|
// the flags here rather than on each command covers the ones added after this
|
|
// comment too. main() exits on the exitError before its own SilenceErrors
|
|
// branch, so nothing prints the placeholder.
|
|
func migrationFreezeGate(cmd *cobra.Command, operation string, res migration.Result) error {
|
|
err := migrationFreezeRefusal(operation, res)
|
|
if err != nil && cmd != nil {
|
|
cmd.SilenceErrors = true
|
|
cmd.SilenceUsage = true
|
|
}
|
|
return err
|
|
}
|
|
|
|
// migrationFreezeGateFor resolves the freeze and gates in one step, for the
|
|
// callers that have no Result to thread: the skip-store commands (bd init,
|
|
// bd bootstrap), which return from PersistentPreRunE long before it resolves
|
|
// one, and any command handed an explicit target path.
|
|
func migrationFreezeGateFor(cmd *cobra.Command, operation string, extraRoots ...string) error {
|
|
return migrationFreezeGate(cmd, operation, migration.Find(freezeRootsWith(extraRoots)...))
|
|
}
|
|
|
|
// migrationFreezeErrorFor is migrationFreezeError against extra roots, for
|
|
// callers that hold a target path but no *cobra.Command to silence — a command
|
|
// given a workspace to operate on that is not the one it was launched in.
|
|
func migrationFreezeErrorFor(operation string, extraRoots ...string) error {
|
|
return migrationFreezeRefusal(operation, migration.Find(freezeRootsWith(extraRoots)...))
|
|
}
|
|
|
|
// migrationFreezeActive is the print-nothing probe for code that must SKIP a
|
|
// write during a freeze rather than refuse the whole command — the diagnosis
|
|
// paths that keep running while frozen but must not apply version tracking or
|
|
// schema auto-migration.
|
|
func migrationFreezeActive() bool {
|
|
return migrationFreezeActiveFor()
|
|
}
|
|
|
|
// migrationFreezeActiveFor is migrationFreezeActive against extra roots — the
|
|
// probe half of the migrationFreezeErrorFor pair, for a diagnosis path handed a
|
|
// workspace that is not the one bd was launched in. `bd doctor /frozen/repo`
|
|
// skips its own maintenance writes on the strength of this, so it has to look
|
|
// at the tree it is about to write to and not just at the caller's cwd.
|
|
func migrationFreezeActiveFor(extraRoots ...string) bool {
|
|
return migration.Find(freezeRootsWith(extraRoots)...).Frozen()
|
|
}
|
|
|
|
func freezeRootsWith(extraRoots []string) []string {
|
|
return append(freezeSearchRoots(), extraRoots...)
|
|
}
|