1package commands
2
3import (
4 "errors"
5 "fmt"
6
7 "github.com/MichaelMure/git-bug/cache"
8 "github.com/MichaelMure/git-bug/identity"
9 "github.com/MichaelMure/git-bug/util/interrupt"
10 "github.com/spf13/cobra"
11)
12
13func runKeyRm(cmd *cobra.Command, args []string) error {
14 backend, err := cache.NewRepoCache(repo)
15 if err != nil {
16 return err
17 }
18 defer backend.Close()
19 interrupt.RegisterCleaner(backend.Close)
20
21 if len(args) == 0 {
22 return errors.New("missing key ID")
23 }
24
25 keyFingerprint := args[0]
26 args = args[1:]
27
28 id, args, err := ResolveUser(backend, args)
29 if err != nil {
30 return err
31 }
32
33 if len(args) > 0 {
34 return fmt.Errorf("unexpected arguments: %s", args)
35 }
36
37 fingerprint, err := identity.DecodeKeyFingerprint(keyFingerprint)
38 if err != nil {
39 return err
40 }
41
42 var removedKey *identity.Key
43 err = id.Mutate(func(mutator identity.Mutator) identity.Mutator {
44 for j, key := range mutator.Keys {
45 pubkey, err := key.GetPublicKey()
46 if err != nil {
47 fmt.Printf("Warning: failed to decode public key: %s", err)
48 continue
49 }
50
51 if pubkey.Fingerprint == fingerprint {
52 removedKey = key
53 copy(mutator.Keys[j:], mutator.Keys[j+1:])
54 mutator.Keys = mutator.Keys[:len(mutator.Keys)-1]
55 break
56 }
57 }
58 return mutator
59 })
60
61 if err != nil {
62 return err
63 }
64
65 if removedKey == nil {
66 return errors.New("key not found")
67 }
68
69 return id.Commit()
70}
71
72var keyRmCmd = &cobra.Command{
73 Use: "rm <key-fingerprint> [<user-id>]",
74 Short: "Remove a PGP key from the adopted or the specified user.",
75 PreRunE: loadRepoEnsureUser,
76 RunE: runKeyRm,
77}
78
79func init() {
80 keyCmd.AddCommand(keyRmCmd)
81}