How to create branch only from my commits

57 Views Asked by At

I have following situation: I created branch A from branch DEV to develop new feature. Other person created branch B from DEV and pulled my code from A. Unfortunately features A and B were so related that I had to pull from B to A too. Now I would like to make code review, but when I do that there are also changes from B visible. Is there a way to create new branch from A that will show only my changes in comparsion to A or DEV or is there any other solution to this problem? I tried to checkout specific commit but it doesn't seem like a good solution.

1

There are 1 best solutions below

0
TTT On

I'm a little confused by the question because it sounds like you had want you wanted in the first sentence:

I created branch A from branch DEV

If you can't use that because you need code from branch B in your branch, then creating a new branch isn't going to help. You could take the code needed by both A and B and do a separate Pull Request for just that, and then A and B could both branch from there which would isolate their respective changes in their own PRs.

Regardless of what you want your branch to look like, I believe the answer to your question centers around the realization that branches are basically just pointers to a commit. You can point an existing branch, or a new one, to any commit you wish. There are multiple ways to do this, some of the most common are:

# create a new branch which points to commit a1b2c3 (newer syntax)
git switch -c my-new-branch a1b2c3
# or older syntax
git checkout -b my-new-branch a1b2c3

# change an existing branch to point to commit a1b2c3
git switch my-existing-branch # checkout the branch if you haven't already
git reset --mixed a1b2c3 # note "--mixed" is the default, you can leave it out
# Note mixed mode will leave all the changes you had on that branch as pending.
# If you don't want them (or have committed them elsewhere) and are
# willing to remove them from your current branch
git reset --hard a1b2c3

# create a new branch pointing to whatever commit I'm on now (don't checkout)
git branch my-new-branch

# create a new branch pointing to a1b2c3 (don't checkout)
git branch my-new-branch a1b2c3

# another way to reset an existing branch to point to a1b2c3 (don't checkout)
git branch -f my-existing-branch a1b2c3 # -f means "force"

# another way to reset an existing branch and checkout (newer syntax)
git switch -C my-existing-branch a1b2c3
# (older syntax)
git checkout -B my-existing-branch a1b2c3