brunel/buildqueue/queue.go
2024-08-10 14:06:31 +01:00

102 lines
2.1 KiB
Go

package buildqueue
import (
"brunel/domain"
"fmt"
"strings"
"errors"
"github.com/alphadose/haxmap"
)
var queue = haxmap.New[string, domain.BuildQueueItem]()
func getQueueKey(name string, buildType domain.BuildType) string {
return fmt.Sprintf("%s_%s", name, buildType)
}
func GetQueue() *haxmap.Map[string, domain.BuildQueueItem] {
return queue
}
func GetCounts() domain.BuildQueueCount {
count := domain.BuildQueueCount{
Queued: 0,
Building: 0,
}
queue.ForEach(func(k string, v domain.BuildQueueItem) bool {
if v.Status == domain.Queued {
count.Queued++
} else if v.Status == domain.Building {
count.Building++
}
return true
})
return count
}
func Add(buildItem domain.BuildQueueItem) error {
if strings.Contains(buildItem.BuildVersion, "+b") {
buildItem.BuildVersion = strings.Split(buildItem.BuildVersion, "+b")[0]
}
key := getQueueKey(buildItem.Source.Name, buildItem.Type)
if _, ok := queue.Get(key); ok {
return errors.New("package already in queue")
}
queue.Set(key, buildItem)
return nil
}
func Get(name string, buildType domain.BuildType) (domain.BuildQueueItem, bool) {
key := getQueueKey(name, buildType)
item, ok := queue.Get(key)
return item, ok
}
func Remove(name string, buildType domain.BuildType) error {
key := getQueueKey(name, buildType)
_, ok := queue.Get(key)
if !ok {
return errors.New("package not in queue")
}
queue.Del(key)
return nil
}
func Update(buildItem domain.BuildQueueItem) error {
key := getQueueKey(buildItem.Source.Name, buildItem.Type)
item, ok := queue.Get(key)
if !ok {
return errors.New("package not in queue")
}
if item.Status == domain.Building {
return errors.New("package is already building")
}
queue.Set(key, buildItem)
return nil
}
func ProcessNext() error {
var item *domain.BuildQueueItem
queue.ForEach(func(k string, v domain.BuildQueueItem) bool {
if v.Status == domain.Queued {
item = &v
return false
}
return true
})
if item == nil {
return nil
}
err := UpdateBuildFile(*item)
if err != nil {
return err
}
item.Status = domain.Building
err = Update(*item)
return err
}