-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgenerate.js
70 lines (60 loc) · 1.89 KB
/
generate.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
const protobufjs = require('protobufjs');
const fs = require('fs');
const path = require('path');
const yargs = require('yargs').option('ignore', {
alias: 'i',
type: 'string',
}).argv;
const ignore = typeof yargs.ignore === 'string' ? [yargs.ignore] : yargs.ignore;
let [rootPath, outFile = 'public/proto.json'] = yargs._;
if (rootPath === undefined) {
console.info('usage: generate.js proto-path');
process.exit(1);
}
rootPath = path.resolve(rootPath);
if (!fs.existsSync(rootPath) || !fs.statSync(rootPath).isDirectory()) {
console.error(`${rootPath}: no such directory exists`);
process.exit(1);
}
const walk = (dir, files = []) => {
fs.readdirSync(dir).forEach(file => {
const path = dir + file;
if (fs.statSync(path).isDirectory()) {
walk(path + '/', files);
} else if (path.endsWith('.proto')) {
files.push(path);
}
});
return files;
};
const sources = walk(rootPath + '/');
const parseOptions = {
keepCase: true,
alternateCommentMode: true, // Important so that it parses trailing comments and non-doc-blocks
};
const root = new protobufjs.Root();
root.resolvePath = (origin, include) => {
for (let i = 0; i < ignore.length; i++) {
if (include.endsWith(ignore[i])) {
return null;
}
}
if (!fs.existsSync(include)) {
include = rootPath + '/' + include;
}
console.log(path.relative(rootPath, include));
return include;
};
root.loadSync(sources, parseOptions);
try {
root.resolveAll();
} catch (err) {
console.error(`fatal: could not resolve root: ${err}`);
process.exit(1);
}
// TODO possibly consider serialising filenames alongside root JSON?
// The JSON descriptor format does not include support for filenames, so it would need to be a side channel.
// e.g. { root: JSON.stringify(root), filenames: {} }
const json = root.toJSON({ keepComments: true });
fs.writeFileSync(outFile, JSON.stringify(json));
console.log('saved', outFile);