index.js 2.4 KB

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