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