main.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. var types = require("./lib/types");
  2. var parse = require("./lib/parser").parse;
  3. var Printer = require("./lib/printer").Printer;
  4. function print(node, options) {
  5. return new Printer(options).print(node);
  6. }
  7. function prettyPrint(node, options) {
  8. return new Printer(options).printGenerically(node);
  9. }
  10. function run(transformer, options) {
  11. return runFile(process.argv[2], transformer, options);
  12. }
  13. function runFile(path, transformer, options) {
  14. require("fs").readFile(path, "utf-8", function(err, code) {
  15. if (err) {
  16. console.error(err);
  17. return;
  18. }
  19. runString(code, transformer, options);
  20. });
  21. }
  22. function defaultWriteback(output) {
  23. process.stdout.write(output);
  24. }
  25. function runString(code, transformer, options) {
  26. var writeback = options && options.writeback || defaultWriteback;
  27. transformer(parse(code, options), function(node) {
  28. writeback(print(node, options).code);
  29. });
  30. }
  31. Object.defineProperties(exports, {
  32. /**
  33. * Parse a string of code into an augmented syntax tree suitable for
  34. * arbitrary modification and reprinting.
  35. */
  36. parse: {
  37. enumerable: true,
  38. value: parse
  39. },
  40. /**
  41. * Traverse and potentially modify an abstract syntax tree using a
  42. * convenient visitor syntax:
  43. *
  44. * recast.visit(ast, {
  45. * names: [],
  46. * visitIdentifier: function(path) {
  47. * var node = path.value;
  48. * this.visitor.names.push(node.name);
  49. * this.traverse(path);
  50. * }
  51. * });
  52. */
  53. visit: {
  54. enumerable: true,
  55. value: types.visit
  56. },
  57. /**
  58. * Reprint a modified syntax tree using as much of the original source
  59. * code as possible.
  60. */
  61. print: {
  62. enumerable: true,
  63. value: print
  64. },
  65. /**
  66. * Print without attempting to reuse any original source code.
  67. */
  68. prettyPrint: {
  69. enumerable: false,
  70. value: prettyPrint
  71. },
  72. /**
  73. * Customized version of require("ast-types").
  74. */
  75. types: {
  76. enumerable: false,
  77. value: types
  78. },
  79. /**
  80. * Convenient command-line interface (see e.g. example/add-braces).
  81. */
  82. run: {
  83. enumerable: false,
  84. value: run
  85. }
  86. });