Python使用GitPython操作Git版本庫的方法
GitPython 是一個用于操作 Git 版本庫的 python 包,它提供了一系列的對象模型(庫 - Repo、樹 - Tree、提交 - Commit等),用于操作版本庫中的相應(yīng)對象。
1、導(dǎo)包
from git import *
2、初始化git倉庫
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__)) empty_repo = Repo.init(os.path.join(CURRENT_DIR, 'bbs')) # bbs目錄不存在則新建
3、如果git倉庫已存在,直接獲取
repo = Repo(os.path.join(CURRENT_DIR, 'bbs'))
4、獲取當(dāng)前遠程庫
repo.remotes # 獲取當(dāng)前有哪些遠程庫 = git remote -v命令,返回一個repo列表
5、新建遠程庫
# 新建遠程庫 = git remote add origin git_url, 返回Remote對象(<class 'git.remote.Remote'>) origin = repo.create_remote('origin', git_url)
6、fetch
origin.fetch()
7、建立一個關(guān)聯(lián)遠程分支的本地分支,分三步
empty_repo.create_head('master', origin.refs.master) # create local branch "master" from remote "master" empty_repo.heads.master.set_tracking_branch(origin.refs.master) # set local "master" to track remote "master empty_repo.heads.master.checkout() # checkout local "master" to working tree # 以上三步可以簡化為一行代碼 repo.create_head('master', origin.refs.master).set_tracking_branch(origin.refs.master).checkout() # 建立本地master分支,關(guān)聯(lián)遠程master分支,checkout
8、獲取所有遠程分支
origin.refs # 返回所有遠程分支列表 [<git.RemoteReference "refs/remotes/new_origin/develop">, <git.RemoteReference "refs/remotes/new_origin/master">]
9、獲取所有本地分支(git.HEAD)和遠程分支(git.RemoteReference)
repo.refs # 返回所有本地分支列表
10、獲取本地heads
repo.heads # 返回Head列表
11、獲取當(dāng)前head指向
repo.head.reference
12、切換分支
a、本地存在此分支 repo.head.reference = repo.heads.develop b、本地不存在,需要從遠程拉去 repo.create_head('master', origin.refs.master).set_tracking_branch(origin.refs.master).checkout()
總結(jié)
到此這篇關(guān)于Python使用GitPython操作Git版本庫的方法的文章就介紹到這了,更多相關(guān)python操作git版本庫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python3.10耙梳加密算法Encryption種類及開發(fā)場景
這篇文章主要為大家介紹了Python3.10加密,各種加密,耙梳加密算法Encryption種類及開發(fā)場景運用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-02-02python交互模式基礎(chǔ)知識點學(xué)習(xí)
在本篇內(nèi)容里小編給大家整理的是關(guān)于python交互模式是什么的相關(guān)基礎(chǔ)知識點,需要的朋友們可以參考下。2020-06-06