2020년 10월 16일 금요일

SVN commit hook connect JIRA - Add Comment(Only My Brain-fficial)

 

have following software installed

1. jira 다운 및 설치

링크 - https://www.atlassian.com/ko/software/jira/download

 - start jira server[8080] 으로 서벼 켜놓고 localhost:8080 으로 접속

 - 설치 후 jira 계정 생성 및 프로젝트 생성에서 대충 이슈 만들어서 세팅


2. VisualSVN server 다운 및 설치.

Visual SVN Server Download

https://www.visualsvn.com/server/download/


2 - 1. repository 생성

- 생성 하면 백업 폴더에 hooks 폴더 생성 되어있음.

참고 - https://www.visualsvn.com/server/getting-started/

create ex) 빨간 박스는 밑에 과정에서 생긴 파일들.



3. php 다운 및 설치 (perl 방식도 있으나 안해봄) - OS종류 잘 보고 따라할것.

 - https://www.lesstif.com/software-architect/svn-hook-commit-jira-17105782.html

 - 위 링크와 같도록 셋팅. (cmd 창 이미지는 기존 svn으로 사용하듯이 commit 해도 됨)

 - 정규식 관련 자료 - https://regexr.com/
    (나도 잘 모르므로 검색하시길..)


4. JIRA REST API v2 Document

 - https://developer.atlassian.com/cloud/jira/platform/rest/v2/api-group-issue-comments/#api-rest-api-2-issue-issueidorkey-comment-post

 - 위 링크에서 필요한 정보들 찾아서 추가 및 수정. (본인은 add comment 만 추가한 상태)


-------------- only my example codes ---------------


pre-commit.cmd

- .bat file

Copy
1 2 3 4 5 6 7 8 9 10 11 12 13 14 echo start 1>&2 echo message 1>&2 echo : %MESSAGE% 1>&2 for /f "tokens=* USEBACKQ" %%i in (`svnlook log %1 -t %2`) do ( set "RESULT=%%i" ) echo "%RESULT%" 1>&2 :: ex ) "C:/Program Files/PHP/v7.2/php.exe" -n C:/Repositories/HookTest/hooks/pre-commit.php %1 %2 "%RESULT%" php "%1\hooks\pre-commit.php" "%1" "%2" "%RESULT%"

 - comment 부분 utf-8로 넘기는 작업



pre-commit.php

 - commit hook php file

Copy
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 #!/usr/bin/env php <?php require_once 'jira_comment.php'; ////// ini 에서 가져온 값들 ////////// $configVars = parse_ini_file('myconfig.ini', TRUE); $username = $configVars['Account']['username']; $password = $configVars['Account']['password']; $jiraURL = $configVars['Address']['url']; $jiraURL_Issue = $configVars['Address']['url_issue']; //////////////////////////////////// # comment 가 4자 미만이면 커밋 거부 $minchars = 4; $svnlook = 'svnlook'; #-------------------------------------------- $repos = $argv[1]; $txn = $argv[2]; $comment = $argv[3]; #$comment = `$svnlook log -t "$txn" "$repos"`; $comment_temp = $comment; $comment = chop($comment); //공백제거. if ( strlen($comment) == 0 ) { fwrite(STDERR, "---------------------------------------------------------------------------\n"); fwrite(STDERR, "Your commit has been blocked because it didn't include a log message.!\n"); fwrite(STDERR, "Do the commit again, this time with a log message that describes your changes.!\n"); fwrite(STDERR, "---------------------------------------------------------------------------\n"); exit(1); } else if ( strlen($comment) < $minchars ) { fwrite(STDERR, "---------------------------------------------------------------------------\n"); fwrite(STDERR, "Comment must be at least $minchars characters. : $comment\n"); fwrite(STDERR, "---------------------------------------------------------------------------\n"); exit(1); } ## 커밋 메시지에 Jira issue keys 가 들어 있는지 확인 #$pattern = '/(?P<prj>[0-9a-zA-Z]{1,10})-{1,10}(?P<inum>[0-9]+):(?P<comm>[\x{1100}-\x{11FF}\x{3130}-\x{318F}\x{AC00}-\x{D7AF}]{0,1000})+/u'; $pattern = '/(?P<prj>[0-9a-zA-Z]{1,10})-{1,10}(?P<inum>[0-9]+)/'; #$pattern = '/[^0-9a-zA-Z]?(?P<prj>[0-9A-Za-z]{1,10})-{1,10}(?P<inum>[0-9]+)./'; #$pattern = '/\w?(?P<prj>\w{1,10})-\d(?P<inum>\d{1,10})./'; $matches = 0; if (!preg_match($pattern, $comment, $matches)) { fwrite(STDERR, "---------------------------------------------------------------------------\n"); fwrite(STDERR, "Comment must match JIRA-ISSUE-KEY!!! \"$comment\"\n"); fwrite(STDERR, print_r($matches,TRUE)); fwrite(STDERR, "---------------------------------------------------------------------------\n"); exit(1); } $issue_key = $matches["prj"] . "-" . $matches["inum"]; #$comment_key = $matches["comm"]; $strLength = mb_strlen($issue_key) + 1; $comment_key = mb_substr($comment_temp,$strLength); ## jira issue key 가 존재하는지 JIRA REST API 로 확인. // ini 로 변경. #$ch = curl_init("http://localhost:8080/rest/api/2/issue/"); #$url = "http://localhost:8080/rest/api/2/search/"; /////////////// curl 날리는 방식 ///////////////////// /* ( $ch = curl_init(); $data = array("jql" => "issuekey=$issue_key","maxResults" => 5); $json_string = json_encode($data); curl_setopt($ch, CURLOPT_URL, $jiraURL); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_VERBOSE, TRUE); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1); curl_setopt($ch, CURLOPT_USERPWD, "$username:$password"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array( "Content-type: application/json", 'Content-Length: ' . strlen($json_string) )); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $json_string); $result = curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); $response = json_decode($result); if ($response == NULL or property_exists ($response,"errorMessages")) { fwrite(STDERR, "Error! " . ($response == NULL ? "Request failed" : $response->errorMessages[0]) . "\n"); exit(1); } else { var_dump($response); } ) */ ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////// jira issue 관련 //////////////////////////////////////////////////////// $url_issue = $jiraURL_Issue.$issue_key; $url_comment = $url_issue.'/comment'; JiraComment::BaseAuth($username, $password); JiraComment::GetIssueFromIssuekey($url_comment, $issue_key); JiraComment::AddIssueComment($url_comment, $comment_key); ######################## 로 그 찍 어 보 는 공 간 ( 에러 났을때 )######################## fwrite(STDERR , "------------------------------------------------------------------------\n"); fwrite(STDERR , "Comment - \"$comment\"\n"); fwrite(STDERR , "------------------------------------------------------------------------\n"); fwrite(STDERR , "Issue Key - \"$issue_key\"\n"); fwrite(STDERR , "------------------------------------------------------------------------\n"); fwrite(STDERR , "Comment key - \"$comment_key\"\n"); fwrite(STDERR , "------------------------------------------------------------------------\n"); fwrite(STDERR, print_r($matches,TRUE)); fwrite(STDERR , "------------------------------------------------------------------------\n"); fwrite(STDERR , print_r($data,TRUE)); fwrite(STDERR , "------------------------------------------------------------------------\n"); fwrite(STDERR , "json string - \" $json_string\"\n"); fwrite(STDERR , "------------------------------------------------------------------------\n"); fwrite(STDERR , "code - \" $code\"\n"); fwrite(STDERR , "------------------------------------------------------------------------\n"); fwrite(STDERR , "result - \" $result\"\n"); fwrite(STDERR , "------------------------------------------------------------------------\n"); ##################################################################################### exit(0); ?>



