extract-props.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #! /usr/bin/env node
  2. "use strict";
  3. var U2 = require("../tools/node");
  4. var fs = require("fs");
  5. var yargs = require("yargs");
  6. var ARGS = yargs
  7. .describe("o", "Output file")
  8. .argv;
  9. var files = ARGS._.slice();
  10. var output = {
  11. vars: {},
  12. props: {}
  13. };
  14. if (ARGS.o) try {
  15. output = JSON.parse(fs.readFileSync(ARGS.o, "utf8"));
  16. } catch(ex) {}
  17. files.forEach(getProps);
  18. if (ARGS.o) {
  19. fs.writeFileSync(ARGS.o, JSON.stringify(output, null, 2), "utf8");
  20. } else {
  21. console.log("%s", JSON.stringify(output, null, 2));
  22. }
  23. function getProps(filename) {
  24. var code = fs.readFileSync(filename, "utf8");
  25. var ast = U2.parse(code);
  26. ast.walk(new U2.TreeWalker(function(node){
  27. if (node instanceof U2.AST_ObjectKeyVal) {
  28. add(node.key);
  29. }
  30. else if (node instanceof U2.AST_ObjectProperty) {
  31. add(node.key.name);
  32. }
  33. else if (node instanceof U2.AST_Dot) {
  34. add(node.property);
  35. }
  36. else if (node instanceof U2.AST_Sub) {
  37. addStrings(node.property);
  38. }
  39. }));
  40. function addStrings(node) {
  41. var out = {};
  42. try {
  43. (function walk(node){
  44. node.walk(new U2.TreeWalker(function(node){
  45. if (node instanceof U2.AST_Seq) {
  46. walk(node.cdr);
  47. return true;
  48. }
  49. if (node instanceof U2.AST_String) {
  50. add(node.value);
  51. return true;
  52. }
  53. if (node instanceof U2.AST_Conditional) {
  54. walk(node.consequent);
  55. walk(node.alternative);
  56. return true;
  57. }
  58. throw out;
  59. }));
  60. })(node);
  61. } catch(ex) {
  62. if (ex !== out) throw ex;
  63. }
  64. }
  65. function add(name) {
  66. output.props[name] = true;
  67. }
  68. }