Search code examples
pythongitgitpython

Reverting local changes to a file using GItPython


Is there a way under the GitPython library to revert local changes to a single file?

Under the Git command line I would just use git checkout filename but attempting to do this under the GitPython API, like so

repo.index.checkout([filename])

leads to the following error,

git.exc.CheckoutError: Some files could not be checked out from the index due to local modifications:['foo']


Solution

  • Ah, figured it out a few minutes after posting by looking at the source.

    If I turn on force by using repo.index.checkout([filename]. force=True) it works fine.

    There may be a better way, but according to the source the force parameter is just there to overwrite local changes.

    :param force:
    If True, existing files will be overwritten even if they contain local modifications.
    If False, these will trigger a CheckoutError.