This repository has been archived by the owner on Jan 6, 2025. It is now read-only.
forked from clinicjs/node-clinic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbin.js
executable file
·502 lines (448 loc) · 13.2 KB
/
bin.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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
#! /usr/bin/env node
'use strict'
const fs = require('fs')
const path = require('path')
const url = require('url')
const open = require('open')
const ora = require('ora')
const shellEscape = require('any-shell-escape')
const commist = require('commist')
const minimist = require('minimist')
const subarg = require('subarg')
const dargs = require('dargs')
const execspawn = require('execspawn')
const envString = require('env-string')
const xargv = require('cross-argv')
const crypto = require('crypto')
const Insight = require('insight')
const updateNotifier = require('update-notifier')
const { promisify } = require('util')
const pkg = require('./package.json')
const helpFormatter = require('./lib/help-formatter.js')
const clean = require('./lib/clean.js')
const GA_TRACKING_CODE = 'UA-29381785-8'
const DEFAULT_DEST = '.clinic'
const insight = new Insight({
trackingCode: GA_TRACKING_CODE,
pkg
})
/* istanbul ignore else: Always used in tests to avoid polluting data */
if ('NO_INSIGHT' in process.env) {
Object.defineProperty(insight, 'optOut', {
get: () => true
})
}
checkForUpdates()
const result = commist()
.register('clean', function (argv) {
const args = minimist(argv, {
alias: {
help: 'h'
}
})
if (args.help) {
printHelp('clinic-clean')
} else {
// support --path to support failure testing
clean(args.path || '.', function (err) {
if (err) throw err
})
}
})
.register('doctor', catchify(async function (argv) {
const version = require('@clinic/doctor/package.json').version
const args = subarg(argv, {
alias: {
help: 'h',
version: 'v'
},
boolean: [
'help',
'version',
'collect-only',
'open',
'debug'
],
string: [
'visualize-only',
'sample-interval',
'on-port',
'dest',
'stop-delay',
'name'
],
default: {
'sample-interval': '10',
open: true,
debug: false,
dest: DEFAULT_DEST
},
'--': true
})
if (args.version) {
printVersion(version)
} else if (args.help) {
printHelp('clinic-doctor', version)
} else if (args['visualize-only'] || args['--'].length > 1) {
checkArgs('doctor', args, 'clinic-doctor', version)
await trackTool('doctor', args, version)
await runTool('doctor', require('@clinic/doctor'), version, args, { color: 'green' })
} else {
printHelp('clinic-doctor', version)
process.exit(1)
}
}))
.register('bubbleprof', catchify(async function (argv) {
const version = require('@clinic/bubbleprof/package.json').version
const args = subarg(argv, {
alias: {
help: 'h',
version: 'v'
},
boolean: [
'help',
'version',
'collect-only',
'open',
'debug'
],
string: [
'visualize-only',
'dest',
'stop-delay',
'name'
],
default: {
open: true,
debug: false,
dest: DEFAULT_DEST
},
'--': true
})
if (args.version) {
printVersion(version)
} else if (args.help) {
printHelp('clinic-bubbleprof', version)
} else if (args['visualize-only'] || args['--'].length > 1) {
checkArgs('bubbleprof', args, 'clinic-bubbleprof', version)
await trackTool('bubbleprof', args, version)
await runTool('bubbleprof', require('@clinic/bubbleprof'), version, args, { color: 'blue' })
} else {
printHelp('clinic-bubbleprof', version)
process.exit(1)
}
}))
.register('flame', catchify(async function (argv) {
const version = require('@clinic/flame/version')
const args = subarg(argv, {
alias: {
help: 'h',
version: 'v'
},
boolean: [
'help',
'version',
'collect-only',
'open',
'debug',
'kernel-tracing'
],
string: [
'visualize-only',
'dest',
'stop-delay',
'name'
],
default: {
open: true,
debug: false,
dest: DEFAULT_DEST
},
'--': true
})
if (args.version) {
printVersion(version)
} else if (args.help) {
printHelp('clinic-flame', version)
} else if (args['visualize-only'] || args['--'].length > 1) {
checkArgs('flame', args, 'clinic-flame', version)
await trackTool('flame', args, version)
await runTool('flame', require('@clinic/flame'), version, args, { color: 'yellow' })
} else {
printHelp('clinic-flame', version)
process.exit(1)
}
}))
.register('heapprofiler', catchify(async function (argv) {
const version = require('@clinic/heap-profiler/package.json').version
const args = subarg(argv, {
alias: {
help: 'h',
version: 'v'
},
boolean: [
'help',
'version',
'collect-only',
'open',
'debug'
],
string: [
'visualize-only',
'dest',
'stop-delay',
'name'
],
default: {
open: true,
debug: false
},
'--': true
})
if (args.version) {
printVersion(version)
} else if (args.help) {
printHelp('clinic-heap-profiler', version)
} else if (args['visualize-only'] || args['--'].length > 1) {
checkArgs('heap-profiler', args, 'clinic-heap-profiler', version)
await trackTool('heap-profiler', args, version)
await runTool('heap-profiler', require('@clinic/heap-profiler'), version, args, { color: 'yellow' })
} else {
printHelp('clinic-heap-profiler', version)
process.exit(1)
}
}))
.parse(xargv(process.argv.slice(2)))
// not `clinic doctor`, `clinic flame`, and not `clinic bubbleprof`
if (result !== null) {
const version = require('./package.json').version
const args = minimist(process.argv.slice(1), {
alias: {
help: 'h',
version: 'v'
},
boolean: [
'help',
'version'
]
})
if (args.version) {
printVersion(version)
} else if (args.help) {
printHelp('clinic', version)
} else {
printHelp('clinic', version)
process.exit(1)
}
}
function catchify (asyncFn) {
return function (...args) {
asyncFn(...args).catch((err) => {
console.error(err.stack)
process.exit(1)
})
}
}
function checkArgs (toolname, args, help, version) {
if (args['--'] && args['--'].length >= 1 && !/^node(\.exe)?$/.test(path.basename(args['--'][0]))) {
console.error(`Clinic.js must be called with a \`node\` command line: \`clinic ${toolname} -- node script.js\`\n`)
printHelp(help, version)
process.exit(1)
}
}
function checkMetricsPermission (cb) {
/* istanbul ignore if: tracking intentionally disabled when running tests */
if (insight.optOut === undefined) {
return promisify(insight.askPermission).call(
insight,
'May Clinic.js report anonymous usage statistics to improve the tool over time?'
)
}
return Promise.resolve()
}
async function trackTool (toolName, args, toolVersion) {
let action = 'run'
if (args['visualize-only']) {
action = 'visualize-only'
} else if (args['collect-only']) {
action = 'collect-only'
}
await checkMetricsPermission()
insight.track(toolName, action)
insight.trackEvent({
category: toolName,
action,
label: toolVersion
})
}
async function runTool (toolName, Tool, version, args, uiOptions) {
const autocannonOpts = typeof args.autocannon === 'string'
// --autocannon /url
? { _: [args.autocannon] }
// --autocannon [ /url -m POST --flags... ]
: args.autocannon
const autocannonPath = require.resolve('autocannon')
const onPort = autocannonOpts
? `node ${shellEscape(autocannonPath)} ${shellEscape(dargs(autocannonOpts))}`
: args['on-port']
if (!onPort && !args['visualize-only']) {
if (args['collect-only']) {
console.log('To stop data collection press: Ctrl + C')
} else {
console.log('To generate the report press: Ctrl + C')
}
}
const openLocalFile = args.open
const tool = new Tool({
sampleInterval: parseInt(args['sample-interval'], 10),
detectPort: !!onPort,
dest: args.dest,
debug: args.debug,
kernelTracing: args['kernel-tracing'],
name: args.name
})
const stopDelayMs = parseInt(args['stop-delay'])
const spinner = ora({
text: 'Analysing data',
color: uiOptions.color,
stream: process.stdout,
spinner: 'bouncingBar'
})
/* istanbul ignore next */
tool.on('warning', function (warning) {
console.log('Warning: ' + warning)
})
tool.on('port', function (port, proc, cb) {
process.env.PORT = port
// inline the PORT env to make it easier for cross platform usage
execspawn(envString(onPort, { PORT: port }), { stdio: 'inherit' })
.on('exit', () => {
if (stopDelayMs) {
tool.emit('status', 'Waiting to close the process')
if (spinner.isEnabled && !spinner.isSpinning) spinner.start()
setTimeout(() => cb(), stopDelayMs)
} else {
cb()
}
})
})
tool.on('analysing', function (message = 'Analysing data') {
/* istanbul ignore if: isEnabled is always false when spawn process. See: https://github.com/sindresorhus/ora#isenabled */
if (spinner.isEnabled) {
spinner.text = message
if (!spinner.isSpinning) {
spinner.start()
}
} else {
console.log(message)
}
})
tool.on('status', status)
function status (message) {
/* istanbul ignore next: isEnabled is always false when spawn process. See: https://github.com/sindresorhus/ora#isenabled */
if (spinner.isEnabled) {
spinner.text = message
} else {
console.log(message)
}
}
/* istanbul ignore next: SIGINT by spawned process is tricky */
function onsigint () {
status('Received Ctrl+C, closing process...')
if (!spinner.isSpinning) spinner.start()
}
let defer
const promise = new Promise((resolve, reject) => {
defer = { resolve, reject }
})
if (args['collect-only']) {
process.once('SIGINT', onsigint)
tool.collect(args['--'], function (err, filename) {
if (err) return defer.reject(err)
/* istanbul ignore if: isEnabled is always false when spawn process. See: https://github.com/sindresorhus/ora#isenabled */
if (spinner.isEnabled) {
spinner.stop()
spinner.stream.write(`${spinner.text}\n`)
}
defer.resolve({ data: filename })
})
} else if (args['visualize-only']) {
const dataPath = args['visualize-only'].replace(/[\\/]$/, '')
viz(toolName, dataPath, function (err) {
if (err) return defer.reject(err)
defer.resolve({ data: dataPath, visualizer: `${dataPath}.html` })
})
} else {
process.once('SIGINT', onsigint)
tool.collect(args['--'], function (err, filename) {
if (err) return defer.reject(err)
viz(toolName, filename, function (err) {
if (err?.code === 'ENOENT' && err?.message.includes('processstat')) return defer.reject(new Error('Process forcefully closed before processstat file generation'))
if (err) return defer.reject(err)
/* istanbul ignore if: isEnabled is always false when spawn process. See: https://github.com/sindresorhus/ora#isenabled */
if (spinner.isEnabled) {
spinner.stop()
spinner.stream.write(`${spinner.text}\n`)
}
// open HTML file in default browser
/* istanbul ignore if: we don't want to open a browser in `npm test` */
if (openLocalFile) {
open('file://' + path.resolve(filename + '.html'), { wait: false })
}
defer.resolve({ data: filename, visualizer: `${filename}.html` })
})
})
}
const outputs = await promise
if (outputs.visualizer) {
console.log(`Generated HTML file is ${url.pathToFileURL(outputs.visualizer)}`)
} else {
console.log(`Output file is ${outputs.data}`)
}
// rest is util functions
function viz (toolName, filename, cb) {
// Before getting to the tool, make sure the filename exists. We don't care whether is a file or a directory.
fs.access(filename, function (err) {
if (err) {
return cb(new Error('No data found.'))
}
const html = filename + '.html'
tool.visualize(filename, html, function (err) {
if (err) return cb(err)
hash(html, function (err, h) {
/* istanbul ignore next */ if (err) return cb(err)
const info = {
tool: toolName,
toolVersion: version,
hash: h.toString('hex')
}
fs.appendFile(html, `<!-- ${JSON.stringify(info)} -->\n`, cb)
})
})
})
}
}
function hash (filename, cb) {
const sha = crypto.createHash('sha512')
sha.update('clinic\n')
fs.createReadStream(filename)
.on('data', data => sha.update(data))
.on('end', () => cb(null, sha.digest()))
.on('error', cb)
}
function printVersion (version) {
console.log('v' + version)
}
function printHelp (name, version) {
const filepath = path.resolve(__dirname, 'docs', name + '.txt')
const usage = helpFormatter(fs.readFileSync(filepath), version)
console.log(usage)
}
function checkForUpdates () {
updateNotifier({
pkg
}).notify({
isGlobal: true,
defer: false
})
}