user.go

  1package commands
  2
  3import (
  4	"errors"
  5	"fmt"
  6
  7	"github.com/spf13/cobra"
  8
  9	"github.com/MichaelMure/git-bug/cache"
 10)
 11
 12type userOptions struct {
 13	fields string
 14}
 15
 16func newUserCommand() *cobra.Command {
 17	env := newEnv()
 18	options := userOptions{}
 19
 20	cmd := &cobra.Command{
 21		Use:      "user [USER-ID]",
 22		Short:    "Display or change the user identity.",
 23		PreRunE:  loadBackendEnsureUser(env),
 24		PostRunE: closeBackend(env),
 25		RunE: func(cmd *cobra.Command, args []string) error {
 26			return runUser(env, options, args)
 27		},
 28	}
 29
 30	cmd.AddCommand(newUserAdoptCommand())
 31	cmd.AddCommand(newUserCreateCommand())
 32	cmd.AddCommand(newUserLsCommand())
 33
 34	flags := cmd.Flags()
 35	flags.SortFlags = false
 36
 37	flags.StringVarP(&options.fields, "field", "f", "",
 38		"Select field to display. Valid values are [email,humanId,id,lastModification,lastModificationLamports,login,metadata,name]")
 39
 40	return cmd
 41}
 42
 43func runUser(env *Env, opts userOptions, args []string) error {
 44	if len(args) > 1 {
 45		return errors.New("only one identity can be displayed at a time")
 46	}
 47
 48	var id *cache.IdentityCache
 49	var err error
 50	if len(args) == 1 {
 51		id, err = env.backend.ResolveIdentityPrefix(args[0])
 52	} else {
 53		id, err = env.backend.GetUserIdentity()
 54	}
 55
 56	if err != nil {
 57		return err
 58	}
 59
 60	if opts.fields != "" {
 61		switch opts.fields {
 62		case "email":
 63			env.out.Printf("%s\n", id.Email())
 64		case "login":
 65			env.out.Printf("%s\n", id.Login())
 66		case "humanId":
 67			env.out.Printf("%s\n", id.Id().Human())
 68		case "id":
 69			env.out.Printf("%s\n", id.Id())
 70		case "lastModification":
 71			env.out.Printf("%s\n", id.LastModification().
 72				Time().Format("Mon Jan 2 15:04:05 2006 +0200"))
 73		case "lastModificationLamport":
 74			for name, t := range id.LastModificationLamports() {
 75				env.out.Printf("%s\n%d\n", name, t)
 76			}
 77		case "metadata":
 78			for key, value := range id.ImmutableMetadata() {
 79				env.out.Printf("%s\n%s\n", key, value)
 80			}
 81		case "name":
 82			env.out.Printf("%s\n", id.Name())
 83
 84		default:
 85			return fmt.Errorf("\nUnsupported field: %s\n", opts.fields)
 86		}
 87
 88		return nil
 89	}
 90
 91	env.out.Printf("Id: %s\n", id.Id())
 92	env.out.Printf("Name: %s\n", id.Name())
 93	env.out.Printf("Email: %s\n", id.Email())
 94	env.out.Printf("Login: %s\n", id.Login())
 95	env.out.Printf("Last modification: %s\n", id.LastModification().Time().Format("Mon Jan 2 15:04:05 2006 +0200"))
 96	env.out.Printf("Last moditication (lamport):\n")
 97	for name, t := range id.LastModificationLamports() {
 98		env.out.Printf("\t%s: %d", name, t)
 99	}
100	env.out.Println("Metadata:")
101	for key, value := range id.ImmutableMetadata() {
102		env.out.Printf("    %s --> %s\n", key, value)
103	}
104	// env.out.Printf("Protected: %v\n", id.IsProtected())
105
106	return nil
107}