"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.makeSureMaterialsTempPathExist = makeSureMaterialsTempPathExist;
exports.downloadFromGit = downloadFromGit;
exports.isGitUrl = isGitUrl;
exports.parseGitUrl = parseGitUrl;
exports.getParsedData = getParsedData;
exports.urlAddGit = void 0;

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

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

  return data;
}

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

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

  return data;
}

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

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

  return data;
}

function _crossSpawn() {
  const data = _interopRequireDefault(require("cross-spawn"));

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

  return data;
}

function _mkdirp() {
  const data = _interopRequireDefault(require("mkdirp"));

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

  return data;
}

function _os() {
  const data = require("os");

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

  return data;
}

function _gitUrlParse() {
  const data = _interopRequireDefault(require("git-url-parse"));

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

  return data;
}

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

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

  return data;
}

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 debug = require('debug')('umi-build-dev:MaterialDownload');

const spawnSync = _crossSpawn().default.sync;

function makeSureMaterialsTempPathExist(dryRun) {
  const userHome = process.env.NODE_ENV === 'test' ? '/Users/test' : (0, _os().homedir)();
  const blocksTempPath = (0, _path().join)(userHome, '.umi/blocks');

  if (dryRun) {
    return blocksTempPath;
  }

  if (!(0, _fs().existsSync)(blocksTempPath)) {
    debug(`mkdir blocksTempPath ${blocksTempPath}`);

    _mkdirp().default.sync(blocksTempPath);
  }

  return blocksTempPath;
}

function downloadFromGit(url, id, branch = 'master', log, args = {}) {
  const dryRun = args.dryRun;
  const blocksTempPath = makeSureMaterialsTempPathExist(dryRun);
  const templateTmpDirPath = (0, _path().join)(blocksTempPath, id);

  if ((0, _fs().existsSync)(templateTmpDirPath)) {
    // git repo already exist, pull it
    // cd id && git pull
    log.info(`${url} exist in cache, start pull from git to update...`);

    if (dryRun) {
      log.log('dryRun is true, skip git pull');
    } else {
      spawnSync('git', ['fetch'], {
        cwd: templateTmpDirPath
      });
      spawnSync('git', ['checkout', branch], {
        cwd: templateTmpDirPath
      });
      spawnSync('git', ['pull'], {
        cwd: templateTmpDirPath
      });
    }
  } else {
    // new git repo, clone
    // git clone url id
    log.info(`start clone code from ${url}...`);

    if (dryRun) {
      log.log('dryRun is true, skip git clone');
    } else {
      spawnSync('git', ['clone', url, id, '-b', branch], {
        cwd: blocksTempPath
      });
    }
  }

  log.info(`code download to ${templateTmpDirPath}`);
  return templateTmpDirPath;
} // git site url maybe like: http://gitlab.alitest-inc.com/bigfish/bigfish-blocks/tree/master/demo
// or http://gitlab.alitest-inc.com/bigfish/testblocks/tree/master
// or http://gitlab.alitest-inc.com/bigfish/testblocks
// or https://github.com/umijs/umi-blocks/tree/master/demo
// or https://github.com/alibaba/ice/tree/master/react-blocks/blocks/AbilityIntroduction


const gitSiteParser = /^(https\:\/\/|http\:\/\/|git\@)((github|gitlab)[\.\w\-]+|(?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))(\/|\:)([\w\-]+)\/([\w\-]+)(\/tree\/([\w\.\-]+)([\w\-\/]+))?(.git)?$/;

function isGitUrl(url) {
  return gitSiteParser.test(url);
}
/**
 * gitlab 不加 .git 会将用户重定向到登录
 * @param {*} url
 */


const urlAddGit = url => {
  if (/\.git$/.test(url)) {
    return url;
  }

  return `${url}.git`;
};
/**
 * 使用 antd@3 的模板和区块
 * @param {*} ref
 */


exports.urlAddGit = urlAddGit;

const getAntdVersion = ref => {
  try {
    const _require = require('antd'),
          version = _require.version;

    if (version.startsWith(3) && ref === 'master') {
      return 'antd@3';
    }
  } catch (error) {// return ref;
  }

  if (process.env.BLOCK_REPO_BRANCH) {
    return process.env.BLOCK_REPO_BRANCH;
  }

  if (ref === 'master' || !ref) {
    return 'umi@2';
  }

  return ref;
};

function parseGitUrl(_x, _x2) {
  return _parseGitUrl.apply(this, arguments);
}

function _parseGitUrl() {
  _parseGitUrl = _asyncToGenerator(function* (url, closeFastGithub) {
    const args = (0, _gitUrlParse().default)(url);
    const ref = args.ref,
          filepath = args.filepath,
          branch = args.branch,
          resource = args.resource,
          fullName = args.full_name;
    const fastGithub = yield (0, _umiUtils().getFastGithub)(); // 如果是 github 并且 autoFastGithub =true 使用
    // 因为自动转化只支持 github 也可以需要关掉

    const repo = resource === 'github.com' && !closeFastGithub ? args.toString().replace(`${resource}`, fastGithub) : args.toString();
    return {
      repo: urlAddGit(repo),
      branch: getAntdVersion(ref) || 'master',
      path: `/${filepath}`,
      id: `${resource}/${fullName}` // 唯一标识一个 git 仓库

    };
  });
  return _parseGitUrl.apply(this, arguments);
}

function getParsedData(_x3, _x4) {
  return _getParsedData.apply(this, arguments);
}

function _getParsedData() {
  _getParsedData = _asyncToGenerator(function* (url, blockConfig) {
    debug(`url: ${url}`);
    let realUrl;
    const defaultGitUrl = blockConfig.defaultGitUrl || 'https://github.com/umijs/umi-blocks';

    if (isGitUrl(url)) {
      realUrl = url;
      debug('is git url');
    } else if (/^[\w]+[\w\-\/]*$/.test(url)) {
      realUrl = `${defaultGitUrl}/tree/master/${url}`;
      debug(`will use ${realUrl} as the block url`);
    } else if (/^[\.\/]|^[c-zC-Z]:/.test(url)) {
      // ^[c-zC-Z]:  目的是为了支持window下的绝对路径，比如 `C:\\Project\\umi`
      // locale path for test
      const sourcePath = (0, _path().resolve)(process.cwd(), url);
      debug(`will use ${sourcePath} as the block url`);
      return {
        isLocal: true,
        sourcePath
      };
    } else {
      throw new Error(`${url} can't match any pattern`);
    }

    const args = yield parseGitUrl(realUrl, blockConfig.closeFastGithub);
    return args;
  });
  return _getParsedData.apply(this, arguments);
}