Home > Software engineering >  Git merge, but adding in all the conflicting lines
Git merge, but adding in all the conflicting lines

Time:10-18

code.go on branch main currently contains:

package code

some Golang code() {
}

code.go on branch new-branch currently has:

package code

some other Golang code() {
}

even more code() {
}

Ideally, I want the end result to be:

package code

some Golang code() {
}

some other Golang code() {
}

even more code() {
}

How can I "merge" the new-branch onto main to achieve the above result? When I merge, git gave me conflict, since some Golang code() and some other Golangcode() are on the same line between branches.

If I choose "Accept both incoming," one of my brace goes missing, resulting in syntax error. I simply want the resulting code.go file to contain all those 3 block of codes in their intact form.

CodePudding user response:

The issue here is that there is no way for git to determine which code should go first: moving the some Golang code to the end instead would be just as natural as having it at the beginning. So doing the merge by hand is the way to go, so that you can make sure the code ends up in the correct order.

CodePudding user response:

You will not be do it automatically, because you have here "classic" conflict (I show it here in GUI, but internally Git see the same thing): one line of code replaced by another snippet

Diff of files

You must to perform manual merge and resolve conflict by hand using any (good) merge-tool, supported by Git

CodePudding user response:

If I choose "Accept both incoming," one of my brace goes missing, resulting in syntax error. I simply want the resulting code.go file to contain all those 3 block of codes in their intact form.

Unfortunately, the merge algorithms used by git and other common VCSes are not "code aware", they are operating only on the level of text.

So, while it is obvious to you which lines belong together, an automated tool has to try and guess which lines should go where with no idea what they mean. To see things from the tool's point of view, keep the structure of the files but replace the words and punctuation with nonsense:

habble hibble

quig quag quog blib-blob frong
gnorf

and

habble hibble

quig quaggledy quog blib-blob frong
gnorf

quoogle quog blib-blob frong
gnorf

The merge algorithm sees that the two branches have added different text at lines 3, 6, and 7, but both have "gnorf" at line 4. So it assumes that's the same "gnorf", and gives you something like this:

habble hibble

quig quag quog blib-blob frong
quig quaggledy quog blib-blob frong
gnorf

quoogle quog blib-blob frong
gnorf

The algorithm could be less clever, and not look for cases where you've added the same code in both branches, but this would be wrong just as often.

  • Related