Use GitPython to Checkout a new branch and push to remote

坚强是说给别人听的谎言 提交于 2019-12-03 16:34:08

I've done something like creating a txt in a remote branch from newly created branch and commit, push to remote. Here's my code

import git
import datetime
import os
from time import *
from os import path
from git import Repo

def commit_files():
    if repo != None:
        new_branch = 'your_new_branch'
        current = repo.create_head(new_branch)
        current.checkout()
        master = self.repo.heads.master
        repo.git.pull('origin', master)
        #creating file
        dtime = strftime('%d-%m-%Y %H:%M:%S', localtime())
        with open(self.local_repo_path + path.sep + 'lastCommit' + '.txt', 'w') as f:
            f.write(str(dtime))
        if not path.exists(self.local_repo_path):
            os.makedirs(self.local_repo_path)
        print('file created---------------------')

        if repo.index.diff(None) or repo.untracked_files:

            repo.git.add(A=True)
            repo.git.commit(m='msg')
            repo.git.push('--set-upstream', 'origin', current)
            print('git push')
        else:
            print('no changes')

gitypython looks like it provides both low and level access to git but you can invoke git commands, see http://gitpython.readthedocs.io/en/stable/reference.html#module-git.cmd.

Alternately, consider using http://www.pygit2.org/ instead, http://www.pygit2.org/ for higher level access. Some examples here http://www.pygit2.org/recipes.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!