forked from octokit/octokit.js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate.js
More file actions
executable file
·289 lines (257 loc) · 10.5 KB
/
generate.js
File metadata and controls
executable file
·289 lines (257 loc) · 10.5 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
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
#!/usr/bin/env node
/** section: github, internal
* class ApiGenerator
*
* Copyright 2012 Cloud9 IDE, Inc.
*
* This product includes software developed by
* Cloud9 IDE, Inc (http://c9.io).
*
* Author: Mike de Boer <mike@c9.io>
**/
'use strict';
function toCamelCase(str, upper) {
upper = upper || false;
str = str.toLowerCase().replace(/(?:(^.)|(\s+.)|(-.))/g, function (match) {
return match.charAt(match.length - 1).toUpperCase();
});
if (!upper) {
str = str.charAt(0).toLowerCase() + str.substr(1);
}
return str;
}
var Fs = require('fs');
var Path = require('path');
var Optimist = require('optimist');
var IndexTpl = Fs.readFileSync(__dirname + '/templates/index.js.tpl', 'utf8');
var SectionTpl = Fs.readFileSync(__dirname + '/templates/section.js.tpl', 'utf8');
var HandlerTpl = Fs.readFileSync(__dirname + '/templates/handler.js.tpl', 'utf8');
var AfterRequestTpl = Fs.readFileSync(__dirname + '/templates/after_request.js.tpl', 'utf8');
//var TestSectionTpl = Fs.readFileSync(__dirname + '/templates/test_section.js.tpl', 'utf8');
var TestHandlerTpl = Fs.readFileSync(__dirname + '/templates/test_handler.js.tpl', 'utf8');
var main = module.exports = function (routes, tests/*, restore*/) {
console.log('Generating');
var dir = Path.join(__dirname, 'lib', 'api');
// If we're in restore mode, move .bak file back to their original position
// and short-circuit.
// if (restore) {
// var bakRE = /\.bak$/;
// var files = Fs.readdirSync(dir).filter(function (file) {
// return bakRE.test(file);
// }).forEach(function (file) {
// var from = Path.join(dir, file);
// var to = Path.join(dir, file.replace(/\.bak$/, ''));
// Fs.renameSync(from, to);
// console.log('Restored: ' + file);
// });
// return;
// }
var defines = routes.defines;
delete routes.defines;
var headers = defines['response-headers'];
// cast header names to lowercase.
if (headers && headers.length) {
headers = headers.map(function (header) {
return header.toLowerCase();
});
}
var sections = {};
var testSections = {};
function createComment(paramsStruct, indent) {
var params = Object.keys(paramsStruct);
var comment = [
'/**',
indent + ' * @function',
indent + ' * @param {Object} msg Object that contains the parameters and their values to be sent to the server.'
];
comment.push(indent + ' * @param {Object} [msg.headers] Key/ value pair ' +
'of request headers to pass along with the HTTP request. Valid headers are: ' +
defines['request-headers'].join(', ')
);
if (!params.length) {
comment.push(indent + ' * No other params, simply pass an empty Object literal `{}`');
}
var paramName, def, line;
for (var i = 0, l = params.length; i < l; i = i + 1) {
paramName = params[i];
if (paramName.charAt(0) === '$') {
paramName = paramName.substr(1);
if (!defines.params[paramName]) {
console.error('Invalid variable parameter name substitution; param ' +
paramName +
' not found in defines block ');
process.exit(1);
} else {
def = defines.params[paramName];
}
} else {
def = paramsStruct[paramName];
}
line = indent + ' * @param {' + (def.type || '*') + '}';
line += ' ';
line += def.required ? 'msg.' + paramName : '[msg.' + paramName + ']';
line += ' ';
if (def.description){
line += def.description;
line += ' ';
}
if (def.validation){
line += 'Validation rule: ` ' + def.validation + ' `.';
}
comment.push(line);
}
comment.push(indent + ' * @param {Function} callback function to call when the request is finished ' +
'with an error as first argument and result data as second argument.');
return comment.join('\n') + '\n' + indent + ' **/';
}
function getParams(paramsStruct, indent) {
var params = Object.keys(paramsStruct);
if (!params.length){
return '{}';
}
var values = [];
var paramName, def;
for (var i = 0, l = params.length; i < l; i = i + 1) {
paramName = params[i];
if (paramName.charAt(0) === '$') {
paramName = paramName.substr(1);
if (!defines.params[paramName]) {
console.log('Invalid variable parameter name substitution; param ' + paramName + ' not found in defines block');
process.exit(1);
} else{
def = defines.params[paramName];
}
} else {
def = paramsStruct[paramName];
}
values.push(indent + ' ' + paramName + ': \'' + def.type + '\'');
}
return '{\n' + values.join(',\n') + '\n' + indent + '}';
}
function prepareApi(struct, baseType) {
if (!baseType){
baseType = '';
}
Object.keys(struct).forEach(function (routePart) {
var block = struct[routePart];
if (!block){
return;
}
var messageType = baseType + '/' + routePart;
if (block.url && block.params) {
// we ended up at an API definition part!
var parts = messageType.split('/');
var section = toCamelCase(parts[1].toLowerCase());
if (!block.method) {
throw new Error('No HTTP method specified for ' + messageType +
'in section ' + section);
}
parts.splice(0, 2);
var funcName = toCamelCase(parts.join('-'));
var comment = createComment(block.params, ' ');
// add the handler to the sections
if (!sections[section]){
sections[section] = [];
}
var afterRequest = '';
if (headers && headers.length) {
afterRequest = AfterRequestTpl.replace('<%headers%>', '\'' +
headers.join('\', \'') + '\'');
}
sections[section].push(HandlerTpl
.replace(/<%funcName%>/g, funcName)
.replace('<%comment%>', comment)
.replace(/<%sectionName%>/g, section)
.replace('<%afterRequest%>', afterRequest)
);
// add test to the testSections
if (!testSections[section]){
testSections[section] = [];
}
testSections[section].push(TestHandlerTpl
.replace('<%name%>', block.method + ' ' + block.url + ' (' + funcName + ')')
.replace('<%funcName%>', section + '.' + funcName)
.replace('<%params%>', getParams(block.params, ' '))
);
} else {
// recurse into this block next:
prepareApi(block, messageType);
}
});
}
console.log('Converting routes to functions');
prepareApi(routes);
console.log('Writing files to version dir');
var sectionNames = Object.keys(sections);
var sectionPaths = sectionNames.map(function(name){
return 'api/' + name;
});
console.log('Writing index.js file');
Fs.writeFileSync(Path.join(dir, 'index.js'),
IndexTpl
.replace('<%name%>', defines.constants.name)
.replace('<%description%>', defines.constants.description)
.replace(/<%scripts%>/g, '\'' + sectionPaths.join('\', \'') + '\''),
'utf8');
Object.keys(sections).forEach(function (section) {
var def = sections[section];
console.log('Writing ' + section + '.js file');
Fs.writeFileSync(Path.join(dir, section + '.js'),
SectionTpl
.replace(/<%sectionName%>/g, section)
.replace('<%sectionBody%>', def.join('\n')),
'utf8'
);
// When we don't need to generate tests, bail out here.
if (!tests){
return;
}
// def = testSections[section];
// test if previous tests already contained implementations by checking
// if the difference in character count between the current test file
// and the newly generated one is more than twenty characters.
// var body = TestSectionTpl
// .replace('<%version%>', version.replace('v', ''))
// .replace(/<%sectionName%>/g, section)
// .replace('<%testBody%>', def.join('\n\n'));
// var path = Path.join(dir, section + 'Test.js');
// if (Fs.existsSync(path) && Math.abs(Fs.readFileSync(path, 'utf8').length - body.length) >= 20) {
// Util.log('Moving old test file to '
// ' + path + '.bak
// ' to preserve tests ' +
// 'that were already implemented. \nPlease be sure te check this file ' +
// 'and move all implemented tests back into the newly generated test!', 'error'
// )
// ;
// Fs.renameSync(path, path + '.bak');
// }
//
// Util.log('Writing test file for ' + section + ', version ' + version);
// Fs.writeFileSync(path, body, 'utf8');
});
};
if (!module.parent) {
var argv = Optimist
.wrap(80)
.usage('Generate the implementation of the node-github module, including ' +
'unit-test scaffolds.\nUsage: $0 [-r] [-v VERSION]')
.alias('r', 'restore')
.describe('r', 'Restore .bak files, generated by a previous run, to the original')
.alias('t', 'tests')
.describe('t', 'Also generate unit test scaffolds')
.alias('h', 'help')
.describe('h', 'Display this usage information')
.boolean(['r', 't', 'h'])
.argv;
if (argv.help) {
console.log(Optimist.help());
process.exit();
}
var baseDir = Path.join(__dirname, 'lib', 'api');
var routes = require(baseDir + '/routes.js');
if (!routes.defines){
process.exit(1);
}
console.log('Starting up...');
main(routes, argv.tests, argv.restore);
}