批量提交git代码

所有的项目需要单独放到一个目录,然后git库中的名称需要与项目文件夹名称一致

import os
import subprocess
import shutil
from pathlib import Path


def is_git_repo(path):
    """检查路径是否为Git仓库"""
    try:
        subprocess.run(
            ['git', '-C', path, 'status'],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            check=True
        )
        return True
    except subprocess.CalledProcessError:
        return False


def delete_git_files(repo_path):
    """删除.git目录和.gitignore文件"""
    print(f"正在删除 {repo_path} 中的 .git 目录和 .gitignore 文件...")

    # 删除.git目录
    git_dir = os.path.join(repo_path, '.git')
    if os.path.exists(git_dir):
        try:
            # 以管理员权限删除只读文件和目录
            def onerror(func, path, exc_info):
                import stat
                if not os.access(path, os.W_OK):
                    os.chmod(path, stat.S_IWUSR)
                    func(path)
                else:
                    raise exc_info[1]

            shutil.rmtree(git_dir, onerror=onerror)
            print(f"✅ 已删除 .git 目录")
        except Exception as e:
            print(f"❌ 删除 .git 目录时出错: {e}")

    # 删除.gitignore文件
    gitignore_file = os.path.join(repo_path, '.gitignore')
    if os.path.exists(gitignore_file):
        try:
            os.remove(gitignore_file)
            print(f"✅ 已删除 .gitignore 文件")
        except Exception as e:
            print(f"❌ 删除 .gitignore 文件时出错: {e}")


def git_push(repo_path):
    """初始化新的Git仓库并推送"""
    print(f"\n==== 在 {repo_path} 创建新的Git仓库并推送 ====")

    try:
        # 初始化新的Git仓库
        print("正在初始化新的Git仓库...")
        subprocess.run(
            ['git', '-C', repo_path, 'init', '-b', 'master'],
            check=True
        )

        # 添加所有文件
        print("正在添加所有文件...")
        subprocess.run(
            ['git', '-C', repo_path, 'add', '.'],
            check=True
        )

        # 提交更改
        print("正在提交更改...")
        subprocess.run(
            ['git', '-C', repo_path, 'commit', '-m', 'Initial commit after reset'],
            check=True
        )

        # 添加远程仓库
        print("正在添加远程仓库...")
        project_name = os.path.basename(os.path.abspath(repo_path))
        remote_url = f"git@gitlab.tenddata.com:adt-nike/{project_name}.git"
        subprocess.run(
            ['git', '-C', repo_path, 'remote', 'add', 'origin', remote_url],
            check=True
        )

        # 切换到主分支
        print(f"正在切换到主分支...")
        subprocess.run(
            ['git', '-C', repo_path, 'checkout', '-b', 'master'],
            check=True
        )

        # 推送代码
        print("正在推送代码到主分支...")
        subprocess.run(
            ['git', '-C', repo_path, 'push', '-u', 'origin', 'master'],
            check=True
        )

        print(f"✅ 仓库 {repo_path} 推送完成")

    except subprocess.CalledProcessError as e:
        print(f"❌ 处理仓库 {repo_path} 时出错: {e}")
    except Exception as e:
        print(f"❌ 未知错误: {e}")


def main():
    # 指定要检查的根目录,请修改为你的实际路径
    root_dir = Path("/Users/anran/Documents/Documents/Projects/TD/adt")

    if not root_dir.exists() or not root_dir.is_dir():
        print(f"错误:目录 '{root_dir}' 不存在")
        return

    print(f"开始处理目录: {root_dir}")

    # 遍历根目录下的所有子目录
    for item in root_dir.iterdir():
        if item.is_dir():
            if is_git_repo(str(item)):
                delete_git_files(str(item))
                git_push(str(item))
            else:
                print(f"跳过非Git仓库: {item}")

    print("\n所有仓库处理完成!")


if __name__ == "__main__":
    main()
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