发布于 更新于
AI总结: 本文介绍了一个用于检测并取消设置 Git 仓库用户信息的工具,该工具通过递归查找指定目录下的所有 Git 仓库,并检查每个仓库的用户配置(user.name 和 user.email),如果存在则将其清理。用户可以通过命令行指定要扫描的目录,工具会输出每个仓库的用户配置信息及清理结果。
优化建议:
1. 在`find_git_repos`函数中,可以增加对.git目录的文件类型检查,以避免误判其他文件夹。
2. 在`check_and_unset_config`函数中,考虑使用`subprocess.run`的`check`参数,自动处理错误并抛出异常,简化错误处理逻辑。
3. 添加日志功能,将输出信息记录到日志文件中,方便后续查看。
4. 在命令行参数中添加一个选项,允许用户选择是否输出详细的清理过程,以提高灵活性。
5. 增强异常处理,确保在出现错误时能够提供更详细的上下文信息,便于调试。
因为在.git/config中采用 includeIf 指令实现智能切换用户信息了, 不需要每个仓库配置用户信息, 所以清一下仓库的用户信息
import os
import argparse
import subprocess
import sys
def find_git_repos(root_dir):
"""
递归查找指定目录下的所有 Git 仓库
"""
git_repos = []
for dirpath, dirnames, filenames in os.walk(root_dir):
if '.git' in dirnames:
repo_path = os.path.abspath(dirpath)
git_repos.append(repo_path)
# 跳过子目录遍历 (避免处理嵌套仓库)
dirnames[:] = []
return git_repos
def check_and_unset_config(repo_path):
"""
检查并取消设置用户配置
返回格式: (是否存在name, 是否存在email, 是否执行了修改)
"""
try:
# 检测 user.name
name_check = subprocess.run(
['git', '-C', repo_path, 'config', '--local', '--get', 'user.name'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True
)
has_name = name_check.returncode == 0
# 检测 user.email
email_check = subprocess.run(
['git', '-C', repo_path, 'config', '--local', '--get', 'user.email'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True
)
has_email = email_check.returncode == 0
modified = False
# 取消设置配置
if has_name:
subprocess.run(
['git', '-C', repo_path, 'config', '--local', '--unset', 'user.name'],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
modified = True
if has_email:
subprocess.run(
['git', '-C', repo_path, 'config', '--local', '--unset', 'user.email'],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
modified = True
return has_name, has_email, modified
except subprocess.CalledProcessError as e:
print(f"处理仓库时出错 {repo_path}: {str(e)}")
return False, False, False
def main():
parser = argparse.ArgumentParser(description='Git 用户信息清理工具')
parser.add_argument(
'directory',
type=str,
help='要扫描的根目录路径',
nargs='?',
default=os.getcwd()
)
args = parser.parse_args()
root_dir = os.path.abspath(args.directory)
if not os.path.isdir(root_dir):
print(f"错误: 路径不存在或不是目录 [{root_dir}]")
sys.exit(1)
repositories = find_git_repos(root_dir)
print(f"共发现 {len(repositories)} 个 Git 仓库")
for repo in repositories:
print(f"\n🔍 正在检查仓库:{repo}")
has_name, has_email, modified = check_and_unset_config(repo)
status = []
if has_name: status.append("存在 user.name")
if has_email: status.append("存在 user.email")
if status:
print(" → 发现配置: " + ", ".join(status))
if modified:
print(" ✅ 已清理本地配置")
else:
print(" ✅ 未配置本地用户信息")
if __name__ == "__main__":
main()
# 扫描当前目录
python git_cleaner.py
# 扫描指定目录
python git_cleaner.py /path/to/projects
输出示例:
共发现 3 个 Git 仓库
🔍 正在检查仓库:/home/user/projects/repo1
→ 发现配置: 存在 user.name, 存在 user.email
✅ 已清理本地配置
🔍 正在检查仓库:/home/user/projects/repo2
✅ 未配置本地用户信息
🔍 正在检查仓库:/home/user/projects/repo3
→ 发现配置: 存在 user.email
✅ 已清理本地配置