diff options
author | Michael Muré <batolettre@gmail.com> | 2020-06-26 01:02:27 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-06-26 01:02:27 +0200 |
commit | 2dd0dbb1344ae9293aae05346f977b5d5907934b (patch) | |
tree | 610ff7e381ef99827dc1b1dbc9ae4ea137fe5e21 /commands/user_ls.go | |
parent | f790083fb28ac0e68acddc9d5e7a709107a70bab (diff) | |
parent | c326007d01b623bcf883f74f31fc3e5ab3078396 (diff) | |
download | git-bug-2dd0dbb1344ae9293aae05346f977b5d5907934b.tar.gz |
Merge pull request #410 from MichaelMure/output-formatting-2
Add formatting options to the 'show' and 'user ls' commands
Diffstat (limited to 'commands/user_ls.go')
-rw-r--r-- | commands/user_ls.go | 47 |
1 files changed, 41 insertions, 6 deletions
diff --git a/commands/user_ls.go b/commands/user_ls.go index 609ff5a4..b3fb32e6 100644 --- a/commands/user_ls.go +++ b/commands/user_ls.go @@ -1,15 +1,21 @@ package commands import ( + "encoding/json" "fmt" + "github.com/spf13/cobra" + "github.com/MichaelMure/git-bug/cache" "github.com/MichaelMure/git-bug/util/colors" "github.com/MichaelMure/git-bug/util/interrupt" - "github.com/spf13/cobra" ) -func runUserLs(cmd *cobra.Command, args []string) error { +var ( + userLsOutputFormat string +) + +func runUserLs(_ *cobra.Command, _ []string) error { backend, err := cache.NewRepoCache(repo) if err != nil { return err @@ -17,21 +23,48 @@ func runUserLs(cmd *cobra.Command, args []string) error { defer backend.Close() interrupt.RegisterCleaner(backend.Close) - for _, id := range backend.AllIdentityIds() { - i, err := backend.ResolveIdentityExcerpt(id) + ids := backend.AllIdentityIds() + var users []*cache.IdentityExcerpt + for _, id := range ids { + user, err := backend.ResolveIdentityExcerpt(id) if err != nil { return err } + users = append(users, user) + } + + switch userLsOutputFormat { + case "json": + return userLsJsonFormatter(users) + case "default": + return userLsDefaultFormatter(users) + default: + return fmt.Errorf("unknown format %s", userLsOutputFormat) + } +} +func userLsDefaultFormatter(users []*cache.IdentityExcerpt) error { + for _, user := range users { fmt.Printf("%s %s\n", - colors.Cyan(i.Id.Human()), - i.DisplayName(), + colors.Cyan(user.Id.Human()), + user.DisplayName(), ) } return nil } +func userLsJsonFormatter(users []*cache.IdentityExcerpt) error { + jsonUsers := make([]JSONIdentity, len(users)) + for i, user := range users { + jsonUsers[i] = NewJSONIdentityFromExcerpt(user) + } + + jsonObject, _ := json.MarshalIndent(jsonUsers, "", " ") + fmt.Printf("%s\n", jsonObject) + return nil +} + var userLsCmd = &cobra.Command{ Use: "ls", Short: "List identities.", @@ -42,4 +75,6 @@ var userLsCmd = &cobra.Command{ func init() { userCmd.AddCommand(userLsCmd) userLsCmd.Flags().SortFlags = false + userLsCmd.Flags().StringVarP(&userLsOutputFormat, "format", "f", "default", + "Select the output formatting style. Valid values are [default,json]") } |