Why Git pre-push does not allow me to run the input selection but fails upon select command in my interactive script?

95 views Asked by At

I made an interactive pre-push git hook that before pushing allows me to bump the version in an npm package.

#!/bin/bash

current_branch=$(git symbolic-ref HEAD | sed -e 's,.*/\(.*\),\1,')

echo "Pushing ${current_branch}"

current_version=$(npm run version -s)

echo "Current version: $current_version"

patch_version=$(npx semver $current_version -i patch)
minor_version=$(npx semver $current_version -i minor)
major_version=$(npx semver $current_version -i major)

# Choose the version bump type
PS3="Select the version bump type: "
select bump_type in "patch - Bump into ${patch_version}" "minor - Bump into ${minor_version}" "major - Bump into ${major_version}" "none - Keep Same"; do

  case $bump_type in
    "patch"*)
      # Increment version based on the chosen bump type
      new_version="patch"
      break
      ;;
    "minor"*)
        new_version="minor"
        break
        ;;
    "major"*)
        new_version="major"
        break
        ;;
    "none"*)
      echo "No version selected, skipping bump."
      exit 0
      ;;
    *)
      echo "Invalid selection, please choose a valid option."
      ;;
  esac
done

echo "Bumping version to $new_version"

# Update package.json with the new version
new_version=$(npm version ${new_version} --force --silent)

echo "Version bumped to $new_version"

echo "Keep package-lock.json up to spec"
npm install
git commit -m "AutoBump Version" package.json package-lock.json

But once I push into my branch:

Pushing dev
Current version: 1.0.3
.husky/pre-push: 17: Syntax error: "do" unexpected
husky - pre-push script failed (code 2)
error: απέτυχε η δημοσίευση κάποιων ref στο 'github.com:ellakcy/fa-checkbox.git'

Seem not to run, but if run manually works fine:

bash .husky/pre-push 
Pushing dev
Current version: 1.0.3
1) patch - Bump into 1.0.4
2) minor - Bump into 1.1.0
3) major - Bump into 2.0.0
4) none - Keep Same
Select the version bump type: 

As a way for fixing the issue, I tried this answer: https://stackoverflow.com/a/22585746/4706711

But seem not to fix the issue.

2

There are 2 answers

3
Philippe On BEST ANSWER

In order for husky to use bash for running hooks, change .husky/_/h which contains :

sh -e "$s" "$@"

change it to :

bash -e "$s" "$@"

In case it's not possible to make above change, you can put following line at the beginning of .husky/pre-push :

test -n "$BASH_VERSION" || exec /bin/bash $0 "$@"
1
jthill On

git help hooks says pre-push invocation is

Information about what is to be pushed is provided on the hook’s standard input with lines of the form:
<local ref> SP <local object name> SP <remote ref> SP <remote object name> LF

so your select statement is reading the first pushed ref from stdin.

Add a <&2 after the select's done terminator stmt to get it trying to read fd 2, that's stderr which I gather is still your terminal.