Repository navigation
Expand file tree
/
Copy pathgithub.go
More file actions
174 lines (163 loc) · 4.4 KB
/
Copy pathgithub.go
File metadata and controls
174 lines (163 loc) · 4.4 KB
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"strings"
)
// GitHub calls go straight to the API with the token from `gh auth token`
// instead of spawning gh, which costs ~200-400ms of process startup each.
// githubAPI is the API root; tests point it at a local server.
var githubAPI = "https://api.github.com"
// githubREST calls the REST API, retrying once if the cached token expired.
func githubREST(method, path string, body any) ([]byte, error) {
var payload []byte
if body != nil {
var err error
if payload, err = json.Marshal(body); err != nil {
return nil, err
}
}
do := func() (*http.Response, error) {
req, err := http.NewRequest(method, githubAPI+path, bytes.NewReader(payload))
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+ghToken)
req.Header.Set("Accept", "application/vnd.github+json")
req.Header.Set("X-GitHub-Api-Version", "2022-11-28")
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
return httpClient.Do(req)
}
resp, err := do()
if err != nil {
return nil, err
}
if resp.StatusCode == 401 {
resp.Body.Close()
invalidateGHToken()
if err := refreshGHToken(); err != nil {
return nil, fmt.Errorf("auth refresh failed: %w", err)
}
if resp, err = do(); err != nil {
return nil, err
}
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
data = stripJSONControls(data)
if resp.StatusCode >= 400 {
return data, apiError(resp.StatusCode, data)
}
return data, nil
}
// apiError turns GitHub's {"message", "errors": [...]} into one readable line.
func apiError(status int, data []byte) error {
var e struct {
Message string `json:"message"`
Errors []struct {
Message string `json:"message"`
} `json:"errors"`
}
if json.Unmarshal(data, &e) != nil || e.Message == "" {
return fmt.Errorf("GitHub API %d", status)
}
parts := []string{e.Message}
for _, d := range e.Errors {
if d.Message != "" {
parts = append(parts, d.Message)
}
}
return fmt.Errorf("%s", strings.Join(parts, ": "))
}
func repoPath(pr PR) string {
return "/repos/" + pr.Repository.Owner.Login + "/" + pr.Repository.Name
}
// graphqlErrors reports the first error a GraphQL response carries, if any.
func graphqlErrors(data []byte) error {
var r struct {
Errors []struct {
Message string `json:"message"`
} `json:"errors"`
}
if json.Unmarshal(data, &r) == nil && len(r.Errors) > 0 {
return fmt.Errorf("%s", r.Errors[0].Message)
}
return nil
}
// fetchViewer returns the signed-in user and their organizations in one request.
func fetchViewer() (string, []string, error) {
out, err := graphqlPOST(`{ viewer { login organizations(first: 100) { nodes { login } } } }`)
if err != nil {
return "", nil, err
}
if err := graphqlErrors(out); err != nil {
return "", nil, err
}
var r struct {
Data struct {
Viewer struct {
Login string `json:"login"`
Organizations struct {
Nodes []struct {
Login string `json:"login"`
} `json:"nodes"`
} `json:"organizations"`
} `json:"viewer"`
} `json:"data"`
}
if err := json.Unmarshal(out, &r); err != nil {
return "", nil, err
}
var orgs []string
for _, o := range r.Data.Viewer.Organizations.Nodes {
orgs = append(orgs, o.Login)
}
return r.Data.Viewer.Login, orgs, nil
}
// stripJSONControls drops terminal control characters (ESC, BEL, C1...) from a
// JSON reply, so nothing GitHub returns can drive the terminal. \n, \r and \t stay.
func stripJSONControls(b []byte) []byte {
out := make([]byte, 0, len(b))
for i := 0; i < len(b); {
switch c := b[i]; {
case c == '\\' && i+1 < len(b):
if b[i+1] == 'u' && i+6 <= len(b) {
if v, err := strconv.ParseUint(string(b[i+2:i+6]), 16, 16); err == nil && isControl(rune(v)) {
i += 6
continue
}
}
out = append(out, c, b[i+1]) // keeps escaped backslashes intact
i += 2
case c == 0x7f:
i++
case c == 0xc2 && i+1 < len(b) && b[i+1] >= 0x80 && b[i+1] <= 0x9f: // raw U+0080-U+009F
i += 2
default:
out = append(out, c)
i++
}
}
return out
}
func isControl(r rune) bool {
return (r < 0x20 && r != '\n' && r != '\r' && r != '\t') || (r >= 0x7f && r <= 0x9f)
}
// stripControls drops terminal control characters from plain text such as a patch.
func stripControls(s string) string {
return strings.Map(func(r rune) rune {
if isControl(r) {
return -1
}
return r
}, s)
}