user_key.go

 1package commands
 2
 3import (
 4	"fmt"
 5
 6	"github.com/MichaelMure/git-bug/cache"
 7	"github.com/MichaelMure/git-bug/identity"
 8	"github.com/MichaelMure/git-bug/util/interrupt"
 9	"github.com/spf13/cobra"
10)
11
12func ResolveUser(repo *cache.RepoCache, args []string) (*cache.IdentityCache, []string, error) {
13	var err error
14	var id *cache.IdentityCache
15	if len(args) > 0 {
16		id, err = repo.ResolveIdentityPrefix(args[0])
17		args = args[1:]
18	} else {
19		id, err = repo.GetUserIdentity()
20	}
21	return id, args, err
22}
23
24func runKey(cmd *cobra.Command, args []string) error {
25	backend, err := cache.NewRepoCache(repo)
26	if err != nil {
27		return err
28	}
29	defer backend.Close()
30	interrupt.RegisterCleaner(backend.Close)
31
32	id, args, err := ResolveUser(backend, args)
33	if err != nil {
34		return err
35	}
36
37	if len(args) > 0 {
38		return fmt.Errorf("unexpected arguments: %s", args)
39	}
40
41	for _, key := range id.Keys() {
42		pubkey, err := key.GetPublicKey()
43		if err != nil {
44			return err
45		}
46		fmt.Println(identity.EncodeKeyFingerprint(pubkey.Fingerprint))
47	}
48
49	return nil
50}
51
52var keyCmd = &cobra.Command{
53	Use:     "key [<user-id>]",
54	Short:   "Display, add or remove keys to/from a user.",
55	PreRunE: loadRepoEnsureUser,
56	RunE:    runKey,
57}
58
59func init() {
60	userCmd.AddCommand(keyCmd)
61}