copy.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. 'use strict';
  2. var assert = require('assert');
  3. var fs = require('fs');
  4. var path = require('path');
  5. var glob = require('glob');
  6. var globby = require('globby');
  7. var extend = require('deep-extend');
  8. var multimatch = require('multimatch');
  9. var ejs = require('ejs');
  10. var util = require('../util');
  11. function applyProcessingFunc(process, contents, filename) {
  12. var output = process(contents, filename);
  13. return output instanceof Buffer ? output : Buffer.from(output);
  14. }
  15. exports.copy = function (from, to, options, context, tplSettings) {
  16. to = path.resolve(to);
  17. options = options || {};
  18. var fromGlob = util.globify(from);
  19. var globOptions = extend(options.globOptions || {}, {nodir: true});
  20. var diskFiles = globby.sync(fromGlob, globOptions);
  21. var storeFiles = [];
  22. this.store.each(file => {
  23. if (multimatch([file.path], fromGlob).length !== 0) {
  24. storeFiles.push(file.path);
  25. }
  26. });
  27. var files = diskFiles.concat(storeFiles);
  28. var generateDestination = () => to;
  29. if (Array.isArray(from) || !this.exists(from) || glob.hasMagic(from)) {
  30. assert(
  31. !this.exists(to) || fs.statSync(to).isDirectory(),
  32. 'When copying multiple files, provide a directory as destination'
  33. );
  34. var root = util.getCommonPath(from);
  35. generateDestination = filepath => {
  36. var toFile = path.relative(root, filepath);
  37. return path.join(to, toFile);
  38. };
  39. }
  40. // Sanity checks: Makes sure we copy at least one file.
  41. assert(files.length > 0, 'Trying to copy from a source that does not exist: ' + from);
  42. files.forEach(file => {
  43. this._copySingle(file, generateDestination(file), options, context, tplSettings);
  44. });
  45. };
  46. exports._copySingle = function (from, to, options, context, tplSettings) {
  47. options = options || {};
  48. assert(this.exists(from), 'Trying to copy from a source that does not exist: ' + from);
  49. var file = this.store.get(from);
  50. var contents = file.contents;
  51. if (options.process) {
  52. contents = applyProcessingFunc(options.process, file.contents, file.path);
  53. }
  54. if (context) {
  55. to = ejs.render(to, context, tplSettings);
  56. }
  57. this.write(to, contents, file.stat);
  58. };