1package commands
2
3import (
4 "errors"
5 "fmt"
6
7 "github.com/spf13/cobra"
8
9 "github.com/MichaelMure/git-bug/cache"
10 "github.com/MichaelMure/git-bug/util/interrupt"
11)
12
13type userOptions struct {
14 fieldsQuery string
15}
16
17func newUserCommand() *cobra.Command {
18 env := newEnv()
19 options := userOptions{}
20
21 cmd := &cobra.Command{
22 Use: "user [<user-id>]",
23 Short: "Display or change the user identity.",
24 PreRunE: loadRepoEnsureUser(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.fieldsQuery, "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 backend, err := cache.NewRepoCache(env.repo)
45 if err != nil {
46 return err
47 }
48 defer backend.Close()
49 interrupt.RegisterCleaner(backend.Close)
50
51 if len(args) > 1 {
52 return errors.New("only one identity can be displayed at a time")
53 }
54
55 var id *cache.IdentityCache
56 if len(args) == 1 {
57 id, err = backend.ResolveIdentityPrefix(args[0])
58 } else {
59 id, err = backend.GetUserIdentity()
60 }
61
62 if err != nil {
63 return err
64 }
65
66 if opts.fieldsQuery != "" {
67 switch opts.fieldsQuery {
68 case "email":
69 env.out.Printf("%s\n", id.Email())
70 case "login":
71 env.out.Printf("%s\n", id.Login())
72 case "humanId":
73 env.out.Printf("%s\n", id.Id().Human())
74 case "id":
75 env.out.Printf("%s\n", id.Id())
76 case "lastModification":
77 env.out.Printf("%s\n", id.LastModification().
78 Time().Format("Mon Jan 2 15:04:05 2006 +0200"))
79 case "lastModificationLamport":
80 env.out.Printf("%d\n", id.LastModificationLamport())
81 case "metadata":
82 for key, value := range id.ImmutableMetadata() {
83 env.out.Printf("%s\n%s\n", key, value)
84 }
85 case "name":
86 env.out.Printf("%s\n", id.Name())
87
88 default:
89 return fmt.Errorf("\nUnsupported field: %s\n", opts.fieldsQuery)
90 }
91
92 return nil
93 }
94
95 env.out.Printf("Id: %s\n", id.Id())
96 env.out.Printf("Name: %s\n", id.Name())
97 env.out.Printf("Email: %s\n", id.Email())
98 env.out.Printf("Login: %s\n", id.Login())
99 env.out.Printf("Last modification: %s (lamport %d)\n",
100 id.LastModification().Time().Format("Mon Jan 2 15:04:05 2006 +0200"),
101 id.LastModificationLamport())
102 env.out.Println("Metadata:")
103 for key, value := range id.ImmutableMetadata() {
104 env.out.Printf(" %s --> %s\n", key, value)
105 }
106 // env.out.Printf("Protected: %v\n", id.IsProtected())
107
108 return nil
109}