jira_comment.php

 - pre-commit jira support php file (feat.unirest)

Copy
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 <?php require_once 'C:\Users\ldy\Documents\unirest-php-master\src\Unirest.php'; class JiraComment { ////////jira 기본 인증. public static function BaseAuth($username, $password) { Unirest\Request::auth($username, $password); } ////////이슈 정보 get. public static function GetIssueInfo($issueURL, $issueKey) { $headers = array( 'Accept' => 'application/json', ); $response = Unirest\Request::get( $issueURL.$issueKey, $headers ); if ($response == NULL or property_exists ($response,"errorMessages")) { fwrite(STDERR, "===============================================\n"); fwrite(STDERR, "Error! GetIssueInfo - " . ($response == NULL ? "Request failed" : $response->errorMessages[0]) . "\n"); fwrite(STDERR, "===============================================\n"); exit(1); } else { var_dump($response); } } ////////이슈에 댓글 정보 get. public static function GetIssueCommentsInfo($issueCommnetURL) { $headers = array( 'Accept' => 'application/json', ); return Unirest\Request::get( $issueCommnetURL, $headers ); } ////////이슈키에 맞는 댓글 정보 get. public static function GetIssueFromIssuekey($issueCommnetURL, $issuekey) { $headers = array( 'Accept' => 'application/json', ); $response_getcomment = Unirest\Request::get( $issueCommnetURL, $headers ); //입력한 이슈 키에 대한 이슈를 못가져 왔다면 error. if($response_getcomment->code != 200) { fwrite(STDERR, "===============================================\n"); fwrite(STDERR, "== Comment must match JIRA-ISSUE-KEY!!!!!!!!!!!!!! \"$issuekey\"\n"); fwrite(STDERR, "===============================================\n"); exit(1); } else { var_dump($response_getcomment); } } ////////이슈키에 맞는 이슈에 댓글 add. public static function AddIssueComment($issueCommnetURL, $comment) { $headers = array( 'Accept' => 'application/json', 'Content-Type' => 'application/json; charset=utf-8', ); /*$body = <<<REQUESTBODY { /////// 관리자전용 댓글 달수있게하는 옵션 ////////// "visibility": { "type": "role", "value": "Administrators" }, ////////////////////////////////////////////////// "body": "{$comment_key}" } REQUESTBODY; */ $body = <<<REQUESTBODY { "body": "{$comment}" } REQUESTBODY; $response = Unirest\Request::post( $issueCommnetURL, $headers, $body ); if ($response == NULL or property_exists ($response,"errorMessages")) { fwrite(STDERR, "===============================================\n"); fwrite(STDERR, "Error! AddIssueComment - " . ($response == NULL ? "Request failed" : $response->errorMessages[0]) . "\n"); fwrite(STDERR, "===============================================\n"); exit(1); } else { var_dump($response); } } } ?>


위 코드 사용시 Unirest관련 not found error 발생.

https://github.com/Kong/unirest-php

- 위 링크에서 받아서 압축 해제 후 php 코드 맨 위에 삽입.

require_once '/path/to/unirest-php/src/Unirest.php';

( jira_comment.php 상단에 있음 )


myconfig.ini

- ini file

Copy
1 2 3 4 5 6 7 8 9 ; My Account Setting [Account] username="jira-id" password="jira-password" ; Jira Address Setting [Address] url="http://'jira url'/rest/api/2/search/" url_issue = "http://'jira url'/rest/api/2/issue/"



- 번 외 -

jira-subversion-plugin

 - https://github.com/kashak88/jira-subversion-plugin/blob/master/atlassian-jira-subversion-plugin-3.0.2-jira8.jar

(jira8 에서 사용가능한 plugin - 설치는 되나 작동하는지 확인은 안됨)