append.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. "use strict";
  2. var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault");
  3. var _interopRequireWildcard = require("@babel/runtime-corejs3/helpers/interopRequireWildcard");
  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 = _default;
  9. var fspp = _interopRequireWildcard(require("../fs-promise-proxy"));
  10. var _commonActionUtils = require("./_common-action-utils");
  11. var _commonActionInterfaceCheck = _interopRequireDefault(require("./_common-action-interface-check"));
  12. const doAppend = async function (data, cfg, plop, fileData) {
  13. const stringToAppend = await (0, _commonActionUtils.getRenderedTemplate)(data, cfg, plop); // if the appended string should be unique (default),
  14. // remove any occurence of it (but only if pattern would match)
  15. const {
  16. separator = '\n'
  17. } = cfg;
  18. if (cfg.unique !== false) {
  19. // only remove after "pattern", so that we remove not too much accidentally
  20. const parts = fileData.split(cfg.pattern);
  21. const lastPart = parts[parts.length - 1];
  22. const lastPartWithoutDuplicates = lastPart.replace(new RegExp(separator + stringToAppend, 'g'), '');
  23. fileData = fileData.replace(lastPart, lastPartWithoutDuplicates);
  24. } // add the appended string to the end of the "fileData" if "pattern"
  25. // was not provided, i.e. null or false
  26. if (!cfg.pattern) {
  27. // make sure to add a "separator" if "fileData" is not empty
  28. if (fileData.length > 0) {
  29. fileData += separator;
  30. }
  31. return fileData + stringToAppend;
  32. }
  33. return fileData.replace(cfg.pattern, '$&' + separator + stringToAppend);
  34. };
  35. async function _default(data, cfg, plop) {
  36. const interfaceTestResult = (0, _commonActionInterfaceCheck.default)(cfg);
  37. if (interfaceTestResult !== true) {
  38. throw interfaceTestResult;
  39. }
  40. const fileDestPath = (0, _commonActionUtils.makeDestPath)(data, cfg, plop);
  41. try {
  42. // check path
  43. const pathExists = await fspp.fileExists(fileDestPath);
  44. if (!pathExists) {
  45. throw 'File does not exist';
  46. } else {
  47. let fileData = await fspp.readFile(fileDestPath);
  48. fileData = await doAppend(data, cfg, plop, fileData);
  49. await fspp.writeFile(fileDestPath, fileData);
  50. }
  51. return (0, _commonActionUtils.getRelativeToBasePath)(fileDestPath, plop);
  52. } catch (err) {
  53. (0, _commonActionUtils.throwStringifiedError)(err);
  54. }
  55. }