Cli.js
3.57 KB
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
Cli = Ext.extend(Object, {
map: {
h: {
name: 'help',
desc: 'Prints this help display'
}
},
// Override this on a subclass of Cli.
// An array with a description on how to use this Cli.
// Each entry in the array is printed on a new line.
usage: [],
constructor : function() {
if (this.map !== this.superproto.map) {
this.map = Ext.apply({}, this.map, this.superproto.map);
}
this.initArguments();
try {
this.run();
}
catch (e) {
Logger.log(e);
if (e.stack) {
Logger.log('\n' + 'Stack trace:\n' + e.stack);
}
}
},
initArguments : function() {
var args = system.arguments,
ln = args.length,
parsedArgs = this.args = {},
curArg = null,
i, arg;
for (i = 0; i < ln; i++) {
arg = args[i];
if (arg[0] == '-') {
if (arg[1] == '-') {
curArg = arg.substr(2);
}
else if (arg.length == 2) {
curArg = this.map[arg[1]] ? this.map[arg[1]].name : arg[1];
}
else {
continue;
}
if (args[i + 1] && args[i + 1][0] != '-') {
parsedArgs[curArg] = args[i + 1] || true;
i++;
}
else {
parsedArgs[curArg] = true;
}
}
}
},
printUsage : function(message) {
var map = this.map,
usage = [''],
i, mapping;
if (!message) {
usage.push(this.name + ' version ' + this.version);
usage.push('Powered by Sencha Inc');
usage.push('');
usage.push('Available arguments:');
for (i in map) {
mapping = map[i];
usage.push(
' --' + mapping.name + ' -' + i
);
usage.push(' ' + (mapping.required ? '(required)' : '(optional)') + ' ' + (mapping.desc || ''));
usage.push('');
}
}
else {
usage.push(message);
}
usage.push('');
usage = usage.concat(this.usage);
usage.push('');
for (i = 0; i < usage.length; i++) {
Logger.log(usage[i]);
}
},
checkRequired : function() {
var args = this.args,
i, req;
for (i in this.map) {
if (this.map[i].required && args[this.map[i].name] === undefined) {
return i;
}
}
return true;
},
run : function() {
if (this.get('help')) {
this.printUsage();
return false;
}
var required = this.checkRequired();
if (required !== true) {
this.error('The --' + this.map[required].name + ' or -' + required + ' argument is required');
this.printUsage();
return false;
}
},
get : function(key) {
return this.args[key] || false;
},
set : function(key, value, ifNotExists) {
if (ifNotExists && this.get(key) !== false) {
return;
}
this.args[key] = value;
},
log : function(variable) {
Logger.log(variable);
},
error : function(error) {
throw error;
}
});