Search code examples
bashgitnpmgithooksgit-husky

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


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.


Solution

  • 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 "$@"