python - python操作git

直接上代码,已整理好,且测试通过:

# 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 ------

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值