0

Step 1. Baseline branch: master

/* file: master.txt */
line 1
line 2
line 3

Step 2. Checkout new branch b1 git checkout -b b1 and edit master.txt as follows, then commit.

/* file: master.txt */
line 1 changed
line 2
line 3

Step 3. Checkout master git checkout master and checkout new branch b2 git checkout -b b2 and edit master.txt as follows, then commit.

/* file: master.txt */
line 1
line 2 changed
line 3

Step 4. Checkout master again git checkout master and merge b1 git merge b1

Step 5. Stay on master branch and try to merge b2 git merge b2, there's a conflict

/* file: master.txt */
<<<<<<< HEAD
line 1 changed
line 2
line 3 
=======
line 1
line 2 changed
line 3
>>>>>>> b2

I guess it's common place that two devs checkout their own branches almost at the same time, edit the same file, and then merge back to baseline one after the other. What would be a practical approach to prevent this from happening in the first place, instead of resolving conflicts afterwards? Thanks for all your advice.

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
magento68
  • 26
  • 4
  • See *Concurrency model* on pp. 31-32 of my prototype-of-a-book [here](http://web.torek.net/torek/tmp/book.pdf). – torek Mar 03 '19 at 16:36

1 Answers1

2

If you want to prevent that happening, you need to use a source control tool based on pessimistic locking of files. Such a tool will not work for distributed or large-team development, and will be constantly interfering with small-to-medium sized teams' workflows. This is why frankly they aren't popular anymore.

Also it should be noted that your example might be misleading you. Changes to the same file will merge without conflict, unless they both edit the same part ("hunk") of the code. Of course changes overlap (and conflict) if they touch the same line; but also they conflict if they touch adjacent lines.

Which is to say, conflicts in practice aren't that common on most projects, and they usually aren't that hard to resolve. The costs of resolving the occasional conflict are much less, for most projects, than the costs of having to wait for the other dev to finish what they're doing and unlock the file you need.

That said, you can search for a pessimistic locking source control tool if you want. Maybe you're not convinced in spite of the overwhelming consensus on this point, or maybe something about your project really is different.

But to the extent your question then boils down to "what is a good tool to do this", that would be off-topic for SO, so I won't get into that.

Mark Adelsberger
  • 42,148
  • 4
  • 35
  • 52
  • ...and the rather low rate of conflicts (or easiness to resolve) that you mention is even furtherly decreased with good practices, like committing often and getting in sync with your source, again, often. Not to nit-pick, I found the answer stellar, never could have written something so useful and concise myself. – Romain Valeri Mar 03 '19 at 18:54