identity_excerpt.go

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