forked from mislav/hub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
277 lines (228 loc) · 7.06 KB
/
api.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
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
package commands
import (
"fmt"
"io"
"io/ioutil"
"os"
"regexp"
"strconv"
"strings"
"github.com/github/hub/github"
"github.com/github/hub/ui"
"github.com/github/hub/utils"
)
var cmdApi = &Command{
Run: apiCommand,
Usage: "api [-it] [-X <METHOD>] [-H <HEADER>] [--cache <TTL>] <ENDPOINT> [-F <FIELD>|--input <FILE>]",
Long: `Low-level GitHub API request interface.
## Options:
-X, --method <METHOD>
The HTTP method to use for the request (default: "GET"). The method is
automatically set to "POST" if '--field', '--raw-field', or '--input' are
used.
Use '-XGET' to force serializing fields into the query string for the GET
request instead of JSON body of the POST request.
-F, --field <KEY>=<VALUE>
Data to serialize with the request. <VALUE> has some magic handling; use
'--raw-field' for sending arbitrary string values.
If <VALUE> starts with "@", the rest of the value is interpreted as a
filename to read the value from. Use "@-" to read from standard input.
If <VALUE> is "true", "false", "null", or looks like a number, an
appropriate JSON type is used instead of a string.
It is not possible to serialize <VALUE> as a nested JSON array or hash.
Instead, construct the request payload externally and pass it via
'--input'.
Unless '-XGET' was used, all fields are sent serialized as JSON within the
request body. When <ENDPOINT> is "graphql", all fields other than "query"
are grouped under "variables". See
<https://graphql.org/learn/queries/#variables>
-f, --raw-field <KEY>=<VALUE>
Same as '--field', except that it allows values starting with "@", literal
strings "true", "false", and "null", as well as strings that look like
numbers.
--input <FILE>
The filename to read the raw request body from. Use "-" to read from standard
input. Use this when you want to manually construct the request payload.
-H, --header <KEY>:<VALUE>
Set an HTTP request header.
-i, --include
Include HTTP response headers in the output.
-t, --flat
Parse response JSON and output the data in a line-based key-value format
suitable for use in shell scripts.
--color[=<WHEN>]
Enable colored output even if stdout is not a terminal. <WHEN> can be one
of "always" (default for '--color'), "never", or "auto" (default).
--cache <TTL>
Cache successful responses to GET requests for <TTL> seconds.
When using "graphql" as <ENDPOINT>, caching will apply to responses to POST
requests as well. Just make sure to not use '--cache' for any GraphQL
mutations.
<ENDPOINT>
The GitHub API endpoint to send the HTTP request to (default: "/").
To learn about available endpoints, see <https://developer.github.com/v3/>.
To make GraphQL queries, use "graphql" as <ENDPOINT> and pass '-F query=QUERY'.
If the literal strings "{owner}" or "{repo}" appear in <ENDPOINT> or in the
GraphQL "query" field, fill in those placeholders with values read from the
git remote configuration of the current git repository.
## Examples:
# fetch information about the currently authenticated user as JSON
$ hub api user
# list user repositories as line-based output
$ hub api --flat users/octocat/repos
# post a comment to issue #23 of the current repository
$ hub api repos/{owner}/{repo}/issues/23/comments --raw-field "body=Nice job!"
# perform a GraphQL query read from a file
$ hub api graphql -F query=@path/to/myquery.graphql
## See also:
hub(1)
`,
}
func init() {
CmdRunner.Use(cmdApi)
}
func apiCommand(cmd *Command, args *Args) {
path := ""
if !args.IsParamsEmpty() {
path = args.GetParam(0)
}
method := "GET"
if args.Flag.HasReceived("--method") {
method = args.Flag.Value("--method")
} else if args.Flag.HasReceived("--field") || args.Flag.HasReceived("--raw-field") || args.Flag.HasReceived("--input") {
method = "POST"
}
cacheTTL := args.Flag.Int("--cache")
params := make(map[string]interface{})
for _, val := range args.Flag.AllValues("--field") {
parts := strings.SplitN(val, "=", 2)
if len(parts) >= 2 {
params[parts[0]] = magicValue(parts[1])
}
}
for _, val := range args.Flag.AllValues("--raw-field") {
parts := strings.SplitN(val, "=", 2)
if len(parts) >= 2 {
params[parts[0]] = parts[1]
}
}
headers := make(map[string]string)
for _, val := range args.Flag.AllValues("--header") {
parts := strings.SplitN(val, ":", 2)
if len(parts) >= 2 {
headers[parts[0]] = strings.TrimLeft(parts[1], " ")
}
}
host := ""
owner := ""
repo := ""
localRepo, localRepoErr := github.LocalRepo()
if localRepoErr == nil {
var project *github.Project
if project, localRepoErr = localRepo.MainProject(); localRepoErr == nil {
host = project.Host
owner = project.Owner
repo = project.Name
}
}
if host == "" {
defHost, err := github.CurrentConfig().DefaultHostNoPrompt()
utils.Check(err)
host = defHost.Host
}
if path == "graphql" && params["query"] != nil {
query := params["query"].(string)
query = strings.Replace(query, quote("{owner}"), quote(owner), 1)
query = strings.Replace(query, quote("{repo}"), quote(repo), 1)
variables := make(map[string]interface{})
for key, value := range params {
if key != "query" {
variables[key] = value
}
}
if len(variables) > 0 {
params = make(map[string]interface{})
params["variables"] = variables
}
params["query"] = query
} else {
path = strings.Replace(path, "{owner}", owner, 1)
path = strings.Replace(path, "{repo}", repo, 1)
}
var body interface{}
if args.Flag.HasReceived("--input") {
fn := args.Flag.Value("--input")
if fn == "-" {
body = os.Stdin
} else {
fi, err := os.Open(fn)
utils.Check(err)
body = fi
defer fi.Close()
}
} else {
body = params
}
gh := github.NewClient(host)
response, err := gh.GenericAPIRequest(method, path, body, headers, cacheTTL)
utils.Check(err)
args.NoForward()
out := ui.Stdout
colorize := colorizeOutput(args.Flag.HasReceived("--color"), args.Flag.Value("--color"))
success := response.StatusCode < 300
parseJSON := args.Flag.Bool("--flat")
if !success {
jsonType, _ := regexp.MatchString(`[/+]json(?:;|$)`, response.Header.Get("Content-Type"))
parseJSON = parseJSON && jsonType
}
if args.Flag.Bool("--include") {
fmt.Fprintf(out, "%s %s\r\n", response.Proto, response.Status)
response.Header.Write(out)
fmt.Fprintf(out, "\r\n")
}
if parseJSON {
utils.JSONPath(out, response.Body, colorize)
} else {
io.Copy(out, response.Body)
}
response.Body.Close()
if !success {
os.Exit(22)
}
}
const (
trueVal = "true"
falseVal = "false"
nilVal = "null"
)
func magicValue(value string) interface{} {
switch value {
case trueVal:
return true
case falseVal:
return false
case nilVal:
return nil
default:
if strings.HasPrefix(value, "@") {
return string(readFile(value[1:]))
} else if i, err := strconv.Atoi(value); err == nil {
return i
} else {
return value
}
}
}
func readFile(file string) (content []byte) {
var err error
if file == "-" {
content, err = ioutil.ReadAll(os.Stdin)
} else {
content, err = ioutil.ReadFile(file)
}
utils.Check(err)
return
}
func quote(s string) string {
return fmt.Sprintf("%q", s)
}