Search code examples
gitintellij-ideagit-checkout

Why checking out to a remote branch creates one locally


Let's say there's a remote branch named origin/nameofbranch. When I checkout to this branch using Git in Intellij, it automatically creates a local branch with the same name, why is that happening?


Solution

  • It seems like IntelliJ is smart enough to call git checkout <branch> behind the scenes, rather than git checkout origin/<branch>. That's a good thing, see knittl's answer to understand why.


    When you try to checkout branch foo, git basically goes through these steps:

    • If it exists locally (i.e. if you have a file .git/refs/heads/foo), it's a simple branch switch (with every usual caveat about git checkout, of course).

    • If it doesn't exist locally, git checks if one of your remotes has a ref named foo. Then:

      • If more than one exists (for instance if you have both origin/foo and origin2/foo) then it stops and asks you to disambiguate.

      • If none exists, the checkout fails with a message about the pathspec not existing.

      • If exactly one exists, then git assumes you want a new local branch to be associated with it. Two consequences: it creates the new branch pointing at the same commit <your-remote>/foo happens to point at, then sets branch tracking config between the two. (It transforms your git checkout foo into an implicit git checkout -b foo <your-remote>/foo then does a git config branch.foo.remote '<your-remote>' and git config branch.foo.merge 'refs/heads/foo')