如何知道一个分支有没有把主干合并过来?
背景就是我想写一个简单的CI,用户指定分支后,用这个分支的代码进行构建
现在会遇到的一个实际问题是,我在做某个迭代的时候,会有其他一些迭代或者hotfix先于当前需求发布,此时就需要把主干的最新代码合并过来,要不然测试的结果并不可靠。
那要怎么判断当前分支是否合并了最新主干?
思路1
命令行执行
git log my-branch
git log
然后对两个结果进行字符串比较,确认是否合并,但是如果 my-branch 先于 主干非常多,这个结果可能会有偏差
思路2
命令行执行
git merge origin/主干
根据执行的结果进行字符串对比,确认是否已经合并,感觉也非常不可靠
大家有更好一点的思路吗
回复
1个回答

test
2024-07-14
经过试探,已经找到解决方法了,代码如下
const { exec } = require('child_process');
async function isBranchUpToDate(branch) {
// Get the latest commit on the master branch and the latest common ancestor between the branch and the master branch
const [masterCommit, commonAncestor] = await Promise.all([
exec('git rev-parse origin/master'),
exec(`git merge-base ${branch} origin/master`)
]);
// Check if the branch is up to date with the master branch
return commonAncestor.stdout.trim() === masterCommit.stdout.trim();
}
// Check if the "my-branch" branch is up to date with the master branch
(async () => {
console.log(await isBranchUpToDate('my-branch'));
})();
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容