How do I programmatically simulate resolving a mer

2019-09-16 06:26发布

问题:

As per my recent question on merging branches using GitPython, I'm trying to unit test the solution there. To do so I need to simulate a user opening their merge tool, resolving the conflicts and committing the result.

If I do this manually using the CLI it all seems to work:

echo 'Something to resolve the conflict' > conflicted_file.txt
git add conflicted_file.txt
git commit -m "Conflict resolved"

I've tried to simulate that same process using GitPython:

filename = 'conflicted_file.txt"
with open(filename, 'w') as f:
    f.write('Some combined content which resolves the merge issue')
# repo is a git.Repo instance
repo.index.add([filename])
repo.index.commit("Simulating user resolving a conflict"+filename)

..but this just raises an exception for me:

Traceback (most recent call last):
  File "C:\Projects\grit\test_Gritter.py", line 240, in test_MergeConflicts
    repo.index.commit("Simulating user resolving a conflict"+filename)
  File "C:\Python34\lib\site-packages\git\index\base.py", line 934, in commit
    tree = self.write_tree()
  File "C:\Python34\lib\site-packages\git\index\base.py", line 531, in write_tree
    binsha, tree_items = write_tree_from_cache(entries, mdb, slice(0, len(entries)))
  File "C:\Python34\lib\site-packages\git\index\fun.py", line 234, in write_tree_from_cache
    raise UnmergedEntriesError(entry)
git.exc.UnmergedEntriesError: 100644 fd05580faebf11aee13944da595112eced471664 2 conflicted_file.txt

Is there something else I need to mark it as resolved?

Edit - some more background on what I'm trying to automate

So just to be clear I want to make it as easy as possible to merge changes in a remote master branch which has been updated into a remote feature branch, resolving any merge conflicts.

As far as I'm aware, the correct way to do that is to:

  1. Create a local feature branch
  2. Make some changes
  3. Push my changes to the remote
  4. ...meanwhile someone else merges their changes into the remote master so I now need to merge those changes into my feature branch...
  5. Switch to master (on my local checkout)
  6. Pull from the remote master to update my local copy
  7. Switch to my local feature branch
  8. Attempt to merge
  9. Resolve any conflicts
  10. Push the merge to the remote feature branch

I've got most of this in a single Python script now but the problem this question pertains to is in simulating step 9 in the steps above.

回答1:

I gave up trying to use the internals of GitPython on the grounds that trying to disentangle the relevent commands from the unit tests was proving rather tricky.

In the end, this worked:

g = git.Git('my/repo')
g.execute(["git","add","conflicted_file.txt"])
g.execute(["git","commit","-m", "Conflict resolved"])