index.js 2.4 KB

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