Search code examples
gitbranchgit-mergegit-commit

How git maintains commits from deleted branch?


enter image description here

This is git merge scenario. When I merge, New merge commit is created, so if I go back from New merge commit, I can see the scheduled history of all Master and Feature branch commits till Common base. This is the scenario I don't understand: If I delete Feature branch, I think Feature branch commits will be deleted, But the reality is that when I am standing on New merge commit, after deleting Feature branch, I can still see Feature branch commits when I type git log. How is that possible? Am i mistaking something?


Solution

  • As mentioned in the comments, a branch is just a note, a bookmark.

    If you dig a bit in the .git directory (which I recommend you to, for educational purposes), you will see a refs/heads directory. It will contain one file per branch that you have locally (the remote branches are stored in refs/remotes).

    If you open one of these files, you will see it contains a single line: the hash of the last commit the branch points to.

    Deleting a branch is effectively just removing the matching file in refs/heads. Which is why deleting a branch does not affect the commits "of the branch" (commits don't really belong to a branch).

    As a result, you can also (again, as educational purposes only, I'd not recommend to do that in a daily workflow of course) create a branch foo by creating the file refs/heads/foo with as content the full hash of the commit you want the branch to point to.

    As a second result, as soon as a branch is merged, there is no reason to keep it around "in case".