feat(cli): preserve table column order (#16843)

Fixes: https://github.com/coder/coder/issues/16055
This commit is contained in:
Marcin Tojek
2025-03-10 12:28:06 +00:00
committed by GitHub
parent 075e5f4f6e
commit 4b1da9b896
11 changed files with 42 additions and 16 deletions
+29 -3
View File
@@ -31,10 +31,33 @@ func Table() table.Writer {
// e.g. `[]any{someRow, TableSeparator, someRow}`
type TableSeparator struct{}
// filterTableColumns returns configurations to hide columns
// filterHeaders filters the headers to only include the columns
// that are provided in the array. If the array is empty, all
// headers are included.
func filterHeaders(header table.Row, columns []string) table.Row {
if len(columns) == 0 {
return header
}
filteredHeaders := make(table.Row, len(columns))
for i, column := range columns {
column = strings.ReplaceAll(column, "_", " ")
for _, headerTextRaw := range header {
headerText, _ := headerTextRaw.(string)
if strings.EqualFold(column, headerText) {
filteredHeaders[i] = headerText
break
}
}
}
return filteredHeaders
}
// createColumnConfigs returns configuration to hide columns
// that are not provided in the array. If the array is empty,
// no filtering will occur!
func filterTableColumns(header table.Row, columns []string) []table.ColumnConfig {
func createColumnConfigs(header table.Row, columns []string) []table.ColumnConfig {
if len(columns) == 0 {
return nil
}
@@ -157,10 +180,13 @@ func DisplayTable(out any, sort string, filterColumns []string) (string, error)
func renderTable(out any, sort string, headers table.Row, filterColumns []string) (string, error) {
v := reflect.Indirect(reflect.ValueOf(out))
headers = filterHeaders(headers, filterColumns)
columnConfigs := createColumnConfigs(headers, filterColumns)
// Setup the table formatter.
tw := Table()
tw.AppendHeader(headers)
tw.SetColumnConfigs(filterTableColumns(headers, filterColumns))
tw.SetColumnConfigs(columnConfigs)
if sort != "" {
tw.SortBy([]table.SortBy{{
Name: sort,