1package commands
2
3import (
4 "encoding/json"
5 "fmt"
6
7 "github.com/spf13/cobra"
8
9 "github.com/MichaelMure/git-bug/cache"
10 "github.com/MichaelMure/git-bug/util/colors"
11)
12
13type userLsOptions struct {
14 format string
15}
16
17func newUserLsCommand() *cobra.Command {
18 env := newEnv()
19 options := userLsOptions{}
20
21 cmd := &cobra.Command{
22 Use: "ls",
23 Short: "List identities.",
24 PreRunE: loadBackend(env),
25 RunE: closeBackend(env, func(cmd *cobra.Command, args []string) error {
26 return runUserLs(env, options)
27 }),
28 }
29
30 flags := cmd.Flags()
31 flags.SortFlags = false
32
33 flags.StringVarP(&options.format, "format", "f", "default",
34 "Select the output formatting style. Valid values are [default,json]")
35
36 return cmd
37}
38
39func runUserLs(env *Env, opts userLsOptions) error {
40 ids := env.backend.AllIdentityIds()
41 var users []*cache.IdentityExcerpt
42 for _, id := range ids {
43 user, err := env.backend.ResolveIdentityExcerpt(id)
44 if err != nil {
45 return err
46 }
47 users = append(users, user)
48 }
49
50 switch opts.format {
51 case "json":
52 return userLsJsonFormatter(env, users)
53 case "default":
54 return userLsDefaultFormatter(env, users)
55 default:
56 return fmt.Errorf("unknown format %s", opts.format)
57 }
58}
59
60func userLsDefaultFormatter(env *Env, users []*cache.IdentityExcerpt) error {
61 for _, user := range users {
62 env.out.Printf("%s %s\n",
63 colors.Cyan(user.Id.Human()),
64 user.DisplayName(),
65 )
66 }
67
68 return nil
69}
70
71func userLsJsonFormatter(env *Env, users []*cache.IdentityExcerpt) error {
72 jsonUsers := make([]JSONIdentity, len(users))
73 for i, user := range users {
74 jsonUsers[i] = NewJSONIdentityFromExcerpt(user)
75 }
76
77 jsonObject, _ := json.MarshalIndent(jsonUsers, "", " ")
78 env.out.Printf("%s\n", jsonObject)
79 return nil
80}