4

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?

JMarsch
  • 21,484
  • 15
  • 77
  • 125
  • AFAIK it is possible to checkout any commit which either exists in a branch or is on the reflog, and create a new bona-fide branch from that commit. If the commit in question is from a branch which has now been deleted, and no other live branches point to it, then yes I would expect that it could go out at some point. Why don't you just keep the branch around if you are worried? – Tim Biegeleisen Aug 14 '16 at 15:32
  • 2
    If a commit can be reached via a ref (and a tag is a ref), then GC won't delete it. – Oliver Charlesworth Aug 14 '16 at 15:36
  • I second Oliver's comment. So deleting the branch wont delete the commits, so long as the commits are reachable (so the tags, and even transient things like reflogs will still point to the commits, so they wont get garbage collected and removed from history). – David Neiss Aug 14 '16 at 15:39

1 Answers1

5

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.

Community
  • 1
  • 1
Piotr Praszmo
  • 17,928
  • 1
  • 57
  • 65