Use GitPython to Checkout a new branch and push to remote
Asked Answered
L

3

8

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)])
Loanloanda answered 15/6, 2016 at 21:14 Comment(0)
E
13

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')
Erethism answered 23/8, 2017 at 4:33 Comment(0)
H
1

This was exactly my use case, with the added requirement that I needed to switch back to original branch afterwards. I did it using this:

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()
Hypersthene answered 27/1, 2022 at 19:13 Comment(0)
G
-2

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

Gerge answered 16/6, 2016 at 1:37 Comment(1)
thanks but using the git module to exactly command is just the same as sub process. ill go deeper into pygit2 but the module seems like he lacks the things i need ( or its very difficult to achieve them)Loanloanda

© 2022 - 2024 — McMap. All rights reserved.