-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgithub.go
78 lines (63 loc) · 1.78 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
package torvalds
import (
"context"
"encoding/json"
"errors"
"os"
"github.com/google/go-github/v61/github"
)
type Event struct {
Number int `json:"number"`
Repository Repository `json:"repository"`
}
type Repository struct {
Name string `json:"name"`
Owner Owner `json:"owner"`
}
type Owner struct {
Login string `json:"login"`
}
var ErrCouldNotFindEvent = errors.New("could not find pull request event")
var ErrCouldNotFindGithubToken = errors.New("could not find github token")
func ParseEventFromGithubActionsEvent() (Event, error) {
pathToEvent, ok := os.LookupEnv("GITHUB_EVENT_PATH")
if !ok {
return Event{}, ErrCouldNotFindEvent
}
return parseEventFromFile(pathToEvent)
}
func parseEventFromFile(path string) (Event, error) {
data, _ := os.ReadFile(path)
var event Event
err := json.Unmarshal(data, &event)
if err != nil {
return Event{}, err
}
return event, nil
}
func GetDiffFromPullRequest(owner string, repositoryName string, prNumber int) (string, error) {
token, ok := os.LookupEnv("GITHUB_TOKEN")
if !ok {
return "", ErrCouldNotFindGithubToken
}
client := github.NewClient(nil).WithAuthToken(token)
bg := context.Background()
diff, _, err := client.PullRequests.GetRaw(bg, owner, repositoryName, prNumber, github.RawOptions{Type: github.Patch})
if err != nil {
return "", err
}
return diff, nil
}
func AddCommentToPullRequest(owner string, repositoryName string, prNumber int, comment string) error {
token, ok := os.LookupEnv("GITHUB_TOKEN")
if !ok {
return ErrCouldNotFindGithubToken
}
client := github.NewClient(nil).WithAuthToken(token)
bg := context.Background()
_, _, err := client.Issues.CreateComment(bg, owner, repositoryName, prNumber, &github.IssueComment{Body: &comment})
if err != nil {
return err
}
return nil
}