index.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. var through = require('through');
  2. var path = require('path');
  3. var gutil = require('gulp-util');
  4. var File = gutil.File;
  5. var PluginError = gutil.PluginError;
  6. function concatFilenames(filename, opts) {
  7. 'use strict';
  8. function identity(x) {
  9. return x;
  10. }
  11. var error = {
  12. noFilename: 'Missing fileName option for gulp-concat-filenames',
  13. badTemplate: 'Error in template function'
  14. };
  15. opts = opts || {};
  16. opts.template = opts.template || identity;
  17. if (!filename) {
  18. throw new PluginError('gulp-concat-filenames', error.noFilename);
  19. }
  20. if (typeof opts.newLine !== 'string') {
  21. opts.newLine = gutil.linefeed;
  22. }
  23. var buffer = [],
  24. firstfile;
  25. function bufferContents(file) {
  26. firstfile = firstfile || file;
  27. var requirePath = path.resolve(file.path);
  28. // Make sure template errors reach the output
  29. var safeTemplate = function(str) {
  30. var output;
  31. try {
  32. output = opts.template(str);
  33. } catch (e) {
  34. e.message = error.badTemplate + ': ' + e.message;
  35. return this.emit('error', new PluginError('gulp-concat-filenames', e));
  36. }
  37. if (typeof output !== 'string') {
  38. return this.emit('error', new PluginError('gulp-concat-filenames', error.badTemplate));
  39. }
  40. return output;
  41. };
  42. requirePath = opts.root ?
  43. path.relative(opts.root, requirePath) :
  44. requirePath;
  45. var thisRequire = [
  46. opts.prepend || '',
  47. safeTemplate.call(this, requirePath.replace(/\\/g, '\/')),
  48. opts.append || '',
  49. opts.newLine
  50. ].join('');
  51. buffer.push(new Buffer(thisRequire));
  52. }
  53. function endStream() {
  54. if (buffer.length === 0) {
  55. return this.emit('end');
  56. }
  57. var outFileContents = Buffer.concat(buffer),
  58. outFilePath = path.join(firstfile.base, filename);
  59. var outFile = new File({
  60. cwd: firstfile.cwd,
  61. base: firstfile.base,
  62. path: outFilePath,
  63. contents: outFileContents
  64. });
  65. this.emit('data', outFile);
  66. this.emit('end');
  67. }
  68. return through(bufferContents, endStream);
  69. }
  70. module.exports = concatFilenames;