user_ls.go

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