Rustavore
Rustavore

Reputation: 1885

git remove branch without removing commits

I have two branches I normally work on: master and homepage_buildout. I was recently told to checkout an old commit from before I was working on the project. I simply did:

 git checkout [commit number]

Then I decided to make this old commit a branch like so:

 git checkout -b old_homepage

Now, I realized that I don't need to be able to reference the branch old_homepage anymore, but I still want it exist as a commit. How do I retain those commits but remove the branch from appearing when I type:

 git branch

Upvotes: 3

Views: 3381

Answers (3)

torek
torek

Reputation: 487755

I think what you're actually asking boils down to: "if I do git branch -d old_homepage will the commits get lost", and the answer is: "Deleting the name only deletes the name; the commits themselves stick around as long as you can see them in git log --all, and actually even longer."

To visualize this better, run something like gitk --all or gitk --tags (try both on some complex git repos). Scroll around through the commits. Now imagine putting a sticky note on any commit. That's a "tag" or "branch" name. Take the sticky note off. Commit is still there, right? :-)

That leaves one obvious question: when do things like commits actually go away? The answer is: only after you remove all the names that lead to them. The gitk command (like most other git commands) starts with the name HEAD. If you give it --all it adds all the branch names it can find. If you give it --tags it adds all the tag names it can find. Then it works backwards, looking at each commit to see what other commit(s) it refers to.

Git removes things (commits, etc) when there is no way to find them by starting at one of these obvious names and working backwards. (Even then it waits a long time, 30 to 90 days by default.) So, if you add a branch or tag label to an old commit whose number you found by doing git log for instance, that gives you a new obvious name for that commit number; but removing again it is safe as long as it's not the only way to find it by name.

Upvotes: 11

Bombe
Bombe

Reputation: 83847

I’m not quite sure but in that situation you would usually use a tag.

git tag <some-name> <commit-id>

It would not show up in git-branch but git-tag will show it.

Upvotes: 0

mipadi
mipadi

Reputation: 410552

You can tag the the commit:

$ git tag <tagname> <commit-hash>

Since a tag references the commit, it won't get garbage-collected.

Upvotes: 3

Related Questions