pbjs.js
8.8 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
/*
Copyright 2013 Daniel Wirtz <dcode@dcode.io>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var ProtoBuf = require(__dirname+"/../index.js"),
fs = require("fs"),
path = require("path"),
cli = require("ascli")("pbjs"),
yargs = require("yargs"),
util = require("./pbjs/util.js"),
glob = require("glob"),
pkg = require("../package.json");
/**
* pbjs namespace.
* @exports pbjs
* @namespace
*/
var pbjs = module.exports = {};
/**
* @alias pbjs/util
*/
pbjs.util = util;
/**
* Source formats.
* @type {!Object.<string,!function(string,!Object.<string,*>)>}
*/
pbjs.sources = {};
fs.readdirSync(__dirname+"/pbjs/sources").forEach(function(source) {
if (/\.js$/.test(source)) {
var src = require(__dirname + "/pbjs/sources/" + source);
if (!src.exclude)
pbjs.sources[source.substring(0, source.lastIndexOf("."))] = src;
}
});
/**
* Target formats.
* @type {!Object.<string,!function(!ProtoBuf.Builder,!Object.<string,*>)>}
*/
pbjs.targets = {};
fs.readdirSync(__dirname+"/pbjs/targets").forEach(function(target) {
if (/\.js$/.test(target))
pbjs.targets[target.substring(0, target.lastIndexOf("."))] = require(__dirname + "/pbjs/targets/" + target);
});
/**
* Status code: Operation successful
* @type {number}
*/
pbjs.STATUS_OK = 0;
/**
* Status code: Displaying usage information
* @type {number}
*/
pbjs.STATUS_USAGE = 1;
/**
* Status code: No such include directory
* @type {number}
*/
pbjs.STATUS_ERR_INCLUDE_DIR = 2;
/**
* Status code: No such source format
* @type {number}
*/
pbjs.STATUS_ERR_SOURCE_FORMAT = 3;
/**
* Status code: No such target format
* @type {number}
*/
pbjs.STATUS_ERR_TARGET_FORMAT = 4;
/**
* Status code: No such namespace
* @type {number}
*/
pbjs.STATUS_ERR_NAMESPACE = 5;
/**
* Status code: Illegal dependency
* @type {number}
*/
pbjs.STATUS_ERR_DEPENDENCY = 6;
/**
* Status code: No matching source files
* @type {number}
*/
pbjs.STATUS_ERR_NOSOURCE = 7;
// Makes a table of available source or target formats
function mkOptions(obj) {
var str = '';
Object.keys(obj).forEach(function(key) {
str += "\n "+util.pad(key, 10)+" "+obj[key].description;
});
return str;
}
/**
* Executes the program.
* @param {!Array.<string>} argv Command line arguments
* @returns {number} Status code
*/
pbjs.main = function(argv) {
var options = yargs
.usage(cli("pb".white.bold+"js".green.bold, util.pad("ProtoBuf.js v"+pkg['version'], 31, true)+" "+pkg['homepage'].grey) + "\n" +
"CLI utility to convert between .proto and JSON syntax / to generate classes.\n\n" +
"Usage: ".white.bold+path.basename(argv[1]).green.bold+" <source files...> [options] [> outFile]")
.help("help")
.version(pkg["version"])
.wrap(null)
.options({
source: {
alias: "s",
describe: "Specifies the source format. Valid formats are:\n" + mkOptions(pbjs.sources)+"\n"
},
target: {
alias: "t",
describe: "Specifies the target format. Valid formats are:\n" + mkOptions(pbjs.targets)+"\n"
},
using: {
alias: "u",
describe: "Specifies an option to apply to the volatile builder\nloading the source, e.g. convertFieldsToCamelCase.",
type: "array"
},
min: {
alias: "m",
describe: "Minifies the output.",
default: false
},
path: {
alias: "p",
describe: "Adds a directory to the include path."
},
legacy: {
alias: "l",
describe: "Includes legacy descriptors from google/protobuf/ if\nexplicitly referenced.",
default: false
},
quiet: {
alias: "q",
describe: "Suppresses any informatory output to stderr.",
default: false
},
out: {
alias: "o",
describe: "Send output to file instead of stdout.",
},
use: {
alias: "i",
describe: "Specifies an option to apply to the emitted builder\nutilized by your program, e.g. populateAccessors.",
type: "array"
},
exports: {
alias: "e",
describe: "Specifies the namespace to export. Defaults to export\nthe root namespace."
},
dependency: {
alias: "d",
describe: "Library dependency to use when generating classes.\nDefaults to 'protobufjs' for CommonJS, 'ProtoBuf' for\nAMD modules and 'dcodeIO.ProtoBuf' for classes."
}
})
.alias("help", "h")
.alias("version", "v")
.check(function (args) {
if (args.source && typeof pbjs.sources[args.source] !== "function") {
return "Unrecognized source format: '" + args.source + "'";
}
if (args.target && typeof pbjs.targets[args.target] !== "function") {
return "Unrecognized target format: '" + args.target + "'";
}
if (args._.length < 3) {
return "The filename to parse is required.";
}
return true;
})
.parse(argv);
var start = Date.now(),
sourceFiles = options._.slice(2);
// Expand glob expressions
var sourceFilesExpand = [];
for (var i=0; i<sourceFiles.length; ++i) {
var filename = sourceFiles[i],
files = glob.sync(filename);
if (files.length === 0) {
cli.fail("No matching source files: "+filename);
return pbjs.STATUS_ERR_NOSOURCE;
}
files.forEach(function(filename) {
if (sourceFilesExpand.indexOf(filename) === -1)
sourceFilesExpand.push(filename);
});
}
sourceFiles = sourceFilesExpand;
if (!options.target)
options.target = "json";
// Set up include paths
var includePath = Array.isArray(options['path']) ? options['path'] : (typeof options['path'] === 'string' ? [options['path']] : []);
sourceFiles.forEach(function (sourceFile) {
var dir = path.dirname(sourceFile);
if (includePath.indexOf(dir) === -1) {
includePath.push(dir);
}
});
includePath.forEach(function(path) { // Verify that include paths actually exist
if (!fs.existsSync(path)) {
if (!options.quiet)
cli.fail("No such include directory: "+path);
return pbjs.STATUS_ERR_INCLUDE_DIR;
}
});
options.path = includePath;
// Detect source format if not specified, then verify
if (typeof options.source !== 'string') {
var source = fs.readFileSync(sourceFiles[0]).toString("utf8").trim();
if (source.substring(0,1) === "{")
options.source = "json";
else
options.source = "proto";
}
// Load the source files to a common builder
var builder = pbjs.sources[options.source](sourceFiles, options);
// Validate exports and dependency if set
if (typeof options.exports !== 'undefined') {
if (!(builder.lookup(options.exports) instanceof ProtoBuf.Reflect.Namespace)) {
if (!options.quiet)
cli.fail("No such export namespace: "+options.exports);
return pbjs.STATUS_ERR_NAMESPACE;
}
if (options.exports.charAt(0) === '.')
options.exports = options.exports.substring(1);
}
if (typeof options.dependency !== 'undefined')
if (typeof options.dependency !== 'string' || !options.dependency) {
if (!options.quiet)
cli.fail("Illegal dependency: "+options.dependency);
return pbjs.STATUS_ERR_DEPENDENCY;
}
// Perform target conversion
if (!options.quiet)
cli.error("\nProcessing: "+sourceFiles.join(", ")+" ...\n");
var res = pbjs.targets[options.target](builder, options);
if (options.out){
fs.writeFileSync(options.out, res);
}else
process.stdout.write(res);
if (!options.quiet)
cli.error(""),
cli.ok("Converted "+sourceFiles.length+" source files to "+options.target+" ("+res.length+" bytes, "+(Date.now()-start)+" ms)");
return pbjs.STATUS_OK;
};