Search code examples
pythongitpygit2

How can I perform a rebase with pygit2?


This question touches on how to perform a merge with pygit2, but, to the best of my understanding, that will result in a new commit. Is there a way to perform a rebase, which will not result in a new commit and will simply fast-forward the branch reference to correspond to the latest from a given remote?


Solution

  • You can fast-forward with Reference.set_target().

    Example (fast-forwarding master to origin/master, assuming that the script starts from checked out master branch in clean state):

    repo.remotes['origin'].fetch()
    origin_master = repo.lookup_branch('origin/master', pygit2.GIT_BRANCH_REMOTE)
    master = repo.lookup_branch('master')
    master.set_target(origin_master.target)
    
    # Fast-forwarding with set_target() leaves the index and the working tree
    # in their old state. That's why we need to checkout() and reset()
    repo.checkout('refs/heads/master')
    repo.reset(master.target, pygit2.GIT_RESET_HARD)