-
Notifications
You must be signed in to change notification settings - Fork 34
/
code_cache.go
85 lines (78 loc) · 2.39 KB
/
code_cache.go
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
77
78
79
80
81
82
83
84
85
package pipeline
import (
"errors"
"github.com/kubespace/kubespace/pkg/model/types"
"gorm.io/gorm"
"time"
)
type PipelineCodeCacheManager struct {
db *gorm.DB
}
func NewPipelineCodeCacheManager(db *gorm.DB) *PipelineCodeCacheManager {
return &PipelineCodeCacheManager{
db: db,
}
}
func (r *PipelineCodeCacheManager) GetById(id uint) (*types.PipelineCodeCache, error) {
var cache types.PipelineCodeCache
if err := r.db.First(&cache, "id=?", id).Error; err != nil {
return nil, err
}
return &cache, nil
}
func (r *PipelineCodeCacheManager) GetByWorkspaceId(workspaceId uint) (*types.PipelineCodeCache, error) {
var cache types.PipelineCodeCache
if err := r.db.First(&cache, "workspace_id=?", workspaceId).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
return nil, err
}
return &cache, nil
}
// CreateOrUpdate 根据流水线是否有代码自动触发,对代码仓库进行分支缓存
func (r *PipelineCodeCacheManager) CreateOrUpdate(workspaceObj *types.PipelineWorkspace) error {
if workspaceObj.Type == types.WorkspaceTypeCustom {
return nil
}
workspaceId := workspaceObj.ID
var codeTriggersCnt int64
if err := r.db.Debug().Model(&types.PipelineTrigger{}).Where("pipeline_id in (?)",
r.db.Table("pipelines").Select("id").Where("workspace_id=?", workspaceId)).Count(
&codeTriggersCnt).Error; err != nil {
return err
}
codeCache, err := r.GetByWorkspaceId(workspaceId)
if err != nil {
return err
}
status := types.PipelineCodeCacheStatusClose
if codeTriggersCnt > 0 {
status = types.PipelineCodeCacheStatusOpen
}
// 有流水线代码更新触发配置,打开代码分支缓存
if codeCache == nil && status == types.PipelineCodeCacheStatusOpen {
codeCache = &types.PipelineCodeCache{
WorkspaceId: workspaceId,
Status: types.PipelineCodeCacheStatusOpen,
CreateTime: time.Now(),
UpdateTime: time.Now(),
}
if err = r.db.Omit("id").Create(codeCache).Error; err != nil {
return err
}
return nil
}
if codeCache != nil {
if err = r.db.Model(&types.PipelineCodeCache{}).Where("id=?", codeCache.ID).Updates(&types.PipelineCodeCache{
Status: status,
UpdateTime: time.Now(),
}).Error; err != nil {
return err
}
}
return nil
}
func (r *PipelineCodeCacheManager) Update(id uint, cache *types.PipelineCodeCache) error {
return r.db.Model(types.PipelineCodeCache{}).Where("id=?", id).Updates(cache).Error
}