Absent a very compelling reason, I would suggest just using the git
binary to perform your tasks. However, if you want to do this using GitPython, take a look at the Advanced Repo usage section of the documentation, which includes an example merge operation.
For example, let's say I have a repository with two branches named main
and feature
. I'm currently on the feature
branch, and I want to merge in changes from main
.
I start by initializing a Repo
object:
>>> import git
>>> repo = git.Repo('.')
Now I need a reference to my current branch; I can do this:
>>> current = repo.active_branch
>>> current
<git.Head "refs/heads/feature">
Or I can get the branch by name:
>>> current = repo.branches['feature']
>>> current
<git.Head "refs/heads/feature">
I also need a reference to the main
branch:
>>> main = repo.branches['main']
>>> main
<git.Head "refs/heads/main">
Now I need to find the merge base of these two branches (that is, the
point at which they diverge:
>>> base = repo.merge_base(current, main)
>>> base
[<git.Commit "9007141b5daa35c39afda2d6baf670438d7424a7">]
Now we stage a merge operation:
>>> repo.index.merge_tree(main, base=base)
<git.index.base.IndexFile object at 0x7fa8bb6a9f70>
And commit it, providing links to the two parent commits:
>>> repo.index.commit('Merge main into feature',
... parent_commits=(current.commit, main.commit))
<git.Commit "fb7051d7be36b7998a8f6c480120f84f3f9d9f73">
>>>
At this point, we have successfully merged the two branches but we
have not modified the working directory. If we return to the shell
prompt, git status
file show that file1
has been modified (because
it no longer matches what is in the repository):
$ git status
On branch feature
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: file1
We need to perform a checkout of the new commit:
>>> current.checkout(force=True)
<git.Head "refs/heads/feature">
And now:
$ git status
On branch feature
nothing to commit, working directory clean
The above process is fragile; if there are merge conflicts, it's just
going to blow up, which is why you are probably better off sticking to
the CLI.