I have two git branchs, branch-a
and branch-b
. I want to get branch-a
to be in the same state (i.e. have the same files with the same contents) as branch-b
while keeping its commit history, so than I can create a new commit with this.
This is very close to what I want:
$ git checkout branch-a
$ git checkout branch-b -- . # copy the state of all files from branch-b to branch-a
$ git add .
$ git commit -A -m"Sync with branch-b"
Now If I go to branch-b
and change some files, I can do the sequence of steps above and have the exact same state in both branches.
The problem with this approach is that it does not work with deleted files. When a file is deleted from branch-b
, doing git checkout branch-b -- .
in branch-a
will not delete the file.
Another alternative would be to merge the changes from branch-b
to branch-a
, but that has other problems. If a file was added on branch-a
but not on branch-b
I want the "sync" process to delete the file in branch-a
, but in a merge it will just be ignored because it's not conflicting.
CodePudding user response:
This can be accomplished by checking out the desired branch, resetting to the other branch and committing:
# make a temporary branch that looks like branch-b
git switch -c temp-branch branch-b
# reset to branch-a
git reset --soft branch-a
# commit the difference
git commit -m "Change to be like branch-b"
# rename your branch to branch-a
git branch -M branch-a
Note my commit message "Change to be like branch-b" instead of "Sync with branch-b". The word sync implies it's 2 way, but in this case it is just an exact copy.