parse.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #!/usr/bin/env node
  2. // Command-line tool that parses a type expression and dumps a JSON version of the parse tree.
  3. const catharsis = require('../catharsis');
  4. const path = require('path');
  5. const util = require('util');
  6. const command = path.basename(process.argv[1]);
  7. const typeExpression = process.argv[2];
  8. const opts = {
  9. describe: false,
  10. jsdoc: false
  11. };
  12. let parsedType;
  13. function usage() {
  14. console.log(util.format('Usage:\n %s typeExpression [--jsdoc] [--describe]', command));
  15. }
  16. function done(err) {
  17. /* eslint-disable no-process-exit */
  18. process.exit(err === undefined ? 0 : err);
  19. /* eslint-enable no-process-exit */
  20. }
  21. process.argv.slice(3).forEach(arg => {
  22. const parsedArg = arg.replace(/^-{2}/, '');
  23. if (opts[parsedArg] !== undefined) {
  24. opts[parsedArg] = true;
  25. } else {
  26. console.error('Unknown option "%s"', arg);
  27. usage();
  28. done(1);
  29. }
  30. });
  31. if (!typeExpression) {
  32. usage();
  33. done(1);
  34. } else {
  35. try {
  36. parsedType = catharsis.parse(typeExpression, opts);
  37. if (opts.describe) {
  38. parsedType = catharsis.describe(parsedType);
  39. }
  40. } catch (e) {
  41. console.error(util.format('Unable to parse "%s" (exception follows):', typeExpression));
  42. console.error(e.stack || e.message);
  43. done(1);
  44. }
  45. console.log(JSON.stringify(parsedType, null, 2));
  46. done();
  47. }