Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ask for user input in a Git hook?

Tags:

git

bash

githooks

I have been trying to write a simple bash script as a pre-push hook, in which I check for missing test files when pushing Java code.

The problem is: the read command isn't waiting for user input, it proceed as if no input has been entered.

has_java="git diff --stat --cached origin/master | grep \"src\/main.*\.java\""
has_test="git diff --stat --cached origin/master | grep \"src\/test.*\.java\""

exit_val=0

if eval $has_java; then
    if eval $has_test; then
        :
    else
        echo "*** NO TESTS WERE FOUND WHILE PUSHING JAVA CODE ***"
        read -n1 -p "Do you want to CONTINUE pushing? [Y/n]" doit
        case $doit in  
            n|N) exit_val=1 ;; 
            y|Y) exit_val=0 ;;
            *) exit_val=0 ;;
        esac
    fi
fi
like image 457
Alvaro Cavalcanti Avatar asked Aug 03 '17 21:08

Alvaro Cavalcanti


People also ask

How do I manually run a git hook?

If you want to manually run all pre-commit hooks on a repository, run pre-commit run --all-files . To run individual hooks use pre-commit run <hook_id> . The first time pre-commit runs on a file it will automatically download, install, and run the hook. Note that running a hook for the first time may be slow.

How do you trigger a pre-commit hook?

Once the terminal windows is open, change directory to . git/hooks . Then use the command chmod +x pre-commit to make the pre-commit file executable.


1 Answers

Git hooks do not use standard input. Thus, one must attach the input from the terminal: dev/tty.

Simply appending the terminal at the end of the command makes it work:

read -n1 -p "Do you want to CONTINUE pushing? [Y/n]" doit < /dev/tty

like image 57
Alvaro Cavalcanti Avatar answered Sep 22 '22 13:09

Alvaro Cavalcanti