github.com/secman-team/gh-api@v1.8.2/pkg/cmd/alias/list/list.go (about) 1 package list 2 3 import ( 4 "fmt" 5 "sort" 6 7 "github.com/MakeNowJust/heredoc" 8 "github.com/secman-team/gh-api/core/config" 9 "github.com/secman-team/gh-api/pkg/cmdutil" 10 "github.com/secman-team/gh-api/pkg/iostreams" 11 "github.com/secman-team/gh-api/utils" 12 "github.com/spf13/cobra" 13 ) 14 15 type ListOptions struct { 16 Config func() (config.Config, error) 17 IO *iostreams.IOStreams 18 } 19 20 func NewCmdList(f *cmdutil.Factory, runF func(*ListOptions) error) *cobra.Command { 21 opts := &ListOptions{ 22 IO: f.IOStreams, 23 Config: f.Config, 24 } 25 26 cmd := &cobra.Command{ 27 Use: "list", 28 Short: "List your aliases", 29 Long: heredoc.Doc(` 30 This command prints out all of the aliases gh is configured to use. 31 `), 32 Args: cobra.NoArgs, 33 RunE: func(cmd *cobra.Command, args []string) error { 34 if runF != nil { 35 return runF(opts) 36 } 37 return listRun(opts) 38 }, 39 } 40 41 return cmd 42 } 43 44 func listRun(opts *ListOptions) error { 45 cfg, err := opts.Config() 46 if err != nil { 47 return err 48 } 49 50 aliasCfg, err := cfg.Aliases() 51 if err != nil { 52 return fmt.Errorf("couldn't read aliases config: %w", err) 53 } 54 55 if aliasCfg.Empty() { 56 if opts.IO.IsStdoutTTY() { 57 fmt.Fprintf(opts.IO.ErrOut, "no aliases configured\n") 58 } 59 return nil 60 } 61 62 tp := utils.NewTablePrinter(opts.IO) 63 64 aliasMap := aliasCfg.All() 65 keys := []string{} 66 for alias := range aliasMap { 67 keys = append(keys, alias) 68 } 69 sort.Strings(keys) 70 71 for _, alias := range keys { 72 tp.AddField(alias+":", nil, nil) 73 tp.AddField(aliasMap[alias], nil, nil) 74 tp.EndRow() 75 } 76 77 return tp.Render() 78 }