How to access commit message with Husky pre-commit hook?
Asked Answered
P

2

9

My husky script:

  "husky": {
    "hooks": {
      "pre-commit": "sh ./tools/githooks/pre-commit.sh"
    }
  }

Let's say I am doing a git commit -m "I want that text". How can I access to my commit message within the shell script? I tried to echo $HUSKY_GIT_PARAMS and $HUSKY_GIT_STDIN within the shell script but no success

Poitiers answered 10/9, 2019 at 4:25 Comment(0)
B
10

A pre-commit hook would not access the commit message, because the hook is triggered before the commit creation.

A commit-msg hook is the right hook for checking a commit message content.

And it is available with husky in 2019

"commit-msg": "echo $HUSKY_GIT_PARAMS"

Update 2020, as commented by galethil

HUSKY_GIT_PARAMS is removed in version 5.
Instead Git parameters should be used directly in scripts (e.g. $1)


Note, since 2019, commit c4e1ed1 (Dec. 2020, Husky v5.0.5) mentions:

Previous HUSKY_GIT_PARAMS environment variable is replaced by native params $1, $2, etc.

Bignonia answered 10/9, 2019 at 4:38 Comment(5)
HUSKY_GIT_PARAMS is removed in version 5. Instead Git parameters should be used directly in scripts (e.g. $1) .Sharkskin
@Sharkskin Thank you for this update. I have included your comment in the answer for more visibility.Bignonia
I think this doesn't work in 7.x. I echo $HUSKY_GIT_PARAMS from inside my script and its empty.Expend
@Expend I agree. I have edited the answer to include the evolution.Bignonia
well I'm not getting git params either :/ github.com/typicode/husky/issues/1141Expend
F
0

A solution that has worked for me (ubuntu:22.04)

In the .husky folder add a bash script, for example "commit-msg", to print the message like in this example:

#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

commit_message="$(cat "$1")"

echo $commit_message
Freehearted answered 11/2, 2023 at 2:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.