How do you merge the master branch into a feature branch with GitPython?

前提是你 提交于 2019-12-03 16:27:25

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 master and feature. I'm currently on the feature branch, and I want to merge in changes from master.

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 master branch:

>>> master = repo.branches['master']
>>> master
<git.Head "refs/heads/master">

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, master)
>>> base
[<git.Commit "9007141b5daa35c39afda2d6baf670438d7424a7">]

Now we stage a merge operation:

>>> repo.index.merge_tree(master, base=base)
<git.index.base.IndexFile object at 0x7fa8bb6a9f70>

And commit it, providing links to the two parent commits:

>>> repo.index.commit('Merge master into feature',
... parent_commits=(current.commit, master.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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!