js拉取仓库的脚本
"dependencies": {
"axios": "^1.6.0",
"chalk": "^4.1.2",
"child_process": "^1.0.2",
"console": "^0.7.2",
"diff": "^5.1.0",
"exceljs": "^4.3.0",
"fs-extra": "^11.1.1",
"git-clone": "^0.2.0",
"https": "^1.0.0",
"minimist": "^1.2.8",
"prettier": "^3.1.0",
"shell": "^0.5.1",
"shelljs": "^0.8.5",
"simple-git": "^3.19.1",
"xlsx-populate": "^1.21.0"
},
1.判断当前文件中是否存在子文件
// 使用fs.readdir()方法读取路径下的文件和文件夹
async function folderPathSubFiles(folderPath) {
// 判断逻辑
return new Promise((resolve, reject) => {
fs.readdir(folderPath, (error, files) => {
if (error) {
reject(error);
}
if (files && files?.length > 0) {
resolve(files);
} else {
const customError = new Error('当前路径下不存在文件');
reject(customError);
}
});
})
}
2.切换到对应分支,并拉取最新代码
//引入git文件
const simpleGit = require('simple-git');
function checkGitSourceExist({ destinationPath, branch }) {
console.log('destinationPath ------ ', destinationPath, branch);
return new Promise((resolve, reject) => {
const git = simpleGit(destinationPath);
// 切换分支命令
git.checkout(branch, (error, result) => {
if (error) {
console.log('切换分支时出错:', error);
reject(error);
}
// 拉取最新代码命令
git.pull((error, update) => {
if (error) {
console.log('拉取代码时出错:', error);
reject(error);
}
if (update && update.summary.changes) {
console.log(`${destinationPath} 已成功拉取最新代码 -- `);
} else {
console.log(`${destinationPath} 代码已是最新 -- `);
}
resolve({ success: true });
});
});
});
}
3.下载对应仓库的代码
function downloadGitSource({ destinationPath, sourceUrl, username, password, branch }) {
const repositoryUrl = sourceUrl;
const git = simpleGit();
// SSH方式进行下载
let urlWithCredentials = repositoryUrl;
// 密码进行recode
if (username && password) {
// 命令拼接 -- 用户名密码方式进行下载
const encodedUsername = encodeURIComponent(username);
const encodedPassword = encodeURIComponent(password);
urlWithCredentials = repositoryUrl?.replace('://', `://${encodedUsername}:${encodedPassword}@`);
}
return new Promise((resolve, reject) => {
// 第一个命令克隆整个历史,且只克隆指定分支的内容。
git.clone(urlWithCredentials, destinationPath, ['--branch', branch])
//第二个命令是一个浅克隆,它还将递归克隆所有子模块(如果存在的话),并且仅包含最新的一次提交。
// git.clone(urlWithCredentials, destinationPath, { '--recursive': null, '--depth': 1 })
.then(() => {
console.log(chalk.green(`${destinationPath} 下载成功 --- `));
resolve({ success: true });
})
.catch((err) => {
console.log(chalk.red(`${destinationPath} 下载失败了 --- ${err}`));
// reject(err);
});
});
}
4.汇总 外部使用文件
async function ru_downLoadGitProject({ projectName, sourceUrl, username, password, branch, targetDirectory }) {
const destinationPath = targetDirectory + '/' + projectName;
return new Promise(async (resolve, reject) => {
// 判断当前文件是否已经存在,如果存在,不需要重复下载 (可以完善一下 如果已存在只执行git pull)
const files = await folderPathSubFiles(destinationPath).catch(async error => {
const downloadRes = await downloadGitSource({ destinationPath, sourceUrl, username, password, branch }).catch(error => {
reject(error);
});
// console.log('downloadRes *****', downloadRes);
if (downloadRes?.success === true) {
// console.log('projectName 下载完毕,并且切换到了分支 -- ', branch);
resolve({ success: true, filePath: destinationPath });
} else {
reject(error);
}
});
if (files?.length > 0) {
// 直接去切换分支
const checkRes = await checkGitSourceExist({ destinationPath, branch }).catch(async error => {
const downloadRes = await downloadGitSource({ destinationPath, sourceUrl, username, password, branch }).catch(error => {
reject(error);
});
if (downloadRes?.success === true) {
// console.log('projectName 下载完毕,并且切换到了分支 -- ', branch);
resolve({ success: true, filePath: destinationPath });
} else {
reject(error);
}
});
if (checkRes?.success === true) {
resolve({ success: true, filePath: destinationPath });
}
}
})
}
//其他获取对应git文件 并执行git push
const { exec, execSync } = require("child_process");
const shell = require("shelljs");
const chalk = require('chalk');
const fs = require('fs')
const path = require('path')
// 在指定目录执行命令的函数
// 使用命令列表链式执行 Git 命令
const gitCommands = [
"git add .",
'git commit -m "feat: 更新 builderVersion 到 v10.1.0"',
// 添加更多命令如果需要的话, 例如: 'git push origin main'
];
// 将命令合并为一个批处理命令
const batchCommand = gitCommands.join(" && ");
// 逐个执行 Git 命令
// commands.forEach(runGitCommand);
function ru_runCommand(command, directory, callBack) {
console.log("开始切换目录", directory);
try {
const result = execSync(command, {
cwd: directory,
stdio: 'inherit', // 'inherit' 选项会将子进程的输出直接在父进程中输出(控制台)
});
console.log("执行成功!");
return true; // 执行成功,返回 true
} catch (err) {
console.error(`执行出错: ${err}`);
return false; // 执行失败,返回 false
}
}
function CR(bundlePath) {
const gitHeadFilePath = path.resolve(bundlePath, ".git/HEAD");
if (!fs.existsSync(gitHeadFilePath)) {
console.log("未找到 .git/HEAD 文件");
process.exit(1);
}
const headContent = fs.readFileSync(gitHeadFilePath);
const headBranchRefName = headContent.toString().trim();
const [_, headBranch] = headBranchRefName.split("refs/heads/");
if (!headBranch) {
console.log("未读取到分支信息");
process.exit(1);
}
const result = shell.exec(`git push origin HEAD:refs/for/${headBranch}`, { cwd: bundlePath, silent: true, async: false });
const stderrWithoutColors = result.stderr.replace(/\u001b\[[0-9;]*m/g, ""); // 清除 ANSI 转义序列 存在颜色字符
const matchResult = stderrWithoutColors.match(/(https\:.+?)\s/) || [];
const CRUrl = matchResult[1];
return CRUrl;
}
function runGitCommand(bundlePath) {
console.log("开始执行git")
const success = runCommand(batchCommand, bundlePath);
console.log("结束执行git")
if(success) {
const CRUrl = CR(bundlePath);
const fileName = path.basename(bundlePath);
return {
originUrl: CRUrl,
fileUrl: `${fileName}: ${CRUrl}`
};
}
return null; // 如果 Git 命令执行失败,返回 null
}
网友评论