使用 Python 操作 Git 版本庫 - GitPython


GitPython 是一個用於操作 Git 版本庫的 python 包,
它提供了一系列的對象模型(庫 - Repo、樹 - Tree、提交 - Commit等)
用於操作版本庫中的相應對象。

版本庫對象 - Repo

首先,使用包含 .git 文件夾的版本庫路徑創建 git.Repo 對象

from git import Repo
# 創建版本庫對象
repo = git.Repo(r'E:\Notes')

然后便可以使用這個 Repo 對象對版本庫進行操作,如:

# 版本庫是否為空版本庫
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 來操作暫存區,如添加、提交操作

index = repo.index
index.add(['new.txt'])
index.remove(['old.txt'])
index.commit('this is a test')

遠程版本庫操作 - Remotes

Remotes 用於操作遠程版本庫,可以通過 Repo.remote 方法獲取遠程版本庫,
Repo.Remotes 屬性獲取遠程版本庫列表

# 獲取默認版本庫 origin
remote = repo.remote()
# 從遠程版本庫拉取分支
remote.pull()
# 推送本地分支到遠程版本庫
remote.push()
# 重命名遠程分支
# remote.rename('new_origin')

直接執行 Git 命令

一般我們在工作目錄做了改變之后,就會調用 git add 命令添加文件到暫存區,
然后調用 git commit 命令提交更改,Repo 雖然沒有添加、提交方法,
但取而代之提供了一個 git.cmd.Git 對象實現對 Git 命令的調用,
通過 Repo.git 來進行 Git 命令操作。

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 命令,而調用對應命令方法所用的參數,
會被轉換成跟在命令后的參數。

而調用命令方法所用的命名參數會被轉換成對應的完整參數,如:git.command(flag=True)
會被轉換成 git command --flag 命令執行

總結

基本的 Git 操作可以概括如下:

# 新建版本庫對象
repo = Repo(r'E:\Notes')

# 進行文件修改操作

# 獲取版本庫暫存區
index = repo.index
# 添加修改文件
index.add(['new.txt'])
# 提交修改到本地倉庫
index.commit('this is a test')

# 獲取遠程倉庫
remote = repo.remote()
# 推送本地修改到遠程倉庫
remote.push()

參考鏈接:

https://my.oschina.net/hopeMan/blog/141221

http://gitpython.readthedocs.io/en/stable/tutorial.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM