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// ResolveBug retrieve a bug matching the exact given id
382func (c *RepoCache) ResolveBug(id entity.Id) (*BugCache, error) {
383	cached, ok := c.bugs[id]
384	if ok {
385		return cached, nil
386	}
387
388	b, err := bug.ReadLocalBug(c.repo, id)
389	if err != nil {
390		return nil, err
391	}
392
393	cached = NewBugCache(c, b)
394	c.bugs[id] = cached
395
396	return cached, nil
397}
398
399// ResolveBugExcerpt retrieve a BugExcerpt matching the exact given id
400func (c *RepoCache) ResolveBugExcerpt(id entity.Id) (*BugExcerpt, error) {
401	e, ok := c.bugExcerpts[id]
402	if !ok {
403		return nil, bug.ErrBugNotExist
404	}
405
406	return e, nil
407}
408
409// ResolveBugPrefix retrieve a bug matching an id prefix. It fails if multiple
410// bugs match.
411func (c *RepoCache) ResolveBugPrefix(prefix string) (*BugCache, error) {
412	// preallocate but empty
413	matching := make([]entity.Id, 0, 5)
414
415	for id := range c.bugExcerpts {
416		if id.HasPrefix(prefix) {
417			matching = append(matching, id)
418		}
419	}
420
421	if len(matching) > 1 {
422		return nil, bug.NewErrMultipleMatchBug(matching)
423	}
424
425	if len(matching) == 0 {
426		return nil, bug.ErrBugNotExist
427	}
428
429	return c.ResolveBug(matching[0])
430}
431
432// ResolveBugCreateMetadata retrieve a bug that has the exact given metadata on
433// its Create operation, that is, the first operation. It fails if multiple bugs
434// match.
435func (c *RepoCache) ResolveBugCreateMetadata(key string, value string) (*BugCache, error) {
436	// preallocate but empty
437	matching := make([]entity.Id, 0, 5)
438
439	for id, excerpt := range c.bugExcerpts {
440		if excerpt.CreateMetadata[key] == value {
441			matching = append(matching, id)
442		}
443	}
444
445	if len(matching) > 1 {
446		return nil, bug.NewErrMultipleMatchBug(matching)
447	}
448
449	if len(matching) == 0 {
450		return nil, bug.ErrBugNotExist
451	}
452
453	return c.ResolveBug(matching[0])
454}
455
456// QueryBugs return the id of all Bug matching the given Query
457func (c *RepoCache) QueryBugs(query *Query) []entity.Id {
458	if query == nil {
459		return c.AllBugsIds()
460	}
461
462	var filtered []*BugExcerpt
463
464	for _, excerpt := range c.bugExcerpts {
465		if query.Match(c, excerpt) {
466			filtered = append(filtered, excerpt)
467		}
468	}
469
470	var sorter sort.Interface
471
472	switch query.OrderBy {
473	case OrderById:
474		sorter = BugsById(filtered)
475	case OrderByCreation:
476		sorter = BugsByCreationTime(filtered)
477	case OrderByEdit:
478		sorter = BugsByEditTime(filtered)
479	default:
480		panic("missing sort type")
481	}
482
483	if query.OrderDirection == OrderDescending {
484		sorter = sort.Reverse(sorter)
485	}
486
487	sort.Sort(sorter)
488
489	result := make([]entity.Id, len(filtered))
490
491	for i, val := range filtered {
492		result[i] = val.Id
493	}
494
495	return result
496}
497
498// AllBugsIds return all known bug ids
499func (c *RepoCache) AllBugsIds() []entity.Id {
500	result := make([]entity.Id, len(c.bugExcerpts))
501
502	i := 0
503	for _, excerpt := range c.bugExcerpts {
504		result[i] = excerpt.Id
505		i++
506	}
507
508	return result
509}
510
511// ValidLabels list valid labels
512//
513// Note: in the future, a proper label policy could be implemented where valid
514// labels are defined in a configuration file. Until that, the default behavior
515// is to return the list of labels already used.
516func (c *RepoCache) ValidLabels() []bug.Label {
517	set := map[bug.Label]interface{}{}
518
519	for _, excerpt := range c.bugExcerpts {
520		for _, l := range excerpt.Labels {
521			set[l] = nil
522		}
523	}
524
525	result := make([]bug.Label, len(set))
526
527	i := 0
528	for l := range set {
529		result[i] = l
530		i++
531	}
532
533	// Sort
534	sort.Slice(result, func(i, j int) bool {
535		return string(result[i]) < string(result[j])
536	})
537
538	return result
539}
540
541// NewBug create a new bug
542// The new bug is written in the repository (commit)
543func (c *RepoCache) NewBug(title string, message string) (*BugCache, *bug.CreateOperation, error) {
544	return c.NewBugWithFiles(title, message, nil)
545}
546
547// NewBugWithFiles create a new bug with attached files for the message
548// The new bug is written in the repository (commit)
549func (c *RepoCache) NewBugWithFiles(title string, message string, files []git.Hash) (*BugCache, *bug.CreateOperation, error) {
550	author, err := c.GetUserIdentity()
551	if err != nil {
552		return nil, nil, err
553	}
554
555	return c.NewBugRaw(author, time.Now().Unix(), title, message, files, nil)
556}
557
558// NewBugWithFilesMeta create a new bug with attached files for the message, as
559// well as metadata for the Create operation.
560// The new bug is written in the repository (commit)
561func (c *RepoCache) NewBugRaw(author *IdentityCache, unixTime int64, title string, message string, files []git.Hash, metadata map[string]string) (*BugCache, *bug.CreateOperation, error) {
562	b, op, err := bug.CreateWithFiles(author.Identity, unixTime, title, message, files)
563	if err != nil {
564		return nil, nil, err
565	}
566
567	for key, value := range metadata {
568		op.SetMetadata(key, value)
569	}
570
571	err = b.Commit(c.repo)
572	if err != nil {
573		return nil, nil, err
574	}
575
576	if _, has := c.bugs[b.Id()]; has {
577		return nil, nil, fmt.Errorf("bug %s already exist in the cache", b.Id())
578	}
579
580	cached := NewBugCache(c, b)
581	c.bugs[b.Id()] = cached
582
583	// force the write of the excerpt
584	err = c.bugUpdated(b.Id())
585	if err != nil {
586		return nil, nil, err
587	}
588
589	return cached, op, nil
590}
591
592// Fetch retrieve updates from a remote
593// This does not change the local bugs or identities state
594func (c *RepoCache) Fetch(remote string) (string, error) {
595	stdout1, err := identity.Fetch(c.repo, remote)
596	if err != nil {
597		return stdout1, err
598	}
599
600	stdout2, err := bug.Fetch(c.repo, remote)
601	if err != nil {
602		return stdout2, err
603	}
604
605	return stdout1 + stdout2, nil
606}
607
608// MergeAll will merge all the available remote bug and identities
609func (c *RepoCache) MergeAll(remote string) <-chan entity.MergeResult {
610	out := make(chan entity.MergeResult)
611
612	// Intercept merge results to update the cache properly
613	go func() {
614		defer close(out)
615
616		results := identity.MergeAll(c.repo, remote)
617		for result := range results {
618			out <- result
619
620			if result.Err != nil {
621				continue
622			}
623
624			switch result.Status {
625			case entity.MergeStatusNew, entity.MergeStatusUpdated:
626				i := result.Entity.(*identity.Identity)
627				c.identitiesExcerpts[result.Id] = NewIdentityExcerpt(i)
628			}
629		}
630
631		results = bug.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				b := result.Entity.(*bug.Bug)
642				snap := b.Compile()
643				c.bugExcerpts[result.Id] = NewBugExcerpt(b, &snap)
644			}
645		}
646
647		err := c.write()
648
649		// No easy way out here ..
650		if err != nil {
651			panic(err)
652		}
653	}()
654
655	return out
656}
657
658// Push update a remote with the local changes
659func (c *RepoCache) Push(remote string) (string, error) {
660	stdout1, err := identity.Push(c.repo, remote)
661	if err != nil {
662		return stdout1, err
663	}
664
665	stdout2, err := bug.Push(c.repo, remote)
666	if err != nil {
667		return stdout2, err
668	}
669
670	return stdout1 + stdout2, nil
671}
672
673// Pull will do a Fetch + MergeAll
674// This function will return an error if a merge fail
675func (c *RepoCache) Pull(remote string) error {
676	_, err := c.Fetch(remote)
677	if err != nil {
678		return err
679	}
680
681	for merge := range c.MergeAll(remote) {
682		if merge.Err != nil {
683			return merge.Err
684		}
685		if merge.Status == entity.MergeStatusInvalid {
686			return errors.Errorf("merge failure: %s", merge.Reason)
687		}
688	}
689
690	return nil
691}
692
693func repoLockFilePath(repo repository.Repo) string {
694	return path.Join(repo.GetPath(), "git-bug", lockfile)
695}
696
697// repoIsAvailable check is the given repository is locked by a Cache.
698// Note: this is a smart function that will cleanup the lock file if the
699// corresponding process is not there anymore.
700// If no error is returned, the repo is free to edit.
701func repoIsAvailable(repo repository.Repo) error {
702	lockPath := repoLockFilePath(repo)
703
704	// Todo: this leave way for a racey access to the repo between the test
705	// if the file exist and the actual write. It's probably not a problem in
706	// practice because using a repository will be done from user interaction
707	// or in a context where a single instance of git-bug is already guaranteed
708	// (say, a server with the web UI running). But still, that might be nice to
709	// have a mutex or something to guard that.
710
711	// Todo: this will fail if somehow the filesystem is shared with another
712	// computer. Should add a configuration that prevent the cleaning of the
713	// lock file
714
715	f, err := os.Open(lockPath)
716
717	if err != nil && !os.IsNotExist(err) {
718		return err
719	}
720
721	if err == nil {
722		// lock file already exist
723		buf, err := ioutil.ReadAll(io.LimitReader(f, 10))
724		if err != nil {
725			return err
726		}
727		if len(buf) == 10 {
728			return fmt.Errorf("the lock file should be < 10 bytes")
729		}
730
731		pid, err := strconv.Atoi(string(buf))
732		if err != nil {
733			return err
734		}
735
736		if process.IsRunning(pid) {
737			return fmt.Errorf("the repository you want to access is already locked by the process pid %d", pid)
738		}
739
740		// The lock file is just laying there after a crash, clean it
741
742		fmt.Println("A lock file is present but the corresponding process is not, removing it.")
743		err = f.Close()
744		if err != nil {
745			return err
746		}
747
748		err = os.Remove(lockPath)
749		if err != nil {
750			return err
751		}
752	}
753
754	return nil
755}
756
757// ResolveIdentity retrieve an identity matching the exact given id
758func (c *RepoCache) ResolveIdentity(id entity.Id) (*IdentityCache, error) {
759	cached, ok := c.identities[id]
760	if ok {
761		return cached, nil
762	}
763
764	i, err := identity.ReadLocal(c.repo, id)
765	if err != nil {
766		return nil, err
767	}
768
769	cached = NewIdentityCache(c, i)
770	c.identities[id] = cached
771
772	return cached, nil
773}
774
775// ResolveIdentityExcerpt retrieve a IdentityExcerpt matching the exact given id
776func (c *RepoCache) ResolveIdentityExcerpt(id entity.Id) (*IdentityExcerpt, error) {
777	e, ok := c.identitiesExcerpts[id]
778	if !ok {
779		return nil, identity.ErrIdentityNotExist
780	}
781
782	return e, nil
783}
784
785// ResolveIdentityPrefix retrieve an Identity matching an id prefix.
786// It fails if multiple identities match.
787func (c *RepoCache) ResolveIdentityPrefix(prefix string) (*IdentityCache, error) {
788	// preallocate but empty
789	matching := make([]entity.Id, 0, 5)
790
791	for id := range c.identitiesExcerpts {
792		if id.HasPrefix(prefix) {
793			matching = append(matching, id)
794		}
795	}
796
797	if len(matching) > 1 {
798		return nil, identity.NewErrMultipleMatch(matching)
799	}
800
801	if len(matching) == 0 {
802		return nil, identity.ErrIdentityNotExist
803	}
804
805	return c.ResolveIdentity(matching[0])
806}
807
808// ResolveIdentityImmutableMetadata retrieve an Identity that has the exact given metadata on
809// one of it's version. If multiple version have the same key, the first defined take precedence.
810func (c *RepoCache) ResolveIdentityImmutableMetadata(key string, value string) (*IdentityCache, error) {
811	// preallocate but empty
812	matching := make([]entity.Id, 0, 5)
813
814	for id, i := range c.identitiesExcerpts {
815		if i.ImmutableMetadata[key] == value {
816			matching = append(matching, id)
817		}
818	}
819
820	if len(matching) > 1 {
821		return nil, identity.NewErrMultipleMatch(matching)
822	}
823
824	if len(matching) == 0 {
825		return nil, identity.ErrIdentityNotExist
826	}
827
828	return c.ResolveIdentity(matching[0])
829}
830
831// AllIdentityIds return all known identity ids
832func (c *RepoCache) AllIdentityIds() []entity.Id {
833	result := make([]entity.Id, len(c.identitiesExcerpts))
834
835	i := 0
836	for _, excerpt := range c.identitiesExcerpts {
837		result[i] = excerpt.Id
838		i++
839	}
840
841	return result
842}
843
844func (c *RepoCache) SetUserIdentity(i *IdentityCache) error {
845	err := identity.SetUserIdentity(c.repo, i.Identity)
846	if err != nil {
847		return err
848	}
849
850	// Make sure that everything is fine
851	if _, ok := c.identities[i.Id()]; !ok {
852		panic("SetUserIdentity while the identity is not from the cache, something is wrong")
853	}
854
855	c.userIdentityId = i.Id()
856
857	return nil
858}
859
860func (c *RepoCache) GetUserIdentity() (*IdentityCache, error) {
861	if c.userIdentityId != "" {
862		i, ok := c.identities[c.userIdentityId]
863		if ok {
864			return i, nil
865		}
866	}
867
868	i, err := identity.GetUserIdentity(c.repo)
869	if err != nil {
870		return nil, err
871	}
872
873	cached := NewIdentityCache(c, i)
874	c.identities[i.Id()] = cached
875	c.userIdentityId = i.Id()
876
877	return cached, nil
878}
879
880func (c *RepoCache) IsUserIdentitySet() (bool, error) {
881	return identity.IsUserIdentitySet(c.repo)
882}
883
884// NewIdentity create a new identity
885// The new identity is written in the repository (commit)
886func (c *RepoCache) NewIdentity(name string, email string) (*IdentityCache, error) {
887	return c.NewIdentityRaw(name, email, "", "", nil)
888}
889
890// NewIdentityFull create a new identity
891// The new identity is written in the repository (commit)
892func (c *RepoCache) NewIdentityFull(name string, email string, login string, avatarUrl string) (*IdentityCache, error) {
893	return c.NewIdentityRaw(name, email, login, avatarUrl, nil)
894}
895
896func (c *RepoCache) NewIdentityRaw(name string, email string, login string, avatarUrl string, metadata map[string]string) (*IdentityCache, error) {
897	i := identity.NewIdentityFull(name, email, login, avatarUrl)
898
899	for key, value := range metadata {
900		i.SetMetadata(key, value)
901	}
902
903	err := i.Commit(c.repo)
904	if err != nil {
905		return nil, err
906	}
907
908	if _, has := c.identities[i.Id()]; has {
909		return nil, fmt.Errorf("identity %s already exist in the cache", i.Id())
910	}
911
912	cached := NewIdentityCache(c, i)
913	c.identities[i.Id()] = cached
914
915	// force the write of the excerpt
916	err = c.identityUpdated(i.Id())
917	if err != nil {
918		return nil, err
919	}
920
921	return cached, nil
922}