1package cache
2
3import (
4 "errors"
5 "sort"
6 "time"
7
8 "github.com/MichaelMure/git-bug/entities/bug"
9 "github.com/MichaelMure/git-bug/entities/identity"
10 "github.com/MichaelMure/git-bug/entity"
11 "github.com/MichaelMure/git-bug/query"
12 "github.com/MichaelMure/git-bug/repository"
13)
14
15type RepoCacheBug struct {
16 *SubCache[*bug.Bug, *BugExcerpt, *BugCache]
17}
18
19func NewRepoCacheBug(repo repository.ClockedRepo,
20 resolvers func() entity.Resolvers,
21 getUserIdentity getUserIdentityFunc) *RepoCacheBug {
22
23 makeCached := func(b *bug.Bug, entityUpdated func(id entity.Id) error) *BugCache {
24 return NewBugCache(b, repo, getUserIdentity, entityUpdated)
25 }
26
27 makeExcerpt := func(b *bug.Bug) *BugExcerpt {
28 return NewBugExcerpt(b, b.Compile())
29 }
30
31 makeIndex := func(b *BugCache) []string {
32 snap := b.Snapshot()
33 var res []string
34 for _, comment := range snap.Comments {
35 res = append(res, comment.Message)
36 }
37 res = append(res, snap.Title)
38 return res
39 }
40
41 sc := NewSubCache[*bug.Bug, *BugExcerpt, *BugCache](
42 repo, resolvers, getUserIdentity,
43 makeCached, makeExcerpt, makeIndex,
44 "bug", "bugs",
45 formatVersion, defaultMaxLoadedBugs,
46 )
47
48 return &RepoCacheBug{SubCache: sc}
49}
50
51// ResolveBugCreateMetadata retrieve a bug that has the exact given metadata on
52// its Create operation, that is, the first operation. It fails if multiple bugs
53// match.
54func (c *RepoCacheBug) ResolveBugCreateMetadata(key string, value string) (*BugCache, error) {
55 return c.ResolveMatcher(func(excerpt *BugExcerpt) bool {
56 return excerpt.CreateMetadata[key] == value
57 })
58}
59
60// ResolveComment search for a Bug/Comment combination matching the merged
61// bug/comment Id prefix. Returns the Bug containing the Comment and the Comment's
62// Id.
63func (c *RepoCacheBug) ResolveComment(prefix string) (*BugCache, entity.CombinedId, error) {
64 bugPrefix, _ := entity.SeparateIds(prefix)
65 bugCandidate := make([]entity.Id, 0, 5)
66
67 // build a list of possible matching bugs
68 c.mu.RLock()
69 for _, excerpt := range c.excerpts {
70 if excerpt.Id().HasPrefix(bugPrefix) {
71 bugCandidate = append(bugCandidate, excerpt.Id())
72 }
73 }
74 c.mu.RUnlock()
75
76 matchingBugIds := make([]entity.Id, 0, 5)
77 matchingCommentId := entity.UnsetCombinedId
78 var matchingBug *BugCache
79
80 // search for matching comments
81 // searching every bug candidate allow for some collision with the bug prefix only,
82 // before being refined with the full comment prefix
83 for _, bugId := range bugCandidate {
84 b, err := c.Resolve(bugId)
85 if err != nil {
86 return nil, entity.UnsetCombinedId, err
87 }
88
89 for _, comment := range b.Snapshot().Comments {
90 if comment.CombinedId().HasPrefix(prefix) {
91 matchingBugIds = append(matchingBugIds, bugId)
92 matchingBug = b
93 matchingCommentId = comment.CombinedId()
94 }
95 }
96 }
97
98 if len(matchingBugIds) > 1 {
99 return nil, entity.UnsetCombinedId, entity.NewErrMultipleMatch("bug/comment", matchingBugIds)
100 } else if len(matchingBugIds) == 0 {
101 return nil, entity.UnsetCombinedId, errors.New("comment doesn't exist")
102 }
103
104 return matchingBug, matchingCommentId, nil
105}
106
107// QueryBugs return the id of all Bug matching the given Query
108func (c *RepoCacheBug) QueryBugs(q *query.Query) ([]entity.Id, error) {
109 c.mu.RLock()
110 defer c.mu.RUnlock()
111
112 if q == nil {
113 return c.AllIds(), nil
114 }
115
116 matcher := compileMatcher(q.Filters)
117
118 var filtered []*BugExcerpt
119 var foundBySearch map[entity.Id]*BugExcerpt
120
121 if q.Search != nil {
122 foundBySearch = map[entity.Id]*BugExcerpt{}
123
124 index, err := c.repo.GetIndex("bug")
125 if err != nil {
126 return nil, err
127 }
128
129 res, err := index.Search(q.Search)
130 if err != nil {
131 return nil, err
132 }
133
134 for _, hit := range res {
135 id := entity.Id(hit)
136 foundBySearch[id] = c.excerpts[id]
137 }
138 } else {
139 foundBySearch = c.excerpts
140 }
141
142 for _, excerpt := range foundBySearch {
143 if matcher.Match(excerpt, c) {
144 filtered = append(filtered, excerpt)
145 }
146 }
147
148 var sorter sort.Interface
149
150 switch q.OrderBy {
151 case query.OrderById:
152 sorter = BugsById(filtered)
153 case query.OrderByCreation:
154 sorter = BugsByCreationTime(filtered)
155 case query.OrderByEdit:
156 sorter = BugsByEditTime(filtered)
157 default:
158 return nil, errors.New("missing sort type")
159 }
160
161 switch q.OrderDirection {
162 case query.OrderAscending:
163 // Nothing to do
164 case query.OrderDescending:
165 sorter = sort.Reverse(sorter)
166 default:
167 return nil, errors.New("missing sort direction")
168 }
169
170 sort.Sort(sorter)
171
172 result := make([]entity.Id, len(filtered))
173
174 for i, val := range filtered {
175 result[i] = val.Id()
176 }
177
178 return result, nil
179}
180
181// ValidLabels list valid labels
182//
183// Note: in the future, a proper label policy could be implemented where valid
184// labels are defined in a configuration file. Until that, the default behavior
185// is to return the list of labels already used.
186func (c *RepoCacheBug) ValidLabels() []bug.Label {
187 c.mu.RLock()
188 defer c.mu.RUnlock()
189
190 set := map[bug.Label]interface{}{}
191
192 for _, excerpt := range c.excerpts {
193 for _, l := range excerpt.Labels {
194 set[l] = nil
195 }
196 }
197
198 result := make([]bug.Label, len(set))
199
200 i := 0
201 for l := range set {
202 result[i] = l
203 i++
204 }
205
206 // Sort
207 sort.Slice(result, func(i, j int) bool {
208 return string(result[i]) < string(result[j])
209 })
210
211 return result
212}
213
214// New create a new bug
215// The new bug is written in the repository (commit)
216func (c *RepoCacheBug) New(title string, message string) (*BugCache, *bug.CreateOperation, error) {
217 return c.NewWithFiles(title, message, nil)
218}
219
220// NewWithFiles create a new bug with attached files for the message
221// The new bug is written in the repository (commit)
222func (c *RepoCacheBug) NewWithFiles(title string, message string, files []repository.Hash) (*BugCache, *bug.CreateOperation, error) {
223 author, err := c.getUserIdentity()
224 if err != nil {
225 return nil, nil, err
226 }
227
228 return c.NewRaw(author, time.Now().Unix(), title, message, files, nil)
229}
230
231// NewRaw create a new bug with attached files for the message, as
232// well as metadata for the Create operation.
233// The new bug is written in the repository (commit)
234func (c *RepoCacheBug) NewRaw(author identity.Interface, unixTime int64, title string, message string, files []repository.Hash, metadata map[string]string) (*BugCache, *bug.CreateOperation, error) {
235 b, op, err := bug.Create(author, unixTime, title, message, files, metadata)
236 if err != nil {
237 return nil, nil, err
238 }
239
240 err = b.Commit(c.repo)
241 if err != nil {
242 return nil, nil, err
243 }
244
245 cached, err := c.add(b)
246 if err != nil {
247 return nil, nil, err
248 }
249
250 return cached, op, nil
251}