github.com/caos/orbos@v1.5.14-0.20221103111702-e6cd0cea7ad4/cmd/orbctl/list.go (about) 1 package main 2 3 import ( 4 "errors" 5 "fmt" 6 "os" 7 "reflect" 8 "strings" 9 10 "github.com/caos/orbos/mntr" 11 12 "github.com/kataras/tablewriter" 13 "github.com/landoop/tableprinter" 14 "github.com/spf13/cobra" 15 16 "github.com/caos/orbos/internal/operator/orbiter/kinds/clusters/core/infra" 17 "github.com/caos/orbos/pkg/tree" 18 ) 19 20 func ListCommand(getRv GetRootValues) *cobra.Command { 21 var ( 22 column, context string 23 cmd = &cobra.Command{ 24 Use: "list", 25 Short: "List available machines", 26 Long: "List available machines", 27 Args: cobra.MaximumNArgs(0), 28 } 29 ) 30 31 flags := cmd.Flags() 32 flags.StringVar(&column, "column", "", "Print this column only") 33 flags.StringVar(&context, "context", "", "Print machines from this context only") 34 35 cmd.RunE = func(cmd *cobra.Command, args []string) (err error) { 36 37 rv := getRv("list", "", map[string]interface{}{"column": column, "context": context}) 38 defer rv.ErrFunc(err) 39 40 if !rv.Gitops { 41 return mntr.ToUserError(errors.New("list command is only supported with the --gitops flag and a committed orbiter.yml")) 42 } 43 44 return machines(monitor, rv.GitClient, rv.OrbConfig, func(machineIDs []string, machines map[string]infra.Machine, _ *tree.Tree) error { 45 46 printer := tableprinter.New(os.Stdout) 47 printer.BorderTop, printer.BorderBottom = true, true 48 printer.HeaderFgColor = tablewriter.FgYellowColor 49 50 var ( 51 tail bool 52 headers []string 53 rows [][]string 54 cellIdx = -1 55 ) 56 57 for path, mach := range machines { 58 ctx := path[:strings.LastIndex(path, ".")] 59 if context == "" || context == ctx { 60 v := reflect.ValueOf(mach).Elem() 61 if !tail { 62 headers = append([]string{"context"}, tableprinter.StructParser.ParseHeaders(v)...) 63 if column != "" { 64 for idx, h := range headers { 65 if strings.Contains(strings.ToLower(h), strings.ToLower(column)) { 66 cellIdx = idx 67 } 68 } 69 if cellIdx == -1 { 70 return fmt.Errorf("unknown column: %s", column) 71 } 72 } 73 tail = true 74 } 75 76 cells, _ := tableprinter.StructParser.ParseRow(v) 77 cells = append([]string{ctx}, cells...) 78 79 if cellIdx > -1 { 80 fmt.Println(cells[cellIdx]) 81 continue 82 } 83 rows = append(rows, cells) 84 } 85 } 86 87 if cellIdx == -1 { 88 printer.Render(headers, rows, nil, false) 89 } 90 91 return nil 92 }) 93 } 94 return cmd 95 }