forked from iOliverNguyen/git-pr
/
github.go
81 lines (75 loc) · 1.99 KB
/
github.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main
import (
"encoding/json"
"errors"
"fmt"
"github.com/tidwall/gjson"
"time"
)
type NewPRBody struct {
Title string `json:"title"`
Body string `json:"body"`
Head string `json:"head"`
Base string `json:"base"`
}
func githubGetLastPRNumber() (int, error) {
ghURL := fmt.Sprintf("https://api.%v/repos/%v/pulls?state=all&sort=created&direction=desc&per_page=1", config.Host, config.Repo)
jsonBody, err := httpGET(ghURL)
if err != nil {
return 0, err
}
number := gjson.GetBytes(jsonBody, "0.number").Int()
if number == 0 {
return 0, errors.New("failed to find last pull request number")
}
return int(number), nil
}
func githubGetPRNumberForCommit(commit *Commit) (int, error) {
type PR struct {
Number int `json:"number"`
Head struct {
Ref string `json:"ref"`
} `json:"head"`
}
ghURL := fmt.Sprintf("https://api.%v/repos/%v/commits/%v/pulls?per_page=100", config.Host, config.Repo, commit.Hash)
jsonBody, err := httpGET(ghURL)
if err != nil {
return 0, err
}
var out []PR
err = json.Unmarshal(jsonBody, &out)
if err != nil {
return 0, errorf("failed to parse request body: %v", err)
}
remoteRef := commit.GetAttr(KeyRemoteRef)
for _, pr := range out {
if pr.Head.Ref == remoteRef {
return pr.Number, nil
}
}
// The commit was pushed and got "Everything up-to-date", try creating new pr
err = githubCreatePRForCommit(commit)
if err != nil {
return 0, err
}
return commit.PRNumber, nil
}
func githubCreatePRForCommit(commit *Commit) error {
// attempt to create new PR
ghURL := fmt.Sprintf("https://api.%v/repos/%v/pulls", config.Host, config.Repo)
body := NewPRBody{
Title: commit.Title,
Body: commit.Message,
Head: commit.GetAttr(KeyRemoteRef),
Base: config.MainBranch,
}
fmt.Printf("create pull request for %q\n", commit.Title)
jsonBody := must(httpPOST(ghURL, body))
number := gjson.GetBytes(jsonBody, "number").Int()
if number == 0 {
return errorf("unexpected")
}
commit.PRNumber = int(number)
time.Sleep(1 * time.Second)
return nil
}