-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathjase.js
99 lines (83 loc) · 2.54 KB
/
jase.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
#!/usr/bin/env node
'use strict';
var fs = require('fs');
var thing = require('core-util-is');
var minimist = require('minimist');
var jase = require('./index');
function parse(obj) {
try {
return JSON.parse(obj);
} catch (err) {
return obj;
}
}
// Sort out command line arguments
var opts, argv;
opts = {
// Save kept for backward compat.
string: ['set', 'save'],
alias: {
file: ['f'],
set: ['s'],
delete: ['d'],
indent: ['i']
},
default: {
indent: 2
}
};
argv = minimist(process.argv.slice(2), opts);
if (argv._.length === 0) {
console.log('Usage:');
console.log(' jase <key> [options]');
console.log('');
console.log('Arguments:');
console.log(' <key> A dot (`.`) delimited key which references the value that should be returned or overwritten.');
console.log(' Escape dot characters in key names using \'\\\', for example \'config.foo\\.bar\'.');
console.log('');
console.log('Options:');
console.log(' -f, --file <file> The JSON file to read.');
console.log(' -s, --set <value> The new value to set for the provided key.');
console.log(' -d, --delete Delete the provided key.');
console.log(' -i, --indent <spaces> The number of spaces to indent the newly written JSON.');
console.log('');
console.log('Example:');
console.log(' jase ./package.json scripts.test');
console.log('');
return;
}
// Process file.
var key, chunks, stream;
key = argv._[0];
chunks = [];
stream = argv.file ? fs.createReadStream(argv.file) : process.stdin;
stream.on('readable', function () {
var chunk;
while ((chunk = this.read()) !== null) {
chunks.push(chunk);
}
});
stream.on('end', function () {
var json, result, saveValue;
json = Buffer.concat(chunks).toString('utf8');
json = JSON.parse(json);
// Preserve fallback to `save` for backward compat reasons.
if (('save' in argv) || ('set' in argv)) {
saveValue = parse(argv.save || argv.set || '');
result = jase.set(json, key, saveValue);
} else if (argv.delete) {
result = jase.del(json, key);
} else {
result = jase.get(json, key);
}
if (result === undefined) {
process.stderr.write('Error: \'' + key + '\' not found.');
process.exit(1);
return;
}
if (!thing.isPrimitive(result)) {
result = JSON.stringify(result, null, argv.indent);
}
process.stdout.write(result);
process.exit(0);
});