Skip to content

Commit 89dcb39

Browse files
committed
feat(cli): preserve order of table columns
1 parent b16275b commit 89dcb39

File tree

1 file changed

+29
-3
lines changed

1 file changed

+29
-3
lines changed

cli/cliui/table.go

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,10 +31,33 @@ func Table() table.Writer {
3131
// e.g. `[]any{someRow, TableSeparator, someRow}`
3232
type TableSeparator struct{}
3333

34-
// filterTableColumns returns configurations to hide columns
34+
// filterHeaders filters the headers to only include the columns
35+
// that are provided in the array. If the array is empty, all
36+
// headers are included.
37+
func filterHeaders(header table.Row, columns []string) table.Row {
38+
if len(columns) == 0 {
39+
return header
40+
}
41+
42+
filteredHeaders := make(table.Row, len(columns))
43+
for i, column := range columns {
44+
column = strings.ReplaceAll(column, "_", " ")
45+
46+
for _, headerTextRaw := range header {
47+
headerText, _ := headerTextRaw.(string)
48+
if strings.EqualFold(column, headerText) {
49+
filteredHeaders[i] = headerText
50+
break
51+
}
52+
}
53+
}
54+
return filteredHeaders
55+
}
56+
57+
// createColumnConfigs returns configuration to hide columns
3558
// that are not provided in the array. If the array is empty,
3659
// no filtering will occur!
37-
func filterTableColumns(header table.Row, columns []string) []table.ColumnConfig {
60+
func createColumnConfigs(header table.Row, columns []string) []table.ColumnConfig {
3861
if len(columns) == 0 {
3962
return nil
4063
}
@@ -157,10 +180,13 @@ func DisplayTable(out any, sort string, filterColumns []string) (string, error)
157180
func renderTable(out any, sort string, headers table.Row, filterColumns []string) (string, error) {
158181
v := reflect.Indirect(reflect.ValueOf(out))
159182

183+
headers = filterHeaders(headers, filterColumns)
184+
columnConfigs := createColumnConfigs(headers, filterColumns)
185+
160186
// Setup the table formatter.
161187
tw := Table()
162188
tw.AppendHeader(headers)
163-
tw.SetColumnConfigs(filterTableColumns(headers, filterColumns))
189+
tw.SetColumnConfigs(columnConfigs)
164190
if sort != "" {
165191
tw.SortBy([]table.SortBy{{
166192
Name: sort,

0 commit comments

Comments
 (0)