Solved – git push – Your branch is ahead of origin/master by x commits

Sunday, 28. October 2012

For those starting to use Git in a team or group of collaborators, it’s common to come across this error when trying to puch changes over to your git server repository. – Your branch is ahead of ‘origin/master’ by x commit

Basically, what git is trying to tell you here is that you are trying to upload changes to a repository that has recent changes than those on your local repository

So the best thing to do here in order to get a successful push, you will simply need to consolidate the two repositories. There are sevaral ways to achieve this consolidation or merging process

1) Using Git Pull
Git pull allows you to automatically fetch (download) changes and fix them automatically. Git pull is context sensitive, which means git try to will merge any pulled (downloaded) commits from remote repository into the branch you are currently working in and automatically merge the commits without letting you review them first. This can be scary process but a quick solution

git pull <repo_name>

2) Using Git fetch
Sometimes it is important to have control over what changes needs to be final for any conflicting file. In order to have such control, you will need to use git fetch and merge commands to achieve this

Git fetch does one cool thing: As opposed to git pull, git fetch will pull down the remote repo and try to merge changes in the current working branch. However, if it encounters the differences in any file, it will report a failure and tell you which files happen to be in conflict.

At this stage, git provides you with an opportunity to review the files in question and decide which which changes should be final for that file.

There are fine tools our there such as gitk, ViewGit etc that can help you to visually checkout the conflicts and decide what to do.

To Fetch the repo you may want to specify RefSpecs for git to be more specific on which repository and branch you want to fetch and merge your current branch with. You can also set default RefSpecs in your .git/config file if you will always be fetching and merging from the same source and destination.

# fetch origin repo and try to merge local master branch with Master branch from origin repo
git fetch origin master:refs/remotes/origin/master
# the merge the stuff from origin repo with current branch
git merge origin

At this level, any conflicts detected will need to be fixed and once you have them changes figured out and fixed, you will then need to add all the changes to the current branch ready for commit

# add all files in the working tree and mark them for commit
git add .
# them commit your changes locally
git commit -a
# push changes to remote
git push <remote_repo> <local_repo>

Leave a Reply

You must be logged in to post a comment.