You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取指定Git分支独有的文件变更列表?

获取当前分支独有的变更文件(GitPython实现)

不需要手动计算HEAD~n的数值,直接通过对比当前分支与基准分支(develop_branch)的差异,或者找到两者的最近公共祖先,就能精准拿到当前分支独有的变更文件,以下是两种可行方案:

方案一:直接对比当前分支与基准分支的最新提交

适合已经将当前分支变基到develop_branch的场景,直接对比两个分支的最新提交差异:

from git import Repo

repo = Repo('My_Repo')
# 获取基准分支develop_branch的最新提交
base_commit = repo.commit('develop_branch')
# 获取当前分支的最新提交
current_commit = repo.head.commit
# 生成两个提交之间的差异
diff = current_commit.diff(base_commit)

# 遍历输出变更文件及类型
for diff_item in diff:
    # 处理新增/删除文件的路径显示
    file_path = diff_item.a_path if diff_item.a_path else diff_item.b_path
    print(f"{file_path} - 变更类型: {diff_item.change_type}")

方案二:基于最近公共祖先对比差异

如果需要精准定位当前分支从develop_branch分叉的节点,先找到两者的最近公共祖先,再对比差异:

from git import Repo

repo = Repo('My_Repo')
current_branch = repo.active_branch
base_branch = repo.branches['develop_branch']

# 获取两个分支的最近公共祖先提交
common_ancestor = repo.merge_base(current_branch, base_branch)[0]
# 对比当前分支最新提交与公共祖先的差异
diff = current_branch.commit.diff(common_ancestor)

# 输出变更文件信息
for diff_item in diff:
    file_path = diff_item.a_path if diff_item.a_path else diff_item.b_path
    print(f"{file_path} ({diff_item.change_type})")

注意事项

  • 执行前确保本地develop_branch是最新状态,可通过repo.remotes.origin.pull('develop_branch')拉取最新代码
  • 如果当前处于 detached HEAD 状态,需替换repo.active_branch为具体的提交对象

内容的提问来源于stack exchange,提问作者lucas_v67

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 23:10:52