fix: route list formats through command writer (#5543) (#5610)

Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell
This commit is contained in:
ecuthiell 2026-08-10 21:59:20 -06:00 • committed by GitHub
commit 192a6cdd69
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
12 changed files with 310 additions and 40 deletions

View file

@ -163,6 +163,12 @@ in total before any individual status trips it.`,
},
}
func writeGraphLine(out io.Writer, value string) error {
w := &graphExportWriter{out: out}
w.println(value)
return w.wrapError("graph")
}
func renderGraphAllSubgraphs(out io.Writer, subgraphs []*TemplateSubgraph) error {
if graphOpen {
var filtered []*TemplateSubgraph
@ -176,8 +182,7 @@ func renderGraphAllSubgraphs(out io.Writer, subgraphs []*TemplateSubgraph) error
}
if len(subgraphs) == 0 {
fmt.Println("No open issues found")
return nil
return writeGraphLine(out, "No open issues found")
}
if jsonOutput {
@ -195,7 +200,9 @@ func renderGraphAllSubgraphs(out io.Writer, subgraphs []*TemplateSubgraph) error
layout := computeLayout(subgraph)
renderGraphCompact(layout, subgraph)
if i < len(subgraphs)-1 {
fmt.Println(strings.Repeat("─", 60))
if err := writeGraphLine(out, strings.Repeat("─", 60)); err != nil {
return err
}
}
}
return nil
@ -215,7 +222,9 @@ func renderGraphAllSubgraphs(out io.Writer, subgraphs []*TemplateSubgraph) error
renderGraphVisual(layout, subgraph)
}
if !graphDOT && i < len(subgraphs)-1 {
fmt.Println(strings.Repeat("─", 60))
if err := writeGraphLine(out, strings.Repeat("─", 60)); err != nil {
return err
}
}
}
return nil
@ -225,8 +234,7 @@ func renderGraphSingleSubgraph(out io.Writer, subgraph *TemplateSubgraph) error
if graphOpen {
subgraph = filterSubgraphOpen(subgraph)
if subgraph == nil || len(subgraph.Issues) == 0 {
fmt.Println("No open issues in subgraph")
return nil
return writeGraphLine(out, "No open issues in subgraph")
}
}

View file

@ -27,10 +27,10 @@ func bdGraph(t *testing.T, bd, dir string, args ...string) string {
return stdout.String()
}
// runGraphWithReadOnlyStdout gives the child a real stdout handle that cannot
// runWithReadOnlyStdout gives the child a real stdout handle that cannot
// be written. Unlike a closed pipe, this produces a normal write error on both
// Unix and Windows instead of depending on SIGPIPE behavior.
func runGraphWithReadOnlyStdout(t *testing.T, bd, dir string, env []string, args ...string) (string, error) {
func runWithReadOnlyStdout(t *testing.T, bd, dir string, env []string, args ...string) (string, error) {
t.Helper()
stdoutPath := filepath.Join(t.TempDir(), "stdout.txt")
if err := os.WriteFile(stdoutPath, nil, 0o600); err != nil {
@ -42,7 +42,7 @@ func runGraphWithReadOnlyStdout(t *testing.T, bd, dir string, env []string, args
}
defer func() { _ = stdout.Close() }()
cmd := exec.Command(bd, append([]string{"graph"}, args...)...)
cmd := exec.Command(bd, args...)
cmd.Dir = dir
cmd.Env = env
cmd.Stdout = stdout
@ -127,7 +127,7 @@ func TestEmbeddedGraph(t *testing.T) {
})
t.Run("dot_output_error", func(t *testing.T) {
stderr, err := runGraphWithReadOnlyStdout(t, bd, dir, bdEnv(dir), "--dot", epic.ID)
stderr, err := runWithReadOnlyStdout(t, bd, dir, bdEnv(dir), "graph", "--dot", epic.ID)
if err == nil {
t.Fatalf("graph --dot succeeded with read-only stdout; stderr:\n%s", stderr)
}
@ -136,6 +136,24 @@ func TestEmbeddedGraph(t *testing.T) {
}
})
for _, tc := range []struct {
name string
args []string
}{
{name: "all_separator_output_error", args: []string{"graph", "--all", "--compact"}},
{name: "all_open_separator_output_error", args: []string{"graph", "--all", "--open"}},
} {
t.Run(tc.name, func(t *testing.T) {
stderr, err := runWithReadOnlyStdout(t, bd, dir, bdEnv(dir), tc.args...)
if err == nil {
t.Fatalf("%s succeeded with read-only stdout; stderr:\n%s", strings.Join(tc.args, " "), stderr)
}
if !strings.Contains(stderr, "writing graph output") {
t.Fatalf("%s stderr = %q, want writer diagnostic", strings.Join(tc.args, " "), stderr)
}
})
}
// ===== --json =====
t.Run("json_output", func(t *testing.T) {

View file

@ -66,8 +66,8 @@ func renderGraphDOT(out io.Writer, layout *GraphLayout, subgraph *TemplateSubgra
}
// graphExportWriter records the first output failure and suppresses later
// writes. Export commands can therefore return one stable root cause without
// buffering the whole graph or changing successful output bytes.
// writes. Writer-aware graph and list paths can therefore return one stable
// root cause without buffering their whole output or changing successful bytes.
type graphExportWriter struct {
out io.Writer
err error

View file

@ -450,4 +450,50 @@ func TestGraphExportDispatchPropagatesWriterErrors(t *testing.T) {
t.Fatalf("renderGraphAllSubgraphs error = %v, want %v", err, io.ErrClosedPipe)
}
})
t.Run("all empty message", func(t *testing.T) {
graphDOT, graphHTML, graphOpen = false, false, false
var out bytes.Buffer
if err := renderGraphAllSubgraphs(&out, nil); err != nil {
t.Fatalf("renderGraphAllSubgraphs: %v", err)
}
if got, want := out.String(), "No open issues found\n"; got != want {
t.Fatalf("empty all output = %q, want %q", got, want)
}
})
t.Run("all empty message error", func(t *testing.T) {
graphDOT, graphHTML, graphOpen = false, false, false
writer := &graphFailWriter{err: io.ErrClosedPipe, failAt: 1}
err := renderGraphAllSubgraphs(writer, nil)
if !errors.Is(err, io.ErrClosedPipe) {
t.Fatalf("renderGraphAllSubgraphs error = %v, want %v", err, io.ErrClosedPipe)
}
})
t.Run("single empty open message", func(t *testing.T) {
graphDOT, graphHTML, graphOpen = false, false, true
subgraph := &TemplateSubgraph{Issues: []*types.Issue{{ID: "closed", Status: types.StatusClosed}}}
var out bytes.Buffer
if err := renderGraphSingleSubgraph(&out, subgraph); err != nil {
t.Fatalf("renderGraphSingleSubgraph: %v", err)
}
if got, want := out.String(), "No open issues in subgraph\n"; got != want {
t.Fatalf("empty single output = %q, want %q", got, want)
}
})
t.Run("single empty open message error", func(t *testing.T) {
graphDOT, graphHTML, graphOpen = false, false, true
subgraph := &TemplateSubgraph{Issues: []*types.Issue{{ID: "closed", Status: types.StatusClosed}}}
writer := &graphFailWriter{err: io.ErrClosedPipe, failAt: 1}
err := renderGraphSingleSubgraph(writer, subgraph)
if !errors.Is(err, io.ErrClosedPipe) {
t.Fatalf("renderGraphSingleSubgraph error = %v, want %v", err, io.ErrClosedPipe)
}
})
}

View file

@ -121,7 +121,7 @@ func TestProxiedServerGraph(t *testing.T) {
})
t.Run("html_output_error", func(t *testing.T) {
stderr, err := runGraphWithReadOnlyStdout(t, bd, p.dir, bdProxiedEnv(p.dir), "--html", epic.ID)
stderr, err := runWithReadOnlyStdout(t, bd, p.dir, bdProxiedEnv(p.dir), "graph", "--html", epic.ID)
if err == nil {
t.Fatalf("proxied graph --html succeeded with read-only stdout; stderr:\n%s", stderr)
}

View file

@ -189,6 +189,7 @@ func runListCore(cmd *cobra.Command, _ []string) error {
if err != nil {
return err
}
out := cmd.OutOrStdout()
if usesProxiedServer() {
// The cap USED to be rejected here: the proxied query path threaded no
@ -197,7 +198,7 @@ func runListCore(cmd *cobra.Command, _ []string) error {
// through the same two functions the store seam uses), so this route
// answers *ErrTooManyRows the same way the direct route below does —
// same message, same exit code.
if err := runListProxiedServer(cmd, rootCtx, in); err != nil {
if err := runListProxiedServer(cmd, rootCtx, out, in); err != nil {
if capErr := handleMaxRowsError(err); capErr != nil {
return capErr
}
@ -331,7 +332,7 @@ func runListCore(cmd *cobra.Command, _ []string) error {
if in.formatStr != "" {
depsByIssueID, _ := activeStore.GetAllDependencyRecords(ctx)
if err := outputFormattedList(issues, depsByIssueID, in.formatStr); err != nil {
if err := outputFormattedList(out, issues, depsByIssueID, in.formatStr); err != nil {
return HandleError("%v", err)
}
printTruncationHint(truncated, in.effectiveLimit)

View file

@ -747,6 +747,16 @@ func TestEmbeddedList(t *testing.T) {
}
})
t.Run("format_dot_output_error", func(t *testing.T) {
stderr, err := runWithReadOnlyStdout(t, bd, dir, bdEnv(dir), "list", "--format", "dot", "--flat", "--all")
if err == nil {
t.Fatalf("list --format dot succeeded with read-only stdout; stderr:\n%s", stderr)
}
if !strings.Contains(stderr, "writing DOT output") {
t.Fatalf("list --format dot stderr = %q, want writer diagnostic", stderr)
}
})
t.Run("compact_default", func(t *testing.T) {
out := bdList(t, bd, dir, "--flat")
if !strings.Contains(out, seed.openBug) {

View file

@ -3,6 +3,7 @@ package main
import (
"bytes"
"fmt"
"io"
"os"
"text/template"
@ -21,11 +22,12 @@ func printTruncationHint(truncated bool, effectiveLimit int) {
fmt.Fprint(os.Stderr, ui.RenderWarn(msg))
}
func outputDotFormat(issues []*types.Issue, depsByIssueID map[string][]*types.Dependency) error {
fmt.Println("digraph dependencies {")
fmt.Println(" rankdir=TB;")
fmt.Println(" node [shape=box, style=rounded];")
fmt.Println()
func outputDotFormat(out io.Writer, issues []*types.Issue, depsByIssueID map[string][]*types.Dependency) error {
w := &graphExportWriter{out: out}
w.println("digraph dependencies {")
w.println(" rankdir=TB;")
w.println(" node [shape=box, style=rounded];")
w.println()
// Build map of all issues for quick lookup
issueMap := make(map[string]*types.Issue)
@ -57,10 +59,10 @@ func outputDotFormat(issues []*types.Issue, depsByIssueID map[string][]*types.De
fillColor = "lightcoral"
}
fmt.Printf(" %q [label=%q, style=\"rounded,filled\", fillcolor=%q, fontcolor=%q];\n",
w.printf(" %q [label=%q, style=\"rounded,filled\", fillcolor=%q, fontcolor=%q];\n",
issue.ID, label, fillColor, fontColor)
}
fmt.Println()
w.println()
// Output edges with labels for dependency type
for _, issue := range issues {
@ -83,21 +85,22 @@ func outputDotFormat(issues []*types.Issue, depsByIssueID map[string][]*types.De
color = "gray"
style = "dashed"
}
fmt.Printf(" %q -> %q [label=%q, color=%s, style=%s];\n",
w.printf(" %q -> %q [label=%q, color=%s, style=%s];\n",
issue.ID, dep.DependsOnID, dep.Type, color, style)
}
}
}
fmt.Println("}")
return nil
w.println("}")
return w.wrapError("DOT")
}
func outputFormattedList(issues []*types.Issue, depsByIssueID map[string][]*types.Dependency, formatStr string) error {
func outputFormattedList(out io.Writer, issues []*types.Issue, depsByIssueID map[string][]*types.Dependency, formatStr string) error {
// Handle special 'dot' format (Graphviz output)
if formatStr == "dot" {
return outputDotFormat(issues, depsByIssueID)
return outputDotFormat(out, issues, depsByIssueID)
}
w := &graphExportWriter{out: out}
// Built-in format presets
presets := map[string]string{
@ -140,10 +143,13 @@ func outputFormattedList(issues []*types.Issue, depsByIssueID map[string][]*type
if err := tmpl.Execute(&buf, data); err != nil {
return fmt.Errorf("template execution error: %w", err)
}
fmt.Println(buf.String())
w.println(buf.String())
if err := w.wrapError("formatted list"); err != nil {
return err
}
}
}
}
return nil
return w.wrapError("formatted list")
}

169
cmd/bd/list_output_test.go Normal file
View file

@ -0,0 +1,169 @@
package main
import (
"bytes"
"errors"
"io"
"strings"
"testing"
"github.com/steveyegge/beads/internal/types"
)
func listOutputFixture() ([]*types.Issue, map[string][]*types.Dependency) {
issues := []*types.Issue{
{
ID: "list-a",
Title: "Alpha",
Status: types.StatusOpen,
Priority: 1,
IssueType: types.TypeBug,
},
{
ID: "list-b",
Title: "Beta",
Status: types.StatusClosed,
Priority: 2,
IssueType: types.TypeTask,
},
}
deps := map[string][]*types.Dependency{
"list-a": {
{
IssueID: "list-a",
DependsOnID: "list-b",
Type: types.DepBlocks,
},
},
}
return issues, deps
}
func TestOutputDotFormatExactBytes(t *testing.T) {
t.Parallel()
issues, deps := listOutputFixture()
var out bytes.Buffer
if err := outputDotFormat(&out, issues, deps); err != nil {
t.Fatalf("outputDotFormat: %v", err)
}
const want = `digraph dependencies {
rankdir=TB;
node [shape=box, style=rounded];
"list-a" [label="list-a\n[bug P1]\nAlpha\n(open)", style="rounded,filled", fillcolor="white", fontcolor="black"];
"list-b" [label="list-b\n[task P2]\nBeta\n(closed)", style="rounded,filled", fillcolor="lightgray", fontcolor="dimgray"];
"list-a" -> "list-b" [label="blocks", color=red, style=bold];
}
`
if got := out.String(); got != want {
t.Fatalf("DOT output bytes differ\ngot:\n%q\nwant:\n%q", got, want)
}
}
func TestOutputFormattedListExactBytes(t *testing.T) {
t.Parallel()
issues, deps := listOutputFixture()
for _, tc := range []struct {
name string
format string
want string
}{
{name: "digraph preset", format: "digraph", want: "list-a list-b\n"},
{name: "custom template", format: "{{.IssueID}} -> {{.DependsOnID}} [{{.Type}}]", want: "list-a -> list-b [blocks]\n"},
} {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
var out bytes.Buffer
if err := outputFormattedList(&out, issues, deps, tc.format); err != nil {
t.Fatalf("outputFormattedList: %v", err)
}
if got := out.String(); got != tc.want {
t.Fatalf("formatted output bytes differ: got %q, want %q", got, tc.want)
}
})
}
}
func TestOutputFormattedListWriterErrors(t *testing.T) {
t.Parallel()
issues, deps := listOutputFixture()
for _, tc := range []struct {
name string
format string
failAt int
wantContext string
}{
{name: "DOT", format: "dot", failAt: 3, wantContext: "writing DOT output"},
{name: "digraph preset", format: "digraph", failAt: 1, wantContext: "writing formatted list output"},
{name: "custom template", format: "{{.IssueID}} {{.DependsOnID}}", failAt: 1, wantContext: "writing formatted list output"},
} {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
writer := &graphFailWriter{err: io.ErrClosedPipe, failAt: tc.failAt}
err := outputFormattedList(writer, issues, deps, tc.format)
if !errors.Is(err, io.ErrClosedPipe) {
t.Fatalf("outputFormattedList error = %v, want %v", err, io.ErrClosedPipe)
}
if !strings.Contains(err.Error(), tc.wantContext) {
t.Fatalf("outputFormattedList error = %q, want context %q", err, tc.wantContext)
}
if writer.writes != writer.failAt {
t.Fatalf("outputFormattedList made %d writes after failure at %d", writer.writes, writer.failAt)
}
})
}
}
func TestOutputFormattedListPreservesFirstWriterError(t *testing.T) {
t.Parallel()
issues := []*types.Issue{{ID: "first"}, {ID: "second"}, {ID: "target"}}
deps := map[string][]*types.Dependency{
"first": {{IssueID: "first", DependsOnID: "target", Type: types.DepBlocks}},
"second": {{IssueID: "second", DependsOnID: "target", Type: types.DepBlocks}},
}
writer := &graphFailWriter{err: io.ErrClosedPipe, failAt: 1}
format := `{{if eq .IssueID "second"}}{{index .Issue.Labels 0}}{{else}}{{.IssueID}}{{end}}`
err := outputFormattedList(writer, issues, deps, format)
if !errors.Is(err, io.ErrClosedPipe) {
t.Fatalf("outputFormattedList error = %v, want first writer error %v", err, io.ErrClosedPipe)
}
if writer.writes != 1 {
t.Fatalf("outputFormattedList made %d writes, want one failing write", writer.writes)
}
}
func TestOutputFormattedListBuffersTemplateExecution(t *testing.T) {
t.Parallel()
issues := []*types.Issue{{ID: "source"}, {ID: "target"}}
deps := map[string][]*types.Dependency{
"source": {{IssueID: "source", DependsOnID: "target", Type: types.DepBlocks}},
}
var out bytes.Buffer
err := outputFormattedList(&out, issues, deps, "prefix{{index .Issue.Labels 0}}")
if err == nil || !strings.Contains(err.Error(), "template execution error") {
t.Fatalf("outputFormattedList error = %v, want template execution error", err)
}
if out.Len() != 0 {
t.Fatalf("failed template leaked partial output %q", out.String())
}
}
func TestOutputFormattedListWithNoEdgesDoesNotWrite(t *testing.T) {
t.Parallel()
writer := &graphFailWriter{err: io.ErrClosedPipe, failAt: 1}
if err := outputFormattedList(writer, []*types.Issue{{ID: "solo"}}, nil, "digraph"); err != nil {
t.Fatalf("outputFormattedList: %v", err)
}
if writer.writes != 0 {
t.Fatalf("zero-edge output made %d writes, want 0", writer.writes)
}
}

View file

@ -470,6 +470,16 @@ func TestProxiedServerList(t *testing.T) {
}
})
t.Run("format_digraph_output_error", func(t *testing.T) {
stderr, err := runWithReadOnlyStdout(t, bd, p.dir, bdProxiedEnv(p.dir), "list", "--format", "digraph", "--all", "--no-pager")
if err == nil {
t.Fatalf("proxied list --format digraph succeeded with read-only stdout; stderr:\n%s", stderr)
}
if !strings.Contains(stderr, "writing formatted list output") {
t.Fatalf("proxied list --format digraph stderr = %q, want writer diagnostic", stderr)
}
})
t.Run("compact_default", func(t *testing.T) {
out := bdProxiedList(t, bd, p, "--flat", "--no-pager")
if !strings.Contains(out, seed.openBug) {

View file

@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"io"
"os"
"os/signal"
"strings"
@ -19,7 +20,7 @@ import (
"github.com/steveyegge/beads/issueops"
)
func runListProxiedServer(cmd *cobra.Command, ctx context.Context, in listInput) error {
func runListProxiedServer(cmd *cobra.Command, ctx context.Context, out io.Writer, in listInput) error {
if in.repoOverrideSet {
return errors.New("--repo is not supported with --proxied-server")
}
@ -32,7 +33,7 @@ func runListProxiedServer(cmd *cobra.Command, ctx context.Context, in listInput)
// The --ready arm is not a case of its own any more: it is
// ListRequest.ReadyFlag, and choosing the ready query from it is the
// ROLE's job on both routes.
return runListProxiedPage(ctx, in)
return runListProxiedPage(ctx, out, in)
}
}
@ -72,7 +73,7 @@ func runListProxiedTree(ctx context.Context, in listInput) error {
// one more than this route used to for a listing that also loads dependency
// records. Nothing here was atomic across those reads before either: the
// renderings ran after the query returned.
func runListProxiedPage(ctx context.Context, in listInput) error {
func runListProxiedPage(ctx context.Context, out io.Writer, in listInput) error {
rd, err := proxiedIssueReader()
if err != nil {
return err
@ -96,7 +97,7 @@ func runListProxiedPage(ctx context.Context, in listInput) error {
return err
}
issues, hasMore := listPageIssues(page)
return renderProxiedListText(ctx, issues, in, hasMore)
return renderProxiedListText(ctx, out, issues, in, hasMore)
}
func runListProxiedWatch(_ *cobra.Command, ctx context.Context, in listInput) error {
@ -216,7 +217,7 @@ func loadDepsForIssues(ctx context.Context, uw uow.UnitOfWork, issues []*types.I
return uw.DependencyUseCase().GetForIssueIDs(ctx, ids)
}
func renderProxiedListText(ctx context.Context, issues []*types.Issue, in listInput, truncated bool) error {
func renderProxiedListText(ctx context.Context, out io.Writer, issues []*types.Issue, in listInput, truncated bool) error {
// --format and the pretty tree want the WHOLE dependency record set for the
// page — every edge type, no status rule — which is neither role's
// question. They open their own unit of work for it, which is what lets
@ -232,7 +233,7 @@ func renderProxiedListText(ctx context.Context, issues []*types.Issue, in listIn
return err
}
if in.formatStr != "" {
if err := outputFormattedList(issues, depsByIssueID, in.formatStr); err != nil {
if err := outputFormattedList(out, issues, depsByIssueID, in.formatStr); err != nil {
return err
}
printTruncationHint(truncated, in.effectiveLimit)

View file

@ -4,6 +4,7 @@ package main
import (
"context"
"io"
"path/filepath"
"slices"
"strings"
@ -196,7 +197,7 @@ func TestListCommandSuite(t *testing.T) {
if derr != nil {
t.Fatalf("GetAllDependencyRecords: %v", derr)
}
err := outputDotFormat(h.issues, deps)
err := outputDotFormat(io.Discard, h.issues, deps)
if err != nil {
t.Errorf("outputDotFormat failed: %v", err)
}
@ -204,7 +205,7 @@ func TestListCommandSuite(t *testing.T) {
t.Run("output formatted list dot", func(t *testing.T) {
deps, _ := h.store.GetAllDependencyRecords(h.ctx)
err := outputFormattedList(h.issues, deps, "dot")
err := outputFormattedList(io.Discard, h.issues, deps, "dot")
if err != nil {
t.Errorf("outputFormattedList with dot format failed: %v", err)
}
@ -212,7 +213,7 @@ func TestListCommandSuite(t *testing.T) {
t.Run("output formatted list digraph preset", func(t *testing.T) {
deps, _ := h.store.GetAllDependencyRecords(h.ctx)
err := outputFormattedList(h.issues, deps, "digraph")
err := outputFormattedList(io.Discard, h.issues, deps, "digraph")
if err != nil {
t.Errorf("outputFormattedList with digraph format failed: %v", err)
}
@ -220,7 +221,7 @@ func TestListCommandSuite(t *testing.T) {
t.Run("output formatted list custom template", func(t *testing.T) {
deps, _ := h.store.GetAllDependencyRecords(h.ctx)
err := outputFormattedList(h.issues, deps, "{{.ID}} {{.Title}}")
err := outputFormattedList(io.Discard, h.issues, deps, "{{.ID}} {{.Title}}")
if err != nil {
t.Errorf("outputFormattedList with custom template failed: %v", err)
}
@ -228,7 +229,7 @@ func TestListCommandSuite(t *testing.T) {
t.Run("output formatted list invalid template", func(t *testing.T) {
deps, _ := h.store.GetAllDependencyRecords(h.ctx)
err := outputFormattedList(h.issues, deps, "{{.ID")
err := outputFormattedList(io.Discard, h.issues, deps, "{{.ID")
if err == nil {
t.Error("Expected error for invalid template")
}