aboutsummaryrefslogtreecommitdiffstats
path: root/commands/user_ls.go
blob: b3fb32e65a629080ca64b36b2ff4633c038d1cbf (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
package commands

import (
	"encoding/json"
	"fmt"

	"github.com/spf13/cobra"

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

var (
	userLsOutputFormat string
)

func runUserLs(_ *cobra.Command, _ []string) error {
	backend, err := cache.NewRepoCache(repo)
	if err != nil {
		return err
	}
	defer backend.Close()
	interrupt.RegisterCleaner(backend.Close)

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

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

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

	return nil
}

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

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

var userLsCmd = &cobra.Command{
	Use:     "ls",
	Short:   "List identities.",
	PreRunE: loadRepo,
	RunE:    runUserLs,
}

func init() {
	userCmd.AddCommand(userLsCmd)
	userLsCmd.Flags().SortFlags = false
	userLsCmd.Flags().StringVarP(&userLsOutputFormat, "format", "f", "default",
		"Select the output formatting style. Valid values are [default,json]")
}