action-create-pr/create-pull-request.go

130 lines
2.7 KiB
Go

package main
import (
"code.gitea.io/sdk/gitea"
"slices"
)
type Agent struct {
client *gitea.Client
}
type CreatePrConfig struct {
// the organization where the PR is created
Org string
// the repository where the PR is created
Repo string
// the branch where the changes are made
HeadBranch string
// the branch where the changes will be added
BaseBranch string
// the title of the pull requests
Title string
// the body of the pull requests
Body string
// the list of assignees
Assignees []string
// the list of requested labels
Labels []string
}
func (a *Agent) branchHasOpenPullRequest(config CreatePrConfig) (bool, error) {
currentPage := 1
for currentPage != 0 {
pulls, response, err := a.client.ListRepoPullRequests(config.Org, config.Repo,
gitea.ListPullRequestsOptions{State: gitea.StateOpen, ListOptions: gitea.ListOptions{Page: currentPage}})
if err != nil {
return true, err
}
for _, p := range pulls {
if p.Head.Name == config.HeadBranch {
return true, nil
}
}
currentPage = response.NextPage
}
return false, nil
}
func (a *Agent) labelsFromString(config CreatePrConfig) ([]gitea.Label, error) {
foundLabels := []gitea.Label{}
currentPage := 1
for currentPage != 0 {
labels, response, err := a.client.ListRepoLabels(config.Org, config.Repo, gitea.ListLabelsOptions{ListOptions: gitea.ListOptions{Page: currentPage}})
if err != nil {
return nil, err
}
for _, label := range labels {
if slices.Contains(config.Labels, label.Name) {
foundLabels = append(foundLabels, *label)
}
}
currentPage = response.NextPage
}
return foundLabels, nil
}
func (a *Agent) createPullRequestGitea(config CreatePrConfig) (*gitea.PullRequest, error) {
labelIds := []int64{}
labels, err := a.labelsFromString(config)
if err != nil {
return nil, err
}
for _, label := range labels {
labelIds = append(labelIds, label.ID)
}
if err != nil {
return nil, err
}
pr, _, err := a.client.CreatePullRequest(config.Org, config.Repo, gitea.CreatePullRequestOption{
Head: config.HeadBranch,
Base: config.BaseBranch,
Title: config.Title,
Body: config.Body,
Assignees: config.Assignees,
Labels: labelIds,
Deadline: nil,
})
if err != nil {
return nil, err
}
return pr, nil
}
func createPullRequest(apiUrl string, token string, config CreatePrConfig) (*gitea.PullRequest, error) {
client, _ := gitea.NewClient(apiUrl, gitea.SetToken(token))
agent := &Agent{client: client}
has, err := agent.branchHasOpenPullRequest(config)
if err != nil {
return nil, err
}
if has {
return nil, nil
}
pr, err := agent.createPullRequestGitea(config)
if err != nil {
return nil, err
}
return pr, nil
}