Search code examples
pythongitpython

Auto commiting changes in a repository


we're trying to autocommit changes on legacy directories, where the people don't want to use something like version control (sigh).

I'm using gitpython to commit these changes every night:

repo = git.Repo(local_directory)

changed_files = [change.a_blob.path for change in repo.index.diff(None)]
if changed_files or repo.untracked_files:

   if changed_files:
      repo.git.add(update=True)

   if repo.untracked_files:
      repo.git.add(repo.untracked_files)

   repo.git.commit(message='Auto committed')
   repo.remotes.origin.push(repo.head)

Sometimes commit fails with "'git commit --message=Auto committed' returned with exit code 1" - which I can't reproduce

Is there something I did wrong? I've read that maybe I should use repo.index to make a commit?

Best, Christopher


Solution

  • You're absolutely right you'll need to use repo.index to make a commit. Here's a working sample from my script using GitPython (which incidentally helps us with version control)

    repo = Repo(repo_dir)
    index = repo.index
    

    And then my commit_version function:

    def commit_version(requested_version, commit_msg, index, version_file):
        """Commits version to index"""
    
        print "Committing: ", requested_version
    
        index.add([version_file])
        index.commit(commit_msg)
    

    So you could just pass in "Auto committed" as your commit_msg. Hope this helps!