cloneRepository static method
克隆Git仓库到指定位置
TODO 待完善逻辑以及测试
执行逻辑:
- 判断当前路径中是否为git仓库,如果不是则进行克隆,如果是则判断是否有变动文件,如果有则暂存,然后更新仓库所有文件
- 判断需求分支在远程是否存在,如果存在则检出,如果不存在则以master分支为基准进行创建
url 仓库URL
pathRep 需要克隆地址
branch 克隆分支
Implementation
static Future<void> cloneRepository(
String url,
String pathRep, {
String branch = 'master',
}) async {
// 远程分支分支
List<String> remoteBranchList = [];
// 是否包含当前分支
bool hasBranch;
final existsPath = await IOUtil.existsAsync(pathRep);
final existsRepo = existsPath &&
(await IOUtil.existsAsync(PathUtil.join(pathRep, '.git')));
if (existsPath && existsRepo) {
// 如果有变更文件则执行暂存
if (await checkHasChange(pathRep)) {
stashChanges(pathRep);
}
remoteBranchList = await getRemoteBranchList(pathRep);
hasBranch = remoteBranchList.contains(branch);
// 更新所有分支代码
for (final remoteBranch in remoteBranchList) {
final cmdCheckout = 'git checkout $remoteBranch';
// 如果有变更文件则执行暂存
if (await checkHasChange(pathRep)) {
stashChanges(pathRep);
}
await ProcessUtil.runCmdWait(
cmd: cmdCheckout,
workingDirectory: pathRep,
);
final cmdPull = 'git pull origin $remoteBranch';
await ProcessUtil.runCmdWait(
cmd: cmdPull,
workingDirectory: pathRep,
);
}
} else {
if (existsPath) {
IOUtil.removeFilesSync(pathRep);
}
final urlRepo = getRepositoryPath(url);
final cmdClone = 'git clone $urlRepo $pathRep';
await ProcessUtil.runCmdWait(cmd: cmdClone, workingDirectory: pathRep);
remoteBranchList = await getRemoteBranchList(pathRep);
hasBranch = remoteBranchList.contains(branch);
}
if (hasBranch) {
// 首先判断远程是否有该分支
final cmdCheckout = 'git checkout $branch';
await ProcessUtil.runCmdWait(cmd: cmdCheckout, workingDirectory: pathRep);
} else {
// 若当前为空仓库,则master分支不存在,默认不执行操作
if (branch != 'master') {
final cmdCheckoutTarget = 'git checkout -b $branch master';
await ProcessUtil.runCmdWait(
cmd: cmdCheckoutTarget,
workingDirectory: pathRep,
);
}
}
}