Python 操作 git (增量从一个仓库同步文件到另一个仓库)
Python 3.6+
先安装 gitpython 包
python3 -m pip install gitpython==3.1.11
# migrate.py
import osfrom datetime import datetimeimport shutilfrom git import Repogitee_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_branchif str(cur_branch) != branch:# switch branchif branch not in branches:br = local_repo.create_head(branch)local_repo.head.reference = brif 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 filesnew_files = local_repo.untracked_filesfor fn in new_files:local_repo.index.add(fn)# add changed filesfor item in local_repo.index.diff(None):local_repo.index.add(item.a_path)# git commitmsg = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")local_repo.index.commit(msg)# git pushorigin_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\"):continues_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_filenew_dest = t_fileif not os.path.exists(new_dest):shutil.copytree(new_src, new_dest)continuecopy_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