common.go

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