json2yaml 5.0 KB

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