Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 2 additions & 0 deletions COMMANDS.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ Commands for interacting with GitHub repositories, teams, and organizations.
| check-release-pr | Check if a release branch PR satisfies the criteria |
| get-commit-for-tag | Get the commit SHA for a given Git tag |
| get-commit-from-acs-version | Get the commit SHA for a given ACS version (from make tag) |
| get-merge-window | Get the merge window status for a given product stream |
| list-merge-windows | List merge window statuses for all supported product streams |
| list-prs | List the pull requests for a given repository and base branch |
| list-vulns-by-cve | List CVEs from image vulnerability scans for a given Git tag |
| list-vulns-by-image | List image vulnerability scan results for a given Git tag |
Expand Down
23 changes: 19 additions & 4 deletions cmd/relacs/github/check_release_pr.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"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/client/konflux"
"github.com/stackrox/relacs/pkg/config"
"github.com/stackrox/relacs/pkg/github"
)
Expand Down Expand Up @@ -213,20 +214,34 @@ func validatePullRequest(cmd *cobra.Command, client *client.Client, org, repo st
return out, nil
}

// Skip checks for PRs by red-hat-konflux[bot]
// The merge window check applies to all PRs, including bot-authored ones.
productStream := konflux.ProductStream{Major: major, Minor: minor}
mergeWindowStatus, err := github.GetMergeWindowStatus(cmd.Context(), client, org, repo, productStream)
if err != nil {
if errors.Is(err, github.ErrInvalidMergeWindowFile) {
// Content problems are validation errors; everything else is environmental.
out.Errors = append(out.Errors, fmt.Sprintf("failed to get merge window status: %v", err))
} else {
return out, fmt.Errorf("failed to get merge window status: %w", err)
}
} else if mergeWindowStatus != "OPEN" {
out.Errors = append(out.Errors, fmt.Sprintf("merge window is %s (expected OPEN) for product stream %s", mergeWindowStatus, productStream))
}

// Skip the remaining 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
out.Valid = len(out.Errors) == 0
return out, nil
}

// For rhacs-bot PRs with 'chore' prefix, print warning and skip checks
// For rhacs-bot PRs with 'chore' prefix, skip the remaining checks
prTitle := pr.GetTitle()
if pr.GetUser().GetLogin() == rhacsBotUsername && strings.HasPrefix(prTitle, "chore") {
//nolint:errcheck
fmt.Fprintf(cmd.ErrOrStderr(), "%s: skipping release PR checks for rhacs-bot PR with 'chore' prefix\n", prRef(org, repo, pullRequestNumber))
out.Valid = true
out.Valid = len(out.Errors) == 0
return out, nil
}

