Wednesday, October 3, 2018

Misc git Tips

git is a version control system that originally began life with the Linux kernel development team (replacing BitKeeper) and has grown to become, arguably, the dominant version control system in use today.  Those who haven't heard of git but have heard of github usually make the association, but it's important to remember that github is just one of many collaboration frontends built on top of git.  Read all about version control over here.

OK, so you're using git for your project.  If you're like me you may follow a model of creating a branch, doing your work there, then merging that branch back in to the main line.  This model is made extremely simple through github's web interface and is called forking a repository and then sending a pull request.

Here are some tips for working with forked repositories.  I am mostly posting this for my own future reference.

Keeping Your Forked Repository Up To Date

Often times you will be doing continual work on a project and want to keep your fork up to date with the main repository.  I do it by creating a new remote called 'upstream', fetching that, and then merging it in to my fork.  Like this (using the timezone database project as an example):

git remote add upstream https://github.com/eggert/tz
git fetch upstream

Now you have the upstream project under the name 'upstream' in your repo.  Your repo is under the name 'origin' and you likely have local tracking branches for work done there.  e.g., 'master' is tracking 'origin/master'.

You just fetched the latest updates from upstream, now you want to merge them in to your repo:

git checkout master
git merge upstream

You can do this for different branches to by checking out a different branch you have and merging from a specific upstream branch.  Such as a stable branch:

git checkout -b stable-release origin/stable-release
git merge upstream/stable-release

Lastly, remember that this is all a one-way pull, so you need to push your newly merged repo back to your origin:

git push

Just don't push to upstream.  In fact, it's good practice to add remotes called 'upstream' using read-only repo URLs.

Branches Get Removed

It's not uncommon for branches to be created and destroyed frequently with git.  While a git fetch operation will pull down new branches, it does not automatically remove any branches that have disappeared at the origin.  Here's how you can do that:

git fetch -p

You can also specify a different remote, such as:

git fetch -p upstream

Remember that you also need to delete any branches you created locally that were tracking removed branches.  Use git branch -D to remove the local branches.

No comments: