typicode / husky

Git hooks made easy 🐶 woof!
https://typicode.github.io/husky
MIT License
32.36k stars 1.02k forks source link

Support hooks on git events triggered by submodules #1450

Open jclaveau opened 3 months ago

jclaveau commented 3 months ago

Summary I see two use cases for submodules with Husky

Here I focus only on the first case

Context

Steps

mkdir husky_submodule_hooks_from_root; cd husky_submodule_hooks_from_root; git init; pnpm init
pnpm install husky; pnpm husky
git config --get core.hooksPath
=> .husky/_

git submodule add git@github.com:typicode/husky.git husky_submodule
cd husky_submodule
git rev-parse --git-path hooks
=> .../husky_submodule_hooks_from_root/.git/modules/husky_submodule/hooks
git config --get core.hooksPath
=> nothing

As a workaround I created the script .husky/link-submodules-hooks.sh

#!/bin/bash
# Create the symlinks .git/modules/<submodule_path>/hooks to .husky/<submodule_paths>
git submodule foreach --quiet '\
    cd $(git rev-parse --git-path hooks)/.. ;\
    mv hooks hooks.bak || true ;\
    mkdir -p ../../../../.husky/$path ;\
    ln -s ../../../../.husky/$path hooks ;\
' || true # No blocking if the .git folder is missing (like during deploy)

And run it from my package.json:

{
    "prepare": "husky; ./.husky/link-submodules-hooks.sh"
}

Glad to it, I have folders in my .husky directory where i can store my hooks like

.husky
-- submodules-path/
---- submodule1
------ pre-commit
------ pre-push
------ ...
---- submodule2
------ ...

This feature should belong, IMHO, to Husky. Meanwhile, this script may help other Husky users to achieve it!

This use case also answers your message, here https://github.com/typicode/husky/issues/1308#issuecomment-1762381639

Thanks a lot for sharing your work!

Zackin-He commented 1 month ago

I am using version v9, how do I write the./.husky/link-submodules-hooks.sh file

jclaveau commented 1 month ago

Just create it and copy the following content as written above

#!/bin/bash
# Create the symlinks .git/modules/<submodule_path>/hooks to .husky/<submodule_paths>
git submodule foreach --quiet '\
    cd $(git rev-parse --git-path hooks)/.. ;\
    mv hooks hooks.bak || true ;\
    mkdir -p ../../../../.husky/$path ;\
    ln -s ../../../../.husky/$path hooks ;\
' || true # No blocking if the .git folder is missing (like during deploy)

NB: Windows doesn't support symlinks for what I know, I personnaly use Linux

Then add the prepare line to your package Then run npm / yarn or pnpm install