GitPython 是一個用于操作 Git 版本庫的 python 包,
它提供了一系列的對象模型(庫 - Repo
、樹 - Tree
、提交 - Commit
等)
用于操作版本庫中的相應(yīng)對象。
Repo
首先,使用包含 .git
文件夾的版本庫路徑創(chuàng)建 git.Repo
對象
from git import Repo# 創(chuàng)建版本庫對象repo = git.Repo(r'E:\Notes')
然后便可以使用這個 Repo
對象對版本庫進(jìn)行操作,如:
# 版本庫是否為空版本庫repo.bare# 當(dāng)前工作區(qū)是否干凈repo.is_dirty()# 版本庫中未跟蹤的文件列表repo.untracked_files# 克隆版本庫repo.clone('clone_path')# 壓縮版本庫到 tar 文件with open('repo.tar', 'wb') as fp: repo.archive(fp)# 新建分支repo.create_head('branchname')# 查看當(dāng)前分支repo.active_branch
Index
Git 術(shù)語中,index 表示暫存區(qū),為下次將要提交到版本庫里的文件,
GitPython 提供 Repo.Index
來操作暫存區(qū),如添加、提交操作
index = repo.indexindex.add(['new.txt'])index.remove(['old.txt'])index.commit('this is a test')
Remotes
Remotes
用于操作遠(yuǎn)程版本庫,可以通過 Repo.remote
方法獲取遠(yuǎn)程版本庫,Repo.Remotes
屬性獲取遠(yuǎn)程版本庫列表
# 獲取默認(rèn)版本庫 originremote = repo.remote()# 從遠(yuǎn)程版本庫拉取分支remote.pull()# 推送本地分支到遠(yuǎn)程版本庫remote.push()# 重命名遠(yuǎn)程分支# remote.rename('new_origin')
一般我們在工作目錄做了改變之后,就會調(diào)用 git add
命令添加文件到暫存區(qū),
然后調(diào)用 git commit
命令提交更改,Repo
雖然沒有添加、提交方法,
但取而代之提供了一個 git.cmd.Git
對象實現(xiàn)對 Git 命令的調(diào)用,
通過 Repo.git
來進(jìn)行 Git 命令操作。
git = repo.gitgit.add('test1.txt') # git add test1.txtgit.commit('-m', 'this is a test') # git commit -m 'this is a test'
Repo.git.[command]
即相當(dāng)于調(diào)用對應(yīng)的 git 命令,而調(diào)用對應(yīng)命令方法所用的參數(shù),
會被轉(zhuǎn)換成跟在命令后的參數(shù)。
而調(diào)用命令方法所用的命名參數(shù)會被轉(zhuǎn)換成對應(yīng)的完整參數(shù),如:git.command(flag=True)
會被轉(zhuǎn)換成 git command --flag
命令執(zhí)行
基本的 Git 操作可以概括如下:
# 新建版本庫對象repo = Repo(r'E:\Notes')# 進(jìn)行文件修改操作# 獲取版本庫暫存區(qū)index = repo.index# 添加修改文件index.add(['new.txt'])# 提交修改到本地倉庫index.commit('this is a test')# 獲取遠(yuǎn)程倉庫remote = repo.remote()# 推送本地修改到遠(yuǎn)程倉庫remote.push()