"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.initPreCommitHook = exports.getGitRootDir = void 0;

var _fs = _interopRequireDefault(require("fs"));

var _path = _interopRequireDefault(require("path"));

var _child_process = require("child_process");

var _log = require("./log");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

let getGitRootDir = () => {
  try {
    return (0, _child_process.execSync)('git rev-parse --show-toplevel').toString();
  } catch (e) {
    return false;
  }
}; //eslint-disable-next-line


exports.getGitRootDir = getGitRootDir;

let copyEslintConfig = rootDir => {
  rootDir = rootDir.replace(/\r?\n|\r/g, ''); //eslint-disable-line

  let srcPath = _path.default.join(__dirname, '..', '..', '.eslintrc.js');

  let targetPath = _path.default.join(rootDir, '.eslintrc.js');

  if (!_fs.default.existsSync(targetPath)) {
    let src = _fs.default.readFileSync(srcPath).toString();

    _fs.default.writeFileSync(targetPath, src);

    (0, _log.log)('Eslint config added in project root path');
  }
};

let initPreCommitHook = (forReactCLI = false) => {
  let gitRootDir = getGitRootDir(); //copyEslintConfig(gitRootDir || process.cwd());

  if (gitRootDir) {
    let precommit = _fs.default.readFileSync(_path.default.join(__dirname, '../sh/pre-commit.sh')).toString();

    let targetPath = _path.default.join(gitRootDir, '.git', 'hooks', 'pre-commit').replace(/\s/g, '');

    if (_fs.default.existsSync(`${targetPath}.sample`)) {
      precommit = precommit.replace('${PREFIX_PATH}', //eslint-disable-line
      process.cwd().replace(/\\/g, '/'));

      _fs.default.renameSync(`${targetPath}.sample`, targetPath);

      _fs.default.writeFileSync(targetPath, precommit);

      (0, _log.log)('pre-commit hook added');
    }

    let packagePath = _path.default.join(process.cwd(), 'package.json');

    try {
      let packageJson = require(packagePath);

      if (packageJson.scripts.lint !== 'react-cli lint') {
        packageJson.scripts.lint = forReactCLI ? 'eslint ./src' : 'react-cli lint';

        _fs.default.writeFileSync(packagePath, JSON.stringify(packageJson, null, 2));

        (0, _log.log)('lint script added in your package.json');
      }
    } catch (e) {
      (0, _log.log)('package.json not found');
    }
  }
};

exports.initPreCommitHook = initPreCommitHook;