Python 操作 git (增量从一个仓库同步文件到另一个仓库)
Python 3.6+
先安装 gitpython 包
python3 -m pip install gitpython==3.1.11
# migrate.py
import os
from datetime import datetime
import shutil
from git import Repo
gitee_url = "ssh://git@192.168.0.11:8222/examples/spring-boot-helloworld.git"
gitee_local_repo_dir = "C:/Users/Administrator/Desktop/spring-boot-helloworld"
gitlab_url = "ssh://git@192.168.0.11:8222/devops/test01.git"
gitlab_local_repo_dir = "C:/Users/Administrator/Desktop/test"
def clone_code(url, local_dir, branch="develop"):
if not os.path.exists(local_dir):
Repo.clone_from(url, local_dir)
local_repo = Repo(local_dir)
origin_repo = local_repo.remote()
branches = [ str(_b) for _b in local_repo.branches ]
cur_branch = local_repo.active_branch
if str(cur_branch) != branch:
# switch branch
if branch not in branches:
br = local_repo.create_head(branch)
local_repo.head.reference = br
if branch == "develop":
local_repo.heads.develop.checkout()
elif branch == "master":
local_repo.heads.master.checkout()
else:
print("needs to add as above")
origin_repo.pull(branch)
def commit_code(local_repo_dir, branch="develop"):
local_repo = Repo(local_repo_dir)
origin_repo = local_repo.remote()
# add new files
new_files = local_repo.untracked_files
for fn in new_files:
local_repo.index.add(fn)
# add changed files
for item in local_repo.index.diff(None):
local_repo.index.add(item.a_path)
# git commit
msg = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
local_repo.index.commit(msg)
# git push
origin_repo.push(branch)
def copy_file(src, dest):
for fn in os.listdir(src):
if fn.startswith(".git") or fn.startswith(".settings") or fn.startswith(".DS_Store") or fn.startswith(".idea"):
continue
s_file = f"{src}/{fn}"
t_file = f"{dest}/{fn}"
if os.path.isfile(s_file):
if os.path.exists(t_file):
os.remove(t_file)
shutil.copyfile(s_file, t_file)
elif os.path.isdir(s_file):
new_src = s_file
new_dest = t_file
if not os.path.exists(new_dest):
shutil.copytree(new_src, new_dest)
continue
copy_file(new_src, new_dest)
else:
print("unsupport file type")
if __name__ == "__main__":
branch = "develop"
clone_code(gitee_url, gitee_local_repo_dir, branch)
clone_code(gitlab_url, gitlab_local_repo_dir, branch)
copy_file(gitee_local_repo_dir, gitlab_local_repo_dir)
commit_code(gitlab_local_repo_dir, branch)
执行
python3 migrate.py
原文:https://www.cnblogs.com/ninejy/p/14117482.html