rewrite_tests_for_commonjs.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /**
  2. * @fileoverview Utility to translate test files to CommonJS imports.
  3. *
  4. * This is a somewhat hacky tool designed to do one very specific thing.
  5. * All of the test files in *_test.js are written with Closure-style
  6. * imports (goog.require()). This works great for running the tests
  7. * against Closure-style generated code, but we also want to run the
  8. * tests against CommonJS-style generated code without having to fork
  9. * the tests.
  10. *
  11. * Closure-style imports import each individual type by name. This is
  12. * very different than CommonJS imports which are by file. So we put
  13. * special comments in these tests like:
  14. *
  15. * // CommonJS-LoadFromFile: test_pb
  16. * goog.require('proto.jspb.test.CloneExtension');
  17. * goog.require('proto.jspb.test.Complex');
  18. * goog.require('proto.jspb.test.DefaultValues');
  19. *
  20. * This script parses that special comment and uses it to generate proper
  21. * CommonJS require() statements so that the tests can run and pass using
  22. * CommonJS imports.
  23. */
  24. var lineReader = require('readline').createInterface({
  25. input: process.stdin,
  26. output: process.stdout
  27. });
  28. var module = null;
  29. lineReader.on('line', function(line) {
  30. var is_require = line.match(/goog\.require\('([^']*\.)([^'.]+)'\)/);
  31. var is_loadfromfile = line.match(/CommonJS-LoadFromFile: (.*)/);
  32. var is_settestonly = line.match(/goog.setTestOnly()/);
  33. if (is_settestonly) {
  34. // Remove this line.
  35. } else if (is_require) {
  36. if (module) { // Skip goog.require() lines before the first directive.
  37. var pkg = is_require[1];
  38. var sym = is_require[2];
  39. console.log("google_protobuf.exportSymbol('" + pkg + sym + "', " + module + "." + sym + ', global);');
  40. }
  41. } else if (is_loadfromfile) {
  42. if (!module) {
  43. console.log("var asserts = require('closure_asserts_commonjs');");
  44. console.log("var global = Function('return this')();");
  45. console.log("");
  46. console.log("// Bring asserts into the global namespace.");
  47. console.log("for (var key in asserts) {");
  48. console.log(" if (asserts.hasOwnProperty(key)) {");
  49. console.log(" global[key] = asserts[key];");
  50. console.log(" }");
  51. console.log("}");
  52. console.log("");
  53. console.log("var google_protobuf = require('google-protobuf');");
  54. }
  55. module = is_loadfromfile[1].replace("-", "_");
  56. if (module != "google_protobuf") { // We unconditionally require this in the header.
  57. console.log("var " + module + " = require('" + is_loadfromfile[1] + "');");
  58. }
  59. } else {
  60. console.log(line);
  61. }
  62. });