(items []T, cmd *cobra.Command, mappers Mappers[T])
| 15 | ) |
| 16 | |
| 17 | func PrintArray[T any](items []T, cmd *cobra.Command, mappers Mappers[T]) error { |
| 18 | outputFormat, _ := cmd.Flags().GetString(constants.FlagOutputFormat) |
| 19 | if outputFormat == "" { |
| 20 | outputFormat = viper.GetString(constants.ConfigOutputFormat) |
| 21 | } |
| 22 | |
| 23 | switch strings.ToLower(outputFormat) { |
| 24 | case constants.OutputFormatJson: |
| 25 | jsonMapper := mappers.Json |
| 26 | if jsonMapper == nil { |
| 27 | return errors.New("command does not support output in JSON format") |
| 28 | } |
| 29 | var outputJson []any |
| 30 | for _, e := range items { |
| 31 | outputJson = append(outputJson, jsonMapper(e)) |
| 32 | } |
| 33 | |
| 34 | data, _ := json.MarshalIndent(outputJson, "", " ") |
| 35 | cmd.Println(string(data)) |
| 36 | |
| 37 | case constants.OutputFormatBasic: |
| 38 | textMapper := mappers.Basic |
| 39 | if textMapper == nil { |
| 40 | return errors.New("command does not support output in plain text") |
| 41 | } |
| 42 | for _, e := range items { |
| 43 | cmd.Println(textMapper(e)) |
| 44 | } |
| 45 | |
| 46 | case constants.OutputFormatTable, "": // table is the default of unspecified |
| 47 | tableMapper := mappers.Table |
| 48 | if tableMapper.Row == nil { |
| 49 | return errors.New("command does not support output in table format") |
| 50 | } |
| 51 | |
| 52 | t := NewTable(cmd.OutOrStdout()) |
| 53 | if tableMapper.Header != nil { |
| 54 | for k, v := range tableMapper.Header { |
| 55 | tableMapper.Header[k] = Bold(v) |
| 56 | } |
| 57 | t.AddRow(tableMapper.Header...) |
| 58 | } |
| 59 | |
| 60 | for _, item := range items { |
| 61 | t.AddRow(tableMapper.Row(item)...) |
| 62 | } |
| 63 | |
| 64 | return t.Print() |
| 65 | |
| 66 | default: |
| 67 | return usage.NewUsageError( |
| 68 | fmt.Sprintf("unsupported output format %s. Valid values are 'json', 'table', 'basic'. Defaults to table", outputFormat), |
| 69 | cmd) |
| 70 | } |
| 71 | return nil |
| 72 | } |
no test coverage detected