aboutsummaryrefslogtreecommitdiffstats
path: root/commands/user_ls.go
blob: 05d343d684a875897620b6944bad3ab9e21dd509 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package commands

import (
	"encoding/json"
	"fmt"

	"github.com/spf13/cobra"

	"github.com/MichaelMure/git-bug/cache"
	"github.com/MichaelMure/git-bug/util/colors"
)

type userLsOptions struct {
	format string
}

func newUserLsCommand() *cobra.Command {
	env := newEnv()
	options := userLsOptions{}

	cmd := &cobra.Command{
		Use:      "ls",
		Short:    "List identities.",
		PreRunE:  loadBackend(env),
		PostRunE: closeBackend(env),
		RunE: func(cmd *cobra.Command, args []string) error {
			return runUserLs(env, options)
		},
	}

	flags := cmd.Flags()
	flags.SortFlags = false

	flags.StringVarP(&options.format, "format", "f", "default",
		"Select the output formatting style. Valid values are [default,json]")

	return cmd
}

func runUserLs(env *Env, opts userLsOptions) error {
	ids := env.backend.AllIdentityIds()
	var users []*cache.IdentityExcerpt
	for _, id := range ids {
		user, err := env.backend.ResolveIdentityExcerpt(id)
		if err != nil {
			return err
		}
		users = append(users, user)
	}

	switch opts.format {
	case "json":
		return userLsJsonFormatter(env, users)
	case "default":
		return userLsDefaultFormatter(env, users)
	default:
		return fmt.Errorf("unknown format %s", opts.format)
	}
}

func userLsDefaultFormatter(env *Env, users []*cache.IdentityExcerpt) error {
	for _, user := range users {
		env.out.Printf("%s %s\n",
			colors.Cyan(user.Id.Human()),
			user.DisplayName(),
		)
	}

	return nil
}

func userLsJsonFormatter(env *Env, users []*cache.IdentityExcerpt) error {
	jsonUsers := make([]JSONIdentity, len(users))
	for i, user := range users {
		jsonUsers[i] = NewJSONIdentityFromExcerpt(user)
	}

	jsonObject, _ := json.MarshalIndent(jsonUsers, "", "    ")
	env.out.Printf("%s\n", jsonObject)
	return nil
}