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