index.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /* jshint node: true */
  2. var jsbeautify = require('js-beautify').js_beautify;
  3. var merge = require('deepmerge');
  4. var through = require('through2');
  5. var PluginError = require('gulp-util').PluginError;
  6. var detectIndent = require('detect-indent');
  7. module.exports = function (editor, jsbeautifyOptions) {
  8. /*
  9. create 'editBy' function from 'editor'
  10. */
  11. var editBy;
  12. if (typeof editor === 'function') {
  13. // edit JSON object by user specific function
  14. editBy = function(json) { return editor(json); };
  15. }
  16. else if (typeof editor === 'object') {
  17. // edit JSON object by merging with user specific object
  18. editBy = function(json) { return merge(json, editor); };
  19. }
  20. else if (typeof editor === 'undefined') {
  21. throw new PluginError('gulp-json-editor', 'missing "editor" option');
  22. }
  23. else {
  24. throw new PluginError('gulp-json-editor', '"editor" option must be a function or object');
  25. }
  26. /*
  27. js-beautify option
  28. */
  29. jsbeautifyOptions = jsbeautifyOptions || {};
  30. // always beautify output
  31. var beautify = true;
  32. /*
  33. create through object and return it
  34. */
  35. return through.obj(function (file, encoding, callback) {
  36. // ignore it
  37. if (file.isNull()) {
  38. this.push(file);
  39. return callback();
  40. }
  41. // stream is not supported
  42. if (file.isStream()) {
  43. this.emit('error', new PluginError('gulp-json-editor', 'Streaming is not supported'));
  44. return callback();
  45. }
  46. try {
  47. // try to get current indentation
  48. var indent = detectIndent(file.contents.toString('utf8'));
  49. // beautify options for this particular file
  50. var beautifyOptions = merge({}, jsbeautifyOptions); // make copy
  51. beautifyOptions.indent_size = beautifyOptions.indent_size || indent.amount || 2;
  52. beautifyOptions.indent_char = beautifyOptions.indent_char || (indent.type === 'tab' ? '\t' : ' ');
  53. // edit JSON object and get it as string notation
  54. var json = JSON.stringify(editBy(JSON.parse(file.contents.toString('utf8'))), null, indent.indent);
  55. // beautify JSON
  56. if (beautify) {
  57. json = jsbeautify(json, beautifyOptions);
  58. }
  59. // write it to file
  60. file.contents = new Buffer(json);
  61. }
  62. catch (err) {
  63. this.emit('error', new PluginError('gulp-json-editor', err));
  64. }
  65. this.push(file);
  66. callback();
  67. });
  68. };