diff --git a/internal/tableprinter/table_printer.go b/internal/tableprinter/table_printer.go index ee1cc07a578..e1454170f71 100644 --- a/internal/tableprinter/table_printer.go +++ b/internal/tableprinter/table_printer.go @@ -63,9 +63,10 @@ func NewWithWriter(w io.Writer, isTTY bool, maxWidth int, cs *iostreams.ColorSch } if isTTY && len(headers.columns) > 0 { - // Make sure all headers are uppercase. + // Make sure all headers are uppercase, taking a copy of the headers to avoid modifying the original slice. + upperCasedHeaders := make([]string, len(headers.columns)) for i := range headers.columns { - headers.columns[i] = strings.ToUpper(headers.columns[i]) + upperCasedHeaders[i] = strings.ToUpper(headers.columns[i]) } // Make sure all header columns are padded - even the last one. Previously, the last header column @@ -77,7 +78,7 @@ func NewWithWriter(w io.Writer, isTTY bool, maxWidth int, cs *iostreams.ColorSch } tp.AddHeader( - headers.columns, + upperCasedHeaders, WithPadding(paddingFunc), WithColor(cs.LightGrayUnderline), ) diff --git a/internal/tableprinter/table_printer_test.go b/internal/tableprinter/table_printer_test.go new file mode 100644 index 00000000000..840c464568b --- /dev/null +++ b/internal/tableprinter/table_printer_test.go @@ -0,0 +1,22 @@ +package tableprinter_test + +import ( + "testing" + + "github.com/cli/cli/v2/internal/tableprinter" + "github.com/cli/cli/v2/pkg/iostreams" + "github.com/stretchr/testify/require" +) + +func TestHeadersAreNotMutated(t *testing.T) { + // Given a TTY environment so that headers are included in the table + ios, _, _, _ := iostreams.Test() + ios.SetStdoutTTY(true) + + // When creating a new table printer + headers := []string{"one", "two", "three"} + _ = tableprinter.New(ios, tableprinter.WithHeader(headers...)) + + // The provided headers should not be mutated + require.Equal(t, []string{"one", "two", "three"}, headers) +}