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,lastModificationLamport,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			env.out.Printf("%d\n", id.LastModificationLamport())
 75		case "metadata":
 76			for key, value := range id.ImmutableMetadata() {
 77				env.out.Printf("%s\n%s\n", key, value)
 78			}
 79		case "name":
 80			env.out.Printf("%s\n", id.Name())
 81
 82		default:
 83			return fmt.Errorf("\nUnsupported field: %s\n", opts.fields)
 84		}
 85
 86		return nil
 87	}
 88
 89	env.out.Printf("Id: %s\n", id.Id())
 90	env.out.Printf("Name: %s\n", id.Name())
 91	env.out.Printf("Email: %s\n", id.Email())
 92	env.out.Printf("Login: %s\n", id.Login())
 93	env.out.Printf("Last modification: %s (lamport %d)\n",
 94		id.LastModification().Time().Format("Mon Jan 2 15:04:05 2006 +0200"),
 95		id.LastModificationLamport())
 96	env.out.Println("Metadata:")
 97	for key, value := range id.ImmutableMetadata() {
 98		env.out.Printf("    %s --> %s\n", key, value)
 99	}
100	// env.out.Printf("Protected: %v\n", id.IsProtected())
101
102	return nil
103}