"use strict";

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

function _react() {
  const data = _interopRequireDefault(require("react"));

  _react = function _react() {
    return data;
  };

  return data;
}

function _assert() {
  const data = _interopRequireDefault(require("assert"));

  _assert = function _assert() {
    return data;
  };

  return data;
}

function _umiUtils() {
  const data = require("umi-utils");

  _umiUtils = function _umiUtils() {
    return data;
  };

  return data;
}

function _fs() {
  const data = require("fs");

  _fs = function _fs() {
    return data;
  };

  return data;
}

function _path() {
  const data = require("path");

  _path = function _path() {
    return data;
  };

  return data;
}

var _getBlockGenerator = require("../../../../getBlockGenerator");

var _this = void 0;

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

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

const isSubmodule = templateTmpDirPath => (0, _fs().existsSync)((0, _path().join)(templateTmpDirPath, '.gitmodules'));

const addPrefix = path => {
  if (!/^\//.test(path)) {
    return `/${path}`;
  }

  return path;
};

const clone = /*#__PURE__*/function () {
  var _ref = _asyncToGenerator(function* (ctx, args) {
    const logger = ctx.logger,
          execa = ctx.execa;
    const _ref2 = ctx.stages.blockCtx,
          branch = _ref2.branch,
          templateTmpDirPath = _ref2.templateTmpDirPath,
          sourcePath = _ref2.sourcePath,
          routePath = _ref2.routePath;
    logger.appendLog('⚓  Start git fetch');

    try {
      yield execa('git', ['fetch'], {
        cwd: templateTmpDirPath
      });
    } catch (e) {
      logger.appendLog(`Faild git fetch: ${e.message}`);
      throw new Error(e);
    }

    logger.appendLog('🎉  Success git fetch\n');
    logger.appendLog(`⚓  Start git checkout ${branch}`);

    try {
      yield execa('git', ['checkout', branch], {
        cwd: templateTmpDirPath
      });
    } catch (e) {
      logger.appendLog(`Faild git checkout: ${e.message}\n`); // throw new Error(e);
    }

    logger.appendLog(`🎉  Success git checkout ${branch}\n`);
    logger.appendLog('⚓  Start git pull');

    try {
      yield execa('git', ['pull'], {
        cwd: templateTmpDirPath
      }); // 如果是 git pull 之后有了
      // git module 只能通过这种办法来初始化一下

      if (isSubmodule(templateTmpDirPath)) {
        // 结束  git pull 的 spinner
        // 如果是分支切换过来，可能没有初始化，初始化一下
        yield execa('git', ['submodule', 'init'], {
          cwd: templateTmpDirPath,
          env: process.env
        });
        yield execa('git', ['submodule', 'update', '--recursive'], {
          cwd: templateTmpDirPath
        });
      }
    } catch (e) {
      if (e.killed) {
        const err = new Error('Cancel git pull');
        err.name = 'GitUpdateError';
        logger.appendLog('Cancel git pull\n');
        throw err;
      }

      logger.appendLog(`Faild git pull: ${e.message || ''}\n`);
      throw e;
    }

    logger.appendLog('🎉  Success git pull\n');
    (0, _assert().default)((0, _fs().existsSync)(sourcePath), `${sourcePath} don't exists`);
    let pkg; // get block's package.json

    const pkgPath = (0, _path().join)(sourcePath, 'package.json');

    if (!(0, _fs().existsSync)(pkgPath)) {
      throw new Error(`not find package.json in ${_this.sourcePath}`);
    } else {
      // eslint-disable-next-line
      pkg = JSON.parse((0, _fs().readFileSync)(pkgPath, 'utf-8'));
      ctx.stages.blockCtx.pkg = pkg;
    } // setup route path


    const path = args.path;
    let filePath = '';

    if (!path) {
      const blockName = (0, _getBlockGenerator.getNameFromPkg)(pkg);

      if (!blockName) {
        const errMsg = "Can not find name in block's package.json";
        logger.appendLog(errMsg);
        const err = new Error(errMsg);
        throw err;
      }

      filePath = `/${blockName}`;
    } else {
      filePath = (0, _umiUtils().winPath)(path);
    }

    ctx.stages.blockCtx.filePath = addPrefix(filePath); // 如果 ctx.routePath 不存在，使用 filePath

    if (!routePath) {
      ctx.stages.blockCtx.routePath = filePath;
    }

    ctx.stages.blockCtx.routePath = addPrefix(ctx.stages.blockCtx.routePath);
  });

  return function clone(_x, _x2) {
    return _ref.apply(this, arguments);
  };
}();

var _default = clone;
exports.default = _default;