直接上代码,已整理好,且测试通过:
# coding=utf-8
from git import Repo
'''
需先将git 分支代码克隆到本地,然后将代码路径赋值给clone_to_path,随后可执行以下代码操作
'''
def operation_push(clone_path, update_file_list):
try:
# 创建版本库对象
repo = Repo(clone_path)
# 获取默认版本库 origin
remote = repo.remote()
print '------ pull auto ------'
# 从远程版本库拉取分支(push之前先pull,避免冲突和覆盖他人提交)
print remote.pull('auto') # 后面跟需要拉取的分支名称
# 获取版本库暂存区
index = repo.index
print '------ add ------'
# 添加修改文件
index.add(update_file_list)
print '------ commit ------'
# 提交修改到本地仓库
index.commit('update ' + str(update_file_list))
print '------ push ------'
# 推送本地分支到远程版本库
print remote.push('auto')
except Exception as e:
print '[ ERROR :] operation_push error: ', e
print '------ operation push end ------'
if __name__ == "__main__":
# git 分支代码路径
clone_to_path = r'/Users/Desktop/my_test_flask_admin/clone_test'
print 'clone_to_path = ', clone_to_path
# 更改的文件列表
update_file_list = list()
update_file = clone_to_path + '/data/test_case.json'
update_file2 = clone_to_path + '/data/test_scen.json'
update_file_list.append(update_file)
update_file_list.append(update_file2)
# 调用函数进行push代码
operation_push(clone_to_path, update_file_list)
输出:
clone_to_path = /Users/Desktop/my_test_flask_admin/clone_test
------ pull auto ------
[<git.remote.FetchInfo object at 0x104d9daa0>]
------ add ------
------ commit ------
------ push ------
[<git.remote.PushInfo object at 0x104d98d10>]
------ operation push end ------