114 lines
2.1 KiB
Go
114 lines
2.1 KiB
Go
package services
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"strconv"
|
|
|
|
"gitea.com/gitea/pr-deployer/pkgs/settings"
|
|
|
|
"github.com/cloudflare/cloudflare-go"
|
|
git "github.com/go-git/go-git/v5"
|
|
"github.com/go-git/go-git/v5/plumbing"
|
|
)
|
|
|
|
func UpdateAndStartPullRequest(number int) error {
|
|
// 1 download the git
|
|
p := filepath.Join(settings.CodeCacheDir, strconv.Itoa(number))
|
|
fmt.Println("clone code into", p)
|
|
|
|
// 1.1 git fetch origin +refs/heads/main
|
|
// 1.2 git checkout main
|
|
// 1.3 git fetch origin refs/pull/17422/head
|
|
// 1.4 git merge <xxxxxx>
|
|
|
|
st, err := os.Stat(p)
|
|
if err != nil {
|
|
if os.IsNotExist(err) {
|
|
_, err = git.PlainClone(p, false, &git.CloneOptions{
|
|
URL: "https://github.com/go-gitea/gitea",
|
|
InsecureSkipTLS: false,
|
|
ReferenceName: plumbing.NewRemoteReferenceName("", fmt.Sprintf("refs/pull/%d/head", number)),
|
|
SingleBranch: true,
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return err
|
|
}
|
|
if !st.IsDir() {
|
|
return fmt.Errorf("%s is a file but not a dir", p)
|
|
}
|
|
|
|
_, err = git.PlainOpen(p)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// 2 build
|
|
|
|
// 3 change domain
|
|
if err := checkAndUpdateSubDomain(number); err != nil {
|
|
return err
|
|
}
|
|
|
|
// 4 change reverse server
|
|
|
|
// 5 send commit status
|
|
|
|
return nil
|
|
}
|
|
|
|
func checkAndUpdateSubDomain(number int) error {
|
|
api, err := cloudflare.New(settings.CloudflareToken, settings.CloudflareEmail)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
zoneID, err := api.ZoneIDByName("gitea.io")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
var found bool
|
|
var name = fmt.Sprintf("try-pr-%d.gitea.io", number)
|
|
foo := cloudflare.DNSRecord{Name: name}
|
|
recs, err := api.DNSRecords(context.Background(), zoneID, foo)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
for _, r := range recs {
|
|
if name == r.Name {
|
|
found = true
|
|
break
|
|
}
|
|
}
|
|
if found {
|
|
// check ip address
|
|
return nil
|
|
}
|
|
|
|
asciiInput := cloudflare.DNSRecord{
|
|
Type: "A",
|
|
Name: name,
|
|
Content: settings.DomainIP,
|
|
TTL: 120,
|
|
//Priority: &priority,
|
|
//Proxied: &proxied,
|
|
}
|
|
|
|
_, err = api.CreateDNSRecord(context.Background(), zoneID, asciiInput)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func StopPullRequest(number int) error {
|
|
return nil
|
|
}
|