git-bug/commands/user_ls.go

82 lines
1.7 KiB
Go
Raw Normal View History

package commands
import (
"encoding/json"
"fmt"
2020-06-24 05:22:32 +03:00
"github.com/spf13/cobra"
"github.com/MichaelMure/git-bug/cache"
"github.com/MichaelMure/git-bug/util/colors"
)
2020-06-28 19:26:29 +03:00
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),
2020-06-28 19:26:29 +03:00
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]")
2020-06-28 19:26:29 +03:00
return cmd
}
func runUserLs(env *Env, opts userLsOptions) error {
ids := env.backend.AllIdentityIds()
2020-06-24 05:22:32 +03:00
var users []*cache.IdentityExcerpt
for _, id := range ids {
user, err := env.backend.ResolveIdentityExcerpt(id)
2020-06-24 05:22:32 +03:00
if err != nil {
return err
}
users = append(users, user)
}
2020-06-28 19:26:29 +03:00
switch opts.format {
case "json":
2020-06-28 19:26:29 +03:00
return userLsJsonFormatter(env, users)
case "default":
2020-06-28 19:26:29 +03:00
return userLsDefaultFormatter(env, users)
default:
2020-06-28 19:26:29 +03:00
return fmt.Errorf("unknown format %s", opts.format)
}
}
2020-06-28 19:26:29 +03:00
func userLsDefaultFormatter(env *Env, users []*cache.IdentityExcerpt) error {
2020-06-24 05:22:32 +03:00
for _, user := range users {
2020-06-28 19:26:29 +03:00
env.out.Printf("%s %s\n",
2020-06-24 05:22:32 +03:00
colors.Cyan(user.Id.Human()),
user.DisplayName(),
)
}
return nil
}
2020-06-28 19:26:29 +03:00
func userLsJsonFormatter(env *Env, users []*cache.IdentityExcerpt) error {
2020-06-24 15:52:48 +03:00
jsonUsers := make([]JSONIdentity, len(users))
for i, user := range users {
jsonUsers[i] = NewJSONIdentityFromExcerpt(user)
}
2020-06-24 05:22:32 +03:00
jsonObject, _ := json.MarshalIndent(jsonUsers, "", " ")
2020-06-28 19:26:29 +03:00
env.out.Printf("%s\n", jsonObject)
return nil
}