aboutsummaryrefslogtreecommitdiffstats
path: root/cache/multi_repo_cache.go
blob: 007737ad2e18f6a59e7c0640a4a5d6a7e13d45ef (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package cache

import (
	"fmt"

	"github.com/MichaelMure/git-bug/repository"
)

const lockfile = "lock"
const defaultRepoName = "__default"

// MultiRepoCache is the root cache, holding multiple RepoCache.
type MultiRepoCache struct {
	repos map[string]*RepoCache
}

func NewMultiRepoCache() *MultiRepoCache {
	return &MultiRepoCache{
		repos: make(map[string]*RepoCache),
	}
}

// RegisterRepository register a named repository. Use this for multi-repo setup
func (c *MultiRepoCache) RegisterRepository(name string, repo repository.ClockedRepo) (*RepoCache, chan BuildEvent, error) {
	r, events, err := NewNamedRepoCache(repo, name)
	if err != nil {
		return nil, nil, err
	}

	c.repos[name] = r
	return r, events, nil
}

// RegisterDefaultRepository register an unnamed repository. Use this for mono-repo setup
func (c *MultiRepoCache) RegisterDefaultRepository(repo repository.ClockedRepo) (*RepoCache, chan BuildEvent, error) {
	r, events, err := NewRepoCache(repo)
	if err != nil {
		return nil, nil, err
	}

	c.repos[defaultRepoName] = r
	return r, events, nil
}

// DefaultRepo retrieve the default repository
func (c *MultiRepoCache) DefaultRepo() (*RepoCache, error) {
	if len(c.repos) != 1 {
		return nil, fmt.Errorf("repository is not unique")
	}

	for _, r := range c.repos {
		return r, nil
	}

	panic("unreachable")
}

// ResolveRepo retrieve a repository by name
func (c *MultiRepoCache) ResolveRepo(name string) (*RepoCache, error) {
	r, ok := c.repos[name]
	if !ok {
		return nil, fmt.Errorf("unknown repo")
	}
	return r, nil
}

// Close will do anything that is needed to close the cache properly
func (c *MultiRepoCache) Close() error {
	for _, cachedRepo := range c.repos {
		err := cachedRepo.Close()
		if err != nil {
			return err
		}
	}
	return nil
}