'Why does git allow deletion of a remote branch with unmerged changes but not a local one?

Running git branch -d unmergedbranch results in an error because git doesn't allow deletion of local branches with unmerged changes (to prevent a user accidentally losing work that hasn't been merged). Why doesn't this also apply to remote branches with unmerged changes (git push --delete origin unmergedbranch)? Is it because git assumes there will be a local branch that corresponds to the remote branch, so deleting the remote on its own won't lose any work?

git


Solution 1:[1]

Why does git allow deletion of a remote branch with unmerged changes but not a local one?

First of all, Git does "allow" deletion of an unmerged local branch too. Perhaps a better wording of the question would be something like:

Why does Git have an option to warn about deleting unmerged local branches but not warn for upstream branches?

Because they're conceptually different, and use different commands with different options. When deleting a local branch, the command option of lowercase -d:

git branch -d branch-name

is documented as:

Delete a branch. The branch must be fully merged in its upstream branch, or in HEAD if no upstream was set with --track or --set-upstream-to.

You can use -D to override that check. Note for an upstream branch that check wouldn't make sense because it already is the upstream branch. Also, the command used for deleting the upstream branch is git push which is conceptually different than the branch command. When you add --delete to push you are deleting a ref, which may not necessarily be a branch.

As for this additional question:

Is it because git assumes there will be a local branch that corresponds to the remote branch, so deleting the remote on its own won't lose any work?

Note you can still delete upstream branches created by other people that you never checked out locally. Regarding losing work though, even unreferenced commits generally hang around for at least 90 days by default, and on many centralized Git server SCM tools, pushed commits stay around indefinitely even though clones may not receive them.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TTT