shell 如何在commit-msg hook中交替运行两个if条件?

jecbmhm3  于 12个月前  发布在  Shell
关注(0)|答案(1)|浏览(103)

我有一个commit-msg脚本:

#!/bin/sh

# This hook enforces commit messages to follow the rules

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

commit_msg="$1"
error_msg="${RED}error: Commit message must start with a capitalized verb${NC}"
error_length_msg="${RED}error: Commit message must be more than 20 characters${NC}"

# Use regex to check if the message starts with a capitalized verb
if ! echo "$commit_msg" | grep -qE "^[A-Z][a-z]+"; then
  echo "$error_msg" >&2
  exit 1
fi

# Check the length of the commit message
if [ ${#commit_msg} -le 20 ]; then
  echo "$error_length_msg"
  exit 1
fi

当我用小写字母开始一条提交消息时,它会很好地执行第一个检查:

git commit -m "test capital letter"
error: Commit message must start with a capitalized verb
husky - pre-commit hook exited with code 1 (error)

然而,当提交消息以大写字母开头但少于20个字母时,它仍然显示(执行)第一条消息:

git commit -m "Test 20 letters"
error: Commit message must start with a capitalized verb
husky - pre-commit hook exited with code 1 (error)

我的预提交:

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

# Run the commit message check
.husky/commit-msg `$1`

# Check the exit status of the previous command
if [ $? -ne 0 ]; then
  exit 1
fi

# Run linting and lint-staged checks
npx lint-staged

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

# Check the exit status of the previous command
if [ $? -ne 0 ]; then
  echo "${RED}Linting failed. Aborting commit.${NC}"
  exit 1
fi

# Run Cypress tests without opening the launchpad
npm run cypress-run-component

根据菲利普的回答

#!/bin/sh

# This hook enforces commit messages to follow the rules

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

commit_msg=`cat $1` // changed this

error_msg="${RED}error: Commit message must start with a capitalized verb${NC}"
error_length_msg="${RED}error: Commit message must be more than 20 characters${NC}"

# Use regex to check if the message starts with a capitalized verb
if ! echo "$commit_msg" | grep -qE "^[A-Z][a-z]+"; then
  echo "$error_msg" >&2
  exit 1
fi

# Check the length of the commit message
if [ ${#commit_msg} -le 20 ]; then
  echo "$error_length_msg"
  exit 1
fi

输出

git commit -m "Test 20 letters"

kcugc4gi

kcugc4gi1#

$1不是提交消息,而是包含提交消息的文件名,因此您需要:

commit_msg=`cat $1`

相关问题