_common-action-add-file.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. "use strict";
  2. var _interopRequireWildcard = require("@babel/runtime-corejs3/helpers/interopRequireWildcard");
  3. var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault");
  4. var _Object$defineProperty = require("@babel/runtime-corejs3/core-js-stable/object/define-property");
  5. _Object$defineProperty(exports, "__esModule", {
  6. value: true
  7. });
  8. exports.default = addFile;
  9. var _path = _interopRequireDefault(require("path"));
  10. var _del = _interopRequireDefault(require("del"));
  11. var _commonActionUtils = require("./_common-action-utils");
  12. var _isbinaryfile = require("isbinaryfile");
  13. var fspp = _interopRequireWildcard(require("../fs-promise-proxy"));
  14. async function addFile(data, cfg, plop) {
  15. const fileDestPath = (0, _commonActionUtils.makeDestPath)(data, cfg, plop);
  16. const {
  17. force,
  18. skipIfExists = false
  19. } = cfg;
  20. try {
  21. // check path
  22. let destExists = await fspp.fileExists(fileDestPath); // if we are forcing and the file already exists, delete the file
  23. if (force === true && destExists) {
  24. await (0, _del.default)([fileDestPath], {
  25. force
  26. });
  27. destExists = false;
  28. } // we can't create files where one already exists
  29. if (destExists) {
  30. if (skipIfExists) {
  31. return `[SKIPPED] ${fileDestPath} (exists)`;
  32. }
  33. throw `File already exists\n -> ${fileDestPath}`;
  34. } else {
  35. await fspp.makeDir(_path.default.dirname(fileDestPath));
  36. const absTemplatePath = cfg.templateFile && _path.default.resolve(plop.getPlopfilePath(), cfg.templateFile) || null;
  37. if (absTemplatePath != null && (0, _isbinaryfile.isBinaryFileSync)(absTemplatePath)) {
  38. const rawTemplate = await fspp.readFileRaw(cfg.templateFile);
  39. await fspp.writeFileRaw(fileDestPath, rawTemplate);
  40. } else {
  41. const renderedTemplate = await (0, _commonActionUtils.getRenderedTemplate)(data, cfg, plop);
  42. const transformedTemplate = await (0, _commonActionUtils.getTransformedTemplate)(renderedTemplate, data, cfg);
  43. await fspp.writeFile(fileDestPath, transformedTemplate);
  44. } // keep the executable flags
  45. if (absTemplatePath != null) {
  46. const sourceStats = await fspp.stat(absTemplatePath);
  47. const destStats = await fspp.stat(fileDestPath);
  48. const executableFlags = sourceStats.mode & (fspp.constants.S_IXUSR | fspp.constants.S_IXGRP | fspp.constants.S_IXOTH);
  49. await fspp.chmod(fileDestPath, destStats.mode | executableFlags);
  50. }
  51. } // return the added file path (relative to the destination path)
  52. return (0, _commonActionUtils.getRelativeToBasePath)(fileDestPath, plop);
  53. } catch (err) {
  54. (0, _commonActionUtils.throwStringifiedError)(err);
  55. }
  56. }