git-bug/commands/user_ls.go

81 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"
"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)
2020-06-24 05:22:32 +03:00
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":
2020-06-24 05:22:32 +03:00
return userLsJsonFormatter(users)
case "default":
2020-06-24 05:22:32 +03:00
return userLsDefaultFormatter(users)
default:
return fmt.Errorf("unknown format %s", userLsOutputFormat)
}
}
2020-06-24 05:22:32 +03:00
func userLsDefaultFormatter(users []*cache.IdentityExcerpt) error {
for _, user := range users {
fmt.Printf("%s %s\n",
2020-06-24 05:22:32 +03:00
colors.Cyan(user.Id.Human()),
user.DisplayName(),
)
}
return nil
}
2020-06-24 05:22:32 +03:00
func userLsJsonFormatter(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, "", " ")
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",
2020-06-24 15:52:48 +03:00
"Select the output formatting style. Valid values are [default,json]")
}