Expand Down
2 changes: 2 additions & 0 deletions cmd/relacs/github/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ func init() {
GitHubCmd.AddCommand(checkReleasePRCmd)
GitHubCmd.AddCommand(getCommitForTagCmd)
GitHubCmd.AddCommand(getCommitFromACSTagCmd)
GitHubCmd.AddCommand(getMergeWindowCmd)
GitHubCmd.AddCommand(listMergeWindowsCmd)
GitHubCmd.AddCommand(listPRsCmd)
GitHubCmd.AddCommand(listVulnsByCVECmd)
GitHubCmd.AddCommand(listVulnsByImageCmd)
Expand Down
60 changes: 60 additions & 0 deletions cmd/relacs/github/get_merge_window.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package github

import (
"fmt"

"github.com/spf13/cobra"
"github.com/stackrox/relacs/cmd/relacs/common"
"github.com/stackrox/relacs/pkg/client"
"github.com/stackrox/relacs/pkg/client/konflux"
"github.com/stackrox/relacs/pkg/config"
"github.com/stackrox/relacs/pkg/github"
)

type GetMergeWindowOutput struct {
ProductStream konflux.ProductStream `json:"product-stream" yaml:"product-stream"`
Status string `json:"status" yaml:"status"`
}

func (o GetMergeWindowOutput) String() string {
return fmt.Sprintf("%s: %s", o.ProductStream.String(), o.Status)
}

var getMergeWindowCmd = &cobra.Command{
Use: "get-merge-window",
Short: "Get the merge window status for a given product stream",
Long: `Get the merge window status for a given product stream`,
RunE: common.RunCommand(RunGetMergeWindow),
}

func init() {
getMergeWindowCmd.Flags().String("org", config.GitHubOrganization, "GitHub organization (optional)")
getMergeWindowCmd.Flags().String("repo", config.MainGitHubRepository, "GitHub repository (optional)")
getMergeWindowCmd.Flags().String("product-stream", "", "Product stream (required)")

//nolint:errcheck
getMergeWindowCmd.MarkFlagRequired("product-stream")
}

// RunGetMergeWindow is the main function of this command and exported for testing purposes.
func RunGetMergeWindow(cmd *cobra.Command, _ []string, c *client.Client) (any, error) {
ctx := cmd.Context()
org, _ := cmd.Flags().GetString("org")
repo, _ := cmd.Flags().GetString("repo")
productStreamInput, _ := cmd.Flags().GetString("product-stream")

productStream, err := konflux.NewProductStream(productStreamInput)
if err != nil {
return nil, err
}

mergeWindowStatus, err := github.GetMergeWindowStatus(ctx, c, org, repo, productStream)
if err != nil {
return nil, err
}

return GetMergeWindowOutput{
ProductStream: productStream,
Status: mergeWindowStatus,
}, nil
}
86 changes: 86 additions & 0 deletions cmd/relacs/github/list_merge_window_statuses.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package github

import (
"bytes"
"fmt"
"strings"

"github.com/olekukonko/tablewriter"
"github.com/olekukonko/tablewriter/renderer"
"github.com/spf13/cobra"
"github.com/stackrox/relacs/cmd/relacs/common"
"github.com/stackrox/relacs/pkg/client"
"github.com/stackrox/relacs/pkg/client/konflux"
"github.com/stackrox/relacs/pkg/config"
"github.com/stackrox/relacs/pkg/github"
)

type ListMergeWindowsOutput struct {
SupportedProductStreams []konflux.ProductStream `json:"supported-product-streams" yaml:"supported-product-streams"`
MergeWindowStatuses map[konflux.ProductStream]string `json:"merge-window-statuses" yaml:"merge-window-statuses"`
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

func (o ListMergeWindowsOutput) String() string {
var buf strings.Builder
fmt.Fprintf(&buf, "# Merge Window Statuses\n\n%s", renderMergeWindowStatusesTable(o))
return buf.String()
}

func renderMergeWindowStatusesTable(output ListMergeWindowsOutput) string {
if len(output.SupportedProductStreams) == 0 {
return " No supported product streams found.\n"
}

var buf bytes.Buffer
table := tablewriter.NewTable(&buf,
tablewriter.WithHeader([]string{"Product Stream", "Status"}),
tablewriter.WithRenderer(renderer.NewMarkdown()),
)

for _, productStream := range output.SupportedProductStreams {
//nolint:errcheck
table.Append([]string{productStream.String(), output.MergeWindowStatuses[productStream]})
}

//nolint:errcheck
table.Render()
return buf.String()
}

var listMergeWindowsCmd = &cobra.Command{
Use: "list-merge-windows",
Short: "List merge window statuses for all supported product streams",
Long: `List merge window statuses for all supported product streams in different formats`,
RunE: common.RunCommand(RunListMergeWindows),
}

func init() {
listMergeWindowsCmd.Flags().String("org", config.GitHubOrganization, "GitHub organization (optional)")
listMergeWindowsCmd.Flags().String("repo", config.MainGitHubRepository, "GitHub repository (optional)")
}

// RunListMergeWindows is the main function of this command and exported for testing purposes.
func RunListMergeWindows(cmd *cobra.Command, _ []string, c *client.Client) (any, error) {
ctx := cmd.Context()
org, _ := cmd.Flags().GetString("org")
repo, _ := cmd.Flags().GetString("repo")

supportedProductStreams, err := c.GetKonflux().GetActiveProductStreams(ctx)
if err != nil {
return nil, err
}

mergeWindowStatuses := map[konflux.ProductStream]string{}
for _, productStream := range supportedProductStreams {
mergeWindowStatus, err := github.GetMergeWindowStatus(ctx, c, org, repo, productStream)
if err != nil {
return nil, err
}
mergeWindowStatuses[productStream] = mergeWindowStatus
}

return ListMergeWindowsOutput{
SupportedProductStreams: supportedProductStreams,
MergeWindowStatuses: mergeWindowStatuses,
}, nil
}
79 changes: 79 additions & 0 deletions cmd/relacs/github/merge_window_output_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package github

import (
"encoding/json"
"testing"

"github.com/stackrox/relacs/pkg/client/konflux"
"gopkg.in/yaml.v3"
)

// The merge window output types must serialize product streams as their
// canonical string (e.g. "4.6"), including as map keys, in both JSON and YAML.
func TestGetMergeWindowOutputSerialization(t *testing.T) {
output := GetMergeWindowOutput{
ProductStream: konflux.ProductStream{Major: 4, Minor: 6},
Status: "OPEN",
}

jsonOutput, err := json.Marshal(output)
if err != nil {
t.Fatal(err)
}
wantJSON := `{"product-stream":"4.6","status":"OPEN"}`
if string(jsonOutput) != wantJSON {
t.Errorf("json: got %s, want %s", jsonOutput, wantJSON)
}

var yamlDecoded map[string]any
if err := yaml.Unmarshal(mustYAML(t, output), &yamlDecoded); err != nil {
t.Fatal(err)
}
if yamlDecoded["product-stream"] != "4.6" {
t.Errorf("yaml: product-stream should be the string 4.6, got %v", yamlDecoded["product-stream"])
}
if yamlDecoded["status"] != "OPEN" {
t.Errorf("yaml: status should be OPEN, got %v", yamlDecoded["status"])
}
}

func TestListMergeWindowsOutputSerialization(t *testing.T) {
productStream := konflux.ProductStream{Major: 4, Minor: 6}
output := ListMergeWindowsOutput{
SupportedProductStreams: []konflux.ProductStream{productStream},
MergeWindowStatuses: map[konflux.ProductStream]string{
productStream: "OPEN",
},
}

jsonOutput, err := json.Marshal(output)
if err != nil {
t.Fatal(err)
}
wantJSON := `{"supported-product-streams":["4.6"],"merge-window-statuses":{"4.6":"OPEN"}}`
if string(jsonOutput) != wantJSON {
t.Errorf("json: got %s, want %s", jsonOutput, wantJSON)
}

var yamlDecoded map[string]any
if err := yaml.Unmarshal(mustYAML(t, output), &yamlDecoded); err != nil {
t.Fatal(err)
}
streams, ok := yamlDecoded["supported-product-streams"].([]any)
if !ok || len(streams) != 1 || streams[0] != "4.6" {
t.Errorf("yaml: supported-product-streams should be [4.6], got %v", yamlDecoded["supported-product-streams"])
}
statuses, ok := yamlDecoded["merge-window-statuses"].(map[string]any)
if !ok || statuses["4.6"] != "OPEN" {
t.Errorf("yaml: merge-window-statuses should map the string key 4.6 to OPEN, got %v", yamlDecoded["merge-window-statuses"])
}
}

func mustYAML(t *testing.T, output any) []byte {
t.Helper()
yamlOutput, err := yaml.Marshal(output)
if err != nil {
t.Fatal(err)
}
return yamlOutput
}
50 changes: 50 additions & 0 deletions pkg/client/konflux/applications.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package konflux

import (
"context"
"fmt"
"regexp"
"sort"
"strconv"

"github.com/stackrox/relacs/pkg/client/konflux/kubearchive"
"github.com/stackrox/relacs/pkg/config"
)

// applicationNamePattern matches Konflux application names like acs-4-6.
var applicationNamePattern = regexp.MustCompile(`^` + config.KonfluxApplicationPrefix + `-(\d+)-(\d+)$`)

// GetActiveProductStreams returns the product streams that currently have a
// Konflux application. Applications are the source of truth because in-flight
// product streams exist as applications before their first release.
func (c *Client) GetActiveProductStreams(ctx context.Context) ([]ProductStream, error) {
ka, err := c.getKubearchive()
if err != nil {
return nil, err
}

applications, err := kubearchive.QueryResources[Application](ctx, ka, "appstudio.redhat.com", "v1alpha1", "applications", kubearchive.QueryOptions{})
if err != nil {
return nil, fmt.Errorf("failed to retrieve applications: %w", err)
}

productStreams := []ProductStream{}
for _, application := range applications {
matches := applicationNamePattern.FindStringSubmatch(application.Metadata.Name)
if matches == nil {
continue
}
major, _ := strconv.Atoi(matches[1])
minor, _ := strconv.Atoi(matches[2])
productStreams = append(productStreams, ProductStream{Major: major, Minor: minor})
}

sort.Slice(productStreams, func(i, j int) bool {
if productStreams[i].Major != productStreams[j].Major {
return productStreams[i].Major < productStreams[j].Major
}
return productStreams[i].Minor < productStreams[j].Minor
})

return productStreams, nil
}
41 changes: 41 additions & 0 deletions pkg/client/konflux/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package konflux
import (
"encoding/json"
"fmt"
"strconv"
"strings"
"time"
)

Expand Down Expand Up @@ -250,3 +252,42 @@ var severityStrings = []string{
func (s Severity) String() string {
return severityStrings[s]
}

type Application struct {
Metadata Metadata `json:"metadata" yaml:"metadata"`
}

func (a Application) GetUID() string { return a.Metadata.UID }

// ProductStream identifies a product stream by its major and minor version,
// e.g. 4.6.
type ProductStream struct {
Major int
Minor int
}

func NewProductStream(input string) (ProductStream, error) {
parts := strings.Split(input, ".")
if len(parts) != 2 {
return ProductStream{}, fmt.Errorf("invalid product stream: %s", input)
}
major, err := strconv.Atoi(parts[0])
if err != nil {
return ProductStream{}, fmt.Errorf("invalid major version: %s", parts[0])
}
minor, err := strconv.Atoi(parts[1])
if err != nil {
return ProductStream{}, fmt.Errorf("invalid minor version: %s", parts[1])
}
return ProductStream{Major: major, Minor: minor}, nil
}

func (ps ProductStream) String() string {
return fmt.Sprintf("%d.%d", ps.Major, ps.Minor)
}

// MarshalText renders the product stream as a scalar so it can be used as a
// map key in JSON and YAML output.
func (ps ProductStream) MarshalText() ([]byte, error) {
return []byte(ps.String()), nil
}
Loading