Skip to content
Open
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
49 changes: 38 additions & 11 deletions dev-tools/mage/release/github.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,16 @@ type gitHubClient struct {

// prOptions holds options for creating a pull request.
type prOptions struct {
Owner string
Repo string
Title string
Head string
Base string
Body string
Draft bool
Reviewers []string
Labels []string
Owner string
Repo string
Title string
Head string
Base string
Body string
Draft bool
Reviewers []string
Labels []string
RemoveLabels []string // removed on create/reuse (e.g. leftover backport-* on PR-A)
}

// newGitHubClient creates a new GitHub API client.
Expand Down Expand Up @@ -59,7 +60,7 @@ func (gh *gitHubClient) createPR(opts prOptions) (*github.PullRequest, error) {
}
if found {
printf("Open PR already exists #%d: %s\n", existingPR.GetNumber(), existingPR.GetHTMLURL())
if err := gh.ensurePRLabels(opts.Owner, opts.Repo, existingPR.GetNumber(), opts.Labels); err != nil {
if err := gh.applyPRLabels(opts.Owner, opts.Repo, existingPR.GetNumber(), opts.Labels, opts.RemoveLabels); err != nil {
return nil, err
}
return existingPR, nil
Expand Down Expand Up @@ -92,7 +93,7 @@ func (gh *gitHubClient) createPR(opts prOptions) (*github.PullRequest, error) {
}
}

if err := gh.ensurePRLabels(opts.Owner, opts.Repo, pr.GetNumber(), opts.Labels); err != nil {
if err := gh.applyPRLabels(opts.Owner, opts.Repo, pr.GetNumber(), opts.Labels, opts.RemoveLabels); err != nil {
return nil, err
}

Expand Down Expand Up @@ -276,6 +277,13 @@ var mergeLabelDefs = map[string]struct {
},
}

func (gh *gitHubClient) applyPRLabels(owner, repo string, number int, add, remove []string) error {
if err := gh.ensurePRLabels(owner, repo, number, add); err != nil {
return err
}
return gh.removePRLabels(owner, repo, number, remove)
}

func (gh *gitHubClient) ensurePRLabels(owner, repo string, number int, labels []string) error {
if len(labels) == 0 {
return nil
Expand All @@ -293,6 +301,25 @@ func (gh *gitHubClient) ensurePRLabels(owner, repo string, number int, labels []
return nil
}

// removePRLabels drops labels from a PR. Missing labels are ignored so reruns stay idempotent.
func (gh *gitHubClient) removePRLabels(owner, repo string, number int, labels []string) error {
for _, label := range labels {
label = strings.TrimSpace(label)
if label == "" {
continue
}
resp, err := gh.client.Issues.RemoveLabelForIssue(gh.ctx, owner, repo, number, label)
if err != nil {
if resp != nil && resp.StatusCode == http.StatusNotFound {
continue
}
return fmt.Errorf("failed to remove label %q on #%d: %w", label, number, err)
}
printf("Removed label %q from #%d\n", label, number)
}
return nil
}

// ensureLabel creates a repository label if it does not already exist.
func (gh *gitHubClient) ensureLabel(owner, repo, name, color, description string) error {
_, resp, err := gh.client.Issues.GetLabel(gh.ctx, owner, repo, name)
Expand Down
56 changes: 56 additions & 0 deletions dev-tools/mage/release/github_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,62 @@ func TestCreatePRIdempotent(t *testing.T) {
}
}

func TestCreatePRRemovesRequestedLabelsOnReuse(t *testing.T) {
existingPR := &github.PullRequest{
Number: new(42),
HTMLURL: new("https://github.com/elastic/fleet-server/pull/42"),
Head: &github.PullRequestBranch{Ref: new("ff-prep-main-9.6.0")},
Base: &github.PullRequestBranch{Ref: new("main")},
State: new("open"),
}
removed := []string{}
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == http.MethodGet && r.URL.Path == testAPIPullsPath:
w.Header().Set("Content-Type", "application/json")
require.NoError(t, json.NewEncoder(w).Encode([]*github.PullRequest{existingPR}))
case r.Method == http.MethodPost && strings.HasPrefix(r.URL.Path, "/repos/elastic/fleet-server/issues/42/labels"):
w.Header().Set("Content-Type", "application/json")
require.NoError(t, json.NewEncoder(w).Encode([]*github.Label{{Name: new(labelRelease)}}))
case r.Method == http.MethodDelete && strings.Contains(r.URL.Path, "/issues/42/labels/"):
parts := strings.Split(r.URL.Path, "/")
removed = append(removed, parts[len(parts)-1])
w.WriteHeader(http.StatusOK)
default:
t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)
http.NotFound(w, r)
}
})

ghClient := newTestGitHubClient(t, handler)
pr, err := ghClient.createPR(prOptions{
Owner: releasesLookupOwner,
Repo: releasesLookupRepo,
Title: "PR-A",
Head: "ff-prep-main-9.6.0",
Base: testBaseBranch,
Labels: []string{labelRelease},
RemoveLabels: []string{"backport-" + testReleaseBranch},
})
require.NoError(t, err)
require.Equal(t, 42, pr.GetNumber())
require.Equal(t, []string{"backport-" + testReleaseBranch}, removed)
}

func TestRemovePRLabelsIgnoresMissing(t *testing.T) {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodDelete && strings.Contains(r.URL.Path, "/labels/") {
w.WriteHeader(http.StatusNotFound)
_, _ = fmt.Fprint(w, `{"message":"Label does not exist"}`)
return
}
t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)
http.NotFound(w, r)
})
ghClient := newTestGitHubClient(t, handler)
require.NoError(t, ghClient.removePRLabels(releasesLookupOwner, releasesLookupRepo, 7, []string{"backport-9.6"}))
}

