Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
21a41fb
pre-factor check-release-pr command
tommartensen Oct 29, 2026
221f9c1
prepare check-release-pr command to handle PR number as input, but loop
tommartensen Oct 29, 2026
387b58b
list pull requests if no ID was provided, add dry-run mode
tommartensen Oct 30, 2026
4508024
paginate reviews
tommartensen Oct 30, 2026
e138460
improve unrecoverable error handling
tommartensen Nov 3, 2026
15e40ef
default --dry-run to true for check-release-pr
tommartensen Nov 3, 2026
a6c8e32
skip draft PRs, reject forks, and prefix stderr messages with PR ref
tommartensen Nov 3, 2026
ecc0f14
fix: disallow --output flag for the command
tommartensen Nov 4, 2026
df3867b
fix: allow setting reviewer-login, because github-actions[bot] cannot…
tommartensen Nov 5, 2026
00edae4
set and filter reviews by a review marker
tommartensen Nov 5, 2026
ff3b2b0
fix tests
tommartensen Nov 5, 2026
6b64951
fix: filter out draft PRs in ListOpenReleasePRs
tommartensen Nov 9, 2026
bb703e7
log skipped draft PRs, skip draft PRs also in single PR mode
tommartensen Nov 9, 2026
29db5bb
add e2e tests for draft PRs
tommartensen Nov 9, 2026
ed7ff4c
Update cmd/relacs/github/check_release_pr.go
tommartensen Nov 9, 2026
0637a8f
add e2e tests for draft PRs
tommartensen Nov 9, 2026
44582cc
fix: check release branch before fork to prevent invalid reviews
tommartensen Nov 9, 2026
1bf8c69
fix: distinguish infra errors from missing fixVersion in validation
tommartensen Nov 9, 2026
3fa8cdc
fix: distinguish Jira 4xx (validation) from 5xx (operational) errors
tommartensen Nov 9, 2026
ad12e67
remove superfluous tests for check-release-pr
tommartensen Nov 9, 2026
1e2ed1c
link JIRA for future task ROX-35283
tommartensen Nov 12, 2026
987c871
test: add fork PR targeting non-release branch test
tommartensen Nov 12, 2026
b9bfb3f
remove accidentally committed scratch files from tracking
tommartensen Nov 12, 2026
a8a609f
fix: address review feedback for check-release-pr
tommartensen Nov 12, 2026
a9e235c
Apply batched suggestions from code review
tommartensen Nov 12, 2026
c4a7c8e
use single ReleaseBranchPattern instead of duplicate regexes
tommartensen Dec 1, 2026
3b15b9f
simplify GetLastReviewForLogin to rely on chronological review order
tommartensen Dec 1, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
272 changes: 217 additions & 55 deletions cmd/relacs/github/check_release_pr.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
package github

import (
"context"
"errors"
"fmt"
"net/http"
"strconv"
"strings"

gogithub "github.com/google/go-github/v79/github"
"github.com/spf13/cobra"
"github.com/stackrox/relacs/cmd/relacs/common"
"github.com/stackrox/relacs/pkg/client"
"github.com/stackrox/relacs/pkg/client/jira"
"github.com/stackrox/relacs/pkg/config"
"github.com/stackrox/relacs/pkg/github"
)

Expand All @@ -17,27 +23,40 @@ const (
resolutionDone = "Done"
statusClosed = "Closed"
statusReleasePending = "Release Pending"

reviewMarker = "<!-- relacs:check-release-pr -->"
)

type ReleasePRCheckOutput struct {
PullRequestURL string `json:"pull-request-url" yaml:"pull-request-url"`
Valid bool `json:"valid"`
Errors []string `json:"errors"`
Org string `json:"org" yaml:"org"`
Repo string `json:"repo" yaml:"repo"`
PullRequestNumber int `json:"pull-request-number" yaml:"pull-request-number"`
Valid bool `json:"valid"`
Errors []string `json:"errors"`
SkipReviewReason string `json:"skip-review-reason"`
}

func (o ReleasePRCheckOutput) String() string {
if o.Valid {
return fmt.Sprintf("The PR '%s' satisfies the release branch PR criteria.", o.PullRequestURL)
return fmt.Sprintf("The PR %s/%s#%d satisfies the release branch PR criteria.", o.Org, o.Repo, o.PullRequestNumber)
}

var buf strings.Builder
fmt.Fprintf(&buf, "The PR '%s' does not satisfy the release branch PR criteria:\n", o.PullRequestURL)
fmt.Fprintf(&buf, "The PR %s/%s#%d does not satisfy the release branch PR criteria:\n", o.Org, o.Repo, o.PullRequestNumber)
for i, err := range o.Errors {
fmt.Fprintf(&buf, " %d. %s\n", i+1, err)
}

if o.SkipReviewReason != "" {
fmt.Fprintf(&buf, "Skipped adding or updating review to this PR because %s.\n", o.SkipReviewReason)
}
return buf.String()
}

