index.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /**
  2. * Module dependencies.
  3. */
  4. const Concat = require('concat-with-sourcemaps');
  5. const through = require('through2');
  6. const lodashTemplate = require('lodash.template');
  7. const stream = require('stream');
  8. const path = require('path');
  9. /**
  10. * gulp-header plugin
  11. */
  12. module.exports = (headerText, data) => {
  13. headerText = headerText || '';
  14. function TransformStream(file, enc, cb) {
  15. // format template
  16. const filename = path.basename(file.path);
  17. const template =
  18. data === false ?
  19. headerText
  20. : lodashTemplate(headerText)(
  21. Object.assign({}, file.data || {}, { file: file, filename: filename }, data)
  22. );
  23. if (file && typeof file === 'string') {
  24. this.push(template + file);
  25. return cb();
  26. }
  27. // if not an existing file, passthrough
  28. if (!isExistingFile(file)) {
  29. this.push(file);
  30. return cb();
  31. }
  32. // handle file stream;
  33. if (file.isStream()) {
  34. const stream = through();
  35. stream.write(Buffer.from(template));
  36. stream.on('error', this.emit.bind(this, 'error'));
  37. file.contents = file.contents.pipe(stream);
  38. this.push(file);
  39. return cb();
  40. }
  41. // variables to handle direct file content manipulation
  42. const concat = new Concat(true, filename);
  43. // add template
  44. concat.add(null, Buffer.from(template));
  45. // add sourcemap
  46. concat.add(file.relative, file.contents, file.sourceMap);
  47. // make sure streaming content is preserved
  48. if (file.contents && !isStream(file.contents)) {
  49. file.contents = concat.content;
  50. }
  51. // apply source map
  52. if (concat.sourceMapping) {
  53. file.sourceMap = JSON.parse(concat.sourceMap);
  54. }
  55. // make sure the file goes through the next gulp plugin
  56. this.push(file);
  57. // tell the stream engine that we are done with this file
  58. cb();
  59. }
  60. return through.obj(TransformStream);
  61. };
  62. /**
  63. * is stream?
  64. */
  65. const isStream = (obj) => {
  66. return obj instanceof stream.Stream;
  67. };
  68. /**
  69. * Is File, and Exists
  70. */
  71. const isExistingFile = (file) => {
  72. try {
  73. if (!(file && typeof file === 'object')) return false;
  74. if (file.isDirectory()) return false;
  75. if (file.isStream()) return true;
  76. if (file.isBuffer()) return true;
  77. if (typeof file.contents === 'string') return true;
  78. } catch (err) {}
  79. return false;
  80. };