concat.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * grunt-contrib-concat
  3. * http://gruntjs.com/
  4. *
  5. * Copyright (c) 2012 "Cowboy" Ben Alman, contributors
  6. * Licensed under the MIT license.
  7. */
  8. 'use strict';
  9. module.exports = function(grunt) {
  10. // Internal lib.
  11. var comment = require('./lib/comment').init(grunt);
  12. grunt.registerMultiTask('concat', 'Concatenate files.', function() {
  13. // Merge task-specific and/or target-specific options with these defaults.
  14. var options = this.options({
  15. separator: grunt.util.linefeed,
  16. banner: '',
  17. footer: '',
  18. stripBanners: false,
  19. process: false
  20. });
  21. // Normalize boolean options that accept options objects.
  22. if (options.stripBanners === true) { options.stripBanners = {}; }
  23. if (options.process === true) { options.process = {}; }
  24. // Process banner and footer.
  25. var banner = grunt.template.process(options.banner);
  26. var footer = grunt.template.process(options.footer);
  27. // Iterate over all src-dest file pairs.
  28. this.files.forEach(function(f) {
  29. // Concat banner + specified files + footer.
  30. var src = banner + f.src.filter(function(filepath) {
  31. // Warn on and remove invalid source files (if nonull was set).
  32. if (!grunt.file.exists(filepath)) {
  33. grunt.log.warn('Source file "' + filepath + '" not found.');
  34. return false;
  35. } else {
  36. return true;
  37. }
  38. }).map(function(filepath) {
  39. // Read file source.
  40. var src = grunt.file.read(filepath);
  41. // Process files as templates if requested.
  42. if (typeof options.process === 'function') {
  43. src = options.process(src, filepath);
  44. } else if (options.process) {
  45. src = grunt.template.process(src, options.process);
  46. }
  47. // Strip banners if requested.
  48. if (options.stripBanners) {
  49. src = comment.stripBanner(src, options.stripBanners);
  50. }
  51. return src;
  52. }).join(options.separator) + footer;
  53. // Write the destination file.
  54. grunt.file.write(f.dest, src);
  55. // Print a success message.
  56. grunt.log.writeln('File "' + f.dest + '" created.');
  57. });
  58. });
  59. };