2024-12-31 22:45:45 +00:00
|
|
|
package cache
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"golang.org/x/mod/semver"
|
2025-01-01 01:12:02 +00:00
|
|
|
|
|
|
|
"gitea.libretechconsulting.com/rmcguire/git-project-manager/internal/remotes/projects"
|
2024-12-31 22:45:45 +00:00
|
|
|
)
|
|
|
|
|
2025-01-01 01:12:02 +00:00
|
|
|
// Migrations funcs should return errors along with
|
|
|
|
// number of records updated
|
|
|
|
type migrationFunc func(c *Cache) (error, int)
|
2024-12-31 22:45:45 +00:00
|
|
|
|
|
|
|
// 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
|
2025-01-01 01:12:02 +00:00
|
|
|
func (c *Cache) DoMigrations() (error, int) {
|
2024-12-31 22:45:45 +00:00
|
|
|
c.lock.Lock()
|
|
|
|
defer c.lock.Unlock()
|
|
|
|
return c.doMigrations()
|
|
|
|
}
|
|
|
|
|
2025-01-01 01:12:02 +00:00
|
|
|
func (c *Cache) doMigrations() (error, int) {
|
2024-12-31 22:45:45 +00:00
|
|
|
var errs error
|
2025-01-01 01:12:02 +00:00
|
|
|
var migrated int
|
2024-12-31 22:45:45 +00:00
|
|
|
for version, migrationFuncs := range migrations {
|
2025-01-01 01:12:02 +00:00
|
|
|
var funcMigrated int
|
2024-12-31 22:45:45 +00:00
|
|
|
if semver.Compare(c.CacheVersion, version) < 0 {
|
|
|
|
for name, migration := range migrationFuncs {
|
2025-01-01 01:12:02 +00:00
|
|
|
err, numMigrated := migration(c)
|
2024-12-31 22:45:45 +00:00
|
|
|
if err != nil {
|
|
|
|
errs = errors.Join(
|
|
|
|
errs,
|
|
|
|
fmt.Errorf("%s - %s: %w", version, name, err),
|
|
|
|
)
|
|
|
|
}
|
2025-01-01 01:12:02 +00:00
|
|
|
funcMigrated += numMigrated
|
2024-12-31 22:45:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// We've reached a cache version, update the CacheVersion
|
|
|
|
// and write to disk
|
2025-01-01 01:12:02 +00:00
|
|
|
if errs == nil && funcMigrated > 0 {
|
2024-12-31 22:45:45 +00:00
|
|
|
c.CacheVersion = version
|
|
|
|
c.write()
|
|
|
|
}
|
|
|
|
}
|
2025-01-01 01:12:02 +00:00
|
|
|
migrated += funcMigrated
|
2024-12-31 22:45:45 +00:00
|
|
|
}
|
|
|
|
|
2025-01-01 01:12:02 +00:00
|
|
|
return errs, migrated
|
2024-12-31 22:45:45 +00:00
|
|
|
}
|
|
|
|
|
2025-01-01 01:12:02 +00:00
|
|
|
func v010_aliases(c *Cache) (error, int) {
|
|
|
|
var aliasesMigrated int
|
|
|
|
var errs error
|
|
|
|
for i, a := range c.Aliases {
|
|
|
|
if a.ID == "" {
|
|
|
|
if a.Remote == "" {
|
|
|
|
errs = errors.Join(errs,
|
|
|
|
fmt.Errorf("alias %s [id:%d] has no remote", a.Alias, a.ProjectID))
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
c.Aliases[i].ID = projects.MakeID(a.Remote, a.ProjectID)
|
|
|
|
aliasesMigrated++
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return errs, aliasesMigrated
|
2024-12-31 22:45:45 +00:00
|
|
|
}
|