"use strict";var _Object$defineProperty = require("@babel/runtime-corejs2/core-js/object/define-property");var _interopRequireDefault = require("@babel/runtime-corejs2/helpers/interopRequireDefault");_Object$defineProperty(exports, "__esModule", { value: true });exports.writeFileTree = exports.replaceFiles = void 0;var _keys = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/object/keys"));var _promise = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/promise"));var _path = _interopRequireDefault(require("path"));
var _index = require("../../cli-shared-utils/index.js");

function deleteRemovedFiles(directory, newFiles, previousFiles) {
  // get all files that are not in the new filesystem and are still existing
  const filesToDelete = (0, _keys.default)(previousFiles).
  filter((filename) => !newFiles[filename]);

  // delete each of these files
  return _promise.default.all(filesToDelete.map((filename) => {
    return _index.fs.unlink(_path.default.join(directory, filename));
  }));
}

const writeFileTree = async (dir, files, previousFiles) => {
  if (previousFiles) {
    await deleteRemovedFiles(dir, files, previousFiles);
  }
  (0, _keys.default)(files).forEach((name) => {
    const filePath = _path.default.join(dir, name);
    _index.fs.ensureDirSync(_path.default.dirname(filePath));
    _index.fs.writeFileSync(filePath, files[name]);
  });
};exports.writeFileTree = writeFileTree;

const replaceFiles = async (names, files) => {
  files.forEach((file) => {
    let content = _index.fs.readFileSync(file, {
      encoding: 'utf-8'
    });
    (0, _keys.default)(names).forEach((n) => {
      /* eslint-disable no-eval */
      content = content.replace(eval(`/{{${n}}}/g`), function (defaultName) {
        return names[n] || defaultName;
      });
      /* eslint-enable no-eval */
    });

    _index.fs.writeFileSync(file, content);
  });
};exports.replaceFiles = replaceFiles;