1package identity
 2
 3import (
 4	"encoding/json"
 5	"errors"
 6	"fmt"
 7
 8	"github.com/MichaelMure/git-bug/entity"
 9)
10
11var ErrIdentityNotExist = errors.New("identity doesn't exist")
12
13func NewErrMultipleMatch(matching []entity.Id) *entity.ErrMultipleMatch {
14	return entity.NewErrMultipleMatch("identity", matching)
15}
16
17// Custom unmarshaling function to allow package user to delegate
18// the decoding of an Identity and distinguish between an Identity
19// and a Bare.
20//
21// If the given message has a "id" field, it's considered being a proper Identity.
22func UnmarshalJSON(raw json.RawMessage) (Interface, error) {
23	aux := &IdentityStub{}
24
25	// First try to decode and load as a normal Identity
26	err := json.Unmarshal(raw, &aux)
27	if err == nil && aux.Id() != "" {
28		return aux, nil
29	}
30
31	// abort if we have an error other than the wrong type
32	if _, ok := err.(*json.UnmarshalTypeError); err != nil && !ok {
33		return nil, err
34	}
35
36	// Fallback on a legacy Bare identity
37	b := &Bare{}
38
39	err = json.Unmarshal(raw, b)
40	if err == nil && (b.name != "" || b.login != "") {
41		return b, nil
42	}
43
44	// abort if we have an error other than the wrong type
45	if _, ok := err.(*json.UnmarshalTypeError); err != nil && !ok {
46		return nil, err
47	}
48
49	return nil, fmt.Errorf("unknown identity type")
50}