aboutsummaryrefslogtreecommitdiffstats
path: root/commands/user/user.go
diff options
context:
space:
mode:
Diffstat (limited to 'commands/user/user.go')
-rw-r--r--commands/user/user.go89
1 files changed, 89 insertions, 0 deletions
diff --git a/commands/user/user.go b/commands/user/user.go
new file mode 100644
index 00000000..191fb828
--- /dev/null
+++ b/commands/user/user.go
@@ -0,0 +1,89 @@
+package usercmd
+
+import (
+ "encoding/json"
+ "fmt"
+
+ "github.com/spf13/cobra"
+
+ json2 "github.com/MichaelMure/git-bug/commands/cmdjson"
+
+ "github.com/MichaelMure/git-bug/cache"
+ "github.com/MichaelMure/git-bug/commands/completion"
+ "github.com/MichaelMure/git-bug/commands/execenv"
+ "github.com/MichaelMure/git-bug/util/colors"
+)
+
+type userOptions struct {
+ format string
+}
+
+func NewUserCommand() *cobra.Command {
+ env := execenv.NewEnv()
+ options := userOptions{}
+
+ cmd := &cobra.Command{
+ Use: "user",
+ Short: "List identities",
+ PreRunE: execenv.LoadBackend(env),
+ RunE: execenv.CloseBackend(env, func(cmd *cobra.Command, args []string) error {
+ return runUser(env, options)
+ }),
+ }
+
+ cmd.AddCommand(newUserNewCommand())
+ cmd.AddCommand(newUserShowCommand())
+ cmd.AddCommand(newUserAdoptCommand())
+
+ flags := cmd.Flags()
+ flags.SortFlags = false
+
+ flags.StringVarP(&options.format, "format", "f", "default",
+ "Select the output formatting style. Valid values are [default,json]")
+ cmd.RegisterFlagCompletionFunc("format", completion.From([]string{"default", "json"}))
+
+ return cmd
+}
+
+func runUser(env *execenv.Env, opts userOptions) 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 userJsonFormatter(env, users)
+ case "default":
+ return userDefaultFormatter(env, users)
+ default:
+ return fmt.Errorf("unknown format %s", opts.format)
+ }
+}
+
+func userDefaultFormatter(env *execenv.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 userJsonFormatter(env *execenv.Env, users []*cache.IdentityExcerpt) error {
+ jsonUsers := make([]json2.Identity, len(users))
+ for i, user := range users {
+ jsonUsers[i] = json2.NewIdentityFromExcerpt(user)
+ }
+
+ jsonObject, _ := json.MarshalIndent(jsonUsers, "", " ")
+ env.Out.Printf("%s\n", jsonObject)
+ return nil
+}