gitpython模块
gitpython模块
能够让你通过python代码操作git仓库
安装
pip3 install gitpython
# 模块:处理excel表格 openpyxl...
基本使用
import os
from git.repo import Repo
# 一般来说,下载远程的仓库的代码可以用clone pull
# 先定义代码的存放位置
download_path = os.path.join('godlover', 'NB')
Repo.clone_from('https://github.com/DominicJi/TeachTest.git', to_path=download_path, branch='master')
更多的操作
# ############## 2. pull最新代码 ##############
import os
from git.repo import Repo
local_path = os.path.join('jason', 'NB')
repo = Repo(local_path)
repo.git.pull()
# ############## 3. 获取所有分支 ##############
import os
from git.repo import Repo
local_path = os.path.join('jason', 'NB')
repo = Repo(local_path)
branches = repo.remote().refs
for item in branches:
print(item.remote_head)
# ############## 4. 获取所有版本 ##############
import os
from git.repo import Repo
local_path = os.path.join('jason', 'NB')
repo = Repo(local_path)
for tag in repo.tags:
print(tag.name)
# ############## 5. 获取所有commit ##############
import os
from git.repo import Repo
local_path = os.path.join('jason', 'NB')
repo = Repo(local_path)
# 将所有提交记录结果格式成json格式字符串 方便后续反序列化操作
commit_log = repo.git.log('--pretty={"commit":"%h","author":"%an","summary":"%s","date":"%cd"}', max_count=50,
date='format:%Y-%m-%d %H:%M')
log_list = commit_log.split("\n")
real_log_list = [eval(item) for item in log_list]
print(real_log_list)
# ############## 6. 切换分支 ##############
import os
from git.repo import Repo
local_path = os.path.join('jason', 'NB')
repo = Repo(local_path)
before = repo.git.branch()
print(before)
repo.git.checkout('master')
after = repo.git.branch()
print(after)
repo.git.reset('--hard', '854ead2e82dc73b634cbd5afcf1414f5b30e94a8')
# ############## 7. 打包代码 ##############
with open(os.path.join('jason', 'NB.tar'), 'wb') as fp:
repo.archive(fp)