multi_repo_cache.go

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