index.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*!
  2. * gulp-dedupe, https://github.com/hoho/gulp-dedupe
  3. * (c) 2014 Marat Abdullin, MIT license
  4. */
  5. 'use strict';
  6. var through = require('through');
  7. var gutil = require('gulp-util');
  8. var PluginError = gutil.PluginError;
  9. var path = require('path');
  10. var defaults = require('lodash.defaults');
  11. module.exports = function(options) {
  12. var filesMap = {};
  13. options = defaults(options || {}, {
  14. error: false, // Throw an error in case of duplicate.
  15. same: true, // Throw an error in case duplicates have different contents.
  16. diff: false // Supply duplicates with different content error with actual diff.
  17. });
  18. function bufferContents(file) {
  19. if (file.isNull()) { return; }
  20. if (file.isStream()) { return this.emit('error', new PluginError('gulp-dedupe', 'Streaming not supported')); }
  21. var fullpath = path.resolve(file.path),
  22. f;
  23. if ((f = filesMap[fullpath])) {
  24. if (options.error) {
  25. this.emit('error', new PluginError('gulp-dedupe', 'Duplicate `' + file.path + '`'));
  26. } else if (options.same && file.contents.toString() !== f.contents.toString()) {
  27. var errorDiff = [];
  28. if (options.diff) {
  29. require('colors');
  30. var diff = require('diff').diffChars(file.contents.toString(), f.contents.toString());
  31. errorDiff.push(':\n');
  32. diff.forEach(function(part){
  33. // green for additions, red for deletions
  34. // grey for common parts
  35. var color = part.added ? 'green' :
  36. part.removed ? 'red' : 'grey';
  37. errorDiff.push(part.value[color]);
  38. });
  39. }
  40. errorDiff = errorDiff.join('');
  41. this.emit('error', new PluginError('gulp-dedupe', 'Duplicate file `' + file.path + '` with different contents' + errorDiff));
  42. }
  43. return;
  44. } else {
  45. filesMap[fullpath] = file;
  46. }
  47. this.emit('data', file);
  48. }
  49. function endStream() {
  50. this.emit('end');
  51. }
  52. return through(bufferContents, endStream);
  53. };