1package cache
 2
 3import (
 4	"fmt"
 5
 6	"github.com/MichaelMure/git-bug/repository"
 7)
 8
 9const lockfile = "lock"
10const defaultRepoName = "__default"
11
12// MultiRepoCache is the root cache, holding multiple RepoCache.
13type MultiRepoCache struct {
14	repos map[string]*RepoCache
15}
16
17func NewMultiRepoCache() *MultiRepoCache {
18	return &MultiRepoCache{
19		repos: make(map[string]*RepoCache),
20	}
21}
22
23// RegisterRepository register a named repository. Use this for multi-repo setup
24func (c *MultiRepoCache) RegisterRepository(repo repository.ClockedRepo, name string) (*RepoCache, chan BuildEvent) {
25	r, events := NewNamedRepoCache(repo, name)
26
27	// intercept events to make sure the cache building process succeed properly
28	out := make(chan BuildEvent)
29	go func() {
30		defer close(out)
31
32		for event := range events {
33			out <- event
34			if event.Err != nil {
35				return
36			}
37		}
38
39		c.repos[name] = r
40	}()
41
42	return r, out
43}
44
45// RegisterDefaultRepository register an unnamed repository. Use this for single-repo setup
46func (c *MultiRepoCache) RegisterDefaultRepository(repo repository.ClockedRepo) (*RepoCache, chan BuildEvent) {
47	return c.RegisterRepository(repo, defaultRepoName)
48}
49
50// DefaultRepo retrieve the default repository
51func (c *MultiRepoCache) DefaultRepo() (*RepoCache, error) {
52	if len(c.repos) != 1 {
53		return nil, fmt.Errorf("repository is not unique")
54	}
55
56	for _, r := range c.repos {
57		return r, nil
58	}
59
60	panic("unreachable")
61}
62
63// ResolveRepo retrieve a repository by name
64func (c *MultiRepoCache) ResolveRepo(name string) (*RepoCache, error) {
65	r, ok := c.repos[name]
66	if !ok {
67		return nil, fmt.Errorf("unknown repo")
68	}
69	return r, nil
70}
71
72// Close will do anything that is needed to close the cache properly
73func (c *MultiRepoCache) Close() error {
74	for _, cachedRepo := range c.repos {
75		err := cachedRepo.Close()
76		if err != nil {
77			return err
78		}
79	}
80	return nil
81}