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		PostRunE: closeBackend(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	ids := env.backend.AllIdentityIds()
42	var users []*cache.IdentityExcerpt
43	for _, id := range ids {
44		user, err := env.backend.ResolveIdentityExcerpt(id)
45		if err != nil {
46			return err
47		}
48		users = append(users, user)
49	}
50
51	switch opts.format {
52	case "json":
53		return userLsJsonFormatter(env, users)
54	case "default":
55		return userLsDefaultFormatter(env, users)
56	default:
57		return fmt.Errorf("unknown format %s", opts.format)
58	}
59}
60
61func userLsDefaultFormatter(env *Env, users []*cache.IdentityExcerpt) error {
62	for _, user := range users {
63		env.out.Printf("%s %s\n",
64			colors.Cyan(user.Id.Human()),
65			user.DisplayName(),
66		)
67	}
68
69	return nil
70}
71
72func userLsJsonFormatter(env *Env, users []*cache.IdentityExcerpt) error {
73	jsonUsers := make([]JSONIdentity, len(users))
74	for i, user := range users {
75		jsonUsers[i] = NewJSONIdentityFromExcerpt(user)
76	}
77
78	jsonObject, _ := json.MarshalIndent(jsonUsers, "", "    ")
79	env.out.Printf("%s\n", jsonObject)
80	return nil
81}