GitPython 是一個用于操作 Git 版本庫的 python 包, 它提供了一系列的對象模型(庫 - Repo 、樹 - Tree 、提交 - Commit 等) 用于操作版本庫中的相應對象。 版本庫對象 - Repo 首先,使用包含 .git 文件夾的版本庫路徑創(chuàng)建 git.Repo 對象 from git import Repo# 創(chuàng)建版本庫對象repo = git.Repo(r'E:\Notes')
然后便可以使用這個 Repo 對象對版本庫進行操作,如: # 版本庫是否為空版本庫repo.bare# 當前工作區(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')# 查看當前分支repo.active_branch
索引/暫存區(qū)對象 - Index Git 術語中,index 表示暫存區(qū),為下次將要提交到版本庫里的文件, GitPython 提供 Repo.Index 來操作暫存區(qū),如添加、提交操作 index = repo.index
index.add(['new.txt'])
index.remove(['old.txt'])
index.commit('this is a test')
遠程版本庫操作 - Remotes Remotes 用于操作遠程版本庫,可以通過 Repo.remote 方法獲取遠程版本庫,
Repo.Remotes 屬性獲取遠程版本庫列表
# 獲取默認版本庫 originremote = repo.remote()# 從遠程版本庫拉取分支remote.pull()# 推送本地分支到遠程版本庫remote.push()# 重命名遠程分支# remote.rename('new_origin')
直接執(zhí)行 Git 命令一般我們在工作目錄做了改變之后,就會調用 git add 命令添加文件到暫存區(qū), 然后調用 git commit 命令提交更改,Repo 雖然沒有添加、提交方法, 但取而代之提供了一個 git.cmd.Git 對象實現對 Git 命令的調用, 通過 Repo.git 來進行 Git 命令操作。 git = repo.git
git.add('test1.txt') # git add test1.txtgit.commit('-m', 'this is a test') # git commit -m 'this is a test'
Repo.git.[command] 即相當于調用對應的 git 命令,而調用對應命令方法所用的參數, 會被轉換成跟在命令后的參數。
而調用命令方法所用的命名參數會被轉換成對應的完整參數,如:git.command(flag=True) 會被轉換成 git command --flag 命令執(zhí)行 總結基本的 Git 操作可以概括如下: # 新建版本庫對象repo = Repo(r'E:\Notes')# 進行文件修改操作# 獲取版本庫暫存區(qū)index = repo.index# 添加修改文件index.add(['new.txt'])# 提交修改到本地倉庫index.commit('this is a test')# 獲取遠程倉庫remote = repo.remote()# 推送本地修改到遠程倉庫remote.push()
|