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