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