脚本 Python

发布于 更新于

AI总结: 本文介绍了一个用于清理 Git 仓库中用户信息的工具,该工具通过递归查找指定目录下的所有 Git 仓库,并检查和取消设置每个仓库的用户配置(user.name 和 user.email)。它使用 argparse 处理命令行参数,并通过 subprocess 调用 Git 命令来执行相关操作。 优化建议: 1. 增加错误处理机制,确保在执行 Git 命令时能够捕获并处理所有可能的异常情况。 2. 为用户提供更多的反馈信息,例如清理完成后的总结,显示清理了多少个仓库的用户信息。 3. 提供日志功能,记录每个仓库的处理结果,以便后续审查。 4. 增加对不同操作系统的兼容性测试,确保在 Windows 和 Unix 系统上都能正常运行。 5. 考虑将用户信息的清理操作设为可选,允许用户选择是否清理特定的配置。

因为在.git/config中采用 includeIf 指令实现智能切换用户信息了, 不需要每个仓库配置用户信息, 所以清一下仓库的用户信息

检测并取消设置 Git 仓库用户信息

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
   ✅ 已清理本地配置