GitPython 是一個用於操做 Git 版本庫的 python 包,
它提供了一系列的對象模型(庫 - Repo
、樹 - Tree
、提交 - Commit
等)
用於操做版本庫中的相應對象。html
Repo
首先,使用包含 .git
文件夾的版本庫路徑建立 git.Repo
對象python
from git import Repo # 建立版本庫對象 repo = git.Repo(r'E:\Notes')
而後即可以使用這個 Repo
對象對版本庫進行操做,如:git
# 版本庫是否爲空版本庫 repo.bare # 當前工做區是否乾淨 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') # 查看當前分支 repo.active_branch
Index
Git 術語中,index 表示暫存區,爲下次將要提交到版本庫裏的文件,
GitPython 提供 Repo.Index
來操做暫存區,如添加、提交操做this
index = repo.index index.add(['new.txt']) index.remove(['old.txt']) index.commit('this is a test')
Remotes
Remotes
用於操做遠程版本庫,能夠經過 Repo.remote
方法獲取遠程版本庫,
Repo.Remotes
屬性獲取遠程版本庫列表spa
# 獲取默認版本庫 origin remote = repo.remote() # 從遠程版本庫拉取分支 remote.pull() # 推送本地分支到遠程版本庫 remote.push() # 重命名遠程分支 # remote.rename('new_origin')
通常咱們在工做目錄作了改變以後,就會調用 git add
命令添加文件到暫存區,
而後調用 git commit
命令提交更改,Repo
雖然沒有添加、提交方法,
但取而代之提供了一個 git.cmd.Git
對象實現對 Git 命令的調用,
經過 Repo.git
來進行 Git 命令操做。.net
git = repo.git git.add('test1.txt') # git add test1.txt git.commit('-m', 'this is a test') # git commit -m 'this is a test'
Repo.git.[command]
即至關於調用對應的 git 命令,而調用對應命令方法所用的參數,
會被轉換成跟在命令後的參數。code
而調用命令方法所用的命名參數會被轉換成對應的完整參數,如:git.command(flag=True)
會被轉換成 git command --flag
命令執行htm
基本的 Git 操做能夠歸納以下:對象
# 新建版本庫對象 repo = Repo(r'E:\Notes') # 進行文件修改操做 # 獲取版本庫暫存區 index = repo.index # 添加修改文件 index.add(['new.txt']) # 提交修改到本地倉庫 index.commit('this is a test') # 獲取遠程倉庫 remote = repo.remote() # 推送本地修改到遠程倉庫 remote.push()
參考連接:blog
分類: Python