autogits/prjgit-updater/main.go
2024-08-28 17:20:09 +02:00

170 lines
5.4 KiB
Go

package main
import (
"flag"
"fmt"
"log"
"math/rand"
"os"
"path/filepath"
"slices"
"sync"
"time"
"src.opensuse.org/autogits/common"
)
type ConfigRepos struct {
prjgit string
branch string // "" == default branch
}
var configuredRepos map[string]ConfigRepos
func processRepositoryAction(h *common.RequestHandler) error {
action := h.Request.Data.(*common.RepositoryWebhookEvent)
if action.Repository.Name == common.DefaultGitPrj {
h.StdLogger.Printf("repository event %s for %s. Ignoring\n", common.DefaultGitPrj, action.Action)
return nil
}
h.CreateRepositoryIfNotExist(*action.Organization, h.PrjGit)
h.Git.GitExec("", "clone", "--depth", "1", action.PrjGit, h.PrjGit)
switch action.Action {
case "created":
h.Git.GitExec(common.DefaultGitPrj, "submodule", "--quiet", "add", "--depth", "1", action.Repository.Clone_Url)
h.Git.GitExec(common.DefaultGitPrj, "commit", "-m", "Automatic package inclusion")
h.Git.GitExec(common.DefaultGitPrj, "push")
case "deleted":
if stat, err := os.Stat(filepath.Join(h.Git.GitPath, common.DefaultGitPrj, action.Repository.Name)); err != nil || !stat.IsDir() {
h.StdLogger.Printf("delete event for %s -- not in project. Ignoring\n", action.Repository.Name)
return nil
}
h.Git.GitExec(common.DefaultGitPrj, "rm", action.Repository.Name)
h.Git.GitExec(common.DefaultGitPrj, "commit", "-m", "Automatic package removal")
h.Git.GitExec(common.DefaultGitPrj, "push")
default:
return fmt.Errorf("%s: %s", "Unknown action type", action.Action)
}
return nil
}
func processPushAction(h *common.RequestHandler) error {
action := h.Request.Data.(*common.PushWebhookEvent)
if action.Repository.Name == common.DefaultGitPrj {
h.StdLogger.Printf("push to %s -- ignoringi\n", common.DefaultGitPrj)
return nil
}
h.Git.GitExec("", "clone", "--depth", "1", h.PrjGit, common.DefaultGitPrj)
if stat, err := os.Stat(filepath.Join(h.Git.GitPath, common.DefaultGitPrj, action.Repository.Name)); err != nil || !stat.IsDir() {
h.StdLogger.Printf("Pushed to package that is not part of the project. Ignoring. : %v\n", err)
return nil
}
h.Git.GitExec(common.DefaultGitPrj, "submodule", "update", "--init", "--depth", "1", "--checkout", action.Repository.Name)
id, _ := h.Git.GitBranchHead(filepath.Join(common.DefaultGitPrj, action.Repository.Name), action.Repository.Default_Branch)
for _, commitId := range action.Commits {
if commitId.Id == id {
h.Git.GitExec(filepath.Join(common.DefaultGitPrj, action.Repository.Name), "fetch", "--depth", "1", "origin", id)
h.Git.GitExec(filepath.Join(common.DefaultGitPrj, action.Repository.Name), "checkout", id)
h.Git.GitExec(common.DefaultGitPrj, "commit", "-a", "-m", "Automatic update via push")
h.Git.GitExec(common.DefaultGitPrj, "push")
return nil
}
}
h.StdLogger.Println("push of refs not on the main branch. ignoring.")
return nil
}
func verifyProjectState(org string, config ConfigRepos) error {
return nil
}
var checkOnStart bool
var checkInterval time.Duration
func consistencyCheckProcess(repos map[string]ConfigRepos) {
if checkOnStart {
var wg sync.WaitGroup
for org, conf := range repos {
wg.Add(1)
go func() {
defer wg.Done()
verifyProjectState(org, conf)
}()
}
wg.Wait()
log.Printf("== Startup consistency check done...")
}
for org, conf := range repos {
time.Sleep(checkInterval - checkInterval/2 + time.Duration(rand.Int63n(int64(checkInterval))))
log.Printf(" ++ starting verification, org: `%s`\n", org)
if err := verifyProjectState(org, conf); err != nil {
log.Printf(" *** verification failed, org: `%s`, err: %#v\n", org, err)
}
log.Printf(" ++ verification complete, org: `%s`\n", org)
}
}
var debugMode bool
func main() {
workflowConfig := flag.String("config", "", "Repository and workflow definition file")
rabbitUrl := flag.String("url", "amqps://rabbit.opensuse.org", "URL for RabbitMQ instance")
flag.BoolVar(&debugMode, "debug", false, "Extra debugging information")
flag.BoolVar(&checkOnStart, "check-on-start", false, "Check all repositories for consistency on start, without delays")
checkIntervalHours := flag.Float64("check-interval", 5, "Check interval (+-random delay) for repositories for consitency, in hours")
flag.Parse()
checkInterval = time.Duration(*checkIntervalHours) * time.Hour
if len(*workflowConfig) == 0 {
log.Fatalln("No configuratio file specified. Aborting")
}
configs, err := common.ReadWorkflowConfigsFile(*workflowConfig)
if err != nil {
log.Fatalf("Error reading config file. err: %v", err)
}
configuredRepos = make(map[string]ConfigRepos)
orgs := make([]string, 0, 10)
for _, c := range configs {
if slices.Contains(c.Workflows, "push") {
if debugMode {
log.Printf(" + adding org: '%s', branch: '%s', prjgit: '%s'\n", c.Organization, c.Branch, c.GitProjectName)
}
configuredRepos[c.Organization] = ConfigRepos{
prjgit: c.GitProjectName,
branch: c.Branch,
}
orgs = append(orgs, c.Organization)
}
}
var defs common.ListenDefinitions
defs.GitAuthor = "GiteaBot - AutoDevel"
defs.RabbitURL = *rabbitUrl
defs.Handlers = make(map[string]common.RequestProcessor)
defs.Handlers[common.RequestType_Push] = processPushAction
defs.Handlers[common.RequestType_Repository] = processRepositoryAction
if err := common.RequireGiteaSecretToken(); err != nil {
log.Fatal(err)
}
if err := common.RequireRabbitSecrets(); err != nil {
log.Fatal(err)
}
log.Fatal(common.ProcessRabbitMQEvents(defs, orgs))
}