7

Im using GitPython to clone a master branch and do a checkout of a feature branch, I do my local updates, commit and push back to git. The code snippet looks like below,

Note : my branch name is feature/pythontest

def git_clone():
    repo = Repo.clone_from(<git-repo>, <local-repo>)
    repo.git.checkout("-b", "feature/pythontest")
    # I have done with file updates 
    repo.git.add(update=True)
    repo.index.commit("commit")
    origin = repo.remote(name="origin")
    origin.push()

When I execute the script, I get the below error,

To push the current branch and set the remote as upstream, use
git push --set-upstream origin feature/pythontest
0

2 Answers 2

3

origin.push() doesn't know how to match the local branch to the one in the origin, so you need to specify it through refspec:

origin.push(refspec="master:origin")

master is your local branch and origin the target.

You can find more details here in the fetch definition.

Sign up to request clarification or add additional context in comments.

1 Comment

I think you'd normally want refspec="master:master" if you've got a local master branch and you want it to track the master branch on the remote called 'origin'. (when I did master:origin I ended up with my 'origin' remote having a branch also called 'origin' which was tracked by my local branch called 'master')
3

For pushing new branches you need to run git push --set-upstream origin branch_name you can read on --set-upstream in git documentation https://git-scm.com/docs/git-push This should do the work for gitpython:

def git_clone():
    branch_name = "feature/pythontest"
    repo = Repo.clone_from(<git-repo>, <local-repo>)
    repo.git.checkout("-b", branch_name)
    repo.git.add(repo.working_dir)
    commit_output = repo.git.commit(m="Commit msg")
    push_output = repo.git.push('--set-upstream', repo.remote().name, branch_name)

Hope this helps!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.