Home > Mobile >  move local commits into a to be created branch
move local commits into a to be created branch

Time:09-16

I've committed some local changes.

Now I would like to move these commits into a branch for later

(in order to start working on the version before my commits).

I already read all the titles of similar question, and they either assume,

  • that one wants to move commits from one branch into another, or
  • they assume that one wants to move uncommitted changes into a branch.
  • Other questions ask to move between (existing) branches. I want to create a branch.

git status tells me the following:

hostname /dir : git status
On branch master
Your branch is ahead of 'origin/master' by 10 commits.
  (use "git push" to publish your local commits)
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

no changes added to commit (use "git add" and/or "git commit -a")
hostname /dir :

CodePudding user response:

Let's say your repository started like this with three commits on main.

A - B - C [main]

I've committed some local changes.

Presumably to your main branch. Let's call them 1, 2, and 3.

A - B - C - 1 - 2 - 3 [main]

Now I would like to move these commits into a branch for later

You don't move the commits, you move the branches. Unlike other version control systems you may be familiar with, branches are just a label pointing at a commit. main points at commit 3.

First, with main checked out, make a new branch. This will point at the same commit as main, 3. It is equivalent to main.

$ git branch other

A - B - C - 1 - 2 - 3 [main]
                      [other]

And now move main back to commit C. You'll have to use git log to figure out which commit ID is C.

Again, this is just moving a label that points at a commit.

$ git reset --hard C

A - B - C [main]
         \
          1 - 2 - 3 [other]

Note that only my drawing changed to make it easier to draw, the commits are exactly the same. There's nothing special about the connection between C and 1. Nothing has changed but what commit main points at.

CodePudding user response:

From what I think I understand (and have never found anywhere stated so clearly):

  • a branch is always a point in a tree. It does not contain information about the original point in the tree at which it was created.
  • merging is done by traversing the tree until the common root and applying all commits found in both branches

So the following two scenarios produce identical results:

  1. creating branch after commit
  • edit
  • commit
  • create branch
  • reset & checkout
  1. creating branch before commit
  • create branch
  • switch to branch
  • edit
  • commit
  •  Tags:  
  • git
  • Related