1package identity
 2
 3import (
 4	"fmt"
 5	"os"
 6
 7	"github.com/pkg/errors"
 8
 9	bootstrap "github.com/MichaelMure/git-bug/entity/boostrap"
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
18func ClearUserIdentity(repo repository.RepoConfig) error {
19	return repo.LocalConfig().RemoveAll(identityConfigKey)
20}
21
22// GetUserIdentity read the current user identity, set with a git config entry
23func GetUserIdentity(repo repository.Repo) (*Identity, error) {
24	id, err := GetUserIdentityId(repo)
25	if err != nil {
26		return nil, err
27	}
28
29	i, err := ReadLocal(repo, id)
30	if bootstrap.IsErrNotFound(err) {
31		innerErr := repo.LocalConfig().RemoveAll(identityConfigKey)
32		if innerErr != nil {
33			_, _ = fmt.Fprintln(os.Stderr, errors.Wrap(innerErr, "can't clear user identity").Error())
34		}
35		return nil, err
36	}
37
38	return i, nil
39}
40
41func GetUserIdentityId(repo repository.Repo) (bootstrap.Id, error) {
42	val, err := repo.LocalConfig().ReadString(identityConfigKey)
43	if errors.Is(err, repository.ErrNoConfigEntry) {
44		return bootstrap.UnsetId, ErrNoIdentitySet
45	}
46	if errors.Is(err, repository.ErrMultipleConfigEntry) {
47		return bootstrap.UnsetId, ErrMultipleIdentitiesSet
48	}
49	if err != nil {
50		return bootstrap.UnsetId, err
51	}
52
53	var id = bootstrap.Id(val)
54
55	if err := id.Validate(); err != nil {
56		return bootstrap.UnsetId, err
57	}
58
59	return id, nil
60}
61
62// IsUserIdentitySet say if the user has set his identity
63func IsUserIdentitySet(repo repository.Repo) (bool, error) {
64	_, err := repo.LocalConfig().ReadString(identityConfigKey)
65	if errors.Is(err, repository.ErrNoConfigEntry) {
66		return false, nil
67	}
68	if err != nil {
69		return false, err
70	}
71	return true, nil
72}