python - 使用 GitPython checkout 新分支并推送到远程

标签 python git gitpython

给定一个来自 GitPython 的 repo,我如何创建一个新的本地分支,添加一些文件,并使用 GitPython 将它推送到远程?

创建一个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)])

最佳答案

我做了一些事情,比如从新创建的分支在远程分支中创建一个 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')

关于python - 使用 GitPython checkout 新分支并推送到远程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37845888/

相关文章:

python - Pandas Dataframe - 对于每一行,返回具有重叠日期的其他行的计数

python - 使用python pandas计算时差并打印到csv

python - 诗歌忽略pyproject.toml中的依赖

git - 如何总结 merge 以检测错误的 `git merge -s ours` ?

python - 在 Windows 7 上安装 GitPython

python - 使用 GitPython 和 https 凭证克隆 AWS CodeCommit git 存储库

python - 在 GDB、C++ 中调试 OpenCV 矩阵

git - 如何让git log不提示继续?

git - 带有 Git LFS 的 Jenkins Git 插件在 Mac 从机上失败并显示 'Bad Credentials'

python-3.x - 使用 gitpython,如何 check out 某个 Git 提交 ID?