如何使用Python检测Git仓库是否存在未暂存/未提交变更或未推送提交
Git仓库状态批量扫描实现方案
实现逻辑
要实现指定根路径下所有Git仓库的状态批量查询,只需要两步即可完成:
- 递归遍历根路径下的所有子目录,识别包含
.git子文件夹的路径,即为Git仓库的根目录 - 对每个识别到的仓库,调用原生Git命令提取所需状态,不需要额外安装第三方依赖
Python实现代码
import os import subprocess def scan_git_repos(root_path: str) -> list: res = [] # 遍历根路径找所有Git仓库 for dirpath, dirnames, filenames in os.walk(root_path): if '.git' in dirnames: repo_path = dirpath # 跳过.git目录的子层级遍历,提高效率 dirnames.remove('.git') # 执行git status命令获取状态 status_out = subprocess.run( ['git', 'status', '--porcelain'], cwd=repo_path, capture_output=True, text=True ).stdout.splitlines() # 解析未暂存/未提交变更状态(排除未跟踪文件) has_change = any(not line.startswith('??') for line in status_out) change_status = "Unstaged/uncommitted changes: 有变更" if has_change else "Unstaged/uncommitted changes: 无变更" # 解析未跟踪文件状态 has_untracked = any(line.startswith('??') for line in status_out) untracked_status = "Untracked files: 存在" if has_untracked else "Untracked files: 不存在" # 解析最新提交是否已推送 push_status = "Latest commit is pushed: 是" # 先检查是否配置了远端分支 check_remote = subprocess.run( ['git', 'status', '-sb'], cwd=repo_path, capture_output=True, text=True ).stdout.splitlines()[0] if 'ahead' in check_remote: push_status = "Latest commit is pushed: 否" elif '...' not in check_remote: push_status = "Latest commit is pushed: 无对应远端分支" # 组装结果 res.append((repo_path, change_status, untracked_status, push_status)) return res # 使用示例 if __name__ == "__main__": result = scan_git_repos("C:/ProgramFiles") for item in result: print(item)
输出说明
返回的列表中每个元素对应一个Git仓库的四项信息,格式完全匹配需求:
- 第一个元素:仓库在本地的绝对路径
- 第二个元素:未暂存/未提交变更的状态
- 第三个元素:未跟踪文件的存在状态
- 第四个元素:最新提交是否已推送到对应远端分支的状态
使用前提
本地需提前安装Git,且Git已添加到系统环境变量中,可直接在命令行执行git命令。
内容的提问来源于stack exchange,提问作者Luk Aron
相关产品推荐
相关产品推荐

