1package cache
 2
 3import (
 4	"encoding/gob"
 5	"fmt"
 6	"strings"
 7
 8	"github.com/MichaelMure/git-bug/entities/identity"
 9	"github.com/MichaelMure/git-bug/entity"
10)
11
12// Package initialisation used to register the type for (de)serialization
13func init() {
14	gob.Register(IdentityExcerpt{})
15}
16
17// IdentityExcerpt hold a subset of the identity values to be able to sort and
18// filter identities efficiently without having to read and compile each raw
19// identity.
20type IdentityExcerpt struct {
21	Id entity.Id
22
23	Name              string
24	Login             string
25	ImmutableMetadata map[string]string
26}
27
28func NewIdentityExcerpt(i *identity.Identity) *IdentityExcerpt {
29	return &IdentityExcerpt{
30		Id:                i.Id(),
31		Name:              i.Name(),
32		Login:             i.Login(),
33		ImmutableMetadata: i.ImmutableMetadata(),
34	}
35}
36
37// DisplayName return a non-empty string to display, representing the
38// identity, based on the non-empty values.
39func (i *IdentityExcerpt) DisplayName() string {
40	switch {
41	case i.Name == "" && i.Login != "":
42		return i.Login
43	case i.Name != "" && i.Login == "":
44		return i.Name
45	case i.Name != "" && i.Login != "":
46		return fmt.Sprintf("%s (%s)", i.Name, i.Login)
47	}
48
49	panic("invalid person data")
50}
51
52// Match matches a query with the identity name, login and ID prefixes
53func (i *IdentityExcerpt) Match(query string) bool {
54	return i.Id.HasPrefix(query) ||
55		strings.Contains(strings.ToLower(i.Name), query) ||
56		strings.Contains(strings.ToLower(i.Login), query)
57}
58
59/*
60 * Sorting
61 */
62
63type IdentityById []*IdentityExcerpt
64
65func (b IdentityById) Len() int {
66	return len(b)
67}
68
69func (b IdentityById) Less(i, j int) bool {
70	return b[i].Id < b[j].Id
71}
72
73func (b IdentityById) Swap(i, j int) {
74	b[i], b[j] = b[j], b[i]
75}