prepareWrite.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. 'use strict';
  2. var assign = require('object-assign');
  3. var path = require('path');
  4. var mkdirp = require('mkdirp');
  5. var fs = require('graceful-fs');
  6. function booleanOrFunc(v, file) {
  7. if (typeof v !== 'boolean' && typeof v !== 'function') {
  8. return null;
  9. }
  10. return typeof v === 'boolean' ? v : v(file);
  11. }
  12. function stringOrFunc(v, file) {
  13. if (typeof v !== 'string' && typeof v !== 'function') {
  14. return null;
  15. }
  16. return typeof v === 'string' ? v : v(file);
  17. }
  18. function prepareWrite(outFolder, file, opt, cb) {
  19. var options = assign({
  20. cwd: process.cwd(),
  21. mode: (file.stat ? file.stat.mode : null),
  22. dirMode: null,
  23. overwrite: true,
  24. }, opt);
  25. var overwrite = booleanOrFunc(options.overwrite, file);
  26. options.flag = (overwrite ? 'w' : 'wx');
  27. var cwd = path.resolve(options.cwd);
  28. var outFolderPath = stringOrFunc(outFolder, file);
  29. if (!outFolderPath) {
  30. throw new Error('Invalid output folder');
  31. }
  32. var basePath = options.base ?
  33. stringOrFunc(options.base, file) : path.resolve(cwd, outFolderPath);
  34. if (!basePath) {
  35. throw new Error('Invalid base option');
  36. }
  37. var writePath = path.resolve(basePath, file.relative);
  38. var writeFolder = path.dirname(writePath);
  39. // Wire up new properties
  40. file.stat = (file.stat || new fs.Stats());
  41. file.stat.mode = options.mode;
  42. file.flag = options.flag;
  43. file.cwd = cwd;
  44. file.base = basePath;
  45. file.path = writePath;
  46. // Mkdirp the folder the file is going in
  47. var mkdirpOpts = {
  48. mode: options.dirMode,
  49. fs: fs,
  50. };
  51. mkdirp(writeFolder, mkdirpOpts, function(err) {
  52. if (err) {
  53. return cb(err);
  54. }
  55. cb(null, writePath);
  56. });
  57. }
  58. module.exports = prepareWrite;