mirror of
https://github.com/coder/coder.git
synced 2026-09-24 15:04:27 +08:00
feat(cli): preserve table column order (#16843)
Fixes: https://github.com/coder/coder/issues/16055
This commit is contained in:
+29
-3
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user