identity_user.go

 1package identity
 2
 3import (
 4	"fmt"
 5	"os"
 6
 7	"github.com/pkg/errors"
 8
 9	"github.com/MichaelMure/git-bug/entity"
10	"github.com/MichaelMure/git-bug/repository"
11)
12
13// SetUserIdentity store the user identity's id in the git config
14func SetUserIdentity(repo repository.RepoConfig, identity *Identity) error {
15	return repo.LocalConfig().StoreString(identityConfigKey, identity.Id().String())
16}
17
18// GetUserIdentity read the current user identity, set with a git config entry
19func GetUserIdentity(repo repository.Repo) (*Identity, error) {
20	id, err := GetUserIdentityId(repo)
21	if err != nil {
22		return nil, err
23	}
24
25	i, err := ReadLocal(repo, id)
26	if err == ErrIdentityNotExist {
27		innerErr := repo.LocalConfig().RemoveAll(identityConfigKey)
28		if innerErr != nil {
29			_, _ = fmt.Fprintln(os.Stderr, errors.Wrap(innerErr, "can't clear user identity").Error())
30		}
31		return nil, err
32	}
33
34	return i, nil
35}
36
37func GetUserIdentityId(repo repository.Repo) (entity.Id, error) {
38	configs, err := repo.LocalConfig().ReadAll(identityConfigKey)
39	if err != nil {
40		return entity.UnsetId, err
41	}
42
43	if len(configs) == 0 {
44		return entity.UnsetId, ErrNoIdentitySet
45	}
46
47	if len(configs) > 1 {
48		return entity.UnsetId, ErrMultipleIdentitiesSet
49	}
50
51	var id entity.Id
52	for _, val := range configs {
53		id = entity.Id(val)
54	}
55
56	if err := id.Validate(); err != nil {
57		return entity.UnsetId, err
58	}
59
60	return id, nil
61}
62
63// IsUserIdentitySet say if the user has set his identity
64func IsUserIdentitySet(repo repository.Repo) (bool, error) {
65	configs, err := repo.LocalConfig().ReadAll(identityConfigKey)
66	if err != nil {
67		return false, err
68	}
69
70	return len(configs) == 1, nil
71}