forked from andyburke/boxcutter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli.js
executable file
·102 lines (79 loc) · 2.47 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
#!/usr/bin/env node
'use strict';
const help = require( './help.json' );
const argv = require( 'yargs' )
.usage( help.usage.join( '\n' ) )
.demand( 1 )
.argv;
const Boxcutter = require( './index.js' );
const path = require( 'path' );
let boxcutter = Object.assign( {}, Boxcutter.Boxcutter );
const directory = process.cwd();
let directoryElements = directory.split( path.sep );
let loaded = false;
const jsonFileName = argv.file ? argv.file : 'package.json';
let jsonFile = null;
do {
jsonFile = path.sep + path.join.apply( path, directoryElements.concat( [ jsonFileName ] ) );
try {
boxcutter.load( jsonFile );
loaded = true;
}
catch( ex ) {
continue;
}
} while( !loaded && directoryElements.pop() );
if ( !loaded ) {
console.error( `Could not locate file ${jsonFileName} in directory ancestry tree.` );
process.exit( 1 );
}
const command = argv._.shift();
const commands = {
get: function() {
const key = argv._.shift();
if ( !key ) {
console.error( 'You must specify a key to get.' );
process.exit( 1 );
}
const value = boxcutter.get( key );
console.log( typeof value === 'object' ? JSON.stringify( value, null, argv.indent || 2 ) : value );
process.exit( 0 );
},
set: function() {
const key = argv._.shift();
if ( !key ) {
console.error( 'You must specify a key to set.' );
process.exit( 1 );
}
const value = argv._.shift();
boxcutter.set( key, value );
boxcutter.save( jsonFile, function( error ) {
if ( error ) {
console.error( error );
process.exit( 1 );
}
process.exit( 0 );
} );
},
help: function() {
const subject = argv._.shift();
const helpOutput = help.commands[ subject ];
if ( !subject ) {
console.log( help.commands[ 'unknown command' ].join( '\n' ) );
}
else if ( !helpOutput ) {
console.error( 'Unknown command: ' + subject );
console.error( help.commands[ 'unknown command' ].join( '\n' ) );
}
else {
console.log( helpOutput.join( '\n' ) );
}
process.exit( 0 );
},
undefined: function() {
console.error( 'Unknown command: ' + command );
process.exit( 1 );
}
};
const action = commands[ command ] || commands[ undefined ];
action();