topskip
topskip

Reputation: 17335

Understanding git: connect branch to a remote repository

I have a repository on github, say testrepo. Now I'd like to set up a local repository repo that has one branch origin-master where I want do be able to edit things from the repository.

repo/origin-master  <-------->  origin/master

The cloning works fine:

mkdir repo && cd repo && git init 
# not necessary of course:
echo "master" > master && git add master && git ci -m "master"
git remote add origin [email protected]:<username>/testrepo.git
git fetch origin
git branch --set-upstream origin-master origin/master 
git checkout origin-master
# create a new file:
echo "for origin-master" > orig-master && git add orig-master && git ci -m "orig-master"

but

git push origin 
To [email protected]:<username>/testrepo.git
 ! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to '[email protected]:<username>/testrepo.git'
To prevent you from losing history, non-fast-forward updates were rejected
Merge the remote changes (e.g. 'git pull') before pushing again.  See the
'Note about fast-forwards' section of 'git push --help' for details.

How can I tell git that if I want to push to origin, I want to push the local branch origin-master to origin/master?

Upvotes: 5

Views: 3154

Answers (3)

ellotheth
ellotheth

Reputation: 4503

Set your default push behavior to upstream:

$ git config push.default upstream
$ git push origin

git push origin is the same as git push origin :, which pushes all "matching" branches by default. Your origin-master branch doesn't match, so it tries to take the branch that does match (master) and push that to origin.

Alternatively, you can specify the push refspecs on a per-remote basis:

$ git config --add remote.origin.push origin-master:master
$ git push origin

See also git-push examples and git-config.

Upvotes: 2

user1338062
user1338062

Reputation: 12735

I have problems understanding what kind of workflow you are trying to set up, but would this help?

"How do you make an existing git branch track a remote branch?"

Upvotes: 3

CharlesB
CharlesB

Reputation: 90286

See this post for good advice of pushing to a non-bare (i.e. with working copy) repo. Basically what's going on here is that when you push this way, the remote repo doesn't update it's working copy (the real files), only its history. You then need to git reset --hard on it to refresh the files, but it's dangerous since you'll lose non committed modifications.

As a general advice I would say to prefer pull to push when dealing with multiple non-bare repositories: push to only bare repositories!

Upvotes: 4

Related Questions