pbjs.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. /*
  2. Copyright 2013 Daniel Wirtz <dcode@dcode.io>
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. var ProtoBuf = require(__dirname+"/../index.js"),
  14. fs = require("fs"),
  15. path = require("path"),
  16. cli = require("ascli")("pbjs"),
  17. yargs = require("yargs"),
  18. util = require("./pbjs/util.js"),
  19. glob = require("glob"),
  20. pkg = require("../package.json");
  21. /**
  22. * pbjs namespace.
  23. * @exports pbjs
  24. * @namespace
  25. */
  26. var pbjs = module.exports = {};
  27. /**
  28. * @alias pbjs/util
  29. */
  30. pbjs.util = util;
  31. /**
  32. * Source formats.
  33. * @type {!Object.<string,!function(string,!Object.<string,*>)>}
  34. */
  35. pbjs.sources = {};
  36. fs.readdirSync(__dirname+"/pbjs/sources").forEach(function(source) {
  37. if (/\.js$/.test(source)) {
  38. var src = require(__dirname + "/pbjs/sources/" + source);
  39. if (!src.exclude)
  40. pbjs.sources[source.substring(0, source.lastIndexOf("."))] = src;
  41. }
  42. });
  43. /**
  44. * Target formats.
  45. * @type {!Object.<string,!function(!ProtoBuf.Builder,!Object.<string,*>)>}
  46. */
  47. pbjs.targets = {};
  48. fs.readdirSync(__dirname+"/pbjs/targets").forEach(function(target) {
  49. if (/\.js$/.test(target))
  50. pbjs.targets[target.substring(0, target.lastIndexOf("."))] = require(__dirname + "/pbjs/targets/" + target);
  51. });
  52. /**
  53. * Status code: Operation successful
  54. * @type {number}
  55. */
  56. pbjs.STATUS_OK = 0;
  57. /**
  58. * Status code: Displaying usage information
  59. * @type {number}
  60. */
  61. pbjs.STATUS_USAGE = 1;
  62. /**
  63. * Status code: No such include directory
  64. * @type {number}
  65. */
  66. pbjs.STATUS_ERR_INCLUDE_DIR = 2;
  67. /**
  68. * Status code: No such source format
  69. * @type {number}
  70. */
  71. pbjs.STATUS_ERR_SOURCE_FORMAT = 3;
  72. /**
  73. * Status code: No such target format
  74. * @type {number}
  75. */
  76. pbjs.STATUS_ERR_TARGET_FORMAT = 4;
  77. /**
  78. * Status code: No such namespace
  79. * @type {number}
  80. */
  81. pbjs.STATUS_ERR_NAMESPACE = 5;
  82. /**
  83. * Status code: Illegal dependency
  84. * @type {number}
  85. */
  86. pbjs.STATUS_ERR_DEPENDENCY = 6;
  87. /**
  88. * Status code: No matching source files
  89. * @type {number}
  90. */
  91. pbjs.STATUS_ERR_NOSOURCE = 7;
  92. // Makes a table of available source or target formats
  93. function mkOptions(obj) {
  94. var str = '';
  95. Object.keys(obj).forEach(function(key) {
  96. str += "\n "+util.pad(key, 10)+" "+obj[key].description;
  97. });
  98. return str;
  99. }
  100. /**
  101. * Executes the program.
  102. * @param {!Array.<string>} argv Command line arguments
  103. * @returns {number} Status code
  104. */
  105. pbjs.main = function(argv) {
  106. var options = yargs
  107. .usage(cli("pb".white.bold+"js".green.bold, util.pad("ProtoBuf.js v"+pkg['version'], 31, true)+" "+pkg['homepage'].grey) + "\n" +
  108. "CLI utility to convert between .proto and JSON syntax / to generate classes.\n\n" +
  109. "Usage: ".white.bold+path.basename(argv[1]).green.bold+" <source files...> [options] [> outFile]")
  110. .help("help")
  111. .version(pkg["version"])
  112. .wrap(null)
  113. .options({
  114. source: {
  115. alias: "s",
  116. describe: "Specifies the source format. Valid formats are:\n" + mkOptions(pbjs.sources)+"\n"
  117. },
  118. target: {
  119. alias: "t",
  120. describe: "Specifies the target format. Valid formats are:\n" + mkOptions(pbjs.targets)+"\n"
  121. },
  122. using: {
  123. alias: "u",
  124. describe: "Specifies an option to apply to the volatile builder\nloading the source, e.g. convertFieldsToCamelCase.",
  125. type: "array"
  126. },
  127. min: {
  128. alias: "m",
  129. describe: "Minifies the output.",
  130. default: false
  131. },
  132. path: {
  133. alias: "p",
  134. describe: "Adds a directory to the include path."
  135. },
  136. legacy: {
  137. alias: "l",
  138. describe: "Includes legacy descriptors from google/protobuf/ if\nexplicitly referenced.",
  139. default: false
  140. },
  141. quiet: {
  142. alias: "q",
  143. describe: "Suppresses any informatory output to stderr.",
  144. default: false
  145. },
  146. out: {
  147. alias: "o",
  148. describe: "Send output to file instead of stdout.",
  149. },
  150. use: {
  151. alias: "i",
  152. describe: "Specifies an option to apply to the emitted builder\nutilized by your program, e.g. populateAccessors.",
  153. type: "array"
  154. },
  155. exports: {
  156. alias: "e",
  157. describe: "Specifies the namespace to export. Defaults to export\nthe root namespace."
  158. },
  159. dependency: {
  160. alias: "d",
  161. describe: "Library dependency to use when generating classes.\nDefaults to 'protobufjs' for CommonJS, 'protobuf' for\nAMD modules and 'dcodeIO.ProtoBuf' for classes."
  162. }
  163. })
  164. .alias("help", "h")
  165. .alias("version", "v")
  166. .check(function (args) {
  167. if (args.source && typeof pbjs.sources[args.source] !== "function") {
  168. return "Unrecognized source format: '" + args.source + "'";
  169. }
  170. if (args.target && typeof pbjs.targets[args.target] !== "function") {
  171. return "Unrecognized target format: '" + args.target + "'";
  172. }
  173. if (args._.length < 3) {
  174. return "The filename to parse is required.";
  175. }
  176. return true;
  177. })
  178. .parse(argv);
  179. var start = Date.now(),
  180. sourceFiles = options._.slice(2);
  181. // Expand glob expressions
  182. var sourceFilesExpand = [];
  183. for (var i=0; i<sourceFiles.length; ++i) {
  184. var filename = sourceFiles[i],
  185. files = glob.sync(filename);
  186. if (files.length === 0) {
  187. cli.fail("No matching source files: "+filename);
  188. return pbjs.STATUS_ERR_NOSOURCE;
  189. }
  190. files.forEach(function(filename) {
  191. if (sourceFilesExpand.indexOf(filename) === -1)
  192. sourceFilesExpand.push(filename);
  193. });
  194. }
  195. sourceFiles = sourceFilesExpand;
  196. if (!options.target)
  197. options.target = "json";
  198. // Set up include paths
  199. var includePath = Array.isArray(options['path']) ? options['path'] : (typeof options['path'] === 'string' ? [options['path']] : []);
  200. sourceFiles.forEach(function (sourceFile) {
  201. var dir = path.dirname(sourceFile);
  202. if (includePath.indexOf(dir) === -1) {
  203. includePath.push(dir);
  204. }
  205. });
  206. includePath.forEach(function(path) { // Verify that include paths actually exist
  207. if (!fs.existsSync(path)) {
  208. if (!options.quiet)
  209. cli.fail("No such include directory: "+path);
  210. return pbjs.STATUS_ERR_INCLUDE_DIR;
  211. }
  212. });
  213. options.path = includePath;
  214. // Detect source format if not specified, then verify
  215. if (typeof options.source !== 'string') {
  216. var source = fs.readFileSync(sourceFiles[0]).toString("utf8").trim();
  217. if (source.substring(0,1) === "{")
  218. options.source = "json";
  219. else
  220. options.source = "proto";
  221. }
  222. // Load the source files to a common builder
  223. var builder = pbjs.sources[options.source](sourceFiles, options);
  224. // Validate exports and dependency if set
  225. if (typeof options.exports !== 'undefined') {
  226. if (!(builder.lookup(options.exports) instanceof ProtoBuf.Reflect.Namespace)) {
  227. if (!options.quiet)
  228. cli.fail("No such export namespace: "+options.exports);
  229. return pbjs.STATUS_ERR_NAMESPACE;
  230. }
  231. if (options.exports.charAt(0) === '.')
  232. options.exports = options.exports.substring(1);
  233. }
  234. if (typeof options.dependency !== 'undefined')
  235. if (typeof options.dependency !== 'string' || !options.dependency) {
  236. if (!options.quiet)
  237. cli.fail("Illegal dependency: "+options.dependency);
  238. return pbjs.STATUS_ERR_DEPENDENCY;
  239. }
  240. // Perform target conversion
  241. if (!options.quiet)
  242. cli.error("\nProcessing: "+sourceFiles.join(", ")+" ...\n");
  243. var res = pbjs.targets[options.target](builder, options);
  244. if (options.out){
  245. fs.writeFileSync(options.out, res);
  246. }else
  247. process.stdout.write(res);
  248. if (!options.quiet)
  249. cli.error(""),
  250. cli.ok("Converted "+sourceFiles.length+" source files to "+options.target+" ("+res.length+" bytes, "+(Date.now()-start)+" ms)");
  251. return pbjs.STATUS_OK;
  252. };