SVN的预提交钩子脚本需要协助检查TaskID

时间:2017-07-11 10:44:09

标签: shell svn pre-commit-hook

我有一个预提交钩子脚本来检查日志消息中的TaskID。我无法弄清楚它的逻辑。在突出显示的**if**语句中,我需要一个逻辑来检查第一行的第一个字母是否为TaskID :(多个数字) - (空格)(日志消息)

预提交钩子:

REPOS="$1"
TXN="$2"

# Check log message for proper task/bug identification

if [ -x ${REPOS}/hooks/check_log_message.sh ]; then
${REPOS}/hooks/check_log_message.sh "${REPOS}" "${TXN}" 1>&2 || exit 1
fi
exit 0

=======>>>>> check_log_message.sh

#!/bin/bash

REPOS="${1}"
TXN="${2}"

SVNLOOK=/usr/bin/svnlook

LOG_MSG_LINE1=`${SVNLOOK} log -t "${TXN}" "${REPOS}" | head -n1`

**if (echo "${LOG_MSG_LINE1}" | egrep '^[T][a][s][k][I][D][:]?[-][1-9]
[\s]*.*$' > /dev/null;) \
|| (echo "${LOG_MSG_LINE1}" | egrep '^[a-zA-Z]+[-][1-9][0-9]*[:]?[\s]*.*$' 
> /dev/null;)**
then
exit 0
else
echo ""
echo "Your log message does not contain a TaskID(or bad format used)"
echo "The TaskID must be the first item on the first line of the log 
message."
echo ""
echo "Proper TaskID format--> TaskID:xxx- 'Your commit message'  "
exit 1
fi

2 个答案:

答案 0 :(得分:1)

我猜您的问题涉及在Bash中使用条件。 您可以直接使用程序的退出代码。 例如,如果egrep匹配某些内容,则会以代码0退出,这意味着成功, 否则以非零退出 这意味着失败。 你可以在条件中使用它,例如:

if command; then
    echo success
else
    echo failure
fi

command可以是管道,例如:

if ${SVNLOOK} log -t "${TXN}" "${REPOS}" | head -n1 | egrep -q ^TaskID:
then
    exit 0
fi

这意味着如果日志的第一行以TaskID:开头,则以0.退出而不是if语句,您也可以使用&&这样的较短格式:

${SVNLOOK} log -t "${TXN}" "${REPOS}" | head -n1 | egrep -q ^TaskID: && exit 0

在两个示例中,我使用-qegrep来抑制输出(匹配的行),因为我猜您可能不需要它。

包含更完整模式的完整脚本:

#!/bin/bash

REPOS="${1}"
TXN="${2}"

SVNLOOK=/usr/bin/svnlook

${SVNLOOK} log -t "${TXN}" "${REPOS}" | head -n1 | egrep -q '^TaskID:[0-9][0-9]*- ' && exit 0

echo ""
echo "Your log message does not contain a TaskID(or bad format used)"
echo "The TaskID must be the first item on the first line of the log 
message."
echo ""
echo "Proper TaskID format--> TaskID:xxx- 'Your commit message'  "
exit 1

答案 1 :(得分:0)

或者,我在同事的帮助下修改了我的脚本。

REPOS="$1"
TXN="$2"

# Make sure that the log message contains some text.
SVNLOOK=/usr/bin/svnlook

LOGMSG=$($SVNLOOK log -t "$TXN" "$REPOS")

# check if any comment has supplied by the commiter
if [ -z "$LOGMSG" ]; then
echo "Your commit was blocked because it have no comments." 1>&2
exit 1
fi

#check minimum size of text
if [ ${#LOGMSG} -lt 15 ]; then
echo "Your Commit was blocked because the comments does not meet minimum length requirements (15 letters)." 1>&2
exit 1
fi

# get TaskID by regex
TaskID=$(expr "$LOGMSG" : '\([#][0-9]\{1,9\}[:][" "]\)[A-Za-z0-9]*')

# Check if task id was found. 
if [ -z "$TaskID" ]; then

echo ""  1>&2
echo "No Task id found in log message \"$LOGMSG\"" 1>&2
echo ""  1>&2
echo "The TaskID must be the first item on the first line of the log message."  1>&2
echo ""  1>&2
echo "Proper TaskID format--> #123- 'Your commit message'  " 1>&2
exit 1
fi