본문 바로가기
Gerrit/Gerrit <-> Slack 연동

6. 게릿 리뷰 웹훅 (3/3)

by 실짱 2023. 10. 18.

이제 포스트 메시지를 이쁘게 채워야 할 차례다.

기본 포맷은 아래처럼 했다.

리뷰 owner
리뷰 주소
커밋 메시지

 

그러면 이렇게 나온다.

뭐...

나름... 뭐... 

하지만 다시봐도, 정말 개발자 스럽다.

이것 자체도 안이쁘지만, 문제는 여러개 겹치면 아래처럼 된다.

 

안이쁨을 넘어서 알아보기조차 어려워졌다. 이래서는 안될것 같았다.

(흔히 말하는 가독성이 너무 떨어진다)

 

방법이 있을꺼야.

슬랙을 뒤져보았다.

 

그래.. 없을리가 없다.

 

↗ An overview of message composition

여기에서 슬랙 메시지에 대한 전반적인것을 알 수 있다.

그리고 그 밑에 바로 내가 원하는 예쁜 메시지 포맷을 위한 가이드가 친절하게 있다.

↗ Rich message layout

여기에 더 고급 기능도 있었다

↗ block-kit

나같은 사용자를 위해 친절히 다양한 형태의 template 도 준다.

↗ block kit template

 

예제>

 

여기있는 template 들을 잘 짜집으면 될것 같다.

여러 시행착오를 겪었지만, 다 설명할수는 없고, 최종 결과물만 공유한다.

 

<최종 comment-added.sh>

더보기
#!/bin/bash

change=$2
change_url=$4
change_owner=$6
change_owner_username=$8
project=${10}
branch=${12}
topic=${14}
author=${16}
author_username=${18}
commit=${20}
comment=${22}
isPrivate=${24}
workInProgress=${26}

debug=false

if [ "$debug" = true ];then
 echo " " >> /opt/gerrit/gerrit/logs/hook-comment-added.log
 echo " " >> /opt/gerrit/gerrit/logs/hook-comment-added.log
 echo "post to slack [[" >> /opt/gerrit/gerrit/logs/hook-comment-added.log
fi

if [ "$debug" = true ];then
 echo "change : $change" >> /opt/gerrit/gerrit/logs/hook-comment-added.log
 echo "change_url : $change_url" >> /opt/gerrit/gerrit/logs/hook-comment-added.log
 echo "change_owner : $change_owner" >> /opt/gerrit/gerrit/logs/hook-comment-added.log
 echo "change_owner_username : $change_owner_username" >> /opt/gerrit/gerrit/logs/hook-comment-added.log
 echo "project : $project" >> /opt/gerrit/gerrit/logs/hook-comment-added.log
 echo "branch : $branch" >> /opt/gerrit/gerrit/logs/hook-comment-added.log
 echo "topic : $topic" >> /opt/gerrit/gerrit/logs/hook-comment-added.log
 echo "author : $author" >> /opt/gerrit/gerrit/logs/hook-comment-added.log
 echo "author_username : $author_username" >> /opt/gerrit/gerrit/logs/hook-comment-added.log
 echo "commit : $commit" >> /opt/gerrit/gerrit/logs/hook-comment-added.log
 echo "comment : $comment" >> /opt/gerrit/gerrit/logs/hook-comment-added.log
 echo "isPrivate : $isPrivate" >> /opt/gerrit/gerrit/logs/hook-comment-added.log
 echo "workInProgress : $workInProgress" >> /opt/gerrit/gerrit/logs/hook-comment-added.log
fi

if [[ $branch == *"develop"* ]]; then
 if [ "$debug" = true ];then
  echo "review branch, we will prepare to post this review to slack" >> /opt/gerrit/gerrit/logs/hook-comment-added.log
 fi

else
 if [ "$debug" = true ];then
  echo "not review branch - $branch, so we skip to post this review" >> /opt/gerrit/gerrit/logs/hook-comment-added.log
 fi
 exit 0
fi

