yaml2json.js 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. /**
  2. * yaml2json cli program
  3. */
  4. var YAML = require('../lib/Yaml.js');
  5. var ArgumentParser = require('argparse').ArgumentParser;
  6. var cli = new ArgumentParser({
  7. prog: "yaml2json",
  8. version: require('../package.json').version,
  9. addHelp: true
  10. });
  11. cli.addArgument(
  12. ['-p', '--pretty'],
  13. {
  14. help: 'Output pretty (indented) JSON.',
  15. action: 'storeTrue'
  16. }
  17. );
  18. cli.addArgument(
  19. ['-i', '--indentation'],
  20. {
  21. action: 'store',
  22. type: 'int',
  23. help: 'Number of space characters used to indent code (use with --pretty, default: 2).',
  24. }
  25. );
  26. cli.addArgument(
  27. ['-s', '--save'],
  28. {
  29. help: 'Save output inside JSON file(s) with the same name.',
  30. action: 'storeTrue'
  31. }
  32. );
  33. cli.addArgument(
  34. ['-r', '--recursive'],
  35. {
  36. help: 'If the input is a directory, also find YAML files in sub-directories recursively.',
  37. action: 'storeTrue'
  38. }
  39. );
  40. cli.addArgument(
  41. ['-w', '--watch'],
  42. {
  43. help: 'Watch for changes.',
  44. action: 'storeTrue'
  45. }
  46. );
  47. cli.addArgument(['input'], {
  48. help: 'YAML file or directory containing YAML files or - to read YAML from stdin.'
  49. });
  50. try {
  51. var options = cli.parseArgs();
  52. var path = require('path');
  53. var fs = require('fs');
  54. var glob = require('glob');
  55. var rootPath = process.cwd();
  56. var parsePath = function(input) {
  57. if (input == '-') return '-';
  58. var output;
  59. if (!(input != null)) {
  60. return rootPath;
  61. }
  62. output = path.normalize(input);
  63. if (output.length === 0) {
  64. return rootPath;
  65. }
  66. if (output.charAt(0) !== '/') {
  67. output = path.normalize(rootPath + '/./' + output);
  68. }
  69. if (output.length > 1 && output.charAt(output.length - 1) === '/') {
  70. return output.substr(0, output.length - 1);
  71. }
  72. return output;
  73. };
  74. // Find files
  75. var findFiles = function(input) {
  76. if (input != '-' && input != null) {
  77. var isDirectory = fs.statSync(input).isDirectory();
  78. var files = [];
  79. if (!isDirectory) {
  80. files.push(input);
  81. }
  82. else {
  83. if (options.recursive) {
  84. files = files.concat(glob.sync(input+'/**/*.yml'));
  85. files = files.concat(glob.sync(input+'/**/*.yaml'));
  86. }
  87. else {
  88. files = files.concat(glob.sync(input+'/*.yml'));
  89. files = files.concat(glob.sync(input+'/*.yaml'));
  90. }
  91. }
  92. return files;
  93. }
  94. return null;
  95. };
  96. // Convert to JSON
  97. var convertToJSON = function(input, pretty, save, spaces, str) {
  98. var json;
  99. if (spaces == null) spaces = 2;
  100. if (str != null) {
  101. if (pretty) {
  102. json = JSON.stringify(YAML.parse(str), null, spaces);
  103. }
  104. else {
  105. json = JSON.stringify(YAML.parse(str));
  106. }
  107. } else {
  108. if (pretty) {
  109. json = JSON.stringify(YAML.parseFile(input), null, spaces);
  110. }
  111. else {
  112. json = JSON.stringify(YAML.parseFile(input));
  113. }
  114. }
  115. if (!save || input == null) {
  116. // Ouput result
  117. process.stdout.write(json+"\n");
  118. }
  119. else {
  120. var output;
  121. if (input.substring(input.length-4) == '.yml') {
  122. output = input.substr(0, input.length-4) + '.json';
  123. }
  124. else if (input.substring(input.length-5) == '.yaml') {
  125. output = input.substr(0, input.length-5) + '.json';
  126. }
  127. else {
  128. output = input + '.json';
  129. }
  130. // Write file
  131. var file = fs.openSync(output, 'w+');
  132. fs.writeSync(file, json);
  133. fs.closeSync(file);
  134. process.stdout.write("saved "+output+"\n");
  135. }
  136. };
  137. var input = parsePath(options.input);
  138. var mtimes = [];
  139. var runCommand = function() {
  140. try {
  141. var files = findFiles(input);
  142. if (files != null) {
  143. var len = files.length;
  144. for (var i = 0; i < len; i++) {
  145. var file = files[i];
  146. var stat = fs.statSync(file);
  147. var time = stat.mtime.getTime();
  148. if (!stat.isDirectory()) {
  149. if (!mtimes[file] || mtimes[file] < time) {
  150. mtimes[file] = time;
  151. convertToJSON(file, options.pretty, options.save, options.indentation);
  152. }
  153. }
  154. }
  155. } else {
  156. // Read from STDIN
  157. var stdin = process.openStdin();
  158. var data = "";
  159. stdin.on('data', function(chunk) {
  160. data += chunk;
  161. });
  162. stdin.on('end', function() {
  163. convertToJSON(null, options.pretty, options.save, options.indentation, data);
  164. });
  165. }
  166. } catch (e) {
  167. process.stderr.write((e.message ? e.message : e)+"\n");
  168. }
  169. };
  170. if (!options.watch) {
  171. runCommand();
  172. } else {
  173. runCommand();
  174. setInterval(runCommand, 1000);
  175. }
  176. } catch (e) {
  177. process.stderr.write((e.message ? e.message : e)+"\n");
  178. }