typicode / husky

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

How to prompt a user in Husky script? #1401

Open alamenai opened 2 months ago

alamenai commented 2 months ago

I have a pre-push script where I want to prompt the developers if they run their tests locally before they push their code:


#!/bin/sh

# This hook prevents pushing if the build fails.

# ANSI color codes for formatting
RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m' # No Color

# Ask the developer if they have run the tests locally
# There is an issue here
echo "Have you run the tests locally? (y/n):"

read REPLY

if [ "$REPLY" = "n" ] || [ "$REPLY" = "N" ]; then
  printf "%s\n" "${RED}error: Please run the tests locally before pushing.${NC}" >&2
  exit 1
fi

# Run your build command (replace with your actual build command)
build_command="docker build -f Dockerfile.prod -t esg-suite-prod:latest ."

if ! $build_command; then
  printf "%s\n" "${RED}error: Build failed. Fix the build issues before pushing.${NC}" >&2
  exit 1
else
  printf "%s\n" "${GREEN}Build succeeded. Processing and Pushing...${NC}" >&2
  exit 0
fi

The problem is passing directly to the build command without waiting to get the response (Y/N):

image

fredericrous commented 2 months ago

you can get tty interaction working with something like exec < /dev/tty && ./myscript.sh ... but your hook still won't prompt the user if he uses a software like github desktop... my solution is to run the tests on pre-push on just the projects that changed in my monorepo

alamenai commented 2 months ago

Yes, we have a pre-commit script for running tests for each changes made but some developers disable it and sometimes miss to run the tests and then push the code.

Do you recommend to add the test command in the pre-push script?