GeezerVison is showing github.com — feat(gitea): add pull request auto-merge by ldbs · Pull Request #11059 · updatecli/updatecli
feat(gitea): add pull request auto-merge
#11059
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement . We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Uh oh!
There was an error while loading. Please reload this page.
Show file tree
Hide file tree
Changes from all commits
Commits
File filter
Filter by extension
.go
(10)
.mod
(1)
All 2 file types selected
Only manifest files
Viewed files
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Hide whitespace
Diff view
Hide whitespace
There are no files selected for viewing
2 changes: 1 addition & 1 deletion
2
go.mod
Original file line number
Diff line number
Diff line change
Expand Up
@@ -35,6 +35,7 @@ require (
github.com/google/go-github/v69 v69.2.0
github.com/google/uuid v1.6.0
github.com/goware/urlx v0.3.2
github.com/hashicorp/go-retryablehttp v0.7.8
github.com/hashicorp/hcl/v2 v2.25.0
github.com/hashicorp/terraform-registry-address v0.5.0
github.com/heimdalr/dag v1.5.1
Expand Down
Expand Up
@@ -237,7 +238,6 @@ require (
github.com/hashicorp/errwrap v1.1.0 // indirect
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
github.com/hashicorp/go-multierror v1.1.1 // indirect
github.com/hashicorp/go-retryablehttp v0.7.8 // indirect
github.com/hashicorp/go-rootcerts v1.0.2 // indirect
github.com/hashicorp/go-secure-stdlib/parseutil v0.2.0 // indirect
github.com/hashicorp/go-secure-stdlib/strutil v0.1.2 // indirect
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -7,6 +7,7 @@ import (
"github.com/drone/go-scm/scm"
gitea "github.com/drone/go-scm/scm/driver/gitea"
"github.com/drone/go-scm/scm/transport/oauth2"
"github.com/hashicorp/go-retryablehttp"
"github.com/updatecli/updatecli/pkg/core/httpclient"
)
Expand Down
Expand Up
@@ -43,8 +44,13 @@ func New(s Spec) (Client, error) {
// NewSDKClient creates a new Gitea client based on the official gitea sdk instead of drone's go-scm
func NewSDKClient(s Spec) (SDKClient, error) {
// Set a global timeout on the underlying HTTP client used by the Gitea SDK
httpClient := httpclient.NewUncachedRetryClient()
// Gitea/Forgejo can return 405 "Please try again later" just after a PR is created or updated (the shared client doesn't retry 405 responses).
retryClient := retryablehttp.NewClient()
retryClient.HTTPClient = httpclient.NewUncachedRetryClient()
retryClient.Logger = nil
retryClient.RetryMax = httpclient.RetryCount
retryClient.CheckRetry = retryMerge
httpClient := retryClient.StandardClient()
httpClient.Timeout = 30 * time.Second
return giteasdk.NewClient(s.URL, giteasdk.SetToken(s.Token), giteasdk.SetHTTPClient(httpClient))
Expand Down
Original file line number
Diff line number
Diff line change
@@ -0,0 +1,55 @@
package client
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"strings"
"github.com/updatecli/updatecli/pkg/core/log"
)
// ErrAutoMergeAlreadyScheduled indicates that the pull request already has an auto-merge schedule.
var ErrAutoMergeAlreadyScheduled = errors.New("pull request is already scheduled to auto merge when checks succeed")
// The SDK discards merge response bodies, so inspect them before returning.
func retryMerge(ctx context.Context, resp *http.Response, err error) (bool, error) {
if ctx.Err() != nil {
return false, ctx.Err()
}
if err != nil {
return false, err
}
if resp.Request.Method != http.MethodPost ||
!strings.Contains(resp.Request.URL.Path, "/pulls/") ||
!strings.HasSuffix(resp.Request.URL.Path, "/merge") {
return false, nil
}
if resp.StatusCode != http.StatusMethodNotAllowed &&
resp.StatusCode != http.StatusConflict {
return false, nil
}
body, err := io.ReadAll(resp.Body)
_ = resp.Body.Close()
if err != nil {
return false, err
}
resp.Body = io.NopCloser(bytes.NewReader(body))
var rejection struct {
Message string
}
if json.Unmarshal(body, &rejection) != nil {
return false, nil
}
if resp.StatusCode == http.StatusConflict && strings.HasPrefix(rejection.Message, ErrAutoMergeAlreadyScheduled.Error()+" [pull_id: ") {
return false, ErrAutoMergeAlreadyScheduled
}
if resp.StatusCode == http.StatusMethodNotAllowed && rejection.Message == "Please try again later" {
log.Debugln("Gitea asked to retry the merge request")
return true, nil
}
return false, nil
}
Original file line number
Diff line number
Diff line change
Expand Up
@@ -343,3 +343,69 @@ func TestFindExistingPullRequest(t *testing.T) {
})
}
}
func TestFindExistingPullRequestPrefersOwned(t *testing.T) {
branches := func(index, headRepoID int64) *giteasdk.PullRequest {
return &giteasdk.PullRequest{
Index: index,
Head: &giteasdk.PRBranchInfo{Name: "updatecli", RepoID: headRepoID},
Base: &giteasdk.PRBranchInfo{Name: "main", RepoID: testRepoID},
}
}
testData := []struct {
name string
pages [][]*giteasdk.PullRequest
expectedIndex int64
}{
{
name: "Fork listed before the owned pull request on the same page",
pages: [][]*giteasdk.PullRequest{{branches(1, testForkID), branches(2, testRepoID)}},
expectedIndex: 2,
},
{
name: "Fork listed before the owned pull request on another page",
pages: [][]*giteasdk.PullRequest{{branches(1, testForkID)}, {branches(2, testRepoID)}},
expectedIndex: 2,
},
{
name: "Only a fork",
pages: [][]*giteasdk.PullRequest{{branches(1, testForkID)}},
expectedIndex: 1,
},
}
for _, tt := range testData {
t.Run(tt.name, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
page, err := strconv.Atoi(r.URL.Query().Get("page"))
if err != nil || page < 1 || page > len(tt.pages) {
http.Error(w, "unexpected page", http.StatusBadRequest)
return
}
if page < len(tt.pages) {
w.Header().Set("Link", fmt.Sprintf(`<http://%s%s?page=%d>; rel="next"`, r.Host, r.URL.Path, page+1))
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(tt.pages[page-1])
}))
defer server.Close()
client, err := giteasdk.NewClient(server.URL)
require.NoError(t, err)
g := Gitea{
client: client,
Owner: "updatecli",
Repository: "updatecli",
SourceBranch: "updatecli",
TargetBranch: "main",
}
got, err := g.findExistingPullRequest(t.Context())
require.NoError(t, err)
require.NotNil(t, got)
assert.Equal(t, tt.expectedIndex, got.Index)
})
}
}
Original file line number
Diff line number
Diff line change
Expand Up
@@ -2,6 +2,8 @@ package pullrequest
import (
"context"
"fmt"
"strings"
giteasdk "gitea.dev/sdk"
"github.com/updatecli/updatecli/pkg/core/log"
Expand Down
Expand Up
@@ -39,12 +41,22 @@ func (g *Gitea) CreateAction(ctx context.Context, report *reports.Action, resetD
// If a pullrequest already exist, we update the report with the existing pullrequest
if pullrequest != nil {
log.Debugf("Gitea pullrequest already exist, nothing to do")
// A pull request opened from a fork isn't managed by Updatecli, even if it uses the same branch name
if pullrequest.Base == nil || pullrequest.Head.RepoID != pullrequest.Base.RepoID {
log.Debugf("Skipping Gitea pull request auto-merge as its head is on another repository:\n\t%s", pullrequest.URL)
report.Title = pullrequest.Title
report.Link = pullrequest.URL
report.Description = pullrequest.Body
return nil
Comment thread
olblak marked this conversation as resolved.
Resolved
Uh oh!
There was an error while loading. Please reload this page.
}
log.Debugf("Gitea pullrequest already exists")
report.Title = pullrequest.Title
report.Link = pullrequest.URL
report.Description = pullrequest.Body
return nil
return g.enableAutoMerge(ctx, pullrequest)
}
// Test that both sourceBranch and targetBranch exists on remote before creating a new one
Expand Down
Expand Up
@@ -93,6 +105,9 @@ func (g *Gitea) CreateAction(ctx context.Context, report *reports.Action, resetD
}
if err != nil {
if strings.EqualFold(g.spec.Merge.Strategy, MergeStrategyAuto) {
return fmt.Errorf("creating Gitea pull request for auto-merge: %w", err)
}
log.Infof("Gitea pullrequest not created, skipping")
return nil
}
Expand All
@@ -103,5 +118,5 @@ func (g *Gitea) CreateAction(ctx context.Context, report *reports.Action, resetD
log.Infof("Gitea pullrequest successfully opened on %q", pr.URL)
return nil
return g.enableAutoMerge(ctx, pr)
}
Original file line number
Diff line number
Diff line change
Expand Up
@@ -48,6 +48,9 @@ func New(spec any, scm *giteascm.Gitea) (Gitea, error) {
if err != nil {
return Gitea{}, fmt.Errorf("error decoding spec: %w", err)
}
if err := s.Validate(); err != nil {
return Gitea{}, err
}
if scm != nil {
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -165,6 +165,18 @@ func TestNew(t *testing.T) {
scm: nil,
wantErr: true,
},
{
name: "Unsupported merge strategy",
spec: Spec{Merge: MergeSpec{Strategy: "client"}},
wantErr: true,
wantErrMessage: `invalid merge strategy "client"`,
},
{
name: "Unsupported merge method",
spec: Spec{MergeMethod: "fast-forward"},
wantErr: true,
wantErrMessage: `invalid merge method "fast-forward"`,
},
}
for _, tt := range testData {
Expand All
@@ -175,6 +187,9 @@ func TestNew(t *testing.T) {
if tt.wantErr {
require.Error(t, gotErr)
if tt.wantErrMessage != "" {
assert.ErrorContains(t, gotErr, tt.wantErrMessage)
}
} else {
require.NoError(t, gotErr)
}
Expand Down
Original file line number
Diff line number
Diff line change
@@ -0,0 +1,52 @@
package pullrequest
import (
"context"
"errors"
"fmt"
"strings"
giteasdk "gitea.dev/sdk"
"github.com/updatecli/updatecli/pkg/core/log"
"github.com/updatecli/updatecli/pkg/plugins/resources/gitea/client"
)
func (g *Gitea) enableAutoMerge(ctx context.Context, pr *giteasdk.PullRequest) error {
if !strings.EqualFold(g.spec.Merge.Strategy, MergeStrategyAuto) {
return nil
}
method := giteasdk.MergeStyle(strings.ToLower(g.spec.MergeMethod))
if method == "" {
repo, _, err := g.client.Repositories.GetRepo(ctx, g.Owner, g.Repository)
if err != nil {
return fmt.Errorf("getting repository default merge method: %w", err)
}
method = repo.DefaultMergeStyle
if !isMergeMethodValid(string(method)) {
return fmt.Errorf("unsupported repository default merge method %q", method)
}
}
if pr.Head == nil || pr.Head.Sha == "" {
return fmt.Errorf("cannot request auto-merge for Gitea pull request %q without a head commit ID", pr.HTMLURL)
}
accepted, resp, err := g.client.PullRequests.MergePullRequest(ctx, g.Owner, g.Repository, pr.Index, giteasdk.MergePullRequestOption{
Style: method,
MergeWhenChecksSucceed: true,
HeadCommitId: pr.Head.Sha,
})
if errors.Is(err, client.ErrAutoMergeAlreadyScheduled) {
log.Infof("Gitea pullrequest auto-merge already enabled on %q; keeping the existing schedule", pr.HTMLURL)
return nil
}
if err != nil {
return fmt.Errorf("requesting auto-merge for Gitea pull request %q: %w", pr.HTMLURL, err)
}
// The SDK closes the response body and returns false, nil for HTTP rejections.
if !accepted {
return fmt.Errorf("auto-merge request for Gitea pull request %q rejected: HTTP %s", pr.HTMLURL, resp.Status)
}
log.Infof("Gitea pullrequest auto-merge requested on %q", pr.HTMLURL)
return nil
}
Original file line number
Diff line number
Diff line change
@@ -0,0 +1,43 @@
package pullrequest
import (
"net/http"
"net/http/httptest"
"testing"
giteasdk "gitea.dev/sdk"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/updatecli/updatecli/pkg/core/reports"
)
func TestCreateActionForkPullRequestSkipsAutoMerge(t *testing.T) {
// The fake server rejects merge requests so requesting an auto-merge returns an error
fake := cleanServer{
headRepoID: testForkID,
listedSha: []string{"abc"},
branchSha: "abc",
}
server := httptest.NewServer(http.HandlerFunc(fake.handler))
defer server.Close()
client, err := giteasdk.NewClient(server.URL)
require.NoError(t, err)
g := Gitea{
spec: Spec{Merge: MergeSpec{Strategy: MergeStrategyAuto}, MergeMethod: "squash"},
client: client,
Owner: "updatecli",
Repository: "updatecli",
SourceBranch: "updatecli",
TargetBranch: "main",
}
report := reports.Action{}
require.NoError(t, g.CreateAction(t.Context(), &report, false))
assert.Equal(t, 1, fake.listCount)
assert.Zero(t, fake.closeCount)
assert.Equal(t, "https://gitea.example.com/updatecli/updatecli/pulls/42", report.Link)
}
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.