copy.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. * grunt-contrib-copy
  3. * http://gruntjs.com/
  4. *
  5. * Copyright (c) 2013 Chris Talkington, contributors
  6. * Licensed under the MIT license.
  7. * https://github.com/gruntjs/grunt-contrib-copy/blob/master/LICENSE-MIT
  8. */
  9. module.exports = function(grunt) {
  10. 'use strict';
  11. var path = require('path');
  12. var fs = require('fs');
  13. grunt.registerMultiTask('copy', 'Copy files.', function() {
  14. var kindOf = grunt.util.kindOf;
  15. var options = this.options({
  16. encoding: grunt.file.defaultEncoding,
  17. // processContent/processContentExclude deprecated renamed to process/noProcess
  18. processContent: false,
  19. processContentExclude: [],
  20. mode: false
  21. });
  22. var copyOptions = {
  23. encoding: options.encoding,
  24. process: options.process || options.processContent,
  25. noProcess: options.noProcess || options.processContentExclude,
  26. };
  27. var dest;
  28. var isExpandedPair;
  29. var tally = {
  30. dirs: 0,
  31. files: 0
  32. };
  33. this.files.forEach(function(filePair) {
  34. isExpandedPair = filePair.orig.expand || false;
  35. filePair.src.forEach(function(src) {
  36. if (detectDestType(filePair.dest) === 'directory') {
  37. dest = (isExpandedPair) ? filePair.dest : unixifyPath(path.join(filePair.dest, src));
  38. } else {
  39. dest = filePair.dest;
  40. }
  41. if (grunt.file.isDir(src)) {
  42. grunt.verbose.writeln('Creating ' + dest.cyan);
  43. grunt.file.mkdir(dest);
  44. tally.dirs++;
  45. } else {
  46. grunt.verbose.writeln('Copying ' + src.cyan + ' -> ' + dest.cyan);
  47. grunt.file.copy(src, dest, copyOptions);
  48. if (options.mode !== false) {
  49. fs.chmodSync(dest, (options.mode === true) ? fs.lstatSync(src).mode : options.mode);
  50. }
  51. tally.files++;
  52. }
  53. });
  54. });
  55. if (tally.dirs) {
  56. grunt.log.write('Created ' + tally.dirs.toString().cyan + ' directories');
  57. }
  58. if (tally.files) {
  59. grunt.log.write((tally.dirs ? ', copied ' : 'Copied ') + tally.files.toString().cyan + ' files');
  60. }
  61. grunt.log.writeln();
  62. });
  63. var detectDestType = function(dest) {
  64. if (grunt.util._.endsWith(dest, '/')) {
  65. return 'directory';
  66. } else {
  67. return 'file';
  68. }
  69. };
  70. var unixifyPath = function(filepath) {
  71. if (process.platform === 'win32') {
  72. return filepath.replace(/\\/g, '/');
  73. } else {
  74. return filepath;
  75. }
  76. };
  77. };