Alternate Timelines

I like this time travel metaphor way too much for my own good, and I'm not going to let it go now.

Remember when I told you that you can't commit when you're on an old revision because you're in the past and you'd change the future?

That's not entirely true.

It is true that you can't change the future. Every commit id (that long string of letters and numbers) corresponds to a specific commit message, state of your files, and history. It is impossible to change the message, state, or history behind that commit id.

However, you can create an alternate timeline, with new commits that have their own id's, history, and states.

This is what we call a "branch".

master is the first branch that is created by default in any Git repository. By convention, most repositories have a master branch.

At any time, you can start a new branch (and start a new timeline) with the command:

git checkout -b nameofnewbranch

Git should then tell you something like

Switched to a new branch "nameofnewbranch"

At this point, any commits you make will go in the new branch, and master will stay exactly where you left it.

That means that, if you want, you can try something crazy now. It's OK, if it doesn't work out, you can just go back to master. Even if it does work out, you can still go back to master.

Branches are cheap and easy to create, so you shouldn't worry about overusing them.

To delete a branch, checkout something else and type:

$ git branch -d nameofbranch

This is another of those commands that Git may fail to complete, rather than see you lose data. In this case, Git will only let you delete branches that are in the past.

If the branch is not within the history of HEAD, that means there may be commits that are only on that branch, and deleting it would mean you lose those commits.

If that's ok with you, here's the dangerous version:

$ git branch -D nameofbranch

If you do delete a branch and lose commits that you, uh, actually wanted, don't worry. The process of losing them happens to be very slow. Unless you tell it otherwise, Git will keep everything you commit for at least 30 days from when you last checked it out, probably longer.

To recover a deleted commit, all you need to do is find its commit id, checkout that commit, and create a branch there.

For help in finding the commit id, you can use the "git reflog" command. That will show you every commit id you've worked on in at least 30 days, probably longer.

Git also has a concept of a "tag" that I should tell you about.

A tag is basically a bookmark that points to a specific commit and never, ever changes.

To create a tag, checkout a revision and run

$ git tag nameoftag

OK, so you actually can delete a tag and create a new one with the same name somewhere else. That is similar to moving it. But that's rewriting history, and you really shouldn't do that.

Vincent Povirk