JMarsch JMarsch - 1 year ago 99
Git Question

If I tag HEAD on a branch and delete the branch, can I recreate the branch from the tag?

Using git: Suppose I create a branch, do some commits, and then decide that I want to delete the branch (after a merge squash, a rebase. Maybe there is the slightest chance that I might want to revisit the squashed commits one day, so before I delete that branch, I create a tag pointing to that branch's HEAD.

Once the branch is deleted, can I create a branch from that tag to get my work back? Ok, so that's easily testable, BUT, will the tag survive Git's garbage collection, or will it get GC'd later on?.

The long story (you don't need to read the rest unless you are curious)

So why would I want to do this at all?
Well, I like squashing my commits when I merge back to master, but if it was a really meaningful branch, I might want a way to get back to those individual commits if something goes wrong in the next sprint or 3.

So I was thinking about squashing my branch back to master, deleting the branch (so there is no confusion as to whether it is active, whether it needs to be merged, or whether it should take new commits), but then keeping a tag around so that I could recreate the branch if some sort of need arises. Would that tagging trick work?

Answer Source

From git manual:

git gc tries very hard to be safe about the garbage it collects. In particular, it will keep not only objects referenced by your current set of branches and tags, but also objects referenced by the index, remote-tracking branches, refs saved by git filter-branch in refs/original/, or reflogs (which may reference commits in branches that were later amended or rewound).

As long as your commit is reachable from a tag - you are safe.

If you want to test this out, you should force git to remove all unreachable objects. If you use git gc with default options, commits you though were safe might disappear after two weeks.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download