Git多仓库同步全部分支代码

2017-03-06  本文已影响344人  tenlee

将一个git远程仓库的所有分支代码同步到另外一个git仓库。

#!/usr/bin/env python3
#coding: utf-8

import os
import sys

git_url = 'git@git.coding.net:tenlee'
remote_name = 'coding'

def get_all_branch_form_path(path):
    branchs = os.popen('cd {} && git branch -r'.format(path))
    all_branch = []
    for branch in branchs.readlines():
        branch = branch.strip()
        if branch.find('HEAD') > 0:
            branch = branch.split()[2]
        branch = branch.split('/')[1]
        all_branch.append(branch)
    return all_branch

def is_git_dir(dir):
    if os.path.isdir(dir):  # 是文件夹
        sub_dirs = os.listdir(dir)
        if '.git' in sub_dirs:
            return True
    return False

def do_push(path):
    for file in os.listdir(path):
        file_path = os.path.join(path, file)
        if is_git_dir(os.path.abspath(file_path)):
            all_branch = get_all_branch_form_path(file_path)
            for branch in all_branch:
                cmd = ('cd {path} &&' 
                        + ' git remote add {remote} {git_url}/{project}.git').format(
                                path=file_path, remote=remote_name,
                                git_url=git_url, project=file)
                os.system(cmd)

                cmd = ('cd {path} &&' 
                        + ' git checkout {branch}').format(
                            path=file_path, branch=branch)
                os.system(cmd)

                cmd = ('cd {path} &&  git push {remote} {branch}').format(
                            path=file_path, remote=remote_name,
                            branch=branch)
                print(cmd)
                if os.system(cmd) != 0:
                    print('Push Error')
                else:
                    print('Push Success')


def main():
    path = os.getcwd()
    if len(sys.argv) > 1:
        path = os.argv[1]
    do_push(path)

if __name__ == '__main__':
    main()
上一篇下一篇

猜你喜欢

热点阅读