feat: add 'bd batch' for atomic multi-op transactions (#3165)

Shell scripts that loop over 'bd' invocations cause severe write
amplification on a dolt sql-server backed by btrfs+compression: each
process opens a connection, runs one operation, and creates one
DOLT_COMMIT. This new command lets a script collapse N operations into
a single dolt transaction with one DOLT_COMMIT.

Reads simple line-oriented commands from stdin (or -f file). Supported
subset matches what existing gascity orders actually loop over:

  close <id> [reason...]
  update <id> <key>=<value> [<key>=<value> ...]
  create <type> <priority> <title...>
  dep add <from-id> <to-id> [type]
  dep remove <from-id> <to-id>

Update keys: status, priority, title, assignee.

The command dispatches directly against storage.Transaction (which
already exists) so no refactoring of the existing cobra handlers is
required. Unsupported commands fail at parse time before any writes,
and any error inside the transaction rolls the whole batch back.

Tests:
- batch_test.go: tokenizer, parser, supported/unsupported commands,
  update key validation, command registration
- batch_embedded_test.go (//go:build cgo): full transaction commit,
  rollback on FK error, empty input no-op, unsupported command guard,
  dep remove path, and a guard test confirming the rollback trigger
  still actually fails at the storage layer

Co-authored-by: Jim Wordelman <jim@wordelman.name>
This commit is contained in:
Jim Wordelman 2026-04-10 13:10:59 -07:00 • committed by GitHub
commit e39f041783
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 997 additions and 0 deletions

463
cmd/bd/batch.go Normal file
View file

@ -0,0 +1,463 @@
package main
import (
"bufio"
"context"
"fmt"
"io"
"os"
"strconv"
"strings"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
)
// Scope note:
// `bd batch` is intentionally a narrow, write-oriented command runner. It does
// NOT re-use the top-level cobra handlers (close/update/create/dep) because
// those handlers read the global `store` and perform a full connection-
// per-operation workflow. Instead, batch parses a simple line-oriented grammar
// and dispatches directly against a shared storage.Transaction so the entire
// batch executes as a single dolt transaction (one DOLT_COMMIT).
//
// The supported grammar is a documented subset that matches what the gascity
// shell-script "orders" (gate-sweep.sh, spawn-storm-detect.sh,
// cross-rig-deps.sh) actually call in loops. See the Long help below for the
// exact list. Unsupported commands error out loudly.
var batchCmd = &cobra.Command{
Use: "batch",
GroupID: "maint",
Short: "Run multiple write operations in a single database transaction",
Long: `Run multiple write operations in a single database transaction.
Commands are read from stdin (one per line) or from a file via -f/--file.
All operations execute inside a single dolt transaction: on any error the
whole batch is rolled back, otherwise it is committed with one DOLT_COMMIT.
This is intended for shell scripts that currently invoke 'bd' many times in
a loop, which causes severe write amplification on a dolt sql-server backed
by btrfs+compression. Batching collapses N invocations into one transaction
and one dolt commit.
Grammar (one command per line):
close <id> [reason...]
update <id> <key>=<value> [<key>=<value> ...]
create <type> <priority> <title...>
dep add <from-id> <to-id> [type]
dep remove <from-id> <to-id>
#comment (blank lines and '# ...' comments are ignored)
Supported 'update' keys: status, priority, title, assignee
Supported dependency types: see 'bd dep add --help' (default: blocks)
Tokens are whitespace-separated. Double-quoted strings ("like this") may
contain spaces; use \" to embed a quote and \\ for a backslash.
Examples:
# From a pipe
bd list --status stale -q | awk '{print "close",$1," stale"}' | bd batch
# From a file
bd batch -f operations.txt
# Inline
printf 'close bd-1 done\nupdate bd-2 status=in_progress\n' | bd batch
On success, exits 0 and prints a summary (or JSON with --json). On any error,
rolls back the entire transaction and exits non-zero with the failing line.
NOTE: This is a narrow subset. Commands like 'show', 'list', 'ready', 'sync',
complex create flows, or any flag not listed above are NOT accepted. Use
normal 'bd' subcommands for interactive/read operations.`,
Args: cobra.NoArgs,
SilenceUsage: true,
SilenceErrors: false,
RunE: func(cmd *cobra.Command, args []string) error {
CheckReadonly("batch")
if store == nil {
return fmt.Errorf("no database connection available (%s)", diagHint())
}
filePath, _ := cmd.Flags().GetString("file")
dryRun, _ := cmd.Flags().GetBool("dry-run")
commitMsg, _ := cmd.Flags().GetString("message")
var reader io.Reader
if filePath != "" {
f, err := os.Open(filePath) // #nosec G304 -- user-supplied batch file
if err != nil {
return fmt.Errorf("open batch file: %w", err)
}
defer f.Close()
reader = f
} else {
reader = cmd.InOrStdin()
}
ops, err := parseBatchScript(reader)
if err != nil {
return fmt.Errorf("parsing batch input: %w", err)
}
if dryRun {
// In dry-run mode, just echo what would run. This is helpful for
// shell script authors verifying their scripts before running.
for _, op := range ops {
fmt.Fprintf(cmd.OutOrStdout(), "line %d: %s\n", op.line, op.raw)
}
if jsonOutput {
outputJSON(map[string]interface{}{
"dry_run": true,
"operations": len(ops),
})
} else {
fmt.Fprintf(cmd.OutOrStdout(), "%d operations parsed (dry-run, nothing executed)\n", len(ops))
}
return nil
}
if len(ops) == 0 {
// Empty input is a no-op success, matching 'bd list | bd batch' on
// an empty list.
if jsonOutput {
outputJSON(map[string]interface{}{
"operations": 0,
"status": "ok",
})
} else {
fmt.Fprintln(cmd.OutOrStdout(), "batch: 0 operations (no-op)")
}
return nil
}
if strings.TrimSpace(commitMsg) == "" {
commitMsg = fmt.Sprintf("bd: batch %d ops by %s", len(ops), getActor())
}
ctx := rootCtx
if ctx == nil {
ctx = context.Background()
}
results := make([]batchOpResult, 0, len(ops))
err = transact(ctx, store, commitMsg, func(tx storage.Transaction) error {
for _, op := range ops {
res, rerr := runBatchOp(ctx, tx, op)
if rerr != nil {
return fmt.Errorf("line %d (%s): %w", op.line, op.raw, rerr)
}
results = append(results, res)
}
return nil
})
if err != nil {
if jsonOutput {
outputJSONError(err, "batch_error")
}
return err
}
commandDidWrite.Store(true)
if jsonOutput {
outputJSON(map[string]interface{}{
"operations": len(results),
"status": "ok",
"results": results,
})
} else {
fmt.Fprintf(cmd.OutOrStdout(), "batch: %d operations committed\n", len(results))
for _, r := range results {
fmt.Fprintf(cmd.OutOrStdout(), " line %d: %s %s\n", r.Line, r.Op, r.Target)
}
}
return nil
},
}
func init() {
batchCmd.Flags().StringP("file", "f", "", "Read commands from file instead of stdin")
batchCmd.Flags().Bool("dry-run", false, "Parse input and echo commands without executing")
batchCmd.Flags().StringP("message", "m", "", "DOLT_COMMIT message (default: 'bd: batch N ops by <actor>')")
rootCmd.AddCommand(batchCmd)
}
// batchOp is one parsed command line.
type batchOp struct {
line int // 1-based source line number
raw string // original source line (for error messages)
cmd string // canonical command name, e.g. "close", "update", "dep.add"
args []string // remaining tokens
}
// batchOpResult is emitted per executed op for JSON reporting.
type batchOpResult struct {
Line int `json:"line"`
Op string `json:"op"`
Target string `json:"target,omitempty"`
}
// parseBatchScript reads the whole input and tokenizes each non-empty,
// non-comment line. It rejects unknown commands immediately so a bad script
// fails before any writes.
func parseBatchScript(r io.Reader) ([]batchOp, error) {
scanner := bufio.NewScanner(r)
// Allow long lines (descriptions, multi-token updates).
scanner.Buffer(make([]byte, 64*1024), 4*1024*1024)
var ops []batchOp
lineNo := 0
for scanner.Scan() {
lineNo++
raw := scanner.Text()
trimmed := strings.TrimSpace(raw)
if trimmed == "" || strings.HasPrefix(trimmed, "#") {
continue
}
tokens, err := tokenizeBatchLine(trimmed)
if err != nil {
return nil, fmt.Errorf("line %d: %w", lineNo, err)
}
if len(tokens) == 0 {
continue
}
op := batchOp{line: lineNo, raw: trimmed}
switch tokens[0] {
case "close":
op.cmd = "close"
op.args = tokens[1:]
case "update":
op.cmd = "update"
op.args = tokens[1:]
case "create":
op.cmd = "create"
op.args = tokens[1:]
case "dep":
if len(tokens) < 2 {
return nil, fmt.Errorf("line %d: 'dep' requires a subcommand (add|remove)", lineNo)
}
switch tokens[1] {
case "add":
op.cmd = "dep.add"
case "remove", "rm":
op.cmd = "dep.remove"
default:
return nil, fmt.Errorf("line %d: unknown dep subcommand %q (want add|remove)", lineNo, tokens[1])
}
op.args = tokens[2:]
default:
return nil, fmt.Errorf("line %d: unsupported batch command %q (supported: close, update, create, dep add, dep remove)", lineNo, tokens[0])
}
ops = append(ops, op)
}
if err := scanner.Err(); err != nil {
return nil, err
}
return ops, nil
}
// tokenizeBatchLine splits a line into whitespace-separated tokens with
// support for double-quoted strings. Escape sequences inside quotes: \" and
// \\. Anything else after a backslash inside quotes is treated literally.
func tokenizeBatchLine(s string) ([]string, error) {
var tokens []string
var cur strings.Builder
inQuote := false
hasToken := false
for i := 0; i < len(s); i++ {
c := s[i]
if inQuote {
if c == '\\' && i+1 < len(s) {
next := s[i+1]
if next == '"' || next == '\\' {
cur.WriteByte(next)
i++
continue
}
cur.WriteByte(c)
continue
}
if c == '"' {
inQuote = false
continue
}
cur.WriteByte(c)
continue
}
if c == '"' {
inQuote = true
hasToken = true
continue
}
if c == ' ' || c == '\t' {
if hasToken {
tokens = append(tokens, cur.String())
cur.Reset()
hasToken = false
}
continue
}
hasToken = true
cur.WriteByte(c)
}
if inQuote {
return nil, fmt.Errorf("unterminated quoted string")
}
if hasToken {
tokens = append(tokens, cur.String())
}
return tokens, nil
}
// runBatchOp dispatches a single parsed op against the shared transaction.
// It intentionally does NOT call any of the non-tx cobra handlers; it talks
// straight to storage.Transaction so everything joins the same SQL tx.
func runBatchOp(ctx context.Context, tx storage.Transaction, op batchOp) (batchOpResult, error) {
actorName := getActor()
result := batchOpResult{Line: op.line, Op: op.cmd}
switch op.cmd {
case "close":
if len(op.args) < 1 {
return result, fmt.Errorf("close requires <id>")
}
id := op.args[0]
reason := "Closed"
if len(op.args) > 1 {
reason = strings.Join(op.args[1:], " ")
}
if err := tx.CloseIssue(ctx, id, reason, actorName, ""); err != nil {
return result, err
}
result.Target = id
return result, nil
case "update":
if len(op.args) < 2 {
return result, fmt.Errorf("update requires <id> and at least one key=value")
}
id := op.args[0]
updates, err := parseUpdateKVs(op.args[1:])
if err != nil {
return result, err
}
if err := tx.UpdateIssue(ctx, id, updates, actorName); err != nil {
return result, err
}
result.Target = id
return result, nil
case "create":
if len(op.args) < 3 {
return result, fmt.Errorf("create requires <type> <priority> <title>")
}
issueType := types.IssueType(op.args[0])
// Accept common custom types too; fall back to type validation by the
// storage layer which knows about configured custom types. We only
// reject obviously-empty input here.
if strings.TrimSpace(op.args[0]) == "" {
return result, fmt.Errorf("create: type cannot be empty")
}
priority, err := strconv.Atoi(op.args[1])
if err != nil {
return result, fmt.Errorf("create: invalid priority %q: %w", op.args[1], err)
}
title := strings.Join(op.args[2:], " ")
if strings.TrimSpace(title) == "" {
return result, fmt.Errorf("create: title cannot be empty")
}
issue := &types.Issue{
Title: title,
IssueType: issueType,
Status: types.StatusOpen,
Priority: priority,
}
if err := tx.CreateIssue(ctx, issue, actorName); err != nil {
return result, err
}
result.Target = issue.ID
return result, nil
case "dep.add":
if len(op.args) < 2 {
return result, fmt.Errorf("dep add requires <from-id> <to-id>")
}
from, to := op.args[0], op.args[1]
depType := "blocks"
if len(op.args) >= 3 {
depType = op.args[2]
}
dt := types.DependencyType(depType)
if !dt.IsValid() {
return result, fmt.Errorf("dep add: invalid dependency type %q", depType)
}
dep := &types.Dependency{
IssueID: from,
DependsOnID: to,
Type: dt,
}
if err := tx.AddDependency(ctx, dep, actorName); err != nil {
return result, err
}
result.Target = fmt.Sprintf("%s->%s", from, to)
return result, nil
case "dep.remove":
if len(op.args) < 2 {
return result, fmt.Errorf("dep remove requires <from-id> <to-id>")
}
from, to := op.args[0], op.args[1]
if err := tx.RemoveDependency(ctx, from, to, actorName); err != nil {
return result, err
}
result.Target = fmt.Sprintf("%s->%s", from, to)
return result, nil
}
return result, fmt.Errorf("internal: unhandled batch op %q", op.cmd)
}
// parseUpdateKVs walks a slice of "key=value" tokens and builds the updates
// map accepted by storage.Transaction.UpdateIssue. Only a small, documented
// subset of fields is allowed — anything else is a hard error so typos in
// scripts never silently drop updates.
func parseUpdateKVs(kvs []string) (map[string]interface{}, error) {
updates := make(map[string]interface{}, len(kvs))
for _, kv := range kvs {
eq := strings.IndexByte(kv, '=')
if eq <= 0 {
return nil, fmt.Errorf("update: expected key=value, got %q", kv)
}
key := strings.TrimSpace(kv[:eq])
value := kv[eq+1:]
switch key {
case "status":
if !types.Status(value).IsValid() {
// IsValid excludes custom statuses; the transaction layer will
// re-validate. Still reject blatantly empty values here.
if strings.TrimSpace(value) == "" {
return nil, fmt.Errorf("update: status cannot be empty")
}
}
updates["status"] = value
case "priority":
p, err := strconv.Atoi(value)
if err != nil {
return nil, fmt.Errorf("update: invalid priority %q: %w", value, err)
}
updates["priority"] = p
case "title":
if strings.TrimSpace(value) == "" {
return nil, fmt.Errorf("update: title cannot be empty")
}
updates["title"] = value
case "assignee":
updates["assignee"] = value
default:
return nil, fmt.Errorf("update: unsupported key %q (allowed: status, priority, title, assignee)", key)
}
}
return updates, nil
}

View file

@ -0,0 +1,249 @@
//go:build cgo
package main
import (
"context"
"path/filepath"
"strings"
"testing"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
)
// runBatchScriptInTx is a tiny helper that mirrors what batchCmd.RunE does,
// minus the cobra/flag plumbing, so tests can drive batch execution against
// a *dolt.DoltStore without spawning a 'bd' subprocess.
func runBatchScriptInTx(t *testing.T, ctx context.Context, st storage.DoltStorage, script string) error {
t.Helper()
ops, err := parseBatchScript(strings.NewReader(script))
if err != nil {
return err
}
return st.RunInTransaction(ctx, "test: bd batch", func(tx storage.Transaction) error {
for _, op := range ops {
if _, err := runBatchOp(ctx, tx, op); err != nil {
return err
}
}
return nil
})
}
// seedBatchTestIssues creates three open issues for batch tests to operate on.
func seedBatchTestIssues(t *testing.T, ctx context.Context, st storage.DoltStorage, ids ...string) {
t.Helper()
for _, id := range ids {
issue := &types.Issue{
ID: id,
Title: "seed " + id,
Status: types.StatusOpen,
Priority: 2,
IssueType: types.TypeTask,
}
if err := st.CreateIssue(ctx, issue, "test"); err != nil {
t.Fatalf("seed CreateIssue %s: %v", id, err)
}
}
}
// TestBatch_AppliesAllInOneTransaction verifies that a batch with several
// supported operations commits atomically and all writes are visible
// afterwards.
func TestBatch_AppliesAllInOneTransaction(t *testing.T) {
tmpDir := t.TempDir()
st := newTestStoreWithPrefix(t, filepath.Join(tmpDir, ".beads", "beads.db"), "tb")
ctx := context.Background()
seedBatchTestIssues(t, ctx, st, "tb-1", "tb-2", "tb-3")
script := `# batch test: close one, update one, link two
close tb-1 done in batch
update tb-2 status=in_progress priority=1
dep add tb-3 tb-2
`
if err := runBatchScriptInTx(t, ctx, st, script); err != nil {
t.Fatalf("batch run: %v", err)
}
// Verify the close
got1, err := st.GetIssue(ctx, "tb-1")
if err != nil {
t.Fatalf("GetIssue tb-1: %v", err)
}
if got1.Status != types.StatusClosed {
t.Errorf("tb-1 status = %q, want closed", got1.Status)
}
// Verify the update
got2, err := st.GetIssue(ctx, "tb-2")
if err != nil {
t.Fatalf("GetIssue tb-2: %v", err)
}
if string(got2.Status) != "in_progress" {
t.Errorf("tb-2 status = %q, want in_progress", got2.Status)
}
if got2.Priority != 1 {
t.Errorf("tb-2 priority = %d, want 1", got2.Priority)
}
// Verify the dependency
deps, err := st.GetDependencies(ctx, "tb-3")
if err != nil {
t.Fatalf("GetDependencies tb-3: %v", err)
}
found := false
for _, d := range deps {
if d.ID == "tb-2" {
found = true
break
}
}
if !found {
t.Errorf("expected tb-3 to depend on tb-2, got %+v", deps)
}
}
// TestBatch_RollbackOnError verifies that if any op in the batch fails the
// entire transaction is rolled back and earlier writes are not visible.
//
// The trigger here is `dep add` referencing nonexistent issue IDs, which
// fails the foreign-key constraint on the dependencies table.
func TestBatch_RollbackOnError(t *testing.T) {
tmpDir := t.TempDir()
st := newTestStoreWithPrefix(t, filepath.Join(tmpDir, ".beads", "beads.db"), "tbr")
ctx := context.Background()
seedBatchTestIssues(t, ctx, st, "tbr-1", "tbr-2")
// Op 1 succeeds (close tbr-1), op 2 succeeds (update tbr-2), op 3
// references nonexistent IDs and must fail (FK violation). The whole tx
// should roll back; tbr-1 must remain open and tbr-2 must remain P2.
script := `close tbr-1 should-roll-back
update tbr-2 priority=0
dep add tbr-DOES-NOT-EXIST tbr-ALSO-MISSING
`
err := runBatchScriptInTx(t, ctx, st, script)
if err == nil {
t.Fatal("expected batch to fail because of foreign key violation")
}
// tbr-1 should still be open
got1, gerr := st.GetIssue(ctx, "tbr-1")
if gerr != nil {
t.Fatalf("GetIssue tbr-1: %v", gerr)
}
if got1.Status == types.StatusClosed {
t.Errorf("tbr-1 was closed despite rollback (status=%q)", got1.Status)
}
// tbr-2 should still be P2
got2, gerr := st.GetIssue(ctx, "tbr-2")
if gerr != nil {
t.Fatalf("GetIssue tbr-2: %v", gerr)
}
if got2.Priority != 2 {
t.Errorf("tbr-2 priority = %d, want 2 (rollback)", got2.Priority)
}
}
// TestBatch_EmptyScriptIsNoOp verifies that an empty input is treated as a
// successful no-op (matches `bd list ... | bd batch` with an empty pipeline).
func TestBatch_EmptyScriptIsNoOp(t *testing.T) {
tmpDir := t.TempDir()
st := newTestStoreWithPrefix(t, filepath.Join(tmpDir, ".beads", "beads.db"), "tbe")
ctx := context.Background()
if err := runBatchScriptInTx(t, ctx, st, ""); err != nil {
t.Errorf("empty script: %v", err)
}
if err := runBatchScriptInTx(t, ctx, st, "# only a comment\n\n"); err != nil {
t.Errorf("comment-only script: %v", err)
}
}
// TestBatch_UnsupportedCommandFailsBeforeWrites verifies that an unknown
// command anywhere in the input causes a parse-time failure with a clear
// message and no operations are executed (the test confirms the error
// surfaces before any writes hit the database).
func TestBatch_UnsupportedCommandFailsBeforeWrites(t *testing.T) {
tmpDir := t.TempDir()
st := newTestStoreWithPrefix(t, filepath.Join(tmpDir, ".beads", "beads.db"), "tbu")
ctx := context.Background()
seedBatchTestIssues(t, ctx, st, "tbu-1")
script := `close tbu-1 will-not-happen
show tbu-1
`
err := runBatchScriptInTx(t, ctx, st, script)
if err == nil {
t.Fatal("expected error for unsupported command")
}
if !strings.Contains(err.Error(), "unsupported batch command") {
t.Errorf("error should mention unsupported command, got: %v", err)
}
if !strings.Contains(err.Error(), "line 2") {
t.Errorf("error should reference the offending line, got: %v", err)
}
// Confirm tbu-1 is still open (parse failed before any tx ran).
got, gerr := st.GetIssue(ctx, "tbu-1")
if gerr != nil {
t.Fatalf("GetIssue tbu-1: %v", gerr)
}
if got.Status == types.StatusClosed {
t.Errorf("tbu-1 was closed even though parse should have failed first")
}
}
// TestBatch_DepRemoveInBatch verifies the dep.remove path inside a batch.
func TestBatch_DepRemoveInBatch(t *testing.T) {
tmpDir := t.TempDir()
st := newTestStoreWithPrefix(t, filepath.Join(tmpDir, ".beads", "beads.db"), "tbd")
ctx := context.Background()
seedBatchTestIssues(t, ctx, st, "tbd-1", "tbd-2")
if err := st.AddDependency(ctx, &types.Dependency{
IssueID: "tbd-1", DependsOnID: "tbd-2", Type: types.DepBlocks,
}, "test"); err != nil {
t.Fatalf("AddDependency: %v", err)
}
if err := runBatchScriptInTx(t, ctx, st, "dep remove tbd-1 tbd-2\n"); err != nil {
t.Fatalf("batch dep remove: %v", err)
}
deps, err := st.GetDependencies(ctx, "tbd-1")
if err != nil {
t.Fatalf("GetDependencies: %v", err)
}
for _, d := range deps {
if d.ID == "tbd-2" {
t.Errorf("dependency tbd-1 -> tbd-2 still present after dep remove")
}
}
}
// TestBatch_RollbackTriggerStillFailsAtStorageLayer is a guard against the
// rollback test silently passing if a future change makes
// tx.AddDependency tolerate missing issue IDs. If this test fails (i.e.
// AddDependency stops returning an error for unknown IDs), the rollback test
// must be rewritten to use a different failure trigger.
func TestBatch_RollbackTriggerStillFailsAtStorageLayer(t *testing.T) {
tmpDir := t.TempDir()
st := newTestStoreWithPrefix(t, filepath.Join(tmpDir, ".beads", "beads.db"), "tbg")
ctx := context.Background()
err := st.RunInTransaction(ctx, "test: trigger guard", func(tx storage.Transaction) error {
return tx.AddDependency(ctx, &types.Dependency{
IssueID: "tbg-MISSING-A",
DependsOnID: "tbg-MISSING-B",
Type: types.DepBlocks,
}, "test")
})
if err == nil {
t.Fatal("expected AddDependency on missing IDs to fail; if not, rewrite TestBatch_RollbackOnError")
}
}

285
cmd/bd/batch_test.go Normal file
View file

@ -0,0 +1,285 @@
package main
import (
"reflect"
"strings"
"testing"
)
func TestTokenizeBatchLine(t *testing.T) {
tests := []struct {
name string
in string
want []string
wantErr bool
}{
{
name: "simple",
in: "close bd-1 done",
want: []string{"close", "bd-1", "done"},
},
{
name: "tabs and spaces",
in: "close\tbd-1 done",
want: []string{"close", "bd-1", "done"},
},
{
name: "quoted with spaces",
in: `update bd-2 title="hello world"`,
want: []string{"update", "bd-2", "title=hello world"},
},
{
name: "escaped quote",
in: `create bug 1 "say \"hi\""`,
want: []string{"create", "bug", "1", `say "hi"`},
},
{
name: "escaped backslash",
in: `create bug 1 "back\\slash"`,
want: []string{"create", "bug", "1", `back\slash`},
},
{
name: "unterminated quote",
in: `close bd-1 "oops`,
wantErr: true,
},
{
name: "empty string",
in: "",
want: nil,
},
{
name: "empty quoted",
in: `update bd-1 title=""`,
want: []string{"update", "bd-1", "title="},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := tokenizeBatchLine(tt.in)
if (err != nil) != tt.wantErr {
t.Fatalf("tokenizeBatchLine(%q) err = %v, wantErr %v", tt.in, err, tt.wantErr)
}
if tt.wantErr {
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("tokenizeBatchLine(%q) = %v, want %v", tt.in, got, tt.want)
}
})
}
}
func TestParseBatchScript(t *testing.T) {
script := `# leading comment
# another
close bd-1 stale
update bd-2 status=in_progress priority=1
create task 2 "triage the backlog"
dep add bd-3 bd-4
dep add bd-3 bd-5 related
dep remove bd-6 bd-7
dep rm bd-8 bd-9
`
ops, err := parseBatchScript(strings.NewReader(script))
if err != nil {
t.Fatalf("parseBatchScript: %v", err)
}
wantCmds := []string{
"close",
"update",
"create",
"dep.add",
"dep.add",
"dep.remove",
"dep.remove",
}
if len(ops) != len(wantCmds) {
t.Fatalf("got %d ops, want %d: %+v", len(ops), len(wantCmds), ops)
}
for i, op := range ops {
if op.cmd != wantCmds[i] {
t.Errorf("op %d: cmd = %q, want %q", i, op.cmd, wantCmds[i])
}
if op.line == 0 {
t.Errorf("op %d: line number not set", i)
}
}
// Spot check: create title is one token via quoting
create := ops[2]
if create.cmd != "create" {
t.Fatalf("expected create, got %q", create.cmd)
}
if len(create.args) != 3 {
t.Fatalf("create args = %v, want 3 tokens", create.args)
}
if create.args[2] != "triage the backlog" {
t.Errorf("create title = %q, want %q", create.args[2], "triage the backlog")
}
// dep.add with type
depWithType := ops[4]
if depWithType.cmd != "dep.add" || len(depWithType.args) != 3 || depWithType.args[2] != "related" {
t.Errorf("dep.add with type mismatch: %+v", depWithType)
}
}
func TestParseBatchScript_Empty(t *testing.T) {
ops, err := parseBatchScript(strings.NewReader(""))
if err != nil {
t.Fatalf("parseBatchScript empty: %v", err)
}
if len(ops) != 0 {
t.Errorf("expected 0 ops, got %d", len(ops))
}
}
func TestParseBatchScript_OnlyCommentsAndBlank(t *testing.T) {
ops, err := parseBatchScript(strings.NewReader("# comment\n\n \n# another\n"))
if err != nil {
t.Fatalf("parseBatchScript: %v", err)
}
if len(ops) != 0 {
t.Errorf("expected 0 ops, got %d", len(ops))
}
}
func TestParseBatchScript_UnsupportedCommand(t *testing.T) {
_, err := parseBatchScript(strings.NewReader("show bd-1\n"))
if err == nil {
t.Fatal("expected error for unsupported command")
}
if !strings.Contains(err.Error(), "unsupported batch command") {
t.Errorf("error should mention unsupported command, got: %v", err)
}
if !strings.Contains(err.Error(), "line 1") {
t.Errorf("error should include line number, got: %v", err)
}
}
func TestParseBatchScript_UnsupportedCommandOnLaterLine(t *testing.T) {
script := "close bd-1\nshow bd-2\n"
_, err := parseBatchScript(strings.NewReader(script))
if err == nil {
t.Fatal("expected error")
}
if !strings.Contains(err.Error(), "line 2") {
t.Errorf("error should include line 2, got: %v", err)
}
}
func TestParseBatchScript_DepRequiresSubcommand(t *testing.T) {
_, err := parseBatchScript(strings.NewReader("dep\n"))
if err == nil {
t.Fatal("expected error for bare 'dep'")
}
if !strings.Contains(err.Error(), "subcommand") {
t.Errorf("error should mention subcommand, got: %v", err)
}
}
func TestParseBatchScript_DepUnknownSubcommand(t *testing.T) {
_, err := parseBatchScript(strings.NewReader("dep list bd-1\n"))
if err == nil {
t.Fatal("expected error for unknown dep subcommand")
}
if !strings.Contains(err.Error(), "dep subcommand") {
t.Errorf("error should mention dep subcommand, got: %v", err)
}
}
func TestParseBatchScript_UnterminatedQuote(t *testing.T) {
_, err := parseBatchScript(strings.NewReader(`create task 1 "oops`))
if err == nil {
t.Fatal("expected error for unterminated quote")
}
}
func TestParseUpdateKVs(t *testing.T) {
tests := []struct {
name string
in []string
want map[string]interface{}
wantErr bool
}{
{
name: "status and priority",
in: []string{"status=in_progress", "priority=1"},
want: map[string]interface{}{"status": "in_progress", "priority": 1},
},
{
name: "title",
in: []string{"title=new title"},
want: map[string]interface{}{"title": "new title"},
},
{
name: "assignee blank allowed (unassign)",
in: []string{"assignee="},
want: map[string]interface{}{"assignee": ""},
},
{
name: "unsupported key",
in: []string{"description=foo"},
wantErr: true,
},
{
name: "missing equals",
in: []string{"status"},
wantErr: true,
},
{
name: "invalid priority",
in: []string{"priority=high"},
wantErr: true,
},
{
name: "empty status",
in: []string{"status="},
wantErr: true,
},
{
name: "empty title",
in: []string{"title="},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := parseUpdateKVs(tt.in)
if (err != nil) != tt.wantErr {
t.Fatalf("parseUpdateKVs err = %v, wantErr %v", err, tt.wantErr)
}
if tt.wantErr {
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("parseUpdateKVs = %v, want %v", got, tt.want)
}
})
}
}
func TestBatchCmd_Registered(t *testing.T) {
// Ensure 'bd batch' is wired into rootCmd with the correct group.
cmd, _, err := rootCmd.Find([]string{"batch"})
if err != nil {
t.Fatalf("rootCmd.Find batch: %v", err)
}
if cmd == nil || cmd.Name() != "batch" {
t.Fatalf("expected batch command, got %+v", cmd)
}
if cmd.GroupID != "maint" {
t.Errorf("batch GroupID = %q, want %q", cmd.GroupID, "maint")
}
if cmd.Flags().Lookup("file") == nil {
t.Error("batch missing --file flag")
}
if cmd.Flags().Lookup("dry-run") == nil {
t.Error("batch missing --dry-run flag")
}
if cmd.Flags().Lookup("message") == nil {
t.Error("batch missing --message flag")
}
}