1package commands
2
3import (
4 "encoding/json"
5 "fmt"
6 "github.com/MichaelMure/git-bug/cache"
7 "github.com/MichaelMure/git-bug/util/colors"
8 "github.com/MichaelMure/git-bug/util/interrupt"
9 "github.com/spf13/cobra"
10)
11
12var (
13 userLsOutputFormat string
14)
15
16func runUserLs(_ *cobra.Command, _ []string) error {
17 backend, err := cache.NewRepoCache(repo)
18 if err != nil {
19 return err
20 }
21 defer backend.Close()
22 interrupt.RegisterCleaner(backend.Close)
23
24 switch userLsOutputFormat {
25 case "org-mode":
26 return userLsOrgmodeFormatter(backend)
27 case "json":
28 return userLsJsonFormatter(backend)
29 case "plain":
30 return userLsPlainFormatter(backend)
31 case "default":
32 return userLsDefaultFormatter(backend)
33 default:
34 return fmt.Errorf("unknown format %s", userLsOutputFormat)
35 }
36}
37
38type JSONIdentity struct {
39 Id string `json:"id"`
40 HumanId string `json:"human_id"`
41 Name string `json:"name"`
42 Login string `json:"login"`
43}
44
45func userLsPlainFormatter(backend *cache.RepoCache) error {
46 for _, id := range backend.AllIdentityIds() {
47 i, err := backend.ResolveIdentityExcerpt(id)
48 if err != nil {
49 return err
50 }
51
52 fmt.Printf("%s %s\n",
53 i.Id.Human(),
54 i.DisplayName(),
55 )
56 }
57
58 return nil
59}
60
61func userLsDefaultFormatter(backend *cache.RepoCache) error {
62 for _, id := range backend.AllIdentityIds() {
63 i, err := backend.ResolveIdentityExcerpt(id)
64 if err != nil {
65 return err
66 }
67
68 fmt.Printf("%s %s\n",
69 colors.Cyan(i.Id.Human()),
70 i.DisplayName(),
71 )
72 }
73
74 return nil
75}
76
77func userLsJsonFormatter(backend *cache.RepoCache) error {
78 users := []JSONIdentity{}
79 for _, id := range backend.AllIdentityIds() {
80 i, err := backend.ResolveIdentityExcerpt(id)
81 if err != nil {
82 return err
83 }
84
85 users = append(users, JSONIdentity{
86 i.Id.String(),
87 i.Id.Human(),
88 i.Name,
89 i.Login,
90 })
91 }
92
93 jsonObject, _ := json.MarshalIndent(users, "", " ")
94 fmt.Printf("%s\n", jsonObject)
95 return nil
96}
97
98func userLsOrgmodeFormatter(backend *cache.RepoCache) error {
99 for _, id := range backend.AllIdentityIds() {
100 i, err := backend.ResolveIdentityExcerpt(id)
101 if err != nil {
102 return err
103 }
104
105 fmt.Printf("* %s %s\n",
106 i.Id.Human(),
107 i.DisplayName(),
108 )
109 }
110
111 return nil
112}
113
114var userLsCmd = &cobra.Command{
115 Use: "ls",
116 Short: "List identities.",
117 PreRunE: loadRepo,
118 RunE: runUserLs,
119}
120
121func init() {
122 userCmd.AddCommand(userLsCmd)
123 userLsCmd.Flags().SortFlags = false
124 userLsCmd.Flags().StringVarP(&userLsOutputFormat, "format", "f", "default",
125 "Select the output formatting style. Valid values are [default,plain,json,org-mode]")
126}