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.dir
Solution 1:
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')
Solution 2:
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()
Solution 3:
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
Post a Comment for "Use GitPython To Checkout A New Branch And Push To Remote"