if [ "$isPrivate" = false ] && [ "$workInProgress" = false ];then
 if [ "$debug" = true ];then
  echo "not private && not WIP => go to next" >> /opt/gerrit/gerrit/logs/hook-comment-added.log
 fi

 if echo "$author_username" | grep -q "AriJenkins"; then
  if [ "$debug" = true ];then
   echo "AriJenkins commented => go to next" >> /opt/gerrit/gerrit/logs/hook-comment-added.log
  fi

  if echo "$comment" | grep -q "Verified+1"; then
   if [ "$debug" = true ];then
    echo "Verified+1 => make slack comment and post to slack" >> /opt/gerrit/gerrit/logs/hook-comment-added.log
   fi
   # Set Git repository location
   repo_dir="/opt/gerrit/gerrit/git"$project".git"

   # Get commit message
   cd $repo_dir
   commit_message=$(git show -s --format=%B $commit)
   if [ "$debug" = true ];then
    echo "commit_message : $commit_message" >> /opt/gerrit/gerrit/logs/hook-comment-added.log
   fi

   cd -

   # Owner string 작업 [[
   # 따옴표 제거
   change_owner_no_quotes=$(echo $change_owner | tr -d '"')
   # '<' 앞의 단어를 찾고 공백 제거
   change_owner_name=$(awk -F'<' '{gsub(/^[[:space:]]+|[[:space:]]+$/, "", $1); print $1}' <<< "$change_owner_no_quotes")
   if [ "$debug" = true ];then
    echo "change_owner_no_quotes : $change_owner_no_quotes" >> /opt/gerrit/gerrit/logs/hook-comment-added.log
    echo "change_owner_name : $change_owner_name" >> /opt/gerrit/gerrit/logs/hook-comment-added.log
   fi
   # Owner string 작업 ]]


   # make JIRA LINK [[
   # 만들어야 하는 최종 문자열 형식 : https://aribio.atalssing.net/browse/ABBOST-120|ABBOST-120
   # 정규식 패턴으로 [ABBOST-100]과 일치하는 문자열 찾기
   pattern='\[([A-Z]+-[0-9]+)\]'
   # commit_message에서 패턴과 일치하는 첫 번째 문자열만 취함
   if [[ $commit_message =~ $pattern ]]; then
    match="${BASH_REMATCH[1]}"
    if [ "$debug" = true ];then
     echo "match : $match" >> /opt/gerrit/gerrit/logs/hook-comment-added.log
    fi
   fi

   # jira url address
   jira_link="https://aribio.atlassian.net/browse/"$match
   if [ "$debug" = true ];then
    echo "jira_link : $jira_link" >> /opt/gerrit/gerrit/logs/hook-comment-added.log
   fi

   # 이미 commit message 에 jira link 가 있으면 패스
   if [[ $commit_message == *$jira_link* ]]; then
    if [ "$debug" = true ];then
     echo "commit message has already jira link, so we skip add jira link" >> /opt/gerrit/gerrit/logs/hook-comment-added.log
    fi
    jira_link=""
   else
    # 원하는 최종 형태로 jira_link 완성
    jira_link=$jira_link"|"$match
    if [ "$debug" = true ];then
     echo "added jira link to message" >> /opt/gerrit/gerrit/logs/hook-comment-added.log
    fi
   fi
   # make JIRA LINK ]]


   # make json data [[

    # 기본 포맷 (이후 필요한 부분 치환)
   json_data='{
    "blocks":[
      {
        "type":"divider"
      },
      {
        "type":"context",
        "elements":[
          {
            "type":"mrkdwn",
            "text":"Created by:"
          },
          {
            "type":"image",
            "image_url":"https://raw.githubusercontent.com/avatar.png",
            "alt_text":"AltTextForImage"
          },
          {
            "type":"mrkdwn",
            "text":"*ReviewRequestOwnerName*"
          },
          {
            "type":"mrkdwn",
            "text":"    |    JIRA:   <https://aribio.atlassian.net/browse>"
          }
        ]
      },
      {
        "type":"section",
        "text":{
          "type":"mrkdwn",
          "text":"ReviewCommitMessage"
        }
      },
      {
        "type":"actions",
        "block_id":"viewrequest",
        "elements":[
          {
            "type":"button",
            "text":{
              "type":"plain_text",
              "text":"View request"
            },
            "style":"primary",
            "url":"http://review.aribio.net/c"
          }
        ]
      },
      {
        "type":"divider"
      }
    ]
   }'

   # commit message 는 코드 블락으로 만들기 위해 backtick 3개로 앞뒤를 감싸야 한다.
   backtick="\`\`\`"
   commit_message=$backtick$commit_message$backtick

   # 이미지의 이름은 소문자여야만 된다. 대문자일 경우 슬랙에서 인식안됨
   lowercase_name=$(echo "$change_owner_name" | tr '[:upper:]' '[:lower:]')
   # 이미지는 github 의 teamwork 저장소의 main 브랜치에 저장해두고 이 url 을 이용한다.
   img_url="https://raw.githubusercontent.com/AriJang/teamwork/main/avatar_"$lowercase_name".png"

   # 필요한 부분 치환
   # 1. image url 치환
   json_data="${json_data/https:\/\/raw.githubusercontent.com\/avatar.png/$img_url}"
   json_data="${json_data/AltTextForImage/$change_owner_no_quotes}"
   # 2. Owner name 치환
   json_data="${json_data/ReviewRequestOwnerName/$change_owner_name}"
   # 3. Jira link 치환
   json_data="${json_data/https:\/\/aribio.atlassian.net\/browse/$jira_link}"
   # 4. commit message 치환
   json_data="${json_data/ReviewCommitMessage/$commit_message}"
   # 5. review url 치환
   json_data="${json_data/http:\/\/review.aribio.net\/c/$change_url}"

   if [ "$debug" = true ];then
       echo "json_data : $json_data" >> /opt/gerrit/gerrit/logs/hook-comment-added.log
   fi

   # make json data ]]

   # 정식 "리뷰 요청 채널" 로 포스트
   curl -X POST -H 'Content-type: application/json' --data "$json_data" https://hooks.slack.com/services/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

   # 테스트를 위한 private 채널로 포스트 (디버깅, 구현시에는 이 채널을 활성화하고 평상시에는 위 채널 활성화)
#   curl -X POST -H 'Content-type: application/json' --data "$json_data" https://hooks.slack.com/services/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
  fi
 fi
else
 echo ""
fi

if [ "$debug" = true ];then
 echo "post to slack ]]" >> /opt/gerrit/gerrit/logs/hook-comment-added.log
fi

 

[Before]

[After]

 

푸하하하하!!

너무너무 깔끔해졌다.

이제 여러개가 동시에 많이 포스트되어도 문제 없다.

 

무언가 더 하고프다면 주저말고 api.slack.com 으로 가서 Messaging 과 Block Kit 항목을 뒤져보자.

원하는건 여기에 다 있다.

 

 

 


< Prev     5. 게릿 리뷰 웹훅 (2/3)                |               Next >     7. Hook 할때 커밋 메시지 가져오기

'Gerrit > Gerrit <-> Slack 연동' 카테고리의 다른 글

2. 생각의 흐름  (1) 2023.10.18
3. 슬랙 채널에 포스팅 하기  (0) 2023.10.18
4. 게릿 리뷰 웹훅 (1/3)  (0) 2023.10.18
5. 게릿 리뷰 웹훅 (2/3)  (0) 2023.10.18
7. Hook 할때 커밋 메시지 가져오기  (1) 2023.10.18