如何使外壳不可知的哈士奇钩子?

问题描述

这是预提交钩子

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

lerna run --concurrency 1 --stream precommit --since HEAD --exclude-dependents

失败原因

.husky/pre-commit: 4: lerna: not found
husky - pre-commit hook exited with code 127 (error)

但如果我将其更改为 ZSH(总是调用 husky.sh 脚本),它会起作用

#!/bin/zsh

编辑:添加 husky.sh 脚本

#!/bin/sh
if [ -z "$husky_skip_init" ]; then
  debug () {
    [ "$HUSKY_DEBUG" = "1" ] && echo "husky (debug) - $1"
  }

  readonly hook_name="$(basename "$0")"
  debug "starting $hook_name..."

  if [ "$HUSKY" = "0" ]; then
    debug "HUSKY env variable is set to 0,skipping hook"
    exit 0
  fi

  if [ -f ~/.huskyrc ]; then
    debug "sourcing ~/.huskyrc"
    . ~/.huskyrc
  fi

  export readonly husky_skip_init=1
  sh -e "$0" "$@"
  exitCode="$?"

  if [ $exitCode != 0 ]; then
    echo "husky - $hook_name hook exited with code $exitCode (error)"
    exit $exitCode
  fi

  exit 0
fi

如何使它与 shell 无关?我正在使用 lerna monorepo

解决方法

有问题的代码使用了 product_uom 命令。这不是 POSIX sh 规范的一部分。

因此,在基线 POSIX shell 上,readonly 根本不能保证设置 readonly hook_name="$(basename "$0")"。取出hook_name。 (另外,我建议不要依赖于 readonly 的行为;如 BashFAQ #28 中所述,它不可靠)。

$0 也不是 POSIX-y;也去掉那里的 export readonly

考虑完全放弃 readonly,直接在 husky.sh 采购。

,

这应该有效:

npx lerna run --concurrency 1 --stream precommit --since HEAD --exclude-dependents