Matt Kantor
Matt Kantor

Reputation: 1769

Use Git's commit message cleanup mode from commit-msg hook

git help commit says the following:

--cleanup=<mode>
   This option determines how the supplied commit message should be
   cleaned up before committing. The <mode> can be strip, whitespace,
   verbatim, or default.

   strip
       Strip leading and trailing empty lines, trailing whitespace,
       and #commentary and collapse consecutive empty lines.

   whitespace
       Same as strip except #commentary is not removed.

   verbatim
       Do not change the message at all.

   default
       Same as strip if the message is to be edited. Otherwise
       whitespace.

I'd like to determine which cleanup mode is going to be applied from the commit-msg hook (correctly using the commit.cleanup config value when necessary). I run some validations on my commit messages and I want to make sure I'm seeing exactly what Git is planning on using.

Alternatively, I'll accept a way to grab the commit message text post-cleanup (maybe I can trick Git into cleaning it up for me?). This would be great for my use case, since then I wouldn't have to worry about re-implementing any cleanup modes.

Upvotes: 14

Views: 1929

Answers (2)

jsharp
jsharp

Reputation: 603

Here's what I'm doing in a commit-msg hook. (I need to check line length, but ignore long lines that will be stripped as comments.)

  • check git config commit.cleanup.
  • if blank or default, check git var GIT_EDITOR: if it is equal to :, then cleanup mode is whitespace, otherwise it is strip.
  • Pray that my team continues its blissful ignorance of the --cleanup option of git commit.

The reason for this, per git help hooks (see the pre-commit entry), is that all the commit-adjacent hooks receive GIT_EDITOR=: when invoked in a context where the commit will not be edited. For merge, and for commit in the absence of --cleanup, this is enough to determine the cleanup mode.

Upvotes: 1

torek
torek

Reputation: 489628

Unfortunately, in current(ish) git source, the cleanup mode is not passed through to the hook in any way. The argument to --cleanup is stored only in the (static, local to builtin/commit.c) variable cleanup_mode and not exported (e.g., as an argument or environment variable) to the various hooks.

(It should be easy to add an environment variable containing the setting. If you want to experiment with this yourself, see builtin/commit.c function parse_and_validate_options; put in a call to setenv() with appropriate arguments.)

Upvotes: 11

Related Questions