-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcuisinart.js
220 lines (201 loc) · 6.91 KB
/
cuisinart.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
var assert = require('assert');
var helpCommand = require('./commands/help');
var async = require('async');
var defaultCommands = [
helpCommand,
require('./commands/version')
];
var cuisinart = module.exports = {};
var optionMatches = function(args,option){
var bothFlags = option.flag && option.longFlag;
var pattern = '(';
if(option.flag){
pattern += ('\\s-' + option.flag);
}
if(option.longFlag){
if(bothFlags) pattern += '|'
pattern += ('\\s--' + option.longFlag);
}
pattern += ')';
pattern += '(?:\\s|$)([^\\s]+)?';
var regex = new RegExp(pattern);
var matches = (' ' + args.join(' ')).match(regex);
return matches && matches[0] ? matches.splice(1) : matches;
};
var matchOption = function(args,option){
var matches = optionMatches(args,option);
if(matches){
return matches[1] ? matches[1].trim() : true;
} else {
return false;
}
};
var matchCommand = function(args,command){
if(command.name){
var regex = new RegExp('(?:\\s|^)(' + command.name + ')(?:\\s|$)');
var matches = args.join(' ').match(regex);
return matches && matches[1] ? matches[1].trim() : false;
} else {
return false;
}
};
var usageLength = function(option){
// check the length of these arguments, so we know how much to indent the options.
var length = (option.flag ? option.flag.length + 1 : 0)
+ (option.longFlag ? option.longFlag.length + 2 : 0)
+ (option.flag && option.longFlag ? 2 : 0) + 2;
return length;
};
var optionMaxLength = function(command){
return (command.options || []).reduce(function(p,option){ return Math.max(p,usageLength(option)); },0);
};
var printUsage = function(command){
var commandPadding = ' ';
var optionPadding = ' ';
var commandString = command.usage;
var maxLength = optionMaxLength(command);
if (!command.root) {
console.log();
var description = command.description ? ' - ' + command.description : '';
console.log(commandPadding + this._name + ' ' + command.name + description);
console.log();
} else {
optionPadding = commandPadding;
}
(command.options || []).forEach(function(option){
var string = '';
if(option.flag) string += ('-' + option.flag);
if(option.flag && option.longFlag) string += ', ';
if(option.longFlag) string += ('--' + option.longFlag);
var numSpaces = maxLength - string.length;
var spaces = new Array(numSpaces + 1).join(' ');
console.log(optionPadding + string + spaces + (option.description || ''));
});
};
var hasCallback = function(fn){
// check if the following are true:
// 1. we have a named argument
// one of:
// 2a. we call, apply, or invoke a variable by that name in the method body
// 2b. we pass a variable of that name as an argument to another function.
// This gives us a good estimate if the function is async or not.
var fnString = fn.toString();
var argMatches = fnString.match(/^function \((?:.*[,\s]+)?([\w]+)\){/);
if(!argMatches) return false;
fnString = fnString.replace(argMatches[0],'').replace(/\n/g,'');
var lastArg = argMatches[1];
var cbPattern = new RegExp(';?[\\s\\S]*' + lastArg + '\\.?(call|apply|bind)?\\([^\\)]*\\)[\\s\\S]*;?');
var argPattern = new RegExp('\\w(\\(|\\(.+?[,\\s])'+lastArg+'([,\\s][^\\)]+\\)|\\))');
return cbPattern.test(fnString) || argPattern.test(fnString);
};
var unmatchedArgs = function(){
var args = this.args;
var argsString = Array.prototype.slice.call(args,1).join('##');
this._commands.forEach(function(command){
var match = matchCommand(args,command);
if(match){
argsString = argsString.replace(match,'');
(command.options || []).forEach(function(option){
var optionMatch = optionMatches(args,option);
if(optionMatch){
argsString = argsString.replace(optionMatch.join('##').trim(),'');
}
});
}
});
return argsString.split('##').filter(function(v){return v;});
};
cuisinart.program = function(name){
assert(name,'programs must have names.');
var self = this;
// properties
self._name = name;
self._version;
self._usage;
self._description;
self._commands = defaultCommands;
self._baseArgs = [];
self._args = [];
// setters
self.version = function(version){
self._version = version;
return self;
};
self.usage = function(usage){
self._usage = usage;
return self;
};
self.description = function(description){
self._description = description;
return self;
};
self.command = function(command){
assert(command.root || command.name,'Non-root commands must have a name');
assert(!command.options || Array.isArray(command.options),'Command options must be an array');
if(command.options){
command.options.forEach(function(option){
assert(!option.flag || (typeof option.flag == 'string' && option.flag.length == 1),'Option flags must be single letter strings.');
assert(!option.longFlag || (typeof option.longFlag == 'string' && option.longFlag.length > 1),'Option long flags must be multiple letter strings.');
assert(!option.description || (typeof option.description == 'string'),'Option description must be a string.');
});
}
// TODO: fully validate this command.
// add the command to our commands
self._commands.push(command);
return self;
}
self.baseArgs = function(){
self._baseArgs = self._baseArgs.concat(Array.prototype.slice.call(arguments));
return self;
};
// methods
self.printUsage = printUsage;
self.run = function(command,args,done){
// trim off the command name
args = args.slice(1);
var optionMap = (command.options || []).reduce(function(o,option){
var value = matchOption(args,option);
if(value){
o[option.name] = value;
}
return o;
},{});
this.unmatchedArgs = unmatchedArgs.apply(this);
var calledBack;
var complete = function(){
if(calledBack) return;
calledBack = true;
var args = Array.prototype.slice.call(arguments);
if(command.stop) args[0] = new Error('complete');
done.apply(null,args);
};
command.run.apply(self,[optionMap].concat(self._baseArgs,complete));
// if we don't detect a callback, assume that this is synchronous.
if(!hasCallback(command.run)){
// console.log('running ' + command.name + ' synchronously.');
complete();
}
};
self.parse = function(args,callback){
args = Array.prototype.slice.call(args,2);
self.args = args;
var matchedCommands = 0;
async.mapSeries(self._commands,function(command,done){
var matched = matchCommand(args,command);
if(matched){
matchedCommands++;
self.run(command,args,done);
} else {
done();
}
},function(err,results){
results = results.filter(function(r){ return r; });
if(!matchedCommands){
// print the help if nothing matches
helpCommand.run.apply(self);
}
if(callback) callback(err,results);
});
};
return self;
};