package bulldozesynclabel import ( "fmt" "strconv" "strings" "github.com/google/go-github/v47/github" "edge-infra.dev/pkg/f8n/devinfra/jack/constants" "edge-infra.dev/pkg/f8n/devinfra/jack/plugin" ) func init() { plugin.RegisterStatusEventHandler(constants.PluginApprovedLabel, handleStatusEvent) } func handleStatusEvent(hp plugin.HandlerParams, se github.StatusEvent) { hp.Log.WithName(constants.PluginApprovedLabel) // check is the status event has a context that matches policybot if se.GetContext() != "mergeable: master" { return } hp.Log.Info("Running approved_label") hp.Log.Info("found a policybot status event") // get the pr number from the target url // maybe not the best way but simplest solution first // ex: "target_url": "https://policy-bot.edge-infra.dev/details/ncrvoyix-swt-retail/edge-infra/2392" prArr := strings.Split(se.GetTargetURL(), "/") // get the last index which should be the pr num prStr := prArr[len(prArr)-1] // convert it from string to int prNum, err := strconv.Atoi(prStr) if err != nil { hp.Log.Error(err, "Failed to get PR number") return } // get the pr pr, _, err := hp.Client.PullRequests().Get(hp.Ctx, hp.Org, hp.Repo, prNum) if err != nil { hp.Log.Error(err, "Failed to retrieve PR") return } // check if the issue already has the labels hasOK := hasApproved(pr.Labels) hasDoNotMerge := hasDoNotMerge(pr.Labels) // We don't want to sync drafts if pr.GetDraft() && hasOK { hp.Log.Info(fmt.Sprintf("PR #%d is a draft. Attempting to remove %s", prNum, constants.Approved)) removeSyncLabel(hp, prNum) return } // Don't sync PR's with do-not-merge label if hasDoNotMerge && hasOK { hp.Log.Info(fmt.Sprintf("Cannot sync while %s is present. Attempting to remove %s", constants.DoNotMerge, constants.Approved)) removeSyncLabel(hp, prNum) return } // check the state and call the appropriate func state := se.GetState() switch { case state == "success" && !hasOK: addLabel(hp, prNum) case (state == "pending" || state == "failure") && hasOK: removeSyncLabel(hp, prNum) } } func hasApproved(labels []*github.Label) bool { for _, label := range labels { if label.GetName() == constants.Approved { return true } } return false } func hasDoNotMerge(labels []*github.Label) bool { for _, label := range labels { if label.GetName() == constants.DoNotMerge { return true } } return false } func addLabel(hp plugin.HandlerParams, num int) { hp.Log.Info(fmt.Sprintf("adding %s", constants.Approved)) labels := []string{constants.Approved} _, _, err := hp.Client.Issues().AddLabelsToIssue(hp.Ctx, hp.Org, hp.Repo, num, labels) if err != nil { hp.Log.Error(err, fmt.Sprintf("Failed to add %s", constants.Approved)) } } func removeSyncLabel(hp plugin.HandlerParams, num int) { hp.Log.Info(fmt.Sprintf("removing %s", constants.Approved)) _, err := hp.Client.Issues().RemoveLabelForIssue(hp.Ctx, hp.Org, hp.Repo, num, constants.Approved) if err != nil { hp.Log.Error(err, fmt.Sprintf("Failed to remove %s", constants.Approved)) } }