无法使用正则表达式提取子字符串

时间:2017-04-20 13:29:31

标签: regex git bash sed githooks

我试图为git编写一个prepare-commit-msg钩子。该脚本应执行以下步骤:

  1. 获取当前的git分支名称(工作)
  2. 提取issue-id(不工作)
  3. 检查issue-id是否已在提交消息中
  4. 如果没有,请在提交消息
  5. 之前插入[issue-id]

    issue-id具有此模式[a-zA-Z]+-\d+,分支名称应为feature/issue-id-my-small-description

    但是现在,提取部分还不行......

    这是我的prepare-commit-msg脚本:

    # Regex used to extract the issue id
    REGEX_ISSUE_ID="s/([a-zA-Z]+-\d+)//"
    
    # Find current branch name
    BRANCH_NAME=$(git symbolic-ref --short HEAD)
    
    # Extract issue id from branch name
    ISSUE_ID= $BRANCH_NAME | sed -r $REGEX_ISSUE_ID
    
    # Check if the issue id is already in the msg
    ISSUE_IN_COMMIT=$(grep -c "\[$ISSUE_ID\]" $1)
    
    # Check if branch name is not null and if the issue id is already in the commit msg
    if [ -n "$BRANCH_NAME" ] && ! [[ $ISSUE_IN_COMMIT -ge 1 ]]; then 
      # Prefix with the issue id surrounded with brackets
      sed -i.bak -e "1s/^/[$ISSUE_ID] /" $1
    fi
    

    编辑以添加输入/输出示例

    输入$1是git commit消息,类似于

    fix bug on login
    

    fix MyIssue-234 which is a bug on login
    

    输出应该是带有问题ID的输入,即:

    [MyIssue-123] fix bug on login
    

1 个答案:

答案 0 :(得分:0)

我不确定你做了什么以及为什么这样做,但这是我通过修复我认为在你的代码中纠正的最接近的方式:

# Regex used to extract the issue id
REGEX_ISSUE_ID="s/\[([a-zA-Z]+-[0-9]+)\].*/\1/"

# Find current branch name
BRANCH_NAME=$(git symbolic-ref --short HEAD)
if [[ -z "$BRANCH_NAME" ]]; then
    echo "No brach name... "; exit 1
fi

# Extract issue id from branch name
ISSUE_ID=$(echo "$BRANCH_NAME" | sed -r "$REGEX_ISSUE_ID")

# Check if the issue id is already in the msg
ISSUE_IN_COMMIT=$(echo "$@" | grep -c "^\[*$ISSUE_ID\]*")

# Check if branch name is not null and if the issue id is already in the commit msg
if [[ -n "$BRANCH_NAME" ]]; then
    if [[ $ISSUE_IN_COMMIT -gt 0 ]]; then 
        shift # Drop the issue if from the msg
    fi
    # Prefix with the issue id surrounded with brackets
    MESSAGE="[$ISSUE_ID] $@"
fi

echo "$MESSAGE"

其中$@是您在"修复"之后提供的所有字词。 (例如"$@" = "bug" "on" "login")。其余的我希望您在将其与原始代码进行比较后了解。