2017-04-20 120 views
0

我想为git写一个prepare-commit-msg钩子。该脚本应该做以下步骤:不能提取正则表达式的子字符串

  1. 获取当前的git分支名(工作)
  2. 提取issue-id(不工作)
  3. 检查是否issue-id已经在提交味精
  4. 如果没有插入[issue-id]提交信息前

issue-id了这种模式[a-zA-Z]+-\d+和分支的名称应该是舒美特像feature/issue-id-my-small-description一样兴奋。

但现在,提取的部分是不正常...

这是我准备提交 - 味精脚本:

# 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 
+0

请发布**输入**和期望**输出的样本** –

+0

@PedroLobito发布更新。我认为我使用我的正则表达式w/sed的方式是错误的 – ylerjen

+0

Inian现在删除的答案显示了主要问题。你应该关闭它并打开一个新问题,或编辑问题以显示新脚本*和*当你运行它时会发生什么。 – torek

回答

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 "[email protected]" | 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] [email protected]" 
fi 

echo "$MESSAGE" 

其中[email protected]是所有你之后“修理”(如提供的话。 "[email protected]" = "bug" "on" "login")。其余的我希望你在把它与你的原始代码进行比较后能够理解。

+0

经过一些尝试,我修复了sed的正则表达式,这个工作。谢谢 – ylerjen