Нет описания

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. #!/usr/bin/env node
  2. 'use strict';
  3. // stdlib
  4. var fs = require('fs');
  5. var util = require('util');
  6. // 3rd-party
  7. var ArgumentParser = require('argparse').ArgumentParser;
  8. // internal
  9. var yaml = require('..');
  10. ////////////////////////////////////////////////////////////////////////////////
  11. var cli = new ArgumentParser({
  12. prog: 'js-yaml',
  13. version: require('../package.json').version,
  14. addHelp: true
  15. });
  16. cli.addArgument(['-c', '--compact'], {
  17. help: 'Display errors in compact mode',
  18. action: 'storeTrue'
  19. });
  20. cli.addArgument(['-j', '--to-json'], {
  21. help: 'Output a non-funky boring JSON',
  22. dest: 'json',
  23. action: 'storeTrue'
  24. });
  25. cli.addArgument(['-t', '--trace'], {
  26. help: 'Show stack trace on error',
  27. action: 'storeTrue'
  28. });
  29. cli.addArgument(['file'], {
  30. help: 'File to read'
  31. });
  32. ////////////////////////////////////////////////////////////////////////////////
  33. var options = cli.parseArgs();
  34. ////////////////////////////////////////////////////////////////////////////////
  35. fs.readFile(options.file, 'utf8', function (error, input) {
  36. var output, isYaml;
  37. if (error) {
  38. if ('ENOENT' === error.code) {
  39. console.error('File not found: ' + options.file);
  40. process.exit(2);
  41. }
  42. console.error(
  43. options.trace && error.stack ||
  44. error.message ||
  45. String(error));
  46. process.exit(1);
  47. }
  48. try {
  49. output = JSON.parse(input);
  50. isYaml = false;
  51. } catch (error) {
  52. if (error instanceof SyntaxError) {
  53. try {
  54. output = [];
  55. yaml.loadAll(input, function (doc) { output.push(doc); }, {});
  56. isYaml = true;
  57. if (0 === output.length) {
  58. output = null;
  59. } else if (1 === output.length) {
  60. output = output[0];
  61. }
  62. } catch (error) {
  63. if (options.trace && error.stack) {
  64. console.error(error.stack);
  65. } else {
  66. console.error(error.toString(options.compact));
  67. }
  68. process.exit(1);
  69. }
  70. } else {
  71. console.error(
  72. options.trace && error.stack ||
  73. error.message ||
  74. String(error));
  75. process.exit(1);
  76. }
  77. }
  78. if (isYaml) {
  79. if (options.json) {
  80. console.log(JSON.stringify(output, null, ' '));
  81. } else {
  82. console.log("\n" + util.inspect(output, false, 10, true) + "\n");
  83. }
  84. } else {
  85. console.log(yaml.dump(output));
  86. }
  87. process.exit(0);
  88. });