From b384e08abf818d8f0c087973eb0b0343613bf67d Mon Sep 17 00:00:00 2001 From: dualfroz Date: Fri, 4 Sep 2026 09:47:25 +0200 Subject: [PATCH] fix: pad short rows in SetRows to the number of columns SetRows stored rows with fewer cells than the header unchanged, so short rows rendered fmt's %!s(MISSING) verb and an empty row combined with a first-column formatter panicked on vals[0]. Pad short rows to the column count, mirroring AddRow's documented behavior of rendering missing cells as empty. --- table.go | 7 +++++-- table_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/table.go b/table.go index ccd5124..70b4bd6 100644 --- a/table.go +++ b/table.go @@ -238,10 +238,13 @@ func (t *table) SetRows(rows [][]string) Table { headerLength := len(t.header) for _, row := range rows { - if len(row) > headerLength { + if len(row) >= headerLength { t.rows = append(t.rows, row[:headerLength]) } else { - t.rows = append(t.rows, row) + // pad short rows so every column is rendered, matching AddRow + padded := make([]string, headerLength) + copy(padded, row) + t.rows = append(t.rows, padded) } } diff --git a/table_test.go b/table_test.go index 992c9f6..204ed29 100644 --- a/table_test.go +++ b/table_test.go @@ -309,3 +309,30 @@ func TestTable_WithWidthFunc(t *testing.T) { assert.Contains(t, actual, "请求 alpha") assert.Contains(t, actual, "abc beta") } + +func TestSetRowsShortRowsPadded(t *testing.T) { + // SetRows must pad short rows like AddRow, not emit %!s(MISSING). + buf := &bytes.Buffer{} + tbl := New("A", "B", "C").WithWriter(buf).WithPadding(1) + tbl.SetRows([][]string{{"x", "y"}}) + tbl.Print() + + out := buf.String() + if strings.Contains(out, "MISSING") { + t.Fatalf("output contains missing-arg verb: %q", out) + } + assert.Equal(t, "A B C \nx y \n", out) +} + +func TestSetRowsEmptyRowWithFirstColumnFormatter(t *testing.T) { + // An empty row must not panic when a first-column formatter is set. + buf := &bytes.Buffer{} + tbl := New("A", "B").WithWriter(buf).WithPadding(1). + WithFirstColumnFormatter(func(f string, v ...interface{}) string { + return fmt.Sprintf(f, v...) + }) + assert.NotPanics(t, func() { + tbl.SetRows([][]string{{}}) + tbl.Print() + }) +}