Avoid Husky from being triggered for changes on every unrelated directory in monorepo project
Asked Answered
Z

2

5

I'm using husky in my lerna monorepo project which has more than one directory (project)

.husky
front
├── package.json
app
└── package.json

on hook prepush I launch my test on front/ and app/ with yarn test.

I would like to have the test for a folder (project) only when the code inside change. Like github Actions.

on:
    paths:
      - 'front/**'

do there is a way in Husky ?

Zillah answered 24/6, 2021 at 13:36 Comment(3)
Not in Husky itself, that hooks into git at the repo level, but depending on what you're trying to do it might be possible with whatever's actually running the tests (e.g. Jest can take a list of the files to run the tests for: jestjs.io/docs/….Pseudocarp
I'm trying for all sort of command actually, for linter check on pre-commit as wellZillah
That's exactly what things like lint-staged are designed for, they pass a list of the staged files to the commands you supply (which you could use with the above Jest flag, for example). So Husky -> lint-staged -> whatever scripts runs the test/lint/whatever given a list of files.Pseudocarp
A
5

for some reason declare not work on my config

my working example:

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

#run husky pre-commit hook only if frontend changed
if git diff --name-only --cached | grep 'frontend/';
  then
    echo "FRONTEND FOLDER CHANGED --> starting husky..."
    cd frontend/ && quasar test --unit vitest
    yarn lint-staged
    yarn test:e2e:ci
    quasar build;
fi

Castro Crea thanks a lot!

Ardenardency answered 1/8, 2023 at 12:8 Comment(1)
This does exactly what I needed, thanks so much!Myrwyn
Z
3

I found a hack

  • I get all the file change in the all commits
  • I check for my folders
  • And trigger a command contextually
// ~/.husky/pre-push

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

declare IS_APP_FOLDER_CHANGE=$(git show --name-only -r --stat --oneline HEAD^^..HEAD | grep 'app/')

echo "IS_APP_FOLDER_CHANGE  --> + $IS_APP_FOLDER_CHANGE"

if [[ $IS_APP_FOLDER_CHANGE ]]; then cd app && yarn test --watchAll=false && cd ..; fi
Zillah answered 24/6, 2021 at 15:22 Comment(1)
This, in fact, doesn't grab files in all commits. It grabs files from the last two commits, hence the HEAD^^..HEADLeucopoiesis

© 2022 - 2024 — McMap. All rights reserved.