使用GitPython签出新分支并推送到远程

时间:2016-06-15 21:14:55

标签: python git github gitpython

鉴于回购(GitPython) - 如何创建新的本地分支,添加一些文件,并使用Gi​​tPython将其推送到远程?

回复示例:

from git import *

curr_dir = os.path.dirname(os.path.realpath(__file__))
repo = Repo(curr_dir)

现在我只是使用子进程:

def publish_changes_to_git(commit_msg):
    curr_time = time.time()
    ts = datetime.datetime.fromtimestamp(curr_time).strftime('%Y-%m-%d-%H-%M-%S')
    branch_name = "auto-commit-{ts}".format(ts=ts)
    subprocess.check_output(["git", "checkout", "-b", branch_name])
    subprocess.check_output(["git", "add", SOME_PATH])
    subprocess.check_output(
        ["git", "commit", "-m", "auto-git-commit: {msg}".format(msg=commit_msg)])

如果有人有其他git-python库,我会很高兴听到。

2 个答案:

答案 0 :(得分:2)

我做过类似的事情,比如在新创建的分支和提交的远程分支中创建一个txt,推送到远程。这是我的代码

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')

答案 1 :(得分:-1)

gitypython看起来提供了对git的低级访问和级别访问,但是你可以调用git命令,参见http://gitpython.readthedocs.io/en/stable/reference.html#module-git.cmd

或者,请考虑使用http://www.pygit2.org/代替http://www.pygit2.org/进行更高级别的访问。这里有一些例子http://www.pygit2.org/recipes.html