GitPython替代Shell实现:获取已合并分支与3个月未用的陈旧分支
基于GitPython的等效分支查询实现
前置说明
- 提前安装GitPython依赖,通过
pip install gitpython即可完成环境准备 - 所有逻辑通过GitPython原生API实现,完全替代原有Shell子进程调用,无额外命令行依赖
已合并至master的本地分支查询
完全对齐原Shell中git branch --merged master的功能逻辑,通过提交祖先关系判断分支是否已被master分支纳入:
import git from datetime import datetime, timedelta # 初始化仓库对象,替换为本地仓库的实际绝对路径 repo = git.Repo("/your/local/repo/path") master_ref = repo.refs.master # 遍历所有本地引用,筛选已合并分支 merged_branches = [] for ref in repo.refs: # 跳过master自身与所有远程分支引用 if ref.name == "master" or ref.name.startswith("origin/"): continue # 判断分支顶端提交是否为master分支提交的祖先(即已被合并进master) if repo.is_ancestor(ref.commit, master_ref.commit): merged_branches.append(ref.name) print("已合并至master的分支列表:") for branch in merged_branches: print(f"- {branch}")
3个月未更新的陈旧远程分支查询
完全对齐原Shell循环遍历远程分支的逻辑,实现细节与原规则一一对应:
- 遍历所有origin远程分支,自动排除指向默认分支的HEAD引用(对应原命令
grep -v HEAD逻辑) - 获取每个分支上最近1条非合并提交(对应原命令
--no-merges -n 1参数) - 对比提交时间与3个月时间阈值,筛选出超过3个月未产生有效提交的分支
- 结果按提交时间排序,输出格式与原Shell输出保持一致(对应原命令
sort -M逻辑)
对应实现代码:
# 计算3个月的陈旧分支时间阈值(按日常维护场景近似为90天) stale_time_threshold = datetime.now() - timedelta(days=90) stale_branch_list = [] for remote_ref in repo.remotes.origin.refs: # 跳过远程的HEAD符号引用 if remote_ref.name == "origin/HEAD": continue # 获取分支最近的非合并提交 try: last_valid_commit = next(remote_ref.commit.iter_items( repo, remote_ref.commit.hexsha, no_merges=True, max_count=1 )) except StopIteration: # 分支无有效提交时跳过 continue # 时区处理:将提交时间转为无时区格式与本地阈值对比,避免时间偏差 commit_time = last_valid_commit.committed_datetime.replace(tzinfo=None) if commit_time < stale_time_threshold: stale_branch_list.append({ "branch": remote_ref.name, "commit_time": commit_time.strftime("%Y-%m-%d %H:%M:%S"), "author": f"{last_valid_commit.author.name} <{last_valid_commit.author.email}>" }) # 按提交时间从旧到新排序 stale_branch_list.sort(key=lambda x: x["commit_time"]) print("\n连续3个月未更新的陈旧分支列表:") for item in stale_branch_list: print(f'- {item["commit_time"]} | {item["author"]} | {item["branch"]}')
提示:如果仓库的默认主分支名称为main而非master,仅需将代码中所有引用
master_ref的位置替换为repo.refs.main即可适配。
内容的提问来源于stack exchange,提问作者Aleksandre Bregadze
相关产品推荐
相关产品推荐

