This repository has been archived by the owner on Jul 30, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
cli.js
344 lines (301 loc) · 8.22 KB
/
cli.js
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
#!/usr/bin/env node
"use strict"
// core
const { readFileSync, writeFileSync } = require("fs")
const { resolve, dirname, basename, format } = require("path")
// npm
const meow = require("meow")
const marked = require("marked")
const TerminalRenderer = require("marked-terminal")
const ProgressBar = require("progress")
const mkdirp = require("mkdirp").sync
const delay = require("delay")
// self
const graphqlGot = require(".")
const { githubColors, localFile, deburred } = graphqlGot
const { name } = require("./package.json")
const sparks = require("./lib/sparks")
const BAR_THROTTLE = 300
marked.setOptions({
renderer: new TerminalRenderer(),
})
const readme = marked(localFile("README.md"))
const normalizePath = (fn, ext) =>
resolve(
format({
dir: dirname(fn),
name: basename(fn, ext),
ext,
})
)
const run = async (cli) => {
let timing
let estimator
const startTime = Date.now()
const write = (content, ext) => {
const fn = normalizePath(cli.flags.output, ext)
mkdirp(dirname(fn))
writeFileSync(fn, content)
}
// FIXME: use last 5, 10 and 15 minutes
// to measure average durations
const makeApprox = (bar) =>
bar.curr &&
Math.round((((Date.now() - startTime) / 1000) * bar.total) / bar.curr)
try {
if (cli.flags.readme) {
return console.log(readme)
}
if (cli.flags.sparks) {
if (!cli.flags.config) {
throw new Error(
"When using the --sparks flag, the --config flag is required."
)
}
const dir = dirname(cli.flags.config)
const ghDataFn = normalizePath(resolve(dir, "data/gh-users.json"))
const json = await sparks(ghDataFn, cli.flags.verbose && ProgressBar)
const output = JSON.stringify(json, null, cli.flags.pretty ? " " : "")
if (!cli.flags.output) {
cli.flags.output = resolve(dir, "data/sparks.json")
}
write(output, ".json")
return
}
if (cli.flags.colors) {
const json = await githubColors()
const output = JSON.stringify(json, null, cli.flags.pretty ? " " : "")
if (!cli.flags.output && cli.flags.config) {
cli.flags.output = resolve(
dirname(cli.flags.config),
"data/language-colors.json"
)
}
if (cli.flags.output) {
write(output, ".json")
} else {
console.log(output)
}
return
}
if (cli.flags.config) {
const { locationSearch } = require(normalizePath(cli.flags.config))
if (locationSearch) {
if (cli.input.length) {
console.error("Ignoring command-line locations", cli.input)
console.log("Using config.js locationSearch field instead.")
}
if (typeof locationSearch === "string") {
cli.input = [locationSearch]
} else {
cli.input = locationSearch
}
}
}
if (!cli.input.length) {
throw new Error(`
Missing required location argument.
Prefer "montréal" over "montreal"
and use quotes to handle spaces in locations.
${cli.help}`)
}
const variables = {
created: cli.flags.before,
lastRepos: parseInt(cli.flags.lastRepos, 10),
}
if (cli.flags.verbose) {
const locations = deburred(cli.input)
if (locations.length > 1) {
console.error("Locations:", locations.join(", "))
} else {
console.error("Location:", locations[0])
}
}
let bar
const tick =
cli.flags.verbose &&
((n, { total, warn } = {}) => {
if (total) {
console.error("Expected results:", total)
}
if (total && !bar) {
if (process.stderr.columns < 60) {
console.error("Terminal is very narrow")
}
const width = Math.max(15, Math.min(100, process.stderr.columns) - 45)
// FIXME: split on 2 lines or more (or use multiple bars)
bar = new ProgressBar(
":bar :percent :elapseds :etas :approxs :rate users/s :current",
{
head: ">",
total,
width,
renderThrottle: BAR_THROTTLE,
}
)
} else {
if (!bar) {
return
}
if (warn) {
bar.interrupt(warn)
} else {
bar.tick(n, {
approx: makeApprox(bar),
})
}
}
})
if (cli.flags.verbose) {
timing = setInterval(() => {
if (!bar) {
return
}
bar.tick(0)
if (bar.complete) {
clearInterval(timing)
}
}, BAR_THROTTLE)
estimator = setInterval(() => {
if (bar && bar.total) {
const approx = makeApprox(bar)
if (!approx) {
return
}
const min = Math.floor(approx / 60)
const sec = approx - min * 60
bar.interrupt(
`Initial estimated duration: ${min}m${sec}s (${approx}s)`
)
clearInterval(estimator)
}
}, 20000)
}
if (cli.flags.repos) {
cli.flags.query = "projects"
/*
const oyoy = readFileSync(normalizePath(cli.flags.query, '.graphql'), 'utf-8')
// console.log('query (projects):', oyoy)
const elelbody = await graphqlGot(cli.input, oyoy)
// console.log('elelbody:', JSON.stringify(elelbody, null, ' '))
return
*/
}
const body = await graphqlGot(
cli.input,
cli.flags.query &&
readFileSync(normalizePath(cli.flags.query, ".graphql"), "utf-8"),
variables,
tick
)
clearInterval(estimator)
clearInterval(timing)
const output = JSON.stringify(body, null, cli.flags.pretty ? " " : "")
if (!cli.flags.output && cli.flags.config) {
cli.flags.output = resolve(
dirname(cli.flags.config),
"data/gh-users.json"
)
}
if (cli.flags.output) {
write(output, ".json")
}
await delay(500)
if (cli.flags.verbose) {
console.error("\n\nResults found:", body.users.length)
if (body.users.length) {
console.error("Last date:", body.users[body.users.length - 1].createdAt)
}
}
if (!cli.flags.output) {
console.log(output)
}
} catch (e) {
clearInterval(estimator)
clearInterval(timing)
await delay(500)
console.error("\n\n", e.errors ? e : e.toString())
console.error(e)
if (e.headers) {
console.error("headers:", e.headers)
}
if (e.data) {
console.error("data:", e.data)
}
process.exitCode = e.statusCodes || 127
}
}
run(
meow(
`
Usage
$ ${name} <location> [<location> ...]
Options
--readme Show readme
--verbose -v Verbose mode
--config Specify config file
--pretty -p Pretty output
--output -o Output to file
--repos Fetch repositories
--sparks -s Fetch contributions and generate week-based sparkline data
--colors -c Fetch GitHub language colors
--before -b Before date, 2018-06-21 or 2018-07-21T10:40:40Z
--last-repos -r Include these last repositories contributed to (50)
--query -q Query to run
Examples
$ ghraphql Montréal
// searches for montreal and montréal
$ ghraphql Montréal "saint jean"
// searches for montreal, montréal and "saint jean"
`,
{
flags: {
output: {
type: "string",
alias: "o",
},
config: {
type: "string",
},
before: {
type: "string",
alias: "b",
},
"last-repos": {
type: "string",
alias: "r",
},
query: {
type: "string",
alias: "q",
},
readme: {
type: "boolean",
},
help: {
type: "boolean",
alias: "h",
},
verbose: {
type: "boolean",
alias: "v",
},
pretty: {
type: "boolean",
alias: "p",
},
repos: {
type: "boolean",
},
sparks: {
type: "boolean",
alias: "s",
},
colors: {
type: "boolean",
alias: "c",
},
},
}
)
)