aboutsummaryrefslogtreecommitdiffstats
path: root/entities/identity/identity_user.go
blob: f9e39bb22ad55e38ff563630aa5500d3a36e2be0 (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
61
62
63
64
65
66
67
68
69
70
71
72
package identity

import (
	"fmt"
	"os"

	"github.com/pkg/errors"

	"github.com/MichaelMure/git-bug/entity"
	"github.com/MichaelMure/git-bug/repository"
)

// SetUserIdentity store the user identity's id in the git config
func SetUserIdentity(repo repository.RepoConfig, identity *Identity) error {
	return repo.LocalConfig().StoreString(identityConfigKey, identity.Id().String())
}

func ClearUserIdentity(repo repository.RepoConfig) error {
	return repo.LocalConfig().RemoveAll(identityConfigKey)
}

// GetUserIdentity read the current user identity, set with a git config entry
func GetUserIdentity(repo repository.Repo) (*Identity, error) {
	id, err := GetUserIdentityId(repo)
	if err != nil {
		return nil, err
	}

	i, err := ReadLocal(repo, id)
	if entity.IsErrNotFound(err) {
		innerErr := repo.LocalConfig().RemoveAll(identityConfigKey)
		if innerErr != nil {
			_, _ = fmt.Fprintln(os.Stderr, errors.Wrap(innerErr, "can't clear user identity").Error())
		}
		return nil, err
	}

	return i, nil
}

func GetUserIdentityId(repo repository.Repo) (entity.Id, error) {
	val, err := repo.LocalConfig().ReadString(identityConfigKey)
	if errors.Is(err, repository.ErrNoConfigEntry) {
		return entity.UnsetId, ErrNoIdentitySet
	}
	if errors.Is(err, repository.ErrMultipleConfigEntry) {
		return entity.UnsetId, ErrMultipleIdentitiesSet
	}
	if err != nil {
		return entity.UnsetId, err
	}

	var id = entity.Id(val)

	if err := id.Validate(); err != nil {
		return entity.UnsetId, err
	}

	return id, nil
}

// IsUserIdentitySet say if the user has set his identity
func IsUserIdentitySet(repo repository.Repo) (bool, error) {
	_, err := repo.LocalConfig().ReadString(identityConfigKey)
	if errors.Is(err, repository.ErrNoConfigEntry) {
		return false, nil
	}
	if err != nil {
		return false, err
	}
	return true, nil
}