1package cache
2
3import (
4 "bytes"
5 "encoding/gob"
6 "fmt"
7 "io"
8 "io/ioutil"
9 "os"
10 "path"
11 "sort"
12 "strconv"
13 "time"
14
15 "github.com/pkg/errors"
16
17 "github.com/MichaelMure/git-bug/bug"
18 "github.com/MichaelMure/git-bug/entity"
19 "github.com/MichaelMure/git-bug/identity"
20 "github.com/MichaelMure/git-bug/repository"
21 "github.com/MichaelMure/git-bug/util/git"
22 "github.com/MichaelMure/git-bug/util/process"
23)
24
25const bugCacheFile = "bug-cache"
26const identityCacheFile = "identity-cache"
27
28// 1: original format
29// 2: added cache for identities with a reference in the bug cache
30const formatVersion = 2
31
32type ErrInvalidCacheFormat struct {
33 message string
34}
35
36func (e ErrInvalidCacheFormat) Error() string {
37 return e.message
38}
39
40var _ repository.RepoCommon = &RepoCache{}
41
42// RepoCache is a cache for a Repository. This cache has multiple functions:
43//
44// 1. After being loaded, a Bug is kept in memory in the cache, allowing for fast
45// access later.
46// 2. The cache maintain in memory and on disk a pre-digested excerpt for each bug,
47// allowing for fast querying the whole set of bugs without having to load
48// them individually.
49// 3. The cache guarantee that a single instance of a Bug is loaded at once, avoiding
50// loss of data that we could have with multiple copies in the same process.
51// 4. The same way, the cache maintain in memory a single copy of the loaded identities.
52//
53// The cache also protect the on-disk data by locking the git repository for its
54// own usage, by writing a lock file. Of course, normal git operations are not
55// affected, only git-bug related one.
56type RepoCache struct {
57 // the underlying repo
58 repo repository.ClockedRepo
59
60 // excerpt of bugs data for all bugs
61 bugExcerpts map[entity.Id]*BugExcerpt
62 // bug loaded in memory
63 bugs map[entity.Id]*BugCache
64
65 // excerpt of identities data for all identities
66 identitiesExcerpts map[entity.Id]*IdentityExcerpt
67 // identities loaded in memory
68 identities map[entity.Id]*IdentityCache
69
70 // the user identity's id, if known
71 userIdentityId entity.Id
72}
73
74func NewRepoCache(r repository.ClockedRepo) (*RepoCache, error) {
75 c := &RepoCache{
76 repo: r,
77 bugs: make(map[entity.Id]*BugCache),
78 identities: make(map[entity.Id]*IdentityCache),
79 }
80
81 err := c.lock()
82 if err != nil {
83 return &RepoCache{}, err
84 }
85
86 err = c.load()
87 if err == nil {
88 return c, nil
89 }
90 if _, ok := err.(ErrInvalidCacheFormat); ok {
91 return nil, err
92 }
93
94 err = c.buildCache()
95 if err != nil {
96 return nil, err
97 }
98
99 return c, c.write()
100}
101
102// LocalConfig give access to the repository scoped configuration
103func (c *RepoCache) LocalConfig() repository.Config {
104 return c.repo.LocalConfig()
105}
106
107// GlobalConfig give access to the git global configuration
108func (c *RepoCache) GlobalConfig() repository.Config {
109 return c.repo.GlobalConfig()
110}
111
112// GetPath returns the path to the repo.
113func (c *RepoCache) GetPath() string {
114 return c.repo.GetPath()
115}
116
117// GetCoreEditor returns the name of the editor that the user has used to configure git.
118func (c *RepoCache) GetCoreEditor() (string, error) {
119 return c.repo.GetCoreEditor()
120}
121
122// GetRemotes returns the configured remotes repositories.
123func (c *RepoCache) GetRemotes() (map[string]string, error) {
124 return c.repo.GetRemotes()
125}
126
127// GetUserName returns the name the the user has used to configure git
128func (c *RepoCache) GetUserName() (string, error) {
129 return c.repo.GetUserName()
130}
131
132// GetUserEmail returns the email address that the user has used to configure git.
133func (c *RepoCache) GetUserEmail() (string, error) {
134 return c.repo.GetUserEmail()
135}
136
137func (c *RepoCache) lock() error {
138 lockPath := repoLockFilePath(c.repo)
139
140 err := repoIsAvailable(c.repo)
141 if err != nil {
142 return err
143 }
144
145 f, err := os.Create(lockPath)
146 if err != nil {
147 return err
148 }
149
150 pid := fmt.Sprintf("%d", os.Getpid())
151 _, err = f.WriteString(pid)
152 if err != nil {
153 return err
154 }
155
156 return f.Close()
157}
158
159func (c *RepoCache) Close() error {
160 c.identities = make(map[entity.Id]*IdentityCache)
161 c.identitiesExcerpts = nil
162 c.bugs = make(map[entity.Id]*BugCache)
163 c.bugExcerpts = nil
164
165 lockPath := repoLockFilePath(c.repo)
166 return os.Remove(lockPath)
167}
168
169// bugUpdated is a callback to trigger when the excerpt of a bug changed,
170// that is each time a bug is updated
171func (c *RepoCache) bugUpdated(id entity.Id) error {
172 b, ok := c.bugs[id]
173 if !ok {
174 panic("missing bug in the cache")
175 }
176
177 c.bugExcerpts[id] = NewBugExcerpt(b.bug, b.Snapshot())
178
179 // we only need to write the bug cache
180 return c.writeBugCache()
181}
182
183// identityUpdated is a callback to trigger when the excerpt of an identity
184// changed, that is each time an identity is updated
185func (c *RepoCache) identityUpdated(id entity.Id) error {
186 i, ok := c.identities[id]
187 if !ok {
188 panic("missing identity in the cache")
189 }
190
191 c.identitiesExcerpts[id] = NewIdentityExcerpt(i.Identity)
192
193 // we only need to write the identity cache
194 return c.writeIdentityCache()
195}
196
197// load will try to read from the disk all the cache files
198func (c *RepoCache) load() error {
199 err := c.loadBugCache()
200 if err != nil {
201 return err
202 }
203 return c.loadIdentityCache()
204}
205
206// load will try to read from the disk the bug cache file
207func (c *RepoCache) loadBugCache() error {
208 f, err := os.Open(bugCacheFilePath(c.repo))
209 if err != nil {
210 return err
211 }
212
213 decoder := gob.NewDecoder(f)
214
215 aux := struct {
216 Version uint
217 Excerpts map[entity.Id]*BugExcerpt
218 }{}
219
220 err = decoder.Decode(&aux)
221 if err != nil {
222 return err
223 }
224
225 if aux.Version != 2 {
226 return ErrInvalidCacheFormat{
227 message: fmt.Sprintf("unknown cache format version %v", aux.Version),
228 }
229 }
230
231 c.bugExcerpts = aux.Excerpts
232 return nil
233}
234
235// load will try to read from the disk the identity cache file
236func (c *RepoCache) loadIdentityCache() error {
237 f, err := os.Open(identityCacheFilePath(c.repo))
238 if err != nil {
239 return err
240 }
241
242 decoder := gob.NewDecoder(f)
243
244 aux := struct {
245 Version uint
246 Excerpts map[entity.Id]*IdentityExcerpt
247 }{}
248
249 err = decoder.Decode(&aux)
250 if err != nil {
251 return err
252 }
253
254 if aux.Version != 2 {
255 return ErrInvalidCacheFormat{
256 message: fmt.Sprintf("unknown cache format version %v", aux.Version),
257 }
258 }
259
260 c.identitiesExcerpts = aux.Excerpts
261 return nil
262}
263
264// write will serialize on disk all the cache files
265func (c *RepoCache) write() error {
266 err := c.writeBugCache()
267 if err != nil {
268 return err
269 }
270 return c.writeIdentityCache()
271}
272
273// write will serialize on disk the bug cache file
274func (c *RepoCache) writeBugCache() error {
275 var data bytes.Buffer
276
277 aux := struct {
278 Version uint
279 Excerpts map[entity.Id]*BugExcerpt
280 }{
281 Version: formatVersion,
282 Excerpts: c.bugExcerpts,
283 }
284
285 encoder := gob.NewEncoder(&data)
286
287 err := encoder.Encode(aux)
288 if err != nil {
289 return err
290 }
291
292 f, err := os.Create(bugCacheFilePath(c.repo))
293 if err != nil {
294 return err
295 }
296
297 _, err = f.Write(data.Bytes())
298 if err != nil {
299 return err
300 }
301
302 return f.Close()
303}
304
305// write will serialize on disk the identity cache file
306func (c *RepoCache) writeIdentityCache() error {
307 var data bytes.Buffer
308
309 aux := struct {
310 Version uint
311 Excerpts map[entity.Id]*IdentityExcerpt
312 }{
313 Version: formatVersion,
314 Excerpts: c.identitiesExcerpts,
315 }
316
317 encoder := gob.NewEncoder(&data)
318
319 err := encoder.Encode(aux)
320 if err != nil {
321 return err
322 }
323
324 f, err := os.Create(identityCacheFilePath(c.repo))
325 if err != nil {
326 return err
327 }
328
329 _, err = f.Write(data.Bytes())
330 if err != nil {
331 return err
332 }
333
334 return f.Close()
335}
336
337func bugCacheFilePath(repo repository.Repo) string {
338 return path.Join(repo.GetPath(), "git-bug", bugCacheFile)
339}
340
341func identityCacheFilePath(repo repository.Repo) string {
342 return path.Join(repo.GetPath(), "git-bug", identityCacheFile)
343}
344
345func (c *RepoCache) buildCache() error {
346 _, _ = fmt.Fprintf(os.Stderr, "Building identity cache... ")
347
348 c.identitiesExcerpts = make(map[entity.Id]*IdentityExcerpt)
349
350 allIdentities := identity.ReadAllLocalIdentities(c.repo)
351
352 for i := range allIdentities {
353 if i.Err != nil {
354 return i.Err
355 }
356
357 c.identitiesExcerpts[i.Identity.Id()] = NewIdentityExcerpt(i.Identity)
358 }
359
360 _, _ = fmt.Fprintln(os.Stderr, "Done.")
361
362 _, _ = fmt.Fprintf(os.Stderr, "Building bug cache... ")
363
364 c.bugExcerpts = make(map[entity.Id]*BugExcerpt)
365
366 allBugs := bug.ReadAllLocalBugs(c.repo)
367
368 for b := range allBugs {
369 if b.Err != nil {
370 return b.Err
371 }
372
373 snap := b.Bug.Compile()
374 c.bugExcerpts[b.Bug.Id()] = NewBugExcerpt(b.Bug, &snap)
375 }
376
377 _, _ = fmt.Fprintln(os.Stderr, "Done.")
378 return nil
379}
380
381// ResolveBugExcerpt retrieve a BugExcerpt matching the exact given id
382func (c *RepoCache) ResolveBugExcerpt(id entity.Id) (*BugExcerpt, error) {
383 e, ok := c.bugExcerpts[id]
384 if !ok {
385 return nil, bug.ErrBugNotExist
386 }
387
388 return e, nil
389}
390
391// ResolveBug retrieve a bug matching the exact given id
392func (c *RepoCache) ResolveBug(id entity.Id) (*BugCache, error) {
393 cached, ok := c.bugs[id]
394 if ok {
395 return cached, nil
396 }
397
398 b, err := bug.ReadLocalBug(c.repo, id)
399 if err != nil {
400 return nil, err
401 }
402
403 cached = NewBugCache(c, b)
404 c.bugs[id] = cached
405
406 return cached, nil
407}
408
409// ResolveBugExcerptPrefix retrieve a BugExcerpt matching an id prefix. It fails if multiple
410// bugs match.
411func (c *RepoCache) ResolveBugExcerptPrefix(prefix string) (*BugExcerpt, error) {
412 return c.ResolveBugExcerptMatcher(func(excerpt *BugExcerpt) bool {
413 return excerpt.Id.HasPrefix(prefix)
414 })
415}
416
417// ResolveBugPrefix retrieve a bug matching an id prefix. It fails if multiple
418// bugs match.
419func (c *RepoCache) ResolveBugPrefix(prefix string) (*BugCache, error) {
420 return c.ResolveBugMatcher(func(excerpt *BugExcerpt) bool {
421 return excerpt.Id.HasPrefix(prefix)
422 })
423}
424
425// ResolveBugCreateMetadata retrieve a bug that has the exact given metadata on
426// its Create operation, that is, the first operation. It fails if multiple bugs
427// match.
428func (c *RepoCache) ResolveBugCreateMetadata(key string, value string) (*BugCache, error) {
429 return c.ResolveBugMatcher(func(excerpt *BugExcerpt) bool {
430 return excerpt.CreateMetadata[key] == value
431 })
432}
433
434func (c *RepoCache) ResolveBugExcerptMatcher(f func(*BugExcerpt) bool) (*BugExcerpt, error) {
435 id, err := c.resolveBugMatcher(f)
436 if err != nil {
437 return nil, err
438 }
439 return c.ResolveBugExcerpt(id)
440}
441
442func (c *RepoCache) ResolveBugMatcher(f func(*BugExcerpt) bool) (*BugCache, error) {
443 id, err := c.resolveBugMatcher(f)
444 if err != nil {
445 return nil, err
446 }
447 return c.ResolveBug(id)
448}
449
450func (c *RepoCache) resolveBugMatcher(f func(*BugExcerpt) bool) (entity.Id, error) {
451 // preallocate but empty
452 matching := make([]entity.Id, 0, 5)
453
454 for _, excerpt := range c.bugExcerpts {
455 if f(excerpt) {
456 matching = append(matching, excerpt.Id)
457 }
458 }
459
460 if len(matching) > 1 {
461 return entity.UnsetId, bug.NewErrMultipleMatchBug(matching)
462 }
463
464 if len(matching) == 0 {
465 return entity.UnsetId, bug.ErrBugNotExist
466 }
467
468 return matching[0], nil
469}
470
471// QueryBugs return the id of all Bug matching the given Query
472func (c *RepoCache) QueryBugs(query *Query) []entity.Id {
473 if query == nil {
474 return c.AllBugsIds()
475 }
476
477 var filtered []*BugExcerpt
478
479 for _, excerpt := range c.bugExcerpts {
480 if query.Match(c, excerpt) {
481 filtered = append(filtered, excerpt)
482 }
483 }
484
485 var sorter sort.Interface
486
487 switch query.OrderBy {
488 case OrderById:
489 sorter = BugsById(filtered)
490 case OrderByCreation:
491 sorter = BugsByCreationTime(filtered)
492 case OrderByEdit:
493 sorter = BugsByEditTime(filtered)
494 default:
495 panic("missing sort type")
496 }
497
498 if query.OrderDirection == OrderDescending {
499 sorter = sort.Reverse(sorter)
500 }
501
502 sort.Sort(sorter)
503
504 result := make([]entity.Id, len(filtered))
505
506 for i, val := range filtered {
507 result[i] = val.Id
508 }
509
510 return result
511}
512
513// AllBugsIds return all known bug ids
514func (c *RepoCache) AllBugsIds() []entity.Id {
515 result := make([]entity.Id, len(c.bugExcerpts))
516
517 i := 0
518 for _, excerpt := range c.bugExcerpts {
519 result[i] = excerpt.Id
520 i++
521 }
522
523 return result
524}
525
526// ValidLabels list valid labels
527//
528// Note: in the future, a proper label policy could be implemented where valid
529// labels are defined in a configuration file. Until that, the default behavior
530// is to return the list of labels already used.
531func (c *RepoCache) ValidLabels() []bug.Label {
532 set := map[bug.Label]interface{}{}
533
534 for _, excerpt := range c.bugExcerpts {
535 for _, l := range excerpt.Labels {
536 set[l] = nil
537 }
538 }
539
540 result := make([]bug.Label, len(set))
541
542 i := 0
543 for l := range set {
544 result[i] = l
545 i++
546 }
547
548 // Sort
549 sort.Slice(result, func(i, j int) bool {
550 return string(result[i]) < string(result[j])
551 })
552
553 return result
554}
555
556// NewBug create a new bug
557// The new bug is written in the repository (commit)
558func (c *RepoCache) NewBug(title string, message string) (*BugCache, *bug.CreateOperation, error) {
559 return c.NewBugWithFiles(title, message, nil)
560}
561
562// NewBugWithFiles create a new bug with attached files for the message
563// The new bug is written in the repository (commit)
564func (c *RepoCache) NewBugWithFiles(title string, message string, files []git.Hash) (*BugCache, *bug.CreateOperation, error) {
565 author, err := c.GetUserIdentity()
566 if err != nil {
567 return nil, nil, err
568 }
569
570 return c.NewBugRaw(author, time.Now().Unix(), title, message, files, nil)
571}
572
573// NewBugWithFilesMeta create a new bug with attached files for the message, as
574// well as metadata for the Create operation.
575// The new bug is written in the repository (commit)
576func (c *RepoCache) NewBugRaw(author *IdentityCache, unixTime int64, title string, message string, files []git.Hash, metadata map[string]string) (*BugCache, *bug.CreateOperation, error) {
577 b, op, err := bug.CreateWithFiles(author.Identity, unixTime, title, message, files)
578 if err != nil {
579 return nil, nil, err
580 }
581
582 for key, value := range metadata {
583 op.SetMetadata(key, value)
584 }
585
586 err = b.Commit(c.repo)
587 if err != nil {
588 return nil, nil, err
589 }
590
591 if _, has := c.bugs[b.Id()]; has {
592 return nil, nil, fmt.Errorf("bug %s already exist in the cache", b.Id())
593 }
594
595 cached := NewBugCache(c, b)
596 c.bugs[b.Id()] = cached
597
598 // force the write of the excerpt
599 err = c.bugUpdated(b.Id())
600 if err != nil {
601 return nil, nil, err
602 }
603
604 return cached, op, nil
605}
606
607// Fetch retrieve updates from a remote
608// This does not change the local bugs or identities state
609func (c *RepoCache) Fetch(remote string) (string, error) {
610 stdout1, err := identity.Fetch(c.repo, remote)
611 if err != nil {
612 return stdout1, err
613 }
614
615 stdout2, err := bug.Fetch(c.repo, remote)
616 if err != nil {
617 return stdout2, err
618 }
619
620 return stdout1 + stdout2, nil
621}
622
623// MergeAll will merge all the available remote bug and identities
624func (c *RepoCache) MergeAll(remote string) <-chan entity.MergeResult {
625 out := make(chan entity.MergeResult)
626
627 // Intercept merge results to update the cache properly
628 go func() {
629 defer close(out)
630
631 results := identity.MergeAll(c.repo, remote)
632 for result := range results {
633 out <- result
634
635 if result.Err != nil {
636 continue
637 }
638
639 switch result.Status {
640 case entity.MergeStatusNew, entity.MergeStatusUpdated:
641 i := result.Entity.(*identity.Identity)
642 c.identitiesExcerpts[result.Id] = NewIdentityExcerpt(i)
643 }
644 }
645
646 results = bug.MergeAll(c.repo, remote)
647 for result := range results {
648 out <- result
649
650 if result.Err != nil {
651 continue
652 }
653
654 switch result.Status {
655 case entity.MergeStatusNew, entity.MergeStatusUpdated:
656 b := result.Entity.(*bug.Bug)
657 snap := b.Compile()
658 c.bugExcerpts[result.Id] = NewBugExcerpt(b, &snap)
659 }
660 }
661
662 err := c.write()
663
664 // No easy way out here ..
665 if err != nil {
666 panic(err)
667 }
668 }()
669
670 return out
671}
672
673// Push update a remote with the local changes
674func (c *RepoCache) Push(remote string) (string, error) {
675 stdout1, err := identity.Push(c.repo, remote)
676 if err != nil {
677 return stdout1, err
678 }
679
680 stdout2, err := bug.Push(c.repo, remote)
681 if err != nil {
682 return stdout2, err
683 }
684
685 return stdout1 + stdout2, nil
686}
687
688// Pull will do a Fetch + MergeAll
689// This function will return an error if a merge fail
690func (c *RepoCache) Pull(remote string) error {
691 _, err := c.Fetch(remote)
692 if err != nil {
693 return err
694 }
695
696 for merge := range c.MergeAll(remote) {
697 if merge.Err != nil {
698 return merge.Err
699 }
700 if merge.Status == entity.MergeStatusInvalid {
701 return errors.Errorf("merge failure: %s", merge.Reason)
702 }
703 }
704
705 return nil
706}
707
708func repoLockFilePath(repo repository.Repo) string {
709 return path.Join(repo.GetPath(), "git-bug", lockfile)
710}
711
712// repoIsAvailable check is the given repository is locked by a Cache.
713// Note: this is a smart function that will cleanup the lock file if the
714// corresponding process is not there anymore.
715// If no error is returned, the repo is free to edit.
716func repoIsAvailable(repo repository.Repo) error {
717 lockPath := repoLockFilePath(repo)
718
719 // Todo: this leave way for a racey access to the repo between the test
720 // if the file exist and the actual write. It's probably not a problem in
721 // practice because using a repository will be done from user interaction
722 // or in a context where a single instance of git-bug is already guaranteed
723 // (say, a server with the web UI running). But still, that might be nice to
724 // have a mutex or something to guard that.
725
726 // Todo: this will fail if somehow the filesystem is shared with another
727 // computer. Should add a configuration that prevent the cleaning of the
728 // lock file
729
730 f, err := os.Open(lockPath)
731
732 if err != nil && !os.IsNotExist(err) {
733 return err
734 }
735
736 if err == nil {
737 // lock file already exist
738 buf, err := ioutil.ReadAll(io.LimitReader(f, 10))
739 if err != nil {
740 return err
741 }
742 if len(buf) == 10 {
743 return fmt.Errorf("the lock file should be < 10 bytes")
744 }
745
746 pid, err := strconv.Atoi(string(buf))
747 if err != nil {
748 return err
749 }
750
751 if process.IsRunning(pid) {
752 return fmt.Errorf("the repository you want to access is already locked by the process pid %d", pid)
753 }
754
755 // The lock file is just laying there after a crash, clean it
756
757 fmt.Println("A lock file is present but the corresponding process is not, removing it.")
758 err = f.Close()
759 if err != nil {
760 return err
761 }
762
763 err = os.Remove(lockPath)
764 if err != nil {
765 return err
766 }
767 }
768
769 return nil
770}
771
772// ResolveIdentityExcerpt retrieve a IdentityExcerpt matching the exact given id
773func (c *RepoCache) ResolveIdentityExcerpt(id entity.Id) (*IdentityExcerpt, error) {
774 e, ok := c.identitiesExcerpts[id]
775 if !ok {
776 return nil, identity.ErrIdentityNotExist
777 }
778
779 return e, nil
780}
781
782// ResolveIdentity retrieve an identity matching the exact given id
783func (c *RepoCache) ResolveIdentity(id entity.Id) (*IdentityCache, error) {
784 cached, ok := c.identities[id]
785 if ok {
786 return cached, nil
787 }
788
789 i, err := identity.ReadLocal(c.repo, id)
790 if err != nil {
791 return nil, err
792 }
793
794 cached = NewIdentityCache(c, i)
795 c.identities[id] = cached
796
797 return cached, nil
798}
799
800// ResolveIdentityExcerptPrefix retrieve a IdentityExcerpt matching an id prefix.
801// It fails if multiple identities match.
802func (c *RepoCache) ResolveIdentityExcerptPrefix(prefix string) (*IdentityExcerpt, error) {
803 return c.ResolveIdentityExcerptMatcher(func(excerpt *IdentityExcerpt) bool {
804 return excerpt.Id.HasPrefix(prefix)
805 })
806}
807
808// ResolveIdentityPrefix retrieve an Identity matching an id prefix.
809// It fails if multiple identities match.
810func (c *RepoCache) ResolveIdentityPrefix(prefix string) (*IdentityCache, error) {
811 return c.ResolveIdentityMatcher(func(excerpt *IdentityExcerpt) bool {
812 return excerpt.Id.HasPrefix(prefix)
813 })
814}
815
816// ResolveIdentityImmutableMetadata retrieve an Identity that has the exact given metadata on
817// one of it's version. If multiple version have the same key, the first defined take precedence.
818func (c *RepoCache) ResolveIdentityImmutableMetadata(key string, value string) (*IdentityCache, error) {
819 return c.ResolveIdentityMatcher(func(excerpt *IdentityExcerpt) bool {
820 return excerpt.ImmutableMetadata[key] == value
821 })
822}
823
824func (c *RepoCache) ResolveIdentityExcerptMatcher(f func(*IdentityExcerpt) bool) (*IdentityExcerpt, error) {
825 id, err := c.resolveIdentityMatcher(f)
826 if err != nil {
827 return nil, err
828 }
829 return c.ResolveIdentityExcerpt(id)
830}
831
832func (c *RepoCache) ResolveIdentityMatcher(f func(*IdentityExcerpt) bool) (*IdentityCache, error) {
833 id, err := c.resolveIdentityMatcher(f)
834 if err != nil {
835 return nil, err
836 }
837 return c.ResolveIdentity(id)
838}
839
840func (c *RepoCache) resolveIdentityMatcher(f func(*IdentityExcerpt) bool) (entity.Id, error) {
841 // preallocate but empty
842 matching := make([]entity.Id, 0, 5)
843
844 for _, excerpt := range c.identitiesExcerpts {
845 if f(excerpt) {
846 matching = append(matching, excerpt.Id)
847 }
848 }
849
850 if len(matching) > 1 {
851 return entity.UnsetId, identity.NewErrMultipleMatch(matching)
852 }
853
854 if len(matching) == 0 {
855 return entity.UnsetId, identity.ErrIdentityNotExist
856 }
857
858 return matching[0], nil
859}
860
861// AllIdentityIds return all known identity ids
862func (c *RepoCache) AllIdentityIds() []entity.Id {
863 result := make([]entity.Id, len(c.identitiesExcerpts))
864
865 i := 0
866 for _, excerpt := range c.identitiesExcerpts {
867 result[i] = excerpt.Id
868 i++
869 }
870
871 return result
872}
873
874func (c *RepoCache) SetUserIdentity(i *IdentityCache) error {
875 err := identity.SetUserIdentity(c.repo, i.Identity)
876 if err != nil {
877 return err
878 }
879
880 // Make sure that everything is fine
881 if _, ok := c.identities[i.Id()]; !ok {
882 panic("SetUserIdentity while the identity is not from the cache, something is wrong")
883 }
884
885 c.userIdentityId = i.Id()
886
887 return nil
888}
889
890func (c *RepoCache) GetUserIdentity() (*IdentityCache, error) {
891 if c.userIdentityId != "" {
892 i, ok := c.identities[c.userIdentityId]
893 if ok {
894 return i, nil
895 }
896 }
897
898 i, err := identity.GetUserIdentity(c.repo)
899 if err != nil {
900 return nil, err
901 }
902
903 cached := NewIdentityCache(c, i)
904 c.identities[i.Id()] = cached
905 c.userIdentityId = i.Id()
906
907 return cached, nil
908}
909
910func (c *RepoCache) GetUserIdentityExcerpt() (*IdentityExcerpt, error) {
911 if c.userIdentityId == "" {
912 id, err := identity.GetUserIdentityId(c.repo)
913 if err != nil {
914 return nil, err
915 }
916 c.userIdentityId = id
917 }
918
919 excerpt, ok := c.identitiesExcerpts[c.userIdentityId]
920 if !ok {
921 return nil, fmt.Errorf("cache: missing identity excerpt %v", c.userIdentityId)
922 }
923 return excerpt, nil
924}
925
926func (c *RepoCache) IsUserIdentitySet() (bool, error) {
927 return identity.IsUserIdentitySet(c.repo)
928}
929
930func (c *RepoCache) NewIdentityFromGitUser() (*IdentityCache, error) {
931 return c.NewIdentityFromGitUserRaw(nil)
932}
933
934func (c *RepoCache) NewIdentityFromGitUserRaw(metadata map[string]string) (*IdentityCache, error) {
935 i, err := identity.NewFromGitUser(c.repo)
936 if err != nil {
937 return nil, err
938 }
939 return c.finishIdentity(i, metadata)
940}
941
942// NewIdentity create a new identity
943// The new identity is written in the repository (commit)
944func (c *RepoCache) NewIdentity(name string, email string) (*IdentityCache, error) {
945 return c.NewIdentityRaw(name, email, "", nil)
946}
947
948// NewIdentityFull create a new identity
949// The new identity is written in the repository (commit)
950func (c *RepoCache) NewIdentityFull(name string, email string, avatarUrl string) (*IdentityCache, error) {
951 return c.NewIdentityRaw(name, email, avatarUrl, nil)
952}
953
954func (c *RepoCache) NewIdentityRaw(name string, email string, avatarUrl string, metadata map[string]string) (*IdentityCache, error) {
955 i := identity.NewIdentityFull(name, email, avatarUrl)
956 return c.finishIdentity(i, metadata)
957}
958
959func (c *RepoCache) finishIdentity(i *identity.Identity, metadata map[string]string) (*IdentityCache, error) {
960 for key, value := range metadata {
961 i.SetMetadata(key, value)
962 }
963
964 err := i.Commit(c.repo)
965 if err != nil {
966 return nil, err
967 }
968
969 if _, has := c.identities[i.Id()]; has {
970 return nil, fmt.Errorf("identity %s already exist in the cache", i.Id())
971 }
972
973 cached := NewIdentityCache(c, i)
974 c.identities[i.Id()] = cached
975
976 // force the write of the excerpt
977 err = c.identityUpdated(i.Id())
978 if err != nil {
979 return nil, err
980 }
981
982 return cached, nil
983}