Skip to content

Commit a90ff4a

Browse files
committed
pkg/cache: configurable backend preference
Signed-off-by: Joe Lanford <[email protected]>
1 parent 2e0d6a2 commit a90ff4a

File tree

1 file changed

+22
-6
lines changed

1 file changed

+22
-6
lines changed

pkg/cache/cache.go

+22-6
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,8 @@ type backend interface {
5151
}
5252

5353
type CacheOptions struct {
54-
Log *logrus.Entry
54+
Log *logrus.Entry
55+
BackendName string
5556
}
5657

5758
func WithLog(log *logrus.Entry) CacheOption {
@@ -60,6 +61,12 @@ func WithLog(log *logrus.Entry) CacheOption {
6061
}
6162
}
6263

64+
func WithBackendName(name string) CacheOption {
65+
return func(o *CacheOptions) {
66+
o.BackendName = name
67+
}
68+
}
69+
6370
type CacheOption func(*CacheOptions)
6471

6572
// New creates a new Cache. It chooses a cache implementation based
@@ -73,7 +80,7 @@ func New(cacheDir string, cacheOpts ...CacheOption) (Cache, error) {
7380
for _, opt := range cacheOpts {
7481
opt(opts)
7582
}
76-
cacheBackend, err := getDefaultBackend(cacheDir, opts.Log)
83+
cacheBackend, err := getBackend(cacheDir, opts.BackendName, opts.Log)
7784
if err != nil {
7885
return nil, err
7986
}
@@ -84,7 +91,7 @@ func New(cacheDir string, cacheOpts ...CacheOption) (Cache, error) {
8491
return &cache{backend: cacheBackend, log: opts.Log}, nil
8592
}
8693

87-
func getDefaultBackend(cacheDir string, log *logrus.Entry) (backend, error) {
94+
func getBackend(cacheDir string, backendName string, log *logrus.Entry) (backend, error) {
8895
entries, err := os.ReadDir(cacheDir)
8996
if err != nil && !errors.Is(err, os.ErrNotExist) {
9097
return nil, fmt.Errorf("detect cache format: read cache directory: %v", err)
@@ -96,12 +103,21 @@ func getDefaultBackend(cacheDir string, log *logrus.Entry) (backend, error) {
96103
}
97104

98105
if len(entries) == 0 {
99-
log.WithField("backend", backends[0].Name()).Info("cache directory is empty, using preferred backend")
100-
return backends[0], nil
106+
if backendName == "" {
107+
log.WithField("backend", backends[0].Name()).Info("cache directory is empty, using preferred backend")
108+
return backends[0], nil
109+
}
110+
for _, b := range backends {
111+
if b.Name() == backendName {
112+
log.WithField("backend", backendName).Info("using preferred backend")
113+
return b, nil
114+
}
115+
}
116+
return nil, fmt.Errorf("preferred backend %q not found", backendName)
101117
}
102118

103119
for _, backend := range backends {
104-
if backend.IsCachePresent() {
120+
if (backendName == "" || backend.Name() == backendName) && backend.IsCachePresent() {
105121
log.WithField("backend", backend.Name()).Info("found existing cache contents")
106122
return backend, nil
107123
}

0 commit comments

Comments
 (0)