HamletHub HamletHub - 1 month ago 7
Git Question

Can git checkout to remote branch without pulling files?

I need to create an empty orphan branch from another remote branch.

The problem is if I checkout to the parent branch, it will pull the files, and those will then be included in the orphan branch. Or does it matter what branch another branch is created from, if I want to add those changes back to a particular branch?

Is there a way to create an orphan branch from a branch, without being checked into that branch? After adding the remote, I tried running

git checkout --orphan orphan_branch parent_branch


but it gives me an error "
Cannot update paths and switch to branch 'orphan_branch' at the same time.
"

Or, is it possible to run "
git remote add origin giturl
", and wind up in a branch other than the master branch?

Answer

If you want to go from:

 x--x--x--x--x    (origin/master)
        \
         Y--y--y  (origin/abranch)

to a local orphan branch:

Y--y--y (abranch)

You need to:

Depending on your case, you might find Y (the first commit from origin/abranch not in origin/master) with "how to find first commit of specific branch":

git log origin/master..origin/abranch --oneline | tail -1

If origin/abranch has a single merge base as shown above, then use git merge-base to find Y^ (parent commit of Y, since cherry-pick does not include the first commit itself):

git cherry-pick $(git merge-base origin/master origin/abranch)..origin/abranch

Or does it matter what branch another branch is created from, if I want to add those changes back to a particular branch?

A branch is just a pointer and help referencing all commits accessible from its HEAD. If a branch is spawned from another, that means all of the other branch commits are part of the new branch as well.
See "Using branches" and "Git Branching - Branches in a Nutshell".

It is best to merge back a branch in its the branch it came from (not exactly a "parent" branch as there is no concept of ancestors for branches)

  x--x--x--x--x--M (master)
   \            /
    Y--y------y    (abranch)

If you don't, that means oyu are cherry-pick or rebasing --onto, which is more complex and risk duplicating commits.
That would go from:

 x--x--x--x--x         (master)
        \
         p--p--p       (anotherbranch)
             \
              Y--y--y  (abranch)

To (with git rebase --onto master $(git merge-base anotherbranch abranch) abranch) :

               Y'--y'--y' (abranch)
              /
 x--x--x--x--x            (master)
        \
         p--p--p          (anotherbranch)

Then you can fast-forward abranch to master.

To experiment some more with branches, see "Learn Git Branching".

Comments