/**
 * git操作在这个文件维护
 */
import cp from 'child_process'

interface TemplateInfo {
  git: string
  branch: string
}

// 获取仓库的目录名
// 取仓库地址.git前面的英文作为目录名
export function getRepoDir(git: string) {
  let name = ''
  if (git) {
    const parseUrl = git.split('/')
    name = parseUrl[parseUrl.length - 1].split('.')[0]
  }
  return name
}

// 下载模板仓库
export function downloadRepo(templateInfo: TemplateInfo, options = {}, path = '') {
  // 为了获取下载进度，这里不用shelljs执行
  const commandParams = ['clone', templateInfo.git, '-b', templateInfo.branch]
  if (path) {
    commandParams.push(path)
  }
  const child = cp.spawnSync('git', commandParams, {
    stdio: 'inherit',
    ...options,
  })
  if (child.status === 0) {
    return true
  }
  return false
}

// 打标签
export function setTag(tagName: string, options = {}) {
  const commandParams = ['tag', tagName]
  const child = cp.spawnSync('git', commandParams, {
    ...options,
  })

  if (child.status === 0) {
    return true
  }
  return false
}

export default {
  getRepoDir,
  downloadRepo,
  setTag
}
