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