GitPython配置
GitPython是一个Python代码库,以编程的方式读取和写入Git 源代码控制存储库。
准备环境
Git, version 2.15.1
GitPython version 2.1.7
pip 和 virtualenv
安装GitPython
为项目创建一个新的虚拟环境。
python3 -m venv gitpy
激活新创建的virtualenv
source gitpy / bin / activate
激活后,virtualenv的名称将被添加到命令提示符前面。
使用pip命令来安装GitPython
pip install gitpython == 2 .1.7
安装完所有内容后,可以看到安装成功消息
(gitpy) $ pip install gitpython==2.1.7
Collecting gitpython==2.1.7
Downloading GitPython-2.1.7-py2.py3-none-any.whl (446kB)
100% |████████████████████████████████| 450kB 651kB/s
Collecting gitdb2>=2.0.0 (from gitpython==2.1.7)
Downloading gitdb2-2.0.3-py2.py3-none-any.whl (63kB)
100% |████████████████████████████████| 71kB 947kB/s
Collecting smmap2>=2.0.0 (from gitdb2>=2.0.0->gitpython==2.1.7)
Downloading smmap2-2.0.3-py2.py3-none-any.whl
Installing collected packages: smmap2, gitdb2, gitpython
Successfully installed gitdb2-2.0.3 gitpython-2.1.7 smmap2-2.0.3
克隆存储库
克隆要与本地系统一起使用的存储库。如果没有特定的一个,请使用 GitHub上托管的开源Full Stack Python Git存储库。
git clone git@github.com:mattmakai/fullstackpython.com fsp
记下克隆存储库的位置,因为GitPython要处理存储库。切换到新Git存储库的目录,cd然后运行pwd(当前工作目录)命令以获取完整路径。
cd fsp
pwd
可以看到一些输出/Users/matt/devel/py/fsp。此路径是您到Git存储库基础的绝对路径。
使用该export命令为Git存储库的绝对路径设置环境变量。
export GIT_REPO_PATH='/Users/matt/devel/py/fsp' # 确保这是你自己的路径
Git存储库和路径环境变量都已设置好,可以使用GitPython的Python代码。
读取存储库和提交数据
创建一个名为的新Python文件read_repo.py并将其打开,编写一个简单的脚本。
先导入常量:
import os
from git import Repo
COMMITS_TO_PRINT = 5
在read_repo.py文件中创建一个函数打印提交信息:
def print_commit(commit):
print('----')
print(str(commit.hexsha))
print("\"{}\" by {} ({})".format(commit.summary,
commit.author.name,
commit.author.email))
print(str(commit.authored_datetime))
print(str("count: {} and size: {}".format(commit.count(),
commit.size)))
该print_commit函数接受GitPython提交对象,并为提交打印40个字符的SHA-1哈希,后跟:
- 提交摘要
- 作者姓名
- 作者电邮
- 提交日期和时间
- 计数和更新大小
在print_commit函数下面,创建另一个名为 print_repository打印Repo对象细节的函数:
def print_repository(repo):
print('Repo description: {}'.format(repo.description))
print('Repo active branch is {}'.format(repo.active_branch))
for remote in repo.remotes:
print('Remote named "{}" with URL "{}"'.format(remote, remote.url))
print('Last commit for repo is {}.'.format(str(repo.head.commit.hexsha)))
最后,当从终端调用python脚本时,需要一个“main”函数。
if __name__ == "__main__":
repo_path = os.getenv('GIT_REPO_PATH')
# Repo object used to programmatically interact with Git repositories
repo = Repo(repo_path)
# check that the repository loaded correctly
if not repo.bare:
print('Repo at {} successfully loaded.'.format(repo_path))
print_repository(repo)
# create list of commits then print some of them to stdout
commits = list(repo.iter_commits('master'))[:COMMITS_TO_PRINT]
for commit in commits:
print_commit(commit)
pass
else:
print('Could not load repository at {} :('.format(repo_path))