func TestLatestReleaseBeforeUsesReleasesWhenPresent(t *testing.T) {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
Expand Down
50 changes: 48 additions & 2 deletions dev-tools/mage/release/issue.go
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,8 @@ func formatPRChecklist(prURLs []string, checked map[string]bool) string {
}

// mergeReleaseIssueBody updates an existing issue body with missing tracker link and PR URLs.
// Checklist item checkboxes outside the PRs section are left untouched.
// Checklist item checkboxes outside the PRs section are left untouched. Text and headings
// after the managed PR list are preserved across updates.
func mergeReleaseIssueBody(existingBody string, isMajorMinor bool, prURLs []string) (string, bool) {
existingChecked := extractPRCheckboxes(existingBody)
allURLs := mergePRURLs(prURLs, keys(existingChecked))
Expand All @@ -240,7 +241,7 @@ func mergeReleaseIssueBody(existingBody string, isMajorMinor bool, prURLs []stri
return updated, true
}

oldPRBlock := strings.TrimPrefix(after, "\n")
oldPRBlock, trailing := splitPRSectionAndTrailing(after)
newPRBlock := formatPRChecklist(allURLs, existingChecked)

oldURLs := keys(extractPRCheckboxes(oldPRBlock))
Expand All @@ -252,9 +253,54 @@ func mergeReleaseIssueBody(existingBody string, isMajorMinor bool, prURLs []stri
}

updated := strings.TrimRight(before, "\n") + "\n\n" + prSection + "\n\n" + newPRBlock
if trailing != "" {
updated = strings.TrimRight(updated, "\n") + "\n\n" + trailing
}
return updated, true
}

// splitPRSectionAndTrailing splits content after the "## PRs" heading into the managed
// PR checklist (checkbox lines and the empty-list placeholder) and any trailing text.
func splitPRSectionAndTrailing(after string) (prBlock, trailing string) {
content := strings.TrimPrefix(after, "\n")
lines := strings.Split(content, "\n")

i := 0
for i < len(lines) && strings.TrimSpace(lines[i]) == "" {
i++
}

managedEnd := i
for managedEnd < len(lines) {
trimmed := strings.TrimSpace(lines[managedEnd])
if trimmed == "" {
j := managedEnd + 1
for j < len(lines) && strings.TrimSpace(lines[j]) == "" {
j++
}
if j < len(lines) && isManagedPRChecklistLine(strings.TrimSpace(lines[j])) {
managedEnd = j
continue
}
break
}
if isManagedPRChecklistLine(trimmed) {
managedEnd++
continue
}
break
}

return strings.Join(lines[i:managedEnd], "\n"), strings.Join(lines[managedEnd:], "\n")
}

func isManagedPRChecklistLine(trimmed string) bool {
if strings.HasPrefix(trimmed, "- [") {
return true
}
return trimmed == "_No related Fleet Server release PRs discovered yet._"
}

func keys(m map[string]bool) []string {
out := make([]string, 0, len(m))
for k := range m {
Expand Down
79 changes: 79 additions & 0 deletions dev-tools/mage/release/issue_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,85 @@ func TestMergeReleaseIssueBodyAddsTrackerWhenMissing(t *testing.T) {
}
}

func TestMergeReleaseIssueBodyPreservesTrailingSections(t *testing.T) {
existing := `Global tracker: https://github.com/elastic/ingest-dev/issues/8866

# Release Checklist

- [ ] Find the Fleet Server release PRs

## PRs

- [x] ` + testPRURL10 + `

## Notes

Operator note: keep this section.
`
updated, changed := mergeReleaseIssueBody(existing, false, []string{
testPRURL10,
testPRURL11,
})
if !changed {
t.Fatal("adding a missing PR should mark the body changed")
}
if !strings.Contains(updated, "- [ ] "+testPRURL11) {
t.Fatal("new PR should be appended")
}
if !strings.Contains(updated, "## Notes") {
t.Fatal("trailing ## Notes section must be preserved")
}
if !strings.Contains(updated, "Operator note: keep this section.") {
t.Fatal("trailing notes text must be preserved")
}

again, changedAgain := mergeReleaseIssueBody(updated, false, []string{
testPRURL10,
testPRURL11,
})
if changedAgain {
t.Fatal("second merge with same PRs should be a no-op")
}
if !strings.Contains(again, "## Notes") {
t.Fatal("trailing section must remain after no-op merge")
}
}

func TestMergeReleaseIssueBodyPreservesPlainAndNestedNotes(t *testing.T) {
existing := `## PRs

- [x] ` + testPRURL10 + `

Operator free-form note.

### Notes

Keep nested notes too.
`
updated, changed := mergeReleaseIssueBody(existing, false, []string{
testPRURL10,
testPRURL11,
})
require.True(t, changed)
require.Contains(t, updated, "Operator free-form note.")
require.Contains(t, updated, "### Notes")
require.Contains(t, updated, "Keep nested notes too.")
}

func TestMergeReleaseIssueBodyPreservesNotesAfterEmptyPRSection(t *testing.T) {
existing := `## PRs

## Notes

Keep me when the PR list was empty.
`
updated, changed := mergeReleaseIssueBody(existing, false, []string{testPRURL10})
require.True(t, changed)
require.Contains(t, updated, "- [ ] "+testPRURL10)
require.Contains(t, updated, "## Notes")
require.Contains(t, updated, "Keep me when the PR list was empty.")
}

func TestEnsureReleaseIssueTrackerDryRun(t *testing.T) {
cfg := &ReleaseConfig{
NextRelease: "9.4.1",
Expand Down
Loading
Loading