2023-12-28 16:49:28 +08:00
|
|
|
package modelrepo
|
2023-12-27 15:59:46 +08:00
|
|
|
|
2023-12-28 14:35:11 +08:00
|
|
|
import "sync"
|
2023-12-27 15:59:46 +08:00
|
|
|
|
2023-12-28 14:35:11 +08:00
|
|
|
// Repo管理
|
|
|
|
type repoManager struct {
|
2023-12-28 16:49:28 +08:00
|
|
|
repoMap map[string]Repo
|
2023-12-28 14:35:11 +08:00
|
|
|
lock sync.Mutex
|
|
|
|
}
|
2023-12-27 15:59:46 +08:00
|
|
|
|
2023-12-28 14:35:11 +08:00
|
|
|
var defaultManager = &repoManager{
|
2023-12-28 16:49:28 +08:00
|
|
|
repoMap: make(map[string]Repo),
|
2023-12-28 14:35:11 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// 获取Repo
|
2023-12-28 16:49:28 +08:00
|
|
|
func GetRepo(id string) Repo {
|
2023-12-28 14:35:11 +08:00
|
|
|
manager := defaultManager
|
|
|
|
manager.lock.Lock()
|
|
|
|
defer manager.lock.Unlock()
|
|
|
|
r, ok := manager.repoMap[id]
|
|
|
|
if !ok {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return r
|
|
|
|
}
|
|
|
|
|
|
|
|
// 保存Repo
|
2023-12-28 16:49:28 +08:00
|
|
|
func SaveRepo(r Repo) {
|
2023-12-28 14:35:11 +08:00
|
|
|
manager := defaultManager
|
|
|
|
manager.lock.Lock()
|
|
|
|
defer manager.lock.Unlock()
|
|
|
|
manager.repoMap[r.Id()] = r
|
|
|
|
}
|
|
|
|
|
|
|
|
// 移除Repo
|
|
|
|
func RemoveRepo(id string) {
|
|
|
|
manager := defaultManager
|
|
|
|
manager.lock.Lock()
|
|
|
|
defer manager.lock.Unlock()
|
|
|
|
delete(manager.repoMap, id)
|
|
|
|
}
|
|
|
|
|
|
|
|
// 获取或构建Repo,若存在则返回已存在的,若不存在则构建保存并返回
|
2023-12-28 16:49:28 +08:00
|
|
|
func GetOrBuildRepo(id string, builder func() (Repo, error)) (Repo, error) {
|
2023-12-28 14:35:11 +08:00
|
|
|
r := GetRepo(id)
|
|
|
|
if r == nil {
|
|
|
|
// 构建模型Repo
|
|
|
|
r, err := builder()
|
|
|
|
// 构建出错直接返回
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
// 保存
|
|
|
|
SaveRepo(r)
|
|
|
|
}
|
|
|
|
return r, nil
|
|
|
|
}
|