-1

I'm trying to recreate the situation where branches have diverged (so I can practice solving the problem) as mentioned in this question: master branch and 'origin/master' have diverged, how to 'undiverge' branches'?

Any examples on how to create this?

Snowcrash
  • 80,579
  • 89
  • 266
  • 376
  • Create a commit on one branch. Checkout another branch. Create a different commit on that branch. – chepner Jun 23 '21 at 14:51
  • 1
    If you are talking specifically about a local branch and the remote branch it tracks, you can reset the local branch to an earlier commit (so that it is *behind* the remote branch), then commit something different to the local branch. – chepner Jun 23 '21 at 14:53

2 Answers2

0

create a repo. Create an initial commit. Set up a new branch (don't checkout, just create the branch). Then commit something (on the original branch, right?). Then checkout the other branch (which will be on the first revision). Then commit something different. There you have a divergence.

git init
# do and add stuff
git commit -m "First commit"
git branch another-branch
# do and add stuff
git commit -m "second commit"
git checkout another-branch # on first revision
# do and add stuff
git commit "A different second commit"

There you have it.

git log --all --graph --oneline
eftshift0
  • 26,375
  • 3
  • 36
  • 60
0

a. create two local diverging branches :

git init
git checkout -b master
echo aaa > a.txt && git add a.txt && git commit -m "first commit"

git checkout -b diverge
echo bbb > b.txt && git add b.txt && git commit -m "diverge: bbb"
echo ccc > c.txt && git add c.txt && git commit -m "diverge: ccc"

# return to 'master' branch (which is 2 commits behind 'left') :
git checkout master
echo ddd > d.txt && git add d.txt && git commit -m "master: ddd"
echo eee > e.txt && git add e.txt && git commit -m "master: eee"


# now 'master' and 'diverge' are two local branches, which diverge :
git log --oneline --graph diverge master

b. if you want a diverging remote, push the 'diverging' branch to origin as 'master' branch :

git push origin diverge:refs/heads/master
# you now have a 'origin/master' branch

# at the same time, set your local 'master' branch to track 'origin/master' :
git branch -u master origin/master

# now 'git status' on master should say 'ahead 2, behind 2'
git checkout master
git status

Other ways to create diverging histories :

  • create a master branch, push it to orgin, then run git rebase -i HEAD~3 for example, and edit or remove the first commit

  • create a master branch, push to origin, then git reset your master branch to some commit in the past, and create new commits on master

LeGEC
  • 46,477
  • 5
  • 57
  • 104
  • I assume the fix, if you'd done this scenario `create a master branch, push it to orgin, then run git rebase -i HEAD~3 for example, and edit or remove the first commit`, is to do a `git rebase origin/main`. Is that right and, if so, how does that work? – Snowcrash Jun 23 '21 at 15:45