Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use GitPython to Checkout a new branch and push to remote

Given a repo from GitPython, how can I create a new local branch, add some files, and push it to remote using GitPython?

To create a repo:

from git import *

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

For now, I'm just using 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)])
like image 950
etlsh Avatar asked Jun 15 '16 21:06

etlsh


People also ask

How do I push a new branch to a remote?

Push a new Git branch to a remote repoClone the remote Git repo locally. Create a new branch with the branch, switch or checkout commands. Perform a git push with the –set-upstream option to set the remote repo for the new branch. Continue to perform Git commits locally on the new branch.

How do I create a checkout and branch at the same time?

Option 2: Creating a Branch using Checkout If you want to create a branch and checkout the branch simultaneously, use the git checkout command. The switch -b specifies the name of the branch. Note that after command completion, Git has moved HEAD to the new branch.


1 Answers

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')
like image 112
BharathKumarMurugan Avatar answered Sep 23 '22 02:09

BharathKumarMurugan