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	"github.com/MichaelMure/git-bug/util/interrupt"
11)
12
13var (
14	userFieldsQuery string
15)
16
17func runUser(cmd *cobra.Command, args []string) error {
18	backend, err := cache.NewRepoCache(repo)
19	if err != nil {
20		return err
21	}
22	defer backend.Close()
23	interrupt.RegisterCleaner(backend.Close)
24
25	if len(args) > 1 {
26		return errors.New("only one identity can be displayed at a time")
27	}
28
29	var id *cache.IdentityCache
30	if len(args) == 1 {
31		id, err = backend.ResolveIdentityPrefix(args[0])
32	} else {
33		id, err = backend.GetUserIdentity()
34	}
35
36	if err != nil {
37		return err
38	}
39
40	if userFieldsQuery != "" {
41		switch userFieldsQuery {
42		case "email":
43			fmt.Printf("%s\n", id.Email())
44		case "humanId":
45			fmt.Printf("%s\n", id.Id().Human())
46		case "id":
47			fmt.Printf("%s\n", id.Id())
48		case "lastModification":
49			fmt.Printf("%s\n", id.LastModification().
50				Time().Format("Mon Jan 2 15:04:05 2006 +0200"))
51		case "lastModificationLamport":
52			fmt.Printf("%d\n", id.LastModificationLamport())
53		case "login":
54			fmt.Printf("%s\n", id.Login())
55		case "metadata":
56			for key, value := range id.ImmutableMetadata() {
57				fmt.Printf("%s\n%s\n", key, value)
58			}
59		case "name":
60			fmt.Printf("%s\n", id.Name())
61
62		default:
63			return fmt.Errorf("\nUnsupported field: %s\n", userFieldsQuery)
64		}
65
66		return nil
67	}
68
69	fmt.Printf("Id: %s\n", id.Id())
70	fmt.Printf("Name: %s\n", id.Name())
71	fmt.Printf("Login: %s\n", id.Login())
72	fmt.Printf("Email: %s\n", id.Email())
73	fmt.Printf("Last modification: %s (lamport %d)\n",
74		id.LastModification().Time().Format("Mon Jan 2 15:04:05 2006 +0200"),
75		id.LastModificationLamport())
76	fmt.Println("Metadata:")
77	for key, value := range id.ImmutableMetadata() {
78		fmt.Printf("    %s --> %s\n", key, value)
79	}
80	// fmt.Printf("Protected: %v\n", id.IsProtected())
81
82	return nil
83}
84
85var userCmd = &cobra.Command{
86	Use:     "user [<user-id>]",
87	Short:   "Display or change the user identity.",
88	PreRunE: loadRepoEnsureUser,
89	RunE:    runUser,
90}
91
92func init() {
93	RootCmd.AddCommand(userCmd)
94	userCmd.Flags().SortFlags = false
95
96	userCmd.Flags().StringVarP(&userFieldsQuery, "field", "f", "",
97		"Select field to display. Valid values are [email,humanId,id,lastModification,lastModificationLamport,login,metadata,name]")
98}