Implement cache migrations

This commit is contained in:
2024-12-31 17:45:45 -05:00
parent 70027a9880
commit 30d86d72ed
5 changed files with 101 additions and 8 deletions

View File

@ -14,6 +14,8 @@ import (
"gitea.libretechconsulting.com/rmcguire/git-project-manager/internal/remotes/projects"
)
const cacheVersion = "v0.1.0"
type Cache struct {
Projects []*projects.Project
Aliases []*ProjectAlias
@ -27,6 +29,7 @@ type Cache struct {
file string
log *pterm.Logger
path string
CacheVersion string
}
type CacheOpts struct {
@ -118,6 +121,11 @@ func (c *Cache) Read() error {
d := yaml.NewDecoder(file)
d.Decode(c)
// Perform migrations
if err := c.doMigrations(); err != nil {
c.log.Error("Failed to run cache migrations", c.log.Args("error", err))
}
c.readFromFile = true
return nil
}

57
internal/cache/cache_migrations.go vendored Normal file
View File

@ -0,0 +1,57 @@
package cache
import (
"errors"
"fmt"
"golang.org/x/mod/semver"
)
type migrationFunc func(c *Cache) error
// Registry of migrations by version
var migrations = map[string]map[string]migrationFunc{
"v0.1.0": {
"Make Aliases Unique": v010_aliases,
},
}
// Performs any required updates based on version
// of cache read from disk.
// Does not check to ensure migrations were successful,
// only checks if a version has been achieved
func (c *Cache) DoMigrations() error {
c.lock.Lock()
defer c.lock.Unlock()
return c.doMigrations()
}
func (c *Cache) doMigrations() error {
var errs error
for version, migrationFuncs := range migrations {
if semver.Compare(c.CacheVersion, version) < 0 {
for name, migration := range migrationFuncs {
err := migration(c)
if err != nil {
errs = errors.Join(
errs,
fmt.Errorf("%s - %s: %w", version, name, err),
)
}
}
// We've reached a cache version, update the CacheVersion
// and write to disk
if errs == nil {
c.CacheVersion = version
c.write()
}
}
}
return errs
}
func v010_aliases(c *Cache) error {
return errors.New("unimplemented migration")
}