2

I have used subprocess.check_output to get the result of Git command but I can't think of a way how to update the commit message that we do with the command git commit -amend ?

2 Answers 2

1

You can pass a commit message to git commit --amend. For example:

git commit --amend -m "This is a new commit message"

Or you can read a new commit message from a file:

git commit --amend -F commitmsg

Or you can read it from stdin:

echo "This is a new commit message" | git commit --amend -F-

You could use any one of these mechanisms through Python.

2
  • What does -F stands for ? Commented Aug 8, 2015 at 16:03
  • That is how you read a commit message from a file...which I thought I had stated clearly in the answer, but if it was unclear I apologize.
    – larsks
    Commented Aug 8, 2015 at 16:08
0

You can use Python as the editor, so amending uses GIT_EDITOR which can be your own Python command to manipulate text, this can even be a call to Python containing a code-snippet, e.g.

import os
import subprocess
# Add "Some Appended Text!" after the commit message.
subprocess.check_call(
    ("git", "commit", "--amend"),
    env={
        **os.environ,
        "GIT_EDITOR": "".join([
            """'%s' -c "import sys\n""" % sys.executable,
            """file = sys.argv[-1]\n""",
            """with open(file, 'r', encoding='utf-8') as fh: data = fh.read()\n""",
            """data = '\\n'.join([l for l in data.split('\\n') if not l.startswith('#')])\n""",
            """data = data.rstrip() + '\\n\\nRef: !%d\\n'\n""" % args.pr,
            """with open(file, 'w', encoding='utf-8') as fh: fh.write(data)\n" - """,
        ]),
    }
)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.