aboutsummaryrefslogtreecommitdiffstats
path: root/commands/user_adopt.go
blob: a7de54d9bfd31b39caf7b1c31f0c1fb80a614f3d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package commands

import (
	"fmt"
	"os"

	"github.com/MichaelMure/git-bug/bridge/core/auth"
	"github.com/MichaelMure/git-bug/cache"
	"github.com/MichaelMure/git-bug/identity"
	"github.com/MichaelMure/git-bug/util/interrupt"
	"github.com/spf13/cobra"
)

func runUserAdopt(cmd *cobra.Command, args []string) error {
	backend, err := cache.NewRepoCache(repo)
	if err != nil {
		return err
	}
	defer backend.Close()
	interrupt.RegisterCleaner(backend.Close)

	prefix := args[0]

	i, err := backend.ResolveIdentityPrefix(prefix)
	if err != nil {
		return err
	}

	_, err = backend.GetUserIdentity()
	if err == identity.ErrNoIdentitySet {
		err = auth.ReplaceDefaultUser(repo, i.Id())
		if err != nil {
			return err
		}
	} else if err != nil {
		return err
	}

	err = backend.SetUserIdentity(i)
	if err != nil {
		return err
	}

	_, _ = fmt.Fprintf(os.Stderr, "Your identity is now: %s\n", i.DisplayName())

	return nil
}

var userAdoptCmd = &cobra.Command{
	Use:     "adopt <user-id>",
	Short:   "Adopt an existing identity as your own.",
	PreRunE: loadRepo,
	RunE:    runUserAdopt,
	Args:    cobra.ExactArgs(1),
}

func init() {
	userCmd.AddCommand(userAdoptCmd)
	userAdoptCmd.Flags().SortFlags = false
}