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

8

如何使用GitPython从给定的repo创建新的本地分支、添加一些文件并将其推送到远程?

要创建一个repo

from git import *

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

目前,我只是使用subprocess

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)])
3个回答

13

我曾经做过类似的事情,从新创建的分支中创建一个 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

这正是我的使用情况,而且我需要在之后切换回原始分支。我用下面的方法处理:

def switch_commit_branch(branch_name, msg='Automatic commit by switch_commit_branch', force=True):
    '''
    This function 
        (1) switches to branch `branch_name` (and creates it if it doesnt aready exist)
        (2) ads and commits all changes
        (3) pushes to origin
    :param branch_name: desired branch name
    :param msg: commit message
    :param force: whether to create branch if it doesnt already exist 
    :return: 
    '''
    repo = Repo(search_parent_directories=True)
    original_branch = repo.active_branch
    branch = [b for b in repo.branches if b.name == branch_name]
    if len(branch) == 0:
        if force:
            print(f'Creating new branch {branch_name}')
            branch = repo.create_head(branch_name)  # create new branch if none exists
        else:
            print(f'Branch {branch_name} does not exist. Set `force=True` to create. Aborting')
            return None
    else:
        branch = branch[0]

    branch.checkout()
    repo.git.add('*')
    repo.git.commit(m=msg)
    repo.git.push('--set-upstream', 'origin', branch)
    original_branch.checkout()

-2

谢谢,但是使用git模块来精确执行命令与子进程的方式是一样的。我会更深入地了解pygit2,但是这个模块似乎缺少我需要的功能(或者实现这些功能非常困难)。 - etlsh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接