func prRef(org, repo string, number int) string {
return fmt.Sprintf("%s/%s#%d", org, repo, number)
}

// checkReleasePRCmd represents the check-release-pr command
var checkReleasePRCmd = &cobra.Command{
Use: "check-release-pr",
Expand All @@ -47,62 +66,160 @@ var checkReleasePRCmd = &cobra.Command{
}

func init() {
checkReleasePRCmd.Flags().String("pull-request", "", "Pull Request URL to check (required)")
checkReleasePRCmd.Flags().String("org", config.GitHubOrganization, "GitHub organization to use")
checkReleasePRCmd.Flags().String("repo", config.MainGitHubRepository, "GitHub repository to use")
checkReleasePRCmd.Flags().Int("pull-request", 0, "Pull Request number to check")
checkReleasePRCmd.Flags().Bool("dry-run", true, "Dry run mode, do not post comments to PRs")
checkReleasePRCmd.Flags().String("reviewer-login", "", "GitHub login to use for finding previous reviews (bypasses the /user API call, useful for GitHub App tokens)")

// We only allow text output in this command, so have override
// and hide the --output flag from the root command.
checkReleasePRCmd.Flags().StringP("output", "o", "text", "")
//nolint:errcheck
checkReleasePRCmd.MarkFlagRequired("pull-request")
checkReleasePRCmd.Flags().MarkHidden("output")
}

func runCheckReleasePRCommand(cmd *cobra.Command, args []string) error {
cmd.SilenceUsage = true
func runCheckReleasePRCommand(cmd *cobra.Command, _ []string) error {
if cmd.Flags().Changed("output") {
return fmt.Errorf("unknown flag: --output")
}

outputFormat, err := common.GetOutputFormat(cmd)
c, err := client.NewClient()
if err != nil {
return err
}

c, err := client.NewClient()
_, err = RunReleasePRCheck(cmd, c)
if err != nil {
return err
}
return nil
}

output, err := RunReleasePRCheck(cmd, args, c)
func RunReleasePRCheck(cmd *cobra.Command, c *client.Client) ([]ReleasePRCheckOutput, error) {
//nolint:errcheck
org, _ := cmd.Flags().GetString("org")
repo, _ := cmd.Flags().GetString("repo")

// Always format output (even on error) since it contains validation errors
formatErr := common.FormatOutput(outputFormat, output)
if formatErr != nil {
return formatErr
var pullRequestNumbers []int
if cmd.Flags().Changed("pull-request") {
pullRequestNumber, _ := cmd.Flags().GetInt("pull-request")
pullRequestNumbers = []int{pullRequestNumber}
} else {
var err error
pullRequestNumbers, err = github.ListOpenReleasePRs(cmd.Context(), c, org, repo)
if err != nil {
return nil, err
}
}

// If there was a validation error, we've already shown the errors
// in the structured output. Silence cobra's error message but still
// return an error to get exit code 1.
if err != nil {
cmd.SilenceErrors = true
return err
singlePRMode := cmd.Flags().Changed("pull-request")

anyValidationFailed := false
var checkOutput []ReleasePRCheckOutput
for _, prNumber := range pullRequestNumbers {
out, err := validatePullRequest(cmd, c, org, repo, prNumber)
if err != nil {
return nil, err
}

if out.SkipReviewReason == "the PR is a draft" {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if singlePRMode {
return nil, fmt.Errorf("PR %s/%s#%d is a draft", org, repo, prNumber)
}
//nolint:errcheck
fmt.Fprintf(cmd.ErrOrStderr(), "%s: skipping because %s\n", prRef(org, repo, prNumber), out.SkipReviewReason)
continue
}

checkOutput = append(checkOutput, out)
if !out.Valid {
anyValidationFailed = true
}

err = common.FormatOutput("text", out)
if err != nil {
return nil, err
}

if out.SkipReviewReason == "" {
dryRun, _ := cmd.Flags().GetBool("dry-run")
if !dryRun {
reviewerLogin, _ := cmd.Flags().GetString("reviewer-login")
err := postVerdictToPR(cmd.Context(), c, out, reviewerLogin)
if err != nil {
return nil, err

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we really want to stop the batch if one is failed?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In my mind, if posting the verdict to the PR fails, it's likely because the authentication failed or the reviewer isn't authorized to review PRs in this repo.

In any case, I believe this is a fatal error and the check should stop.

}
} else {
//nolint:errcheck
fmt.Fprintf(cmd.ErrOrStderr(), "%s: dry run mode, skipping posting comment to PR\n", prRef(org, repo, out.PullRequestNumber))
}
} else {
//nolint:errcheck
fmt.Fprintf(cmd.ErrOrStderr(), "%s: skipping review because %s\n", prRef(org, repo, out.PullRequestNumber), out.SkipReviewReason)
}
}

return nil
if anyValidationFailed {
return checkOutput, errors.New("one or more release branch PRs do not satisfy the criteria")
}

return checkOutput, nil
}

func RunReleasePRCheck(cmd *cobra.Command, args []string, c *client.Client) (any, error) {
ctx := cmd.Context()
//nolint:errcheck
pullRequest, _ := cmd.Flags().GetString("pull-request")
// validatePullRequest runs PR checks and returns the structured output including validation errors.
// It only returns an error if the validation cannot be performed.
// The validation result can be found in the Valid field of the output.
// The validation errors can be found in the Errors field of the output.
func validatePullRequest(cmd *cobra.Command, client *client.Client, org, repo string, pullRequestNumber int) (ReleasePRCheckOutput, error) {
out := ReleasePRCheckOutput{
PullRequestURL: pullRequest,
Valid: false,
Errors: []string{},
Org: org,
Repo: repo,
PullRequestNumber: pullRequestNumber,
Errors: []string{},
}

pr, err := github.GetPullRequestFromURL(ctx, c, pullRequest)
if pullRequestNumber <= 0 {
return out, fmt.Errorf("pull request number must be set and greater than 0")
}

pr, err := github.GetPullRequest(cmd.Context(), client, org, repo, pullRequestNumber)
if err != nil {
out.Errors = append(out.Errors, fmt.Sprintf("failed to get pull request: %v", err))
return out, fmt.Errorf("release branch PR check failed")
var ghErr *gogithub.ErrorResponse
if errors.As(err, &ghErr) && ghErr.Response != nil && ghErr.Response.StatusCode == http.StatusNotFound {
out.Errors = append(out.Errors, fmt.Sprintf("failed to get pull request: %v", err))
out.SkipReviewReason = "the PR could not be found"
return out, nil
}
return out, fmt.Errorf("failed to get pull request: %w", err)
}

if pr.GetDraft() {
out.SkipReviewReason = "the PR is a draft"
return out, nil
}

// Check if the PR targets a release branch (base is release-<major>.<minor>)
baseBranch := pr.GetBase().GetRef()
matches := github.ReleaseBranchPattern.FindStringSubmatch(baseBranch)
if matches == nil {
out.Errors = append(out.Errors, fmt.Sprintf("the PR does not target a valid release branch (expected release-<major>.<minor>): %s", baseBranch))
out.SkipReviewReason = "the check should not have run for this PR"
return out, nil
}
major, _ := strconv.Atoi(matches[1])
minor, _ := strconv.Atoi(matches[2])

// Reject PRs to release branches that are from forks.
if !strings.EqualFold(pr.GetHead().GetRepo().GetFullName(), fmt.Sprintf("%s/%s", org, repo)) {
out.Errors = append(out.Errors, "PRs to release branches cannot be forks. Instead, let your PR target the default branch of this repository and the team will backport it, if necessary.")
return out, nil
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

// Skip checks for PRs by red-hat-konflux[bot]
if pr.GetUser().GetLogin() == konfluxBotUsername {
//nolint:errcheck
fmt.Fprintf(cmd.ErrOrStderr(), "%s: skipping release PR checks for %s\n", prRef(org, repo, pullRequestNumber), konfluxBotUsername)
out.Valid = true
return out, nil
}
Expand All @@ -111,47 +228,46 @@ func RunReleasePRCheck(cmd *cobra.Command, args []string, c *client.Client) (any
prTitle := pr.GetTitle()
if pr.GetUser().GetLogin() == rhacsBotUsername && strings.HasPrefix(prTitle, "chore") {
//nolint:errcheck
fmt.Fprintln(cmd.ErrOrStderr(), "Warning: Skipping release PR checks for rhacs-bot PR with 'chore' prefix")
fmt.Fprintf(cmd.ErrOrStderr(), "%s: skipping release PR checks for rhacs-bot PR with 'chore' prefix\n", prRef(org, repo, pullRequestNumber))
out.Valid = true
return out, nil
}

// Check if the PR targets a release branch (base is release-<major>.<minor>)
baseBranch := pr.GetBase().GetRef()
matches := releaseBranchPattern.FindStringSubmatch(baseBranch)
if matches == nil {
out.Errors = append(out.Errors, fmt.Sprintf("the PR does not target a valid release branch (expected release-<major>.<minor>): %s", baseBranch))
return out, fmt.Errorf("release branch PR check failed")
}
major, _ := strconv.Atoi(matches[1])
minor, _ := strconv.Atoi(matches[2])

// Check if Jira client is configured
jiraClient := c.GetJira()
jiraClient := client.GetJira()
if jiraClient == nil {
out.Errors = append(out.Errors, "Jira client is not configured (JIRA_TOKEN environment variable is required)")
return out, fmt.Errorf("release branch PR check failed")
return out, fmt.Errorf("jira client is not configured (JIRA_TOKEN environment variable is required)")
}

expectedFixVersion, err := jiraClient.GetLowestUnreleasedFixVersion(major, minor)
if err != nil {
out.Errors = append(out.Errors, err.Error())
return out, fmt.Errorf("release branch PR check failed")
if errors.Is(err, jira.ErrNoFixVersion) {
out.Errors = append(out.Errors, fmt.Sprintf("failed to get lowest unreleased fix version: %v", err))
return out, nil
}
return out, fmt.Errorf("failed to get lowest unreleased fix version: %w", err)
}

// Extract all Jira issue keys from the PR title (format: "PROJ-123, PROJ-456: description" or "PROJ-123: description")
issueKeys := issueKeyPattern.FindAllString(prTitle, -1)

if len(issueKeys) == 0 {
out.Errors = append(out.Errors, fmt.Sprintf("the PR title does not mention at least one Jira issue key: %s", prTitle))
return out, fmt.Errorf("release branch PR check failed")
return out, nil
}

for _, issueKey := range issueKeys {
issue, err := jiraClient.GetIssueFromKey(issueKey)
if err != nil {
out.Errors = append(out.Errors, fmt.Sprintf("failed to get Jira issue: %v", err))
continue
var apiErr *jira.APIError
if errors.As(err, &apiErr) && !apiErr.IsServerError() &&
apiErr.StatusCode != http.StatusTooManyRequests &&
apiErr.StatusCode != http.StatusUnauthorized &&
apiErr.StatusCode != http.StatusForbidden {
out.Errors = append(out.Errors, fmt.Sprintf("failed to get Jira issue: %v", err))
continue
}
return out, fmt.Errorf("failed to get Jira issue %s: %w", issueKey, err)
}

status := issue.Fields.Status.Name
Expand Down Expand Up @@ -179,10 +295,56 @@ func RunReleasePRCheck(cmd *cobra.Command, args []string, c *client.Client) (any
}
}

if len(out.Errors) > 0 {
return out, fmt.Errorf("release branch PR check failed")
if len(out.Errors) == 0 {
out.Valid = true
}

out.Valid = true
return out, nil
}

func postVerdictToPR(ctx context.Context, client *client.Client, out ReleasePRCheckOutput, reviewerLogin string) error {
// TODO(ROX-35283): remove disclaimer once the check goes live
previewDisclaimer := "**This is a preview of the release branch PR check. It is not a blocking review yet.**"

event := "COMMENT"
// TODO(ROX-35283): uncomment this once the check goes live
// if !out.Valid {
// event = "REQUEST_CHANGES"
// }

// TODO(ROX-35283): remove the Event field once the check goes live
comment := fmt.Sprintf("%s\n%s\n\nEvent: *%s*\n\n%s", reviewMarker, previewDisclaimer, event, out.String())

reviewer := reviewerLogin
if reviewer == "" {
reviewer = "current user"
}

var (
lastReview *gogithub.PullRequestReview
err error
)
if reviewerLogin != "" {
lastReview, err = github.GetLastReviewForLogin(ctx, client, out.Org, out.Repo, out.PullRequestNumber, reviewerLogin, reviewMarker)
} else {
lastReview, err = github.GetLastReviewForCurrentUser(ctx, client, out.Org, out.Repo, out.PullRequestNumber, reviewMarker)
}
if err != nil {
return fmt.Errorf("failed to get last review for %s: %w", reviewer, err)
}

// TODO(ROX-35283): update workflows based on new event once the check goes live
if lastReview == nil {
err = github.PostCommentToPR(ctx, client, out.Org, out.Repo, out.PullRequestNumber, event, comment)
if err != nil {
return fmt.Errorf("failed to post comment to PR: %w", err)
}
} else {
// TODO(ROX-35283): once the check goes live, update the logic to dismiss previous review (if has different event), then create new review
err = github.UpdateReview(ctx, client, out.Org, out.Repo, out.PullRequestNumber, lastReview.GetID(), comment)
if err != nil {
return fmt.Errorf("failed to update review: %w", err)
}
}
return nil
}
3 changes: 1 addition & 2 deletions cmd/relacs/github/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ import (
)

var (
releaseBranchPattern = regexp.MustCompile(`^release-(\d+)\.(\d+)$`)
issueKeyPattern = regexp.MustCompile(`[A-Z]+-[0-9]+`)
issueKeyPattern = regexp.MustCompile(`[A-Z]+-[0-9]+`)
)

// GitHubCmd represents the github command group
Expand Down
Loading