-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
99 lines (84 loc) · 2.46 KB
/
index.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
var fs = require('fs');
var util = require('util');
var status = require('./lib/status');
var request = require('request');
var program = require('commander');
var commands = require('./commands')(program);
var packageJson = require('./package.json');
program.LOG_PATH = process.env.HOME + '/.cli-log';
// Initialize cli options
program
.version(packageJson.version)
.usage('<command> [options]')
.option('-d, --debug', 'show debug info');
// Initialize prompt
program.prompt = require('prompt');
program.prompt.message = '';
program.prompt.delimiter = '';
program.prompt.colors = false;
// Turn off colors when non-interactive
var colors = require('colors');
colors.mode = process.stdout.isTTY ? colors.mode : 'none';
// Setup logging and messaging
var logMessages = [];
program.log = (function (debugMode) {
return function _log(logEntry, noPrint) {
logMessages.push(logEntry);
if (!noPrint && debugMode) {
console.log('--debug-- '.cyan + logEntry);
}
};
})(process.argv.indexOf('--debug') >= 0);
program.successMessage = function successMessage() {
var msg = util.format.apply(this, arguments);
program.log('Success: ' + msg, true);
console.log(msg.green);
};
program.errorMessage = function errorMessage() {
var msg = util.format.apply(this, arguments);
program.log('Error: ' + msg, true);
console.log(msg.red);
};
program.handleError = function handleError(err, exitCode) {
if (err) {
if (err.message) {
program.errorMessage(err.message);
} else {
program.errorMessage(err);
}
}
console.log('For more information see: ' + program.LOG_PATH);
fs.writeFileSync(program.LOG_PATH, logMessages.join('\n') + '\n');
process.exit(exitCode || 1);
};
// Create request wrapper
program.request = function (opts, next) {
if (program.debug) {
program.log('REQUEST: '.bold + JSON.stringify(opts, null, 2));
} else {
program.log(opts.uri);
}
status.start();
return request(opts, function (err, res, body) {
status.stop();
if (err) {
if (program.debug) {
program.errorMessage(err.message);
}
return next(err, res, body);
}
else {
if (program.debug) {
program.log('RESPONSE: '.bold + JSON.stringify(res.headers, null, 2));
program.log('BODY: '.bold + JSON.stringify(res.body, null, 2));
}
return next(err, res, body);
}
});
};
program.on('*', function() {
console.log('Unknown Command: ' + program.args.join(' '));
program.help();
});
// Process Commands
program.parse(process.argv);