/
repository.go
98 lines (82 loc) · 2.41 KB
/
repository.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package providers
import (
"hash/crc32"
"sort"
"strconv"
"time"
"github.com/lithammer/fuzzysearch/fuzzy"
)
// Repository holds details of a git repository
type Repository struct {
ProviderType ProviderType
Name string
Refs Refs
RefsLastUpdate time.Time
RefsCurrentlyUpdating bool
WebURL string
}
// RepositoryKey is a unique identifier for a Repository
type RepositoryKey string
// Key returns a unique identifier based upon the Name and ProviderType
// of the Repository
func (r Repository) Key() RepositoryKey {
return RepositoryKey(strconv.Itoa(int(crc32.ChecksumIEEE([]byte(r.ProviderType.String() + r.Name)))))
}
// Repositories holds multiple Repository with their unique identifiers (RepositoryKey)
type Repositories map[RepositoryKey]Repository
// RankedRepository can be used when fuzzy searching Repositories, attributing a "rank"
// for the Repository given the pertinence of its attributes given the search
type RankedRepository struct {
Repository
Rank int
}
// RankedRepositories is a slice of *RankedRepository
type RankedRepositories []*RankedRepository
// GetByKey returns a Repository given its RepositoryKey
func (rs Repositories) GetByKey(k RepositoryKey) (r Repository, ok bool) {
r, ok = rs[k]
return
}
// Search looks up for repositories by Name in a fuzzy finding fashion, it will return
// them sorted by pertinence
func (rs Repositories) Search(filter string, limit int) (repos RankedRepositories) {
for _, r := range rs {
if len(filter) == 0 {
repos = append(repos, &RankedRepository{
Repository: r,
Rank: 0,
})
} else if rank := fuzzy.RankMatchNormalizedFold(filter, r.Name); rank >= 0 {
repos = append(repos, &RankedRepository{
Repository: r,
Rank: rank,
})
}
}
sort.SliceStable(repos, func(i, j int) bool {
if repos[i].Rank == repos[j].Rank {
return repos[i].Name > repos[j].Name
}
return repos[i].Rank < repos[j].Rank
})
if len(repos) > limit {
return repos[:limit]
}
return
}
// GetByClosestNameMatch returns the Repository which is the most pertinent
// given its Name
func (rs Repositories) GetByClosestNameMatch(name string) (repo Repository) {
if len(name) == 0 {
return
}
for _, r := range rs.Search(name, 1) {
repo = r.Repository
break
}
return
}
// IsEmpty assess the variable is empty or not
func (r Repository) IsEmpty() bool {
return r.Name == ""
}