index.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. var through = require('through'),
  2. path = require('path'),
  3. fs = require('fs'),
  4. exec = require('child_process').exec,
  5. PluginError = require('gulp-util').PluginError;
  6. module.exports = function(destination, opts) {
  7. if (!destination) {
  8. throw new PluginError('gulp-copy', 'Missing destination option for gulp-copy');
  9. }
  10. opts = opts || {};
  11. function copyFiles(file) {
  12. if (file.isNull()) return; // ignore
  13. if (file.isStream()) return this.emit('error', new PluginError('gulp-copy', 'Streaming not supported'));
  14. var rel = path.relative(file.cwd, file.path).replace(/\\/g, '/'),
  15. self = this,
  16. fileDestination;
  17. // Strip path prefixes
  18. if(opts.prefix) {
  19. var p = opts.prefix;
  20. while(p-- > 0) {
  21. rel = rel.substring(rel.indexOf('/') + 1);
  22. }
  23. }
  24. fileDestination = destination + '/' + rel;
  25. // Make sure destination exists
  26. if (!fs.existsSync(fileDestination)) {
  27. createDestination(fileDestination.substr(0, fileDestination.lastIndexOf('/')));
  28. }
  29. // Copy the file
  30. copyFile(file.path, fileDestination, function (error) {
  31. if (error) {
  32. throw new PluginError('gulp-copy', 'Could not copy file <' + file.path + '>: ' + error.message);
  33. }
  34. // Update path for file so this path is used later on
  35. file.path = fileDestination;
  36. self.emit('data', file);
  37. });
  38. }
  39. function streamEnd()
  40. {
  41. this.emit('end');
  42. }
  43. function createDestination(destination)
  44. {
  45. var folders = destination.split('/'),
  46. path = [],
  47. l = folders.length,
  48. i = 0;
  49. for (; i < l; i++) {
  50. path.push(folders[i]);
  51. if (!fs.existsSync(path.join('/'))) {
  52. try {
  53. fs.mkdirSync(path.join('/'));
  54. } catch (error) {
  55. throw new PluginError('gulp-copy', 'Could not create destination <' + destination + '>: ' + error.message);
  56. }
  57. }
  58. }
  59. }
  60. function copyFile(source, target, cb)
  61. {
  62. var cbCalled = false,
  63. rd = fs.createReadStream(source),
  64. wr;
  65. rd.on("error", function(err) {
  66. done(err);
  67. });
  68. wr = fs.createWriteStream(target);
  69. wr.on("error", function(err) {
  70. done(err);
  71. });
  72. wr.on("close", function(ex) {
  73. done();
  74. });
  75. rd.pipe(wr);
  76. function done(err)
  77. {
  78. if (!cbCalled) {
  79. cb(err);
  80. cbCalled = true;
  81. }
  82. }
  83. }
  84. return through(copyFiles, streamEnd);
  85. };