yaml2json 5.5 KB

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