Pushing local branch to remote branch
Asked Answered
M

2

7

I created new repository in my Github repository.

Using the gitpython library I'm able to get this repository. Then I create new branch, add new file, commit and try to push to the new branch.

Please check be code below:

import git
import random
import os

repo_name = 'test'
branch_name = 'feature4'

remote_repo_addr_git = 'git@repo:DevOps/z_sandbox1.git'

no = random.randint(0,1000)
repo = git.Repo.clone_from(remote_repo_addr_git, repo_name)
new_branch = repo.create_head(branch_name)
repo.head.set_reference(new_branch)
os.chdir(repo_name)
open("parasol" + str(no), "w+").write(str(no)) # this is added
print repo.active_branch
repo.git.add(A=True)
repo.git.commit(m='okej')
repo.git.push(u='origin feature4')

Everything working fine until last push method. I got this error:

stderr: 'fatal: 'origin feature4' does not appear to be a git repository fatal: Could not read from remote repository.

Please make sure you have the correct access rights and the repository exists.'

I'm able to run this method from command line and it's working fine:

git puth -u origin feature4

But it doesn't work in Python.

Matte answered 11/10, 2016 at 7:43 Comment(0)
M
4

This worked for me:

repo.git.push("origin", "feature4")
Mummer answered 13/3, 2017 at 0:12 Comment(0)
H
1

Useful documentation for fetch/pull/push operations with gitpython: https://gitpython.readthedocs.io/en/stable/reference.html?highlight=index.fetch#git.remote.Remote.fetch

from git import GitCommandError, Repo

repo_name = 'test'
branch_name = 'feature4'
remote_repo_addr_git = 'git@repo:DevOps/z_sandbox1.git'

# clone repo
repo = git.Repo.clone_from(remote_repo_addr_git, repo_name)

# refspec is a sort of mapping between remote:local references
refspec = f'refs/heads/{branch_name}:refs/heads/{branch_name}'

# get branch
try:
    # if exists pull the branch
    # the refspec here means: grab the {branch_name} branch head
    # from the remote repo and store it as my {branch_name} branch head
    repo.remotes.origin.pull(refspec)
except GitCommandError:
    # if not exists create it
    repo.create_head(branch_name)

# checkout branch
branch = repo.heads[branch_name]
branch.checkout()

# modify files
with open(f'{repo_name}/hello.txt', 'w') as file:
    file.write('hello')

# stage & commit & push
repo.index.add('**')
repo.index.commit('added good manners')
# refspec here means: publish my {branch_name} branch head
# as {branch_name} remote branch
repo.remotes.origin.push(refspec)
Hayrick answered 17/6, 2022 at 13:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.