From d801e9d5fe69825b6dbacc25a7d7d670b843729d Mon Sep 17 00:00:00 2001 From: suhee Date: Sat, 19 Oct 2024 13:55:12 +0900 Subject: [PATCH 01/34] refactor: Modify customException, memberService MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - CustomException 확장성 개선 및 핸들러 추가 - MemberService 예외 처리 일부 삭제 --- .../exception/CustomException.java | 30 ++++++- .../exception/CustomExceptionHandler.java | 78 +++++++++++++++++-- .../member/domain/service/MemberService.java | 28 +++---- 3 files changed, 111 insertions(+), 25 deletions(-) diff --git a/src/main/java/app/common/infrastructure/exception/CustomException.java b/src/main/java/app/common/infrastructure/exception/CustomException.java index 835694e..0941c3d 100644 --- a/src/main/java/app/common/infrastructure/exception/CustomException.java +++ b/src/main/java/app/common/infrastructure/exception/CustomException.java @@ -1,11 +1,35 @@ package app.common.infrastructure.exception; import app.common.domain.model.common.ResponseCode; -import lombok.AllArgsConstructor; import lombok.Getter; -@AllArgsConstructor +import java.io.Serializable; + @Getter -public class CustomException extends RuntimeException { +public class CustomException extends RuntimeException implements Serializable { + private static final long serialVersionUID = 1L; + private final ResponseCode responseCode; + private final String additionalMessage; + + public CustomException(ResponseCode responseCode) { + this(responseCode, null, null); + } + + public CustomException(ResponseCode responseCode, String additionalMessage) { + this(responseCode, additionalMessage, null); + } + + public CustomException(ResponseCode responseCode, String additionalMessage, Throwable cause) { + super(additionalMessage, cause); + this.responseCode = responseCode; + this.additionalMessage = additionalMessage; + } + + @Override + public String getMessage() { + return (additionalMessage != null) + ? responseCode.getMessage() + ": " + additionalMessage + : responseCode.getMessage(); + } } \ No newline at end of file diff --git a/src/main/java/app/common/infrastructure/exception/CustomExceptionHandler.java b/src/main/java/app/common/infrastructure/exception/CustomExceptionHandler.java index 9c89372..8d08318 100644 --- a/src/main/java/app/common/infrastructure/exception/CustomExceptionHandler.java +++ b/src/main/java/app/common/infrastructure/exception/CustomExceptionHandler.java @@ -1,20 +1,86 @@ package app.common.infrastructure.exception; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.servlet.NoHandlerFoundException; +import org.springframework.web.HttpRequestMethodNotSupportedException; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.dao.DataAccessException; +import org.springframework.security.access.AccessDeniedException; + +import javax.validation.ConstraintViolationException; import app.common.domain.model.common.BaseResponse; @RestControllerAdvice public class CustomExceptionHandler { - @ExceptionHandler(Exception.class) - protected BaseResponse handleException(Exception e) { - return BaseResponse.failResponse(e); - } + + private static final Logger logger = LoggerFactory.getLogger(CustomExceptionHandler.class); @ExceptionHandler(CustomException.class) - protected BaseResponse handleCustomException(CustomException e) { - return BaseResponse.failResponse(e.getResponseCode()); + protected ResponseEntity handleCustomException(CustomException e) { + logger.error("CustomException occurred: ", e); + BaseResponse response = BaseResponse.failResponse(e.getResponseCode()); + return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST); + } + + @ExceptionHandler(IllegalArgumentException.class) + protected ResponseEntity handleIllegalArgumentException(IllegalArgumentException e) { + logger.error("IllegalArgumentException occurred: ", e); + BaseResponse response = BaseResponse.failResponse("INVALID_ARGUMENT"); + return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST); + } + + @ExceptionHandler(NoHandlerFoundException.class) + protected ResponseEntity handleNoHandlerFoundException(NoHandlerFoundException e) { + logger.error("NoHandlerFoundException occurred: ", e); + BaseResponse response = BaseResponse.failResponse("RESOURCE_NOT_FOUND"); + return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); + } + + @ExceptionHandler(HttpRequestMethodNotSupportedException.class) + protected ResponseEntity handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) { + logger.error("HttpRequestMethodNotSupportedException occurred: ", e); + BaseResponse response = BaseResponse.failResponse("METHOD_NOT_ALLOWED"); + return new ResponseEntity<>(response, HttpStatus.METHOD_NOT_ALLOWED); } + @ExceptionHandler(MethodArgumentNotValidException.class) + protected ResponseEntity handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { + logger.error("MethodArgumentNotValidException occurred: ", e); + BaseResponse response = BaseResponse.failResponse("INVALID_INPUT"); + return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST); + } + + @ExceptionHandler(ConstraintViolationException.class) + protected ResponseEntity handleConstraintViolationException(ConstraintViolationException e) { + logger.error("ConstraintViolationException occurred: ", e); + BaseResponse response = BaseResponse.failResponse("CONSTRAINT_VIOLATION"); + return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST); + } + + @ExceptionHandler(DataAccessException.class) + protected ResponseEntity handleDataAccessException(DataAccessException e) { + logger.error("DataAccessException occurred: ", e); + BaseResponse response = BaseResponse.failResponse("DATABASE_ERROR"); + return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); + } + + @ExceptionHandler(AccessDeniedException.class) + protected ResponseEntity handleAccessDeniedException(AccessDeniedException e) { + logger.error("AccessDeniedException occurred: ", e); + BaseResponse response = BaseResponse.failResponse("ACCESS_DENIED"); + return new ResponseEntity<>(response, HttpStatus.FORBIDDEN); + } + + @ExceptionHandler(Exception.class) + protected ResponseEntity handleException(Exception e) { + logger.error("Unexpected exception occurred: ", e); + BaseResponse response = BaseResponse.failResponse("INTERNAL_SERVER_ERROR"); + return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); + } } \ No newline at end of file diff --git a/src/main/java/app/member/domain/service/MemberService.java b/src/main/java/app/member/domain/service/MemberService.java index c6e526d..2aced12 100644 --- a/src/main/java/app/member/domain/service/MemberService.java +++ b/src/main/java/app/member/domain/service/MemberService.java @@ -24,23 +24,19 @@ public class MemberService { @Transactional public CreateMemberVo createMember(CreateMemberDto dto) { - try { - Member member = Member.builder() - .name(dto.getName()) - .email(dto.getEmail()) - .role(dto.getRole()) - .build(); - Member result = memberRepository.save(member); - log.info("### 회원 생성 결과: {}", result); + validateNewMember(dto); - return CreateMemberVo.toVo(result); - } catch (DataIntegrityViolationException e) { - throw new CustomException(ResponseCode.CONFLICT_DATA); - } catch (CustomException e) { - throw new CustomException(e.getResponseCode()); - } catch (Exception e) { - throw e; - } + Member member = Member.builder() + .name(dto.getName()) + .email(dto.getEmail()) + .role(dto.getRole()) + .build(); + + Member savedMember = memberRepository.save(member); + + log.info("New member created with ID: {}", savedMember.getId()); + + return CreateMemberVo.toVo(savedMember); } @Transactional(readOnly = true) From c5d6486bffd70817964e4798993b0ef9395d5201 Mon Sep 17 00:00:00 2001 From: suhee Date: Sat, 19 Oct 2024 13:59:49 +0900 Subject: [PATCH 02/34] fix: Modify code-review.yml MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 액션 미동작 bug fix - workflows 하위로 이동 --- .github/{ => workflows}/code-review.yml | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename .github/{ => workflows}/code-review.yml (100%) diff --git a/.github/code-review.yml b/.github/workflows/code-review.yml similarity index 100% rename from .github/code-review.yml rename to .github/workflows/code-review.yml From e5ab6e1bce4e3aa903b84133098930e7d4423819 Mon Sep 17 00:00:00 2001 From: suhee Date: Sat, 19 Oct 2024 14:09:39 +0900 Subject: [PATCH 03/34] fix: Apply openai 1.x.x --- .github/workflows/code-review.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/workflows/code-review.yml b/.github/workflows/code-review.yml index d28c362..f9a42ca 100644 --- a/.github/workflows/code-review.yml +++ b/.github/workflows/code-review.yml @@ -45,8 +45,7 @@ jobs: with open('pr_diff.txt', 'r') as file: diff_content = file.read() - # GPT 모델 호출 - response = openai.ChatCompletion.create( + response = openai.chat.completions.create( model=model_name, messages=[ {"role": "system", "content": system_prompt}, From d13f89c0760e5c67d347d924a2bbb78f7cebb53c Mon Sep 17 00:00:00 2001 From: suhee Date: Sat, 19 Oct 2024 14:11:13 +0900 Subject: [PATCH 04/34] fix: Modify openai response format --- .github/workflows/code-review.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/code-review.yml b/.github/workflows/code-review.yml index f9a42ca..1c45051 100644 --- a/.github/workflows/code-review.yml +++ b/.github/workflows/code-review.yml @@ -45,6 +45,7 @@ jobs: with open('pr_diff.txt', 'r') as file: diff_content = file.read() + # GPT 모델 호출 response = openai.chat.completions.create( model=model_name, messages=[ @@ -53,7 +54,7 @@ jobs: ] ) - # GPT 리뷰 결과 출력 + # GPT 리뷰 결과 추출 review_feedback = response['choices'][0]['message']['content'] print(review_feedback) EOF From f21922fdafb857c75390aadacfec3fceb3125e63 Mon Sep 17 00:00:00 2001 From: suhee Date: Sat, 19 Oct 2024 14:14:58 +0900 Subject: [PATCH 05/34] fix: Modify openai response format --- .github/workflows/code-review.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/code-review.yml b/.github/workflows/code-review.yml index 1c45051..4d97462 100644 --- a/.github/workflows/code-review.yml +++ b/.github/workflows/code-review.yml @@ -55,7 +55,7 @@ jobs: ) # GPT 리뷰 결과 추출 - review_feedback = response['choices'][0]['message']['content'] + review_feedback = response.choices[0].message.content print(review_feedback) EOF From ead87549dc685cd2711072e9071141c69ff5cd9c Mon Sep 17 00:00:00 2001 From: suhee Date: Sat, 19 Oct 2024 14:18:42 +0900 Subject: [PATCH 06/34] fix: Create gpt_review.txt --- .github/workflows/code-review.yml | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/.github/workflows/code-review.yml b/.github/workflows/code-review.yml index 4d97462..267a11a 100644 --- a/.github/workflows/code-review.yml +++ b/.github/workflows/code-review.yml @@ -56,12 +56,15 @@ jobs: # GPT 리뷰 결과 추출 review_feedback = response.choices[0].message.content - print(review_feedback) + + # 리뷰 결과를 gpt_review.txt 파일에 저장 + with open('gpt_review.txt', 'w') as output_file: + output_file.write(review_feedback) EOF - name: Post review comment on PR run: | - REVIEW_COMMENT=$(python -c 'import json; print(open("gpt_review.txt").read())') + REVIEW_COMMENT=$(cat gpt_review.txt) curl -X POST -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \ -d "{\"body\": \"${REVIEW_COMMENT}\"}" \ "https://api.github.com/repos/${{ github.repository }}/issues/${{ github.event.pull_request.number }}/comments" From 1330aebc1bd83b90193ebe9842cd5dcb82af3ba6 Mon Sep 17 00:00:00 2001 From: suhee Date: Sat, 19 Oct 2024 14:21:38 +0900 Subject: [PATCH 07/34] fix: Add log --- .github/workflows/code-review.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/code-review.yml b/.github/workflows/code-review.yml index 267a11a..3b3bfd7 100644 --- a/.github/workflows/code-review.yml +++ b/.github/workflows/code-review.yml @@ -65,6 +65,7 @@ jobs: - name: Post review comment on PR run: | REVIEW_COMMENT=$(cat gpt_review.txt) + echo "Review Comment: $REVIEW_COMMENT" # 코멘트 내용 확인 curl -X POST -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \ -d "{\"body\": \"${REVIEW_COMMENT}\"}" \ "https://api.github.com/repos/${{ github.repository }}/issues/${{ github.event.pull_request.number }}/comments" From a84d9d0687b21725edb400497bb275e0f72a017a Mon Sep 17 00:00:00 2001 From: suhee Date: Sat, 19 Oct 2024 14:24:57 +0900 Subject: [PATCH 08/34] fix: Modify code-review.yml - json parsing --- .github/workflows/code-review.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/code-review.yml b/.github/workflows/code-review.yml index 3b3bfd7..c4eff1a 100644 --- a/.github/workflows/code-review.yml +++ b/.github/workflows/code-review.yml @@ -65,7 +65,8 @@ jobs: - name: Post review comment on PR run: | REVIEW_COMMENT=$(cat gpt_review.txt) - echo "Review Comment: $REVIEW_COMMENT" # 코멘트 내용 확인 + echo "Review Comment: $REVIEW_COMMENT" + REVIEW_COMMENT_ESCAPED=$(echo "${REVIEW_COMMENT}" | python -c 'import json,sys; print(json.dumps(sys.stdin.read()))') curl -X POST -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \ - -d "{\"body\": \"${REVIEW_COMMENT}\"}" \ + -d "{\"body\": ${REVIEW_COMMENT_ESCAPED}}" \ "https://api.github.com/repos/${{ github.repository }}/issues/${{ github.event.pull_request.number }}/comments" From 25ace9e5b204bf0761f3ebf111497c03e4bb3777 Mon Sep 17 00:00:00 2001 From: suhee Date: Sat, 19 Oct 2024 14:34:32 +0900 Subject: [PATCH 09/34] fix: Modify code-review.yml MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 라인 별 코멘트 남기도록 수정 --- .github/workflows/code-review.yml | 62 ++++++++++++++++++------------- 1 file changed, 36 insertions(+), 26 deletions(-) diff --git a/.github/workflows/code-review.yml b/.github/workflows/code-review.yml index c4eff1a..4339b88 100644 --- a/.github/workflows/code-review.yml +++ b/.github/workflows/code-review.yml @@ -29,44 +29,54 @@ jobs: git diff origin/${{ github.event.pull_request.base.ref }} ${{ github.sha }} > pr_diff.txt shell: bash - - name: Perform Code Review with GPT + - name: Perform Code Review with GPT and Comment on Changed Lines id: gpt_review run: | python - < Date: Sat, 19 Oct 2024 14:58:05 +0900 Subject: [PATCH 10/34] fix: Modify code-review.yml MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - java 파일만 리뷰하도록 수정 - 컨텍스트 제공(+++, --- 라인들) --- .github/workflows/code-review.yml | 65 +++++++++++++++++++------------ 1 file changed, 40 insertions(+), 25 deletions(-) diff --git a/.github/workflows/code-review.yml b/.github/workflows/code-review.yml index 4339b88..2d78c67 100644 --- a/.github/workflows/code-review.yml +++ b/.github/workflows/code-review.yml @@ -54,29 +54,44 @@ jobs: for file in files_changed: file_path = file['filename'] - for change in file['patch'].split('\n'): - if change.startswith('+'): # 변경된 라인만 처리 - line_content = change[1:].strip() - - # GPT 모델 호출 - gpt_response = openai.chat.completions.create( - model=model_name, - messages=[ - {"role": "system", "content": system_prompt}, - {"role": "user", "content": f"Here is the code diff for line:\n{line_content}"} - ] - ) - - review_comment = gpt_response.choices[0].message.content - - # 변경된 파일과 라인에 리뷰 코멘트를 추가 - position = file['changes'] # 변경된 라인 위치 정보 - comment_body = { - "body": review_comment, - "path": file_path, - "position": position - } - - comment_url = f"https://api.github.com/repos/${{ github.repository }}/pulls/${{ github.event.pull_request.number }}/comments" - requests.post(comment_url, headers=headers, data=json.dumps(comment_body)) + + # .java 파일만 처리 + if file_path.endswith('.java'): + patch = file.get('patch', '') + + # 패치 파일에서 변경된 라인(+로 시작하는 라인과 -로 시작하는 라인) 처리 + removed_lines = [] + added_lines = [] + + for line in patch.split('\n'): + if line.startswith('-') and not line.startswith('---'): # 삭제된 라인 + removed_lines.append(line[1:].strip()) + elif line.startswith('+') and not line.startswith('+++'): # 추가된 라인 + added_lines.append(line[1:].strip()) + + # 삭제된 라인과 추가된 라인을 모두 컨텍스트로 GPT에게 전달 + for added_line in added_lines: + context = "\n".join(removed_lines + [added_line]) # 삭제된 라인과 추가된 라인을 컨텍스트로 묶기 + + if added_line: # 추가된 내용이 있을 때만 GPT 분석 + gpt_response = openai.chat.completions.create( + model=model_name, + messages=[ + {"role": "system", "content": system_prompt}, + {"role": "user", "content": f"Here is the code diff for context:\n{context}"} + ] + ) + + review_comment = gpt_response.choices[0].message.content + + # 변경된 파일과 라인에 리뷰 코멘트를 추가 + position = file['changes'] # 변경된 라인 위치 정보 + comment_body = { + "body": review_comment, + "path": file_path, + "position": position + } + + comment_url = f"https://api.github.com/repos/${{ github.repository }}/pulls/${{ github.event.pull_request.number }}/comments" + requests.post(comment_url, headers=headers, data=json.dumps(comment_body)) EOF From 88c0f68e7ffc5a2226a75daa63ef77df3b6b8b15 Mon Sep 17 00:00:00 2001 From: suhee Date: Sat, 19 Oct 2024 15:11:09 +0900 Subject: [PATCH 11/34] fix: Modify code-review.yml --- .github/workflows/code-review.yml | 140 ++++++++++++++++-------------- 1 file changed, 77 insertions(+), 63 deletions(-) diff --git a/.github/workflows/code-review.yml b/.github/workflows/code-review.yml index 2d78c67..2d740e8 100644 --- a/.github/workflows/code-review.yml +++ b/.github/workflows/code-review.yml @@ -32,66 +32,80 @@ jobs: - name: Perform Code Review with GPT and Comment on Changed Lines id: gpt_review run: | - python - < Date: Sat, 19 Oct 2024 15:13:30 +0900 Subject: [PATCH 12/34] fix: Add log code-review.yml --- .github/workflows/code-review.yml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.github/workflows/code-review.yml b/.github/workflows/code-review.yml index 2d740e8..43f703e 100644 --- a/.github/workflows/code-review.yml +++ b/.github/workflows/code-review.yml @@ -44,6 +44,9 @@ jobs: system_prompt = """${{ secrets.SYSTEM_PROMPT }}""" model_name = "${{ secrets.OPENAI_MODEL }}" + # GitHub API 호출 로그 + print("Fetching changed files from GitHub API...") + # 변경된 파일과 라인 정보를 가져오기 위한 GitHub API 호출 files_url = "https://api.github.com/repos/comeevery-git/basic_java/pulls/11/files" headers = {"Authorization": f"token ${{ secrets.GITHUB_TOKEN }}"} @@ -56,6 +59,7 @@ jobs: exit(1) if response.status_code == 200: + print("Files fetched successfully. Analyzing changes...") files_changed = response.json() for file in files_changed: @@ -65,6 +69,7 @@ jobs: # .java 파일만 처리 if file_path.endswith('.java'): patch = file.get('patch', '') + print(f"Analyzing patch for file: {file_path}") # 패치 파일에서 변경된 라인(+로 시작하는 라인과 -로 시작하는 라인) 처리 removed_lines = [] @@ -81,6 +86,7 @@ jobs: context = "\n".join(removed_lines + [added_line]) # 삭제된 라인과 추가된 라인을 컨텍스트로 묶기 if added_line: # 추가된 내용이 있을 때만 GPT 분석 + print(f"Calling GPT API for added line: {added_line}") try: gpt_response = openai.chat.completions.create( model=model_name, @@ -94,6 +100,7 @@ jobs: continue review_comment = gpt_response.choices[0].message.content + print(f"GPT response received for file: {file_path}") # 변경된 파일과 라인에 리뷰 코멘트를 추가 position = file['changes'] # 변경된 라인 위치 정보 @@ -104,6 +111,7 @@ jobs: } comment_url = f"https://api.github.com/repos/comeevery-git/basic_java/pulls/11/comments" + print(f"Posting comment to GitHub for file: {file_path}") requests.post(comment_url, headers=headers, data=json.dumps(comment_body)) else: print(f"Unexpected status code: {response.status_code}") From ddeb9de412801de9f802615da1134123801165df Mon Sep 17 00:00:00 2001 From: suhee Date: Sat, 19 Oct 2024 15:14:48 +0900 Subject: [PATCH 13/34] fix: Add log code-review.yml --- .github/workflows/code-review.yml | 168 +++++++++++++++--------------- 1 file changed, 84 insertions(+), 84 deletions(-) diff --git a/.github/workflows/code-review.yml b/.github/workflows/code-review.yml index 43f703e..b96ccf7 100644 --- a/.github/workflows/code-review.yml +++ b/.github/workflows/code-review.yml @@ -33,87 +33,87 @@ jobs: id: gpt_review run: | python < Date: Sat, 19 Oct 2024 15:17:16 +0900 Subject: [PATCH 14/34] fix: Modify code-review.yml --- .github/workflows/code-review.yml | 168 +++++++++++++++--------------- 1 file changed, 84 insertions(+), 84 deletions(-) diff --git a/.github/workflows/code-review.yml b/.github/workflows/code-review.yml index b96ccf7..f5484c3 100644 --- a/.github/workflows/code-review.yml +++ b/.github/workflows/code-review.yml @@ -33,87 +33,87 @@ jobs: id: gpt_review run: | python < Date: Sat, 19 Oct 2024 15:19:40 +0900 Subject: [PATCH 15/34] fix: Modify code-review.yml --- .github/workflows/code-review.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/code-review.yml b/.github/workflows/code-review.yml index f5484c3..8507c7a 100644 --- a/.github/workflows/code-review.yml +++ b/.github/workflows/code-review.yml @@ -88,12 +88,14 @@ jobs: if added_line: # 추가된 내용이 있을 때만 GPT 분석 print(f"Calling GPT API for added line: {added_line}") try: + # OpenAI API 호출에 타임아웃 설정 (15초로 설정) gpt_response = openai.chat.completions.create( model=model_name, messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": f"Here is the code diff for context:\n{context}"} - ] + ], + timeout=15 # 타임아웃 설정 ) except Exception as e: print(f"Error in GPT request: {e}") From 40bb9e96286dd2ee5f74c2989002aad392426ff9 Mon Sep 17 00:00:00 2001 From: suhee Date: Sat, 19 Oct 2024 15:23:22 +0900 Subject: [PATCH 16/34] fix: Modify code-review.yml --- .github/workflows/code-review.yml | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/.github/workflows/code-review.yml b/.github/workflows/code-review.yml index 8507c7a..f0c82f2 100644 --- a/.github/workflows/code-review.yml +++ b/.github/workflows/code-review.yml @@ -36,6 +36,7 @@ jobs: import openai import requests import json + import time # OpenAI API Key 설정 openai.api_key = "${{ secrets.OPENAI_API_KEY }}" @@ -61,6 +62,7 @@ jobs: if response.status_code == 200: print("Files fetched successfully. Analyzing changes...") files_changed = response.json() + print(f"Files Changed: {files_changed}") # 응답 데이터 출력 for file in files_changed: file_path = file['filename'] @@ -88,14 +90,14 @@ jobs: if added_line: # 추가된 내용이 있을 때만 GPT 분석 print(f"Calling GPT API for added line: {added_line}") try: - # OpenAI API 호출에 타임아웃 설정 (15초로 설정) + # OpenAI API 호출에 타임아웃 설정 (30초로 설정) gpt_response = openai.chat.completions.create( model=model_name, messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": f"Here is the code diff for context:\n{context}"} ], - timeout=15 # 타임아웃 설정 + timeout=30 # 타임아웃 30초로 늘림 ) except Exception as e: print(f"Error in GPT request: {e}") @@ -103,6 +105,7 @@ jobs: review_comment = gpt_response.choices[0].message.content print(f"GPT response received for file: {file_path}") + print(f"Review comment: {review_comment}") # GPT 응답 데이터 출력 # 변경된 파일과 라인에 리뷰 코멘트를 추가 position = file['changes'] # 변경된 라인 위치 정보 @@ -115,6 +118,7 @@ jobs: comment_url = f"https://api.github.com/repos/${{ github.repository }}/pulls/${{ github.event.pull_request.number }}/comments" print(f"Posting comment to GitHub for file: {file_path}") requests.post(comment_url, headers=headers, data=json.dumps(comment_body)) + print(f"Comment posted successfully for file: {file_path}") # 댓글이 성공적으로 포스팅됐는지 확인 else: print(f"Unexpected status code: {response.status_code}") exit(1) From 47a60ff225fa5690a78ec91879a57935f653c69a Mon Sep 17 00:00:00 2001 From: suhee Date: Sat, 19 Oct 2024 15:36:26 +0900 Subject: [PATCH 17/34] fix: Modify code-review.yml --- .github/workflows/code-review.yml | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/.github/workflows/code-review.yml b/.github/workflows/code-review.yml index f0c82f2..773d65e 100644 --- a/.github/workflows/code-review.yml +++ b/.github/workflows/code-review.yml @@ -45,6 +45,9 @@ jobs: system_prompt = """${{ secrets.SYSTEM_PROMPT }}""" model_name = "${{ secrets.OPENAI_MODEL }}" + # 처리된 라인을 저장하기 위한 집합 (중복 방지) + processed_lines = set() + # GitHub API 호출 로그 print("Fetching changed files from GitHub API...") @@ -78,11 +81,18 @@ jobs: added_lines = [] for line in patch.split('\n'): + # 중복된 라인은 건너뜀 + if line in processed_lines: + continue + if line.startswith('-') and not line.startswith('***'): # 삭제된 라인 removed_lines.append(line[1:].strip()) elif line.startswith('+') and not line.startswith('+++'): # 추가된 라인 added_lines.append(line[1:].strip()) + # 라인을 처리한 후 기록 + processed_lines.add(line) + # 삭제된 라인과 추가된 라인을 모두 컨텍스트로 GPT에게 전달 for added_line in added_lines: context = "\n".join(removed_lines + [added_line]) # 삭제된 라인과 추가된 라인을 컨텍스트로 묶기 @@ -97,7 +107,7 @@ jobs: {"role": "system", "content": system_prompt}, {"role": "user", "content": f"Here is the code diff for context:\n{context}"} ], - timeout=30 # 타임아웃 30초로 늘림 + timeout=30 # 타임아웃 30초로 설정 ) except Exception as e: print(f"Error in GPT request: {e}") @@ -122,4 +132,14 @@ jobs: else: print(f"Unexpected status code: {response.status_code}") exit(1) + + # 리뷰가 완료된 후 최종 요약 코멘트를 PR에 추가 + final_comment = "### 최종 리뷰 요약: 각 파일 및 라인의 모든 변경 사항을 검토 완료했습니다." + comment_url = f"https://api.github.com/repos/${{ github.repository }}/issues/${{ github.event.pull_request.number }}/comments" + requests.post(comment_url, headers=headers, data=json.dumps({"body": final_comment})) + print("Final review comment posted.") + + # 리뷰 완료 후 종료 + print("Review completed. Exiting...") + exit(0) EOF From 231785a150c1e04107957288b954e9b3beadc34d Mon Sep 17 00:00:00 2001 From: suhee Date: Sat, 19 Oct 2024 15:40:29 +0900 Subject: [PATCH 18/34] fix: Modify code-review.yml --- .github/workflows/code-review.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/code-review.yml b/.github/workflows/code-review.yml index 773d65e..ed3669e 100644 --- a/.github/workflows/code-review.yml +++ b/.github/workflows/code-review.yml @@ -36,7 +36,6 @@ jobs: import openai import requests import json - import time # OpenAI API Key 설정 openai.api_key = "${{ secrets.OPENAI_API_KEY }}" From 70928d3dc65d200efd4aba8e7dc312615f3644d9 Mon Sep 17 00:00:00 2001 From: suhee Date: Sat, 19 Oct 2024 15:49:02 +0900 Subject: [PATCH 19/34] fix: Modify code-review.yml --- .github/workflows/code-review.yml | 30 +++++++++++++++++------------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/.github/workflows/code-review.yml b/.github/workflows/code-review.yml index ed3669e..2709065 100644 --- a/.github/workflows/code-review.yml +++ b/.github/workflows/code-review.yml @@ -44,8 +44,9 @@ jobs: system_prompt = """${{ secrets.SYSTEM_PROMPT }}""" model_name = "${{ secrets.OPENAI_MODEL }}" - # 처리된 라인을 저장하기 위한 집합 (중복 방지) - processed_lines = set() + # 중복된 파일과 라인을 처리하기 위한 집합 + processed_files = set() # 중복 파일 방지 + processed_lines = set() # 중복 라인 방지 # GitHub API 호출 로그 print("Fetching changed files from GitHub API...") @@ -68,6 +69,12 @@ jobs: for file in files_changed: file_path = file['filename'] + + # 중복 파일 방지 + if file_path in processed_files: + continue # 이미 처리된 파일은 건너뜀 + processed_files.add(file_path) # 파일을 처리했음을 기록 + print(f"Processing file: {file_path}") # .java 파일만 처리 @@ -75,12 +82,11 @@ jobs: patch = file.get('patch', '') print(f"Analyzing patch for file: {file_path}") - # 패치 파일에서 변경된 라인(+로 시작하는 라인과 -로 시작하는 라인) 처리 removed_lines = [] added_lines = [] for line in patch.split('\n'): - # 중복된 라인은 건너뜀 + # 중복된 라인 처리 방지 if line in processed_lines: continue @@ -89,8 +95,7 @@ jobs: elif line.startswith('+') and not line.startswith('+++'): # 추가된 라인 added_lines.append(line[1:].strip()) - # 라인을 처리한 후 기록 - processed_lines.add(line) + processed_lines.add(line) # 라인을 처리했음을 기록 # 삭제된 라인과 추가된 라인을 모두 컨텍스트로 GPT에게 전달 for added_line in added_lines: @@ -99,8 +104,7 @@ jobs: if added_line: # 추가된 내용이 있을 때만 GPT 분석 print(f"Calling GPT API for added line: {added_line}") try: - # OpenAI API 호출에 타임아웃 설정 (30초로 설정) - gpt_response = openai.chat.completions.create( + gpt_response = openai.ChatCompletion.create( model=model_name, messages=[ {"role": "system", "content": system_prompt}, @@ -112,7 +116,7 @@ jobs: print(f"Error in GPT request: {e}") continue - review_comment = gpt_response.choices[0].message.content + review_comment = gpt_response['choices'][0]['message']['content'] print(f"GPT response received for file: {file_path}") print(f"Review comment: {review_comment}") # GPT 응답 데이터 출력 @@ -127,15 +131,15 @@ jobs: comment_url = f"https://api.github.com/repos/${{ github.repository }}/pulls/${{ github.event.pull_request.number }}/comments" print(f"Posting comment to GitHub for file: {file_path}") requests.post(comment_url, headers=headers, data=json.dumps(comment_body)) - print(f"Comment posted successfully for file: {file_path}") # 댓글이 성공적으로 포스팅됐는지 확인 + print(f"Comment posted successfully for file: {file_path}") # 댓글 성공 확인 else: print(f"Unexpected status code: {response.status_code}") exit(1) # 리뷰가 완료된 후 최종 요약 코멘트를 PR에 추가 - final_comment = "### 최종 리뷰 요약: 각 파일 및 라인의 모든 변경 사항을 검토 완료했습니다." - comment_url = f"https://api.github.com/repos/${{ github.repository }}/issues/${{ github.event.pull_request.number }}/comments" - requests.post(comment_url, headers=headers, data=json.dumps({"body": final_comment})) + final_comment_url = f"https://api.github.com/repos/${{ github.repository }}/issues/${{ github.event.pull_request.number }}/comments" + final_comment_body = "### 최종 리뷰 요약: 각 파일 및 라인의 모든 변경 사항을 검토 완료했습니다." + requests.post(final_comment_url, headers=headers, data=json.dumps({"body": final_comment_body})) print("Final review comment posted.") # 리뷰 완료 후 종료 From 0d950773f2411810291182e2875824b72c30a204 Mon Sep 17 00:00:00 2001 From: suhee Date: Sat, 19 Oct 2024 15:51:26 +0900 Subject: [PATCH 20/34] fix: Modify code-review.yml --- .github/workflows/code-review.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/code-review.yml b/.github/workflows/code-review.yml index 2709065..74cf7a5 100644 --- a/.github/workflows/code-review.yml +++ b/.github/workflows/code-review.yml @@ -104,7 +104,7 @@ jobs: if added_line: # 추가된 내용이 있을 때만 GPT 분석 print(f"Calling GPT API for added line: {added_line}") try: - gpt_response = openai.ChatCompletion.create( + gpt_response = openai.chat.completions.create( model=model_name, messages=[ {"role": "system", "content": system_prompt}, @@ -116,7 +116,7 @@ jobs: print(f"Error in GPT request: {e}") continue - review_comment = gpt_response['choices'][0]['message']['content'] + review_comment = gpt_response.choices[0].message.content print(f"GPT response received for file: {file_path}") print(f"Review comment: {review_comment}") # GPT 응답 데이터 출력 From 3fe36dbf86469fdd3add094fb73232310f4efe9a Mon Sep 17 00:00:00 2001 From: suhee Date: Sat, 19 Oct 2024 15:56:09 +0900 Subject: [PATCH 21/34] fix: Modify code-review.yml --- .github/workflows/code-review.yml | 127 +++++++++++++++--------------- 1 file changed, 63 insertions(+), 64 deletions(-) diff --git a/.github/workflows/code-review.yml b/.github/workflows/code-review.yml index 74cf7a5..4f53753 100644 --- a/.github/workflows/code-review.yml +++ b/.github/workflows/code-review.yml @@ -44,9 +44,8 @@ jobs: system_prompt = """${{ secrets.SYSTEM_PROMPT }}""" model_name = "${{ secrets.OPENAI_MODEL }}" - # 중복된 파일과 라인을 처리하기 위한 집합 - processed_files = set() # 중복 파일 방지 - processed_lines = set() # 중복 라인 방지 + # 처리된 라인을 저장하기 위한 집합 (중복 방지) + processed_lines = set() # GitHub API 호출 로그 print("Fetching changed files from GitHub API...") @@ -70,76 +69,76 @@ jobs: for file in files_changed: file_path = file['filename'] - # 중복 파일 방지 - if file_path in processed_files: - continue # 이미 처리된 파일은 건너뜀 - processed_files.add(file_path) # 파일을 처리했음을 기록 - - print(f"Processing file: {file_path}") - # .java 파일만 처리 - if file_path.endswith('.java'): - patch = file.get('patch', '') - print(f"Analyzing patch for file: {file_path}") + if not file_path.endswith('.java'): + print(f"Skipping non-Java file: {file_path}") + continue - removed_lines = [] - added_lines = [] - - for line in patch.split('\n'): - # 중복된 라인 처리 방지 - if line in processed_lines: + print(f"Processing file: {file_path}") + patch = file.get('patch', '') + print(f"Analyzing patch for file: {file_path}") + + # 패치 파일에서 변경된 라인(+로 시작하는 라인과 -로 시작하는 라인) 처리 + removed_lines = [] + added_lines = [] + + for line in patch.split('\n'): + # 중복된 라인은 건너뜀 + if line in processed_lines: + continue + + if line.startswith('-') and not line.startswith('***'): # 삭제된 라인 + removed_lines.append(line[1:].strip()) + elif line.startswith('+') and not line.startswith('+++'): # 추가된 라인 + added_lines.append(line[1:].strip()) + + # 라인을 처리한 후 기록 + processed_lines.add(line) + + # 삭제된 라인과 추가된 라인을 모두 컨텍스트로 GPT에게 전달 + for added_line in added_lines: + context = "\n".join(removed_lines + [added_line]) # 삭제된 라인과 추가된 라인을 컨텍스트로 묶기 + + if added_line: # 추가된 내용이 있을 때만 GPT 분석 + print(f"Calling GPT API for added line: {added_line}") + try: + # OpenAI API 호출에 타임아웃 설정 (30초로 설정) + gpt_response = openai.chat.completions.create( + model=model_name, + messages=[ + {"role": "system", "content": system_prompt}, + {"role": "user", "content": f"Here is the code diff for context:\n{context}"} + ], + timeout=30 # 타임아웃 30초로 설정 + ) + except Exception as e: + print(f"Error in GPT request: {e}") continue - if line.startswith('-') and not line.startswith('***'): # 삭제된 라인 - removed_lines.append(line[1:].strip()) - elif line.startswith('+') and not line.startswith('+++'): # 추가된 라인 - added_lines.append(line[1:].strip()) - - processed_lines.add(line) # 라인을 처리했음을 기록 - - # 삭제된 라인과 추가된 라인을 모두 컨텍스트로 GPT에게 전달 - for added_line in added_lines: - context = "\n".join(removed_lines + [added_line]) # 삭제된 라인과 추가된 라인을 컨텍스트로 묶기 - - if added_line: # 추가된 내용이 있을 때만 GPT 분석 - print(f"Calling GPT API for added line: {added_line}") - try: - gpt_response = openai.chat.completions.create( - model=model_name, - messages=[ - {"role": "system", "content": system_prompt}, - {"role": "user", "content": f"Here is the code diff for context:\n{context}"} - ], - timeout=30 # 타임아웃 30초로 설정 - ) - except Exception as e: - print(f"Error in GPT request: {e}") - continue - - review_comment = gpt_response.choices[0].message.content - print(f"GPT response received for file: {file_path}") - print(f"Review comment: {review_comment}") # GPT 응답 데이터 출력 - - # 변경된 파일과 라인에 리뷰 코멘트를 추가 - position = file['changes'] # 변경된 라인 위치 정보 - comment_body = { - "body": review_comment, - "path": file_path, - "position": position - } - - comment_url = f"https://api.github.com/repos/${{ github.repository }}/pulls/${{ github.event.pull_request.number }}/comments" - print(f"Posting comment to GitHub for file: {file_path}") - requests.post(comment_url, headers=headers, data=json.dumps(comment_body)) - print(f"Comment posted successfully for file: {file_path}") # 댓글 성공 확인 + review_comment = gpt_response.choices[0].message.content + print(f"GPT response received for file: {file_path}") + print(f"Review comment: {review_comment}") # GPT 응답 데이터 출력 + + # 변경된 파일과 라인에 리뷰 코멘트를 추가 + position = file['changes'] # 변경된 라인 위치 정보 + comment_body = { + "body": review_comment, + "path": file_path, + "position": position + } + + comment_url = f"https://api.github.com/repos/${{ github.repository }}/pulls/${{ github.event.pull_request.number }}/comments" + print(f"Posting comment to GitHub for file: {file_path}") + requests.post(comment_url, headers=headers, data=json.dumps(comment_body)) + print(f"Comment posted successfully for file: {file_path}") # 댓글이 성공적으로 포스팅됐는지 확인 else: print(f"Unexpected status code: {response.status_code}") exit(1) # 리뷰가 완료된 후 최종 요약 코멘트를 PR에 추가 - final_comment_url = f"https://api.github.com/repos/${{ github.repository }}/issues/${{ github.event.pull_request.number }}/comments" - final_comment_body = "### 최종 리뷰 요약: 각 파일 및 라인의 모든 변경 사항을 검토 완료했습니다." - requests.post(final_comment_url, headers=headers, data=json.dumps({"body": final_comment_body})) + final_comment = "### 최종 리뷰 요약: .java 파일에 대한 모든 변경 사항을 검토 완료했습니다." + comment_url = f"https://api.github.com/repos/${{ github.repository }}/issues/${{ github.event.pull_request.number }}/comments" + requests.post(comment_url, headers=headers, data=json.dumps({"body": final_comment})) print("Final review comment posted.") # 리뷰 완료 후 종료 From a14ff3dda9543d326aaa26f59056bbc151cc1f41 Mon Sep 17 00:00:00 2001 From: suhee Date: Sat, 19 Oct 2024 15:57:20 +0900 Subject: [PATCH 22/34] fix: Modify code-review.yml --- .github/workflows/code-review.yml | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/.github/workflows/code-review.yml b/.github/workflows/code-review.yml index 4f53753..df17fb9 100644 --- a/.github/workflows/code-review.yml +++ b/.github/workflows/code-review.yml @@ -45,7 +45,7 @@ jobs: model_name = "${{ secrets.OPENAI_MODEL }}" # 처리된 라인을 저장하기 위한 집합 (중복 방지) - processed_lines = set() + processed_files = set() # 각 파일을 기록 # GitHub API 호출 로그 print("Fetching changed files from GitHub API...") @@ -69,6 +69,11 @@ jobs: for file in files_changed: file_path = file['filename'] + # 이미 처리한 파일은 건너뛰기 + if file_path in processed_files: + print(f"Skipping already processed file: {file_path}") + continue + # .java 파일만 처리 if not file_path.endswith('.java'): print(f"Skipping non-Java file: {file_path}") @@ -83,17 +88,13 @@ jobs: added_lines = [] for line in patch.split('\n'): - # 중복된 라인은 건너뜀 - if line in processed_lines: - continue - if line.startswith('-') and not line.startswith('***'): # 삭제된 라인 removed_lines.append(line[1:].strip()) elif line.startswith('+') and not line.startswith('+++'): # 추가된 라인 added_lines.append(line[1:].strip()) - # 라인을 처리한 후 기록 - processed_lines.add(line) + # 각 파일을 처리한 후 파일 이름을 기록 + processed_files.add(file_path) # 삭제된 라인과 추가된 라인을 모두 컨텍스트로 GPT에게 전달 for added_line in added_lines: From 80e2723ede9aa9e8cab580b0b848903b42682a0b Mon Sep 17 00:00:00 2001 From: suhee Date: Sat, 19 Oct 2024 16:01:16 +0900 Subject: [PATCH 23/34] fix: Modify code-review.yml --- .github/workflows/code-review.yml | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/.github/workflows/code-review.yml b/.github/workflows/code-review.yml index df17fb9..ce676ad 100644 --- a/.github/workflows/code-review.yml +++ b/.github/workflows/code-review.yml @@ -44,8 +44,9 @@ jobs: system_prompt = """${{ secrets.SYSTEM_PROMPT }}""" model_name = "${{ secrets.OPENAI_MODEL }}" - # 처리된 라인을 저장하기 위한 집합 (중복 방지) + # 처리된 파일과 라인 기록 (중복 방지) processed_files = set() # 각 파일을 기록 + processed_lines = set() # 각 라인을 기록 # GitHub API 호출 로그 print("Fetching changed files from GitHub API...") @@ -83,16 +84,23 @@ jobs: patch = file.get('patch', '') print(f"Analyzing patch for file: {file_path}") - # 패치 파일에서 변경된 라인(+로 시작하는 라인과 -로 시작하는 라인) 처리 + # 각 라인 중복 처리 방지 removed_lines = [] added_lines = [] for line in patch.split('\n'): + if line in processed_lines: + print(f"Skipping already processed line: {line}") + continue + if line.startswith('-') and not line.startswith('***'): # 삭제된 라인 removed_lines.append(line[1:].strip()) elif line.startswith('+') and not line.startswith('+++'): # 추가된 라인 added_lines.append(line[1:].strip()) + # 처리된 라인 기록 + processed_lines.add(line) + # 각 파일을 처리한 후 파일 이름을 기록 processed_files.add(file_path) From 87e2c6e89869e3b28c54b7b62da972ba96e52b82 Mon Sep 17 00:00:00 2001 From: suhee Date: Sat, 19 Oct 2024 16:05:46 +0900 Subject: [PATCH 24/34] fix: Modify code-review.yml --- .github/workflows/code-review.yml | 37 +++++++++++++------------------ 1 file changed, 15 insertions(+), 22 deletions(-) diff --git a/.github/workflows/code-review.yml b/.github/workflows/code-review.yml index ce676ad..cf79ecb 100644 --- a/.github/workflows/code-review.yml +++ b/.github/workflows/code-review.yml @@ -44,9 +44,8 @@ jobs: system_prompt = """${{ secrets.SYSTEM_PROMPT }}""" model_name = "${{ secrets.OPENAI_MODEL }}" - # 처리된 파일과 라인 기록 (중복 방지) + # 처리된 파일 기록 (중복 방지) processed_files = set() # 각 파일을 기록 - processed_lines = set() # 각 라인을 기록 # GitHub API 호출 로그 print("Fetching changed files from GitHub API...") @@ -67,7 +66,13 @@ jobs: files_changed = response.json() print(f"Files Changed: {files_changed}") # 응답 데이터 출력 - for file in files_changed: + java_files = [file for file in files_changed if file['filename'].endswith('.java')] + + if not java_files: + print("No .java files to review.") + exit(0) + + for file in java_files: file_path = file['filename'] # 이미 처리한 파일은 건너뛰기 @@ -75,35 +80,20 @@ jobs: print(f"Skipping already processed file: {file_path}") continue - # .java 파일만 처리 - if not file_path.endswith('.java'): - print(f"Skipping non-Java file: {file_path}") - continue - print(f"Processing file: {file_path}") patch = file.get('patch', '') print(f"Analyzing patch for file: {file_path}") - # 각 라인 중복 처리 방지 + # GPT API 호출을 위한 라인 추출 removed_lines = [] added_lines = [] for line in patch.split('\n'): - if line in processed_lines: - print(f"Skipping already processed line: {line}") - continue - if line.startswith('-') and not line.startswith('***'): # 삭제된 라인 removed_lines.append(line[1:].strip()) elif line.startswith('+') and not line.startswith('+++'): # 추가된 라인 added_lines.append(line[1:].strip()) - # 처리된 라인 기록 - processed_lines.add(line) - - # 각 파일을 처리한 후 파일 이름을 기록 - processed_files.add(file_path) - # 삭제된 라인과 추가된 라인을 모두 컨텍스트로 GPT에게 전달 for added_line in added_lines: context = "\n".join(removed_lines + [added_line]) # 삭제된 라인과 추가된 라인을 컨텍스트로 묶기 @@ -111,14 +101,13 @@ jobs: if added_line: # 추가된 내용이 있을 때만 GPT 분석 print(f"Calling GPT API for added line: {added_line}") try: - # OpenAI API 호출에 타임아웃 설정 (30초로 설정) gpt_response = openai.chat.completions.create( model=model_name, messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": f"Here is the code diff for context:\n{context}"} ], - timeout=30 # 타임아웃 30초로 설정 + timeout=30 ) except Exception as e: print(f"Error in GPT request: {e}") @@ -139,7 +128,11 @@ jobs: comment_url = f"https://api.github.com/repos/${{ github.repository }}/pulls/${{ github.event.pull_request.number }}/comments" print(f"Posting comment to GitHub for file: {file_path}") requests.post(comment_url, headers=headers, data=json.dumps(comment_body)) - print(f"Comment posted successfully for file: {file_path}") # 댓글이 성공적으로 포스팅됐는지 확인 + print(f"Comment posted successfully for file: {file_path}") + + # 각 파일을 처리한 후 파일 이름을 기록 + processed_files.add(file_path) + else: print(f"Unexpected status code: {response.status_code}") exit(1) From 1aa7e9b20f660e660b660da694521345eca7c275 Mon Sep 17 00:00:00 2001 From: suhee Date: Sat, 19 Oct 2024 16:11:38 +0900 Subject: [PATCH 25/34] fix: Modify code-review.yml --- .github/workflows/code-review.yml | 122 ++++++++++++++---------------- 1 file changed, 56 insertions(+), 66 deletions(-) diff --git a/.github/workflows/code-review.yml b/.github/workflows/code-review.yml index cf79ecb..009fa78 100644 --- a/.github/workflows/code-review.yml +++ b/.github/workflows/code-review.yml @@ -36,20 +36,21 @@ jobs: import openai import requests import json - + # OpenAI API Key 설정 openai.api_key = "${{ secrets.OPENAI_API_KEY }}" - + # 시스템 프롬프트 및 모델명 가져오기 system_prompt = """${{ secrets.SYSTEM_PROMPT }}""" model_name = "${{ secrets.OPENAI_MODEL }}" - - # 처리된 파일 기록 (중복 방지) + + # 처리된 파일과 라인 기록 (중복 방지) processed_files = set() # 각 파일을 기록 - + processed_lines = {} # 각 파일별로 라인을 기록하기 위한 딕셔너리로 수정 + # GitHub API 호출 로그 print("Fetching changed files from GitHub API...") - + # 변경된 파일과 라인 정보를 가져오기 위한 GitHub API 호출 files_url = "https://api.github.com/repos/${{ github.repository }}/pulls/${{ github.event.pull_request.number }}/files" headers = {"Authorization": f"token ${{ secrets.GITHUB_TOKEN }}"} @@ -60,90 +61,79 @@ jobs: except requests.exceptions.RequestException as e: print(f"Error fetching files: {e}") exit(1) - + if response.status_code == 200: print("Files fetched successfully. Analyzing changes...") files_changed = response.json() - print(f"Files Changed: {files_changed}") # 응답 데이터 출력 - + + # .java 파일만 필터링 java_files = [file for file in files_changed if file['filename'].endswith('.java')] - + if not java_files: print("No .java files to review.") exit(0) - + for file in java_files: file_path = file['filename'] - + # 이미 처리한 파일은 건너뛰기 if file_path in processed_files: print(f"Skipping already processed file: {file_path}") continue - + print(f"Processing file: {file_path}") patch = file.get('patch', '') print(f"Analyzing patch for file: {file_path}") - - # GPT API 호출을 위한 라인 추출 - removed_lines = [] - added_lines = [] - - for line in patch.split('\n'): - if line.startswith('-') and not line.startswith('***'): # 삭제된 라인 - removed_lines.append(line[1:].strip()) - elif line.startswith('+') and not line.startswith('+++'): # 추가된 라인 - added_lines.append(line[1:].strip()) - - # 삭제된 라인과 추가된 라인을 모두 컨텍스트로 GPT에게 전달 - for added_line in added_lines: - context = "\n".join(removed_lines + [added_line]) # 삭제된 라인과 추가된 라인을 컨텍스트로 묶기 - - if added_line: # 추가된 내용이 있을 때만 GPT 분석 - print(f"Calling GPT API for added line: {added_line}") - try: - gpt_response = openai.chat.completions.create( - model=model_name, - messages=[ - {"role": "system", "content": system_prompt}, - {"role": "user", "content": f"Here is the code diff for context:\n{context}"} - ], - timeout=30 - ) - except Exception as e: - print(f"Error in GPT request: {e}") - continue - - review_comment = gpt_response.choices[0].message.content - print(f"GPT response received for file: {file_path}") - print(f"Review comment: {review_comment}") # GPT 응답 데이터 출력 - - # 변경된 파일과 라인에 리뷰 코멘트를 추가 - position = file['changes'] # 변경된 라인 위치 정보 - comment_body = { - "body": review_comment, - "path": file_path, - "position": position - } - - comment_url = f"https://api.github.com/repos/${{ github.repository }}/pulls/${{ github.event.pull_request.number }}/comments" - print(f"Posting comment to GitHub for file: {file_path}") - requests.post(comment_url, headers=headers, data=json.dumps(comment_body)) - print(f"Comment posted successfully for file: {file_path}") - + + # 각 파일마다 중복 라인 처리를 위한 집합 생성 + if file_path not in processed_lines: + processed_lines[file_path] = set() + + # 전체 패치 내용을 GPT에게 전달 (삭제된 라인, 추가된 라인 구분 없이) + if patch: # 패치가 존재할 경우에만 처리 + print(f"Calling GPT API for patch in file: {file_path}") + try: + gpt_response = openai.chat.completions.create( + model=model_name, + messages=[ + {"role": "system", "content": system_prompt}, + {"role": "user", "content": f"Here is the code diff for context:\n{patch}"} + ], + timeout=30 + ) + except Exception as e: + print(f"Error in GPT request: {e}") + continue + + review_comment = gpt_response.choices[0].message.content + print(f"GPT response received for file: {file_path}") + print(f"Review comment: {review_comment}") + + # 변경된 파일과 라인에 리뷰 코멘트를 추가 + position = file['changes'] # 변경된 라인 위치 정보 + comment_body = { + "body": review_comment, + "path": file_path, + "position": position + } + + comment_url = f"https://api.github.com/repos/${{ github.repository }}/pulls/${{ github.event.pull_request.number }}/comments" + print(f"Posting comment to GitHub for file: {file_path}") + requests.post(comment_url, headers=headers, data=json.dumps(comment_body)) + print(f"Comment posted successfully for file: {file_path}") + # 각 파일을 처리한 후 파일 이름을 기록 processed_files.add(file_path) - + else: print(f"Unexpected status code: {response.status_code}") exit(1) - - # 리뷰가 완료된 후 최종 요약 코멘트를 PR에 추가 + + # 최종 리뷰 요약 코멘트 추가 final_comment = "### 최종 리뷰 요약: .java 파일에 대한 모든 변경 사항을 검토 완료했습니다." comment_url = f"https://api.github.com/repos/${{ github.repository }}/issues/${{ github.event.pull_request.number }}/comments" requests.post(comment_url, headers=headers, data=json.dumps({"body": final_comment})) print("Final review comment posted.") - - # 리뷰 완료 후 종료 - print("Review completed. Exiting...") exit(0) EOF + From 63fd0539863059f645bd2ffd7bfec4dcd6bc9f80 Mon Sep 17 00:00:00 2001 From: suhee Date: Sat, 19 Oct 2024 16:18:45 +0900 Subject: [PATCH 26/34] fix: Modify code-review.yml --- .github/workflows/code-review.yml | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/.github/workflows/code-review.yml b/.github/workflows/code-review.yml index 009fa78..0edd302 100644 --- a/.github/workflows/code-review.yml +++ b/.github/workflows/code-review.yml @@ -116,11 +116,17 @@ jobs: "path": file_path, "position": position } - + + print(f"Commenting on file: {file_path}, position: {position}") + comment_url = f"https://api.github.com/repos/${{ github.repository }}/pulls/${{ github.event.pull_request.number }}/comments" print(f"Posting comment to GitHub for file: {file_path}") - requests.post(comment_url, headers=headers, data=json.dumps(comment_body)) - print(f"Comment posted successfully for file: {file_path}") + response = requests.post(comment_url, headers=headers, data=json.dumps(comment_body)) + if response.status_code == 201: + print(f"Comment posted successfully for file: {file_path}") + else: + print(f"Failed to post comment. Status code: {response.status_code}, Response: {response.text}") + # 각 파일을 처리한 후 파일 이름을 기록 processed_files.add(file_path) From 4b3d9b4eeb471bfd51156bdac6675518d6f33707 Mon Sep 17 00:00:00 2001 From: suhee Date: Sat, 19 Oct 2024 16:21:19 +0900 Subject: [PATCH 27/34] fix: Modify code-review.yml --- .github/workflows/code-review.yml | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/.github/workflows/code-review.yml b/.github/workflows/code-review.yml index 0edd302..1c501f6 100644 --- a/.github/workflows/code-review.yml +++ b/.github/workflows/code-review.yml @@ -108,25 +108,31 @@ jobs: review_comment = gpt_response.choices[0].message.content print(f"GPT response received for file: {file_path}") print(f"Review comment: {review_comment}") - + # 변경된 파일과 라인에 리뷰 코멘트를 추가 - position = file['changes'] # 변경된 라인 위치 정보 + commit_id = file['sha'] # 현재 파일의 커밋 ID + line_number = file['line'] # 파일에서 변경된 라인의 실제 번호 comment_body = { "body": review_comment, "path": file_path, - "position": position + "line": line_number, + "side": "RIGHT", # 변경된 코드에 대한 코멘트를 추가할 경우 'RIGHT' + "commit_id": commit_id } - - print(f"Commenting on file: {file_path}, position: {position}") - + + # 코멘트를 추가하기 전 파일 경로와 위치를 로그로 출력 + print(f"Commenting on file: {file_path}, line: {line_number}") + comment_url = f"https://api.github.com/repos/${{ github.repository }}/pulls/${{ github.event.pull_request.number }}/comments" - print(f"Posting comment to GitHub for file: {file_path}") response = requests.post(comment_url, headers=headers, data=json.dumps(comment_body)) + + # 응답 상태 확인 if response.status_code == 201: print(f"Comment posted successfully for file: {file_path}") else: print(f"Failed to post comment. Status code: {response.status_code}, Response: {response.text}") + # 각 파일을 처리한 후 파일 이름을 기록 processed_files.add(file_path) From 48610ee87245ec8a224ed79bc6d5f69bb7743d8f Mon Sep 17 00:00:00 2001 From: suhee Date: Sat, 19 Oct 2024 16:24:10 +0900 Subject: [PATCH 28/34] fix: Modify code-review.yml --- .github/workflows/code-review.yml | 100 ++++++++++++++---------------- 1 file changed, 48 insertions(+), 52 deletions(-) diff --git a/.github/workflows/code-review.yml b/.github/workflows/code-review.yml index 1c501f6..affc40a 100644 --- a/.github/workflows/code-review.yml +++ b/.github/workflows/code-review.yml @@ -52,7 +52,7 @@ jobs: print("Fetching changed files from GitHub API...") # 변경된 파일과 라인 정보를 가져오기 위한 GitHub API 호출 - files_url = "https://api.github.com/repos/${{ github.repository }}/pulls/${{ github.event.pull_request.number }}/files" + files_url = f"https://api.github.com/repos/${{ github.repository }}/pulls/${{ github.event.pull_request.number }}/files" headers = {"Authorization": f"token ${{ secrets.GITHUB_TOKEN }}"} try: response = requests.get(files_url, headers=headers, timeout=10) @@ -65,34 +65,37 @@ jobs: if response.status_code == 200: print("Files fetched successfully. Analyzing changes...") files_changed = response.json() + print(f"Files Changed: {files_changed}") # 응답 데이터 출력 - # .java 파일만 필터링 - java_files = [file for file in files_changed if file['filename'].endswith('.java')] - - if not java_files: - print("No .java files to review.") - exit(0) - - for file in java_files: + for file in files_changed: file_path = file['filename'] - + # 이미 처리한 파일은 건너뛰기 if file_path in processed_files: print(f"Skipping already processed file: {file_path}") continue + # .java 파일만 처리 + if not file_path.endswith('.java'): + print(f"Skipping non-Java file: {file_path}") + continue + print(f"Processing file: {file_path}") patch = file.get('patch', '') - print(f"Analyzing patch for file: {file_path}") + if not patch: + print(f"No patch data for file: {file_path}") + continue - # 각 파일마다 중복 라인 처리를 위한 집합 생성 - if file_path not in processed_lines: - processed_lines[file_path] = set() + # 패치에서 변경된 라인의 위치를 추출 + lines = patch.split('\n') + position = 0 # position은 패치 파일에서의 상대적인 위치 - # 전체 패치 내용을 GPT에게 전달 (삭제된 라인, 추가된 라인 구분 없이) - if patch: # 패치가 존재할 경우에만 처리 - print(f"Calling GPT API for patch in file: {file_path}") - try: + for i, line in enumerate(lines): + if line.startswith('+') and not line.startswith('+++'): + position = i + 1 # 변경된 라인의 위치를 추적 + + # GPT API 호출 및 리뷰 코멘트 생성 + print(f"Calling GPT API for patch in file: {file_path}") gpt_response = openai.chat.completions.create( model=model_name, messages=[ @@ -101,51 +104,44 @@ jobs: ], timeout=30 ) - except Exception as e: - print(f"Error in GPT request: {e}") - continue - - review_comment = gpt_response.choices[0].message.content - print(f"GPT response received for file: {file_path}") - print(f"Review comment: {review_comment}") - - # 변경된 파일과 라인에 리뷰 코멘트를 추가 - commit_id = file['sha'] # 현재 파일의 커밋 ID - line_number = file['line'] # 파일에서 변경된 라인의 실제 번호 - comment_body = { - "body": review_comment, - "path": file_path, - "line": line_number, - "side": "RIGHT", # 변경된 코드에 대한 코멘트를 추가할 경우 'RIGHT' - "commit_id": commit_id - } - - # 코멘트를 추가하기 전 파일 경로와 위치를 로그로 출력 - print(f"Commenting on file: {file_path}, line: {line_number}") - - comment_url = f"https://api.github.com/repos/${{ github.repository }}/pulls/${{ github.event.pull_request.number }}/comments" - response = requests.post(comment_url, headers=headers, data=json.dumps(comment_body)) - - # 응답 상태 확인 - if response.status_code == 201: - print(f"Comment posted successfully for file: {file_path}") - else: - print(f"Failed to post comment. Status code: {response.status_code}, Response: {response.text}") - - + review_comment = gpt_response.choices[0].message.content + + # 코멘트를 달기 위한 commit_id와 position 설정 + commit_id = file['sha'] + comment_body = { + "body": review_comment, + "path": file_path, + "position": position, + "commit_id": commit_id, + "side": "RIGHT" + } + + # 코멘트를 달기 전에 로그 출력 + print(f"Commenting on file: {file_path}, position: {position}") + + comment_url = f"https://api.github.com/repos/${{ github.repository }}/pulls/${{ github.event.pull_request.number }}/comments" + response = requests.post(comment_url, headers=headers, data=json.dumps(comment_body)) + + # 응답 상태 확인 + if response.status_code == 201: + print(f"Comment posted successfully for file: {file_path}") + else: + print(f"Failed to post comment. Status code: {response.status_code}, Response: {response.text}") # 각 파일을 처리한 후 파일 이름을 기록 processed_files.add(file_path) - else: print(f"Unexpected status code: {response.status_code}") exit(1) - # 최종 리뷰 요약 코멘트 추가 + # 리뷰가 완료된 후 최종 요약 코멘트를 PR에 추가 final_comment = "### 최종 리뷰 요약: .java 파일에 대한 모든 변경 사항을 검토 완료했습니다." comment_url = f"https://api.github.com/repos/${{ github.repository }}/issues/${{ github.event.pull_request.number }}/comments" requests.post(comment_url, headers=headers, data=json.dumps({"body": final_comment})) print("Final review comment posted.") + + # 리뷰 완료 후 종료 + print("Review completed. Exiting...") exit(0) EOF From 42e74192845e3445c284560c88e10c0d5699519b Mon Sep 17 00:00:00 2001 From: suhee Date: Sat, 19 Oct 2024 16:27:39 +0900 Subject: [PATCH 29/34] fix: Modify code-review.yml --- .github/workflows/code-review.yml | 106 ++++++++++++++++-------------- 1 file changed, 58 insertions(+), 48 deletions(-) diff --git a/.github/workflows/code-review.yml b/.github/workflows/code-review.yml index affc40a..721e488 100644 --- a/.github/workflows/code-review.yml +++ b/.github/workflows/code-review.yml @@ -65,37 +65,34 @@ jobs: if response.status_code == 200: print("Files fetched successfully. Analyzing changes...") files_changed = response.json() - print(f"Files Changed: {files_changed}") # 응답 데이터 출력 - for file in files_changed: + # .java 파일만 필터링 + java_files = [file for file in files_changed if file['filename'].endswith('.java')] + + if not java_files: + print("No .java files to review.") + exit(0) + + for file in java_files: file_path = file['filename'] - + # 이미 처리한 파일은 건너뛰기 if file_path in processed_files: print(f"Skipping already processed file: {file_path}") continue - # .java 파일만 처리 - if not file_path.endswith('.java'): - print(f"Skipping non-Java file: {file_path}") - continue - print(f"Processing file: {file_path}") patch = file.get('patch', '') - if not patch: - print(f"No patch data for file: {file_path}") - continue + print(f"Analyzing patch for file: {file_path}") - # 패치에서 변경된 라인의 위치를 추출 - lines = patch.split('\n') - position = 0 # position은 패치 파일에서의 상대적인 위치 + # 각 파일마다 중복 라인 처리를 위한 집합 생성 + if file_path not in processed_lines: + processed_lines[file_path] = set() - for i, line in enumerate(lines): - if line.startswith('+') and not line.startswith('+++'): - position = i + 1 # 변경된 라인의 위치를 추적 - - # GPT API 호출 및 리뷰 코멘트 생성 - print(f"Calling GPT API for patch in file: {file_path}") + # 전체 패치 내용을 GPT에게 전달 (삭제된 라인, 추가된 라인 구분 없이) + if patch: # 패치가 존재할 경우에만 처리 + print(f"Calling GPT API for patch in file: {file_path}") + try: gpt_response = openai.chat.completions.create( model=model_name, messages=[ @@ -104,44 +101,57 @@ jobs: ], timeout=30 ) - review_comment = gpt_response.choices[0].message.content - - # 코멘트를 달기 위한 commit_id와 position 설정 - commit_id = file['sha'] - comment_body = { - "body": review_comment, - "path": file_path, - "position": position, - "commit_id": commit_id, - "side": "RIGHT" - } - - # 코멘트를 달기 전에 로그 출력 - print(f"Commenting on file: {file_path}, position: {position}") - - comment_url = f"https://api.github.com/repos/${{ github.repository }}/pulls/${{ github.event.pull_request.number }}/comments" - response = requests.post(comment_url, headers=headers, data=json.dumps(comment_body)) - - # 응답 상태 확인 - if response.status_code == 201: - print(f"Comment posted successfully for file: {file_path}") - else: - print(f"Failed to post comment. Status code: {response.status_code}, Response: {response.text}") + except Exception as e: + print(f"Error in GPT request: {e}") + continue + + review_comment = gpt_response.choices[0].message.content + print(f"GPT response received for file: {file_path}") + print(f"Review comment: {review_comment}") + + # 변경된 파일과 라인에 리뷰 코멘트를 추가 (position 사용) + commit_id = file['sha'] # 현재 파일의 커밋 ID + patch_lines = patch.split('\n') + position = 0 # position은 패치 파일에서의 상대적인 위치 + + # 패치에서 추가된 (+) 라인의 position을 추적 + for i, line in enumerate(patch_lines): + if line.startswith('+') and not line.startswith('+++'): + position = i + 1 # 변경된 라인의 위치를 추적 + break + + comment_body = { + "body": review_comment, + "path": file_path, + "position": position, # 패치에서 계산된 position 사용 + "side": "RIGHT", # 변경된 코드에 대한 코멘트를 추가할 경우 'RIGHT' + "commit_id": commit_id + } + + # 코멘트를 추가하기 전 파일 경로와 위치를 로그로 출력 + print(f"Commenting on file: {file_path}, position: {position}") + + comment_url = f"https://api.github.com/repos/${{ github.repository }}/pulls/${{ github.event.pull_request.number }}/comments" + response = requests.post(comment_url, headers=headers, data=json.dumps(comment_body)) + + # 응답 상태 확인 + if response.status_code == 201: + print(f"Comment posted successfully for file: {file_path}") + else: + print(f"Failed to post comment. Status code: {response.status_code}, Response: {response.text}") + # 각 파일을 처리한 후 파일 이름을 기록 processed_files.add(file_path) + else: print(f"Unexpected status code: {response.status_code}") exit(1) - # 리뷰가 완료된 후 최종 요약 코멘트를 PR에 추가 + # 최종 리뷰 요약 코멘트 추가 final_comment = "### 최종 리뷰 요약: .java 파일에 대한 모든 변경 사항을 검토 완료했습니다." comment_url = f"https://api.github.com/repos/${{ github.repository }}/issues/${{ github.event.pull_request.number }}/comments" requests.post(comment_url, headers=headers, data=json.dumps({"body": final_comment})) print("Final review comment posted.") - - # 리뷰 완료 후 종료 - print("Review completed. Exiting...") exit(0) EOF - From 035b5b1b059bdf21884b1a4515aa9dd5a0edea6e Mon Sep 17 00:00:00 2001 From: suhee Date: Sat, 19 Oct 2024 16:30:38 +0900 Subject: [PATCH 30/34] fix: Modify code-review.yml --- .github/workflows/code-review.yml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/.github/workflows/code-review.yml b/.github/workflows/code-review.yml index 721e488..8c95338 100644 --- a/.github/workflows/code-review.yml +++ b/.github/workflows/code-review.yml @@ -109,8 +109,8 @@ jobs: print(f"GPT response received for file: {file_path}") print(f"Review comment: {review_comment}") - # 변경된 파일과 라인에 리뷰 코멘트를 추가 (position 사용) - commit_id = file['sha'] # 현재 파일의 커밋 ID + # 변경된 파일과 라인에 리뷰 코멘트를 추가 + commit_id = "${{ github.sha }}" # 현재 PR에 맞는 commit SHA 값을 사용 patch_lines = patch.split('\n') position = 0 # position은 패치 파일에서의 상대적인 위치 @@ -125,7 +125,7 @@ jobs: "path": file_path, "position": position, # 패치에서 계산된 position 사용 "side": "RIGHT", # 변경된 코드에 대한 코멘트를 추가할 경우 'RIGHT' - "commit_id": commit_id + "commit_id": commit_id # 현재 커밋 ID를 명시적으로 설정 } # 코멘트를 추가하기 전 파일 경로와 위치를 로그로 출력 @@ -155,3 +155,4 @@ jobs: print("Final review comment posted.") exit(0) EOF + From 456a8cf0abb13778482ff966a17eba0f99372bb1 Mon Sep 17 00:00:00 2001 From: suhee Date: Sat, 19 Oct 2024 16:35:21 +0900 Subject: [PATCH 31/34] fix: Modify code-review.yml --- .github/workflows/code-review.yml | 66 +++++++++++++------------------ 1 file changed, 28 insertions(+), 38 deletions(-) diff --git a/.github/workflows/code-review.yml b/.github/workflows/code-review.yml index 8c95338..bb9c970 100644 --- a/.github/workflows/code-review.yml +++ b/.github/workflows/code-review.yml @@ -36,21 +36,21 @@ jobs: import openai import requests import json - + # OpenAI API Key 설정 openai.api_key = "${{ secrets.OPENAI_API_KEY }}" - + # 시스템 프롬프트 및 모델명 가져오기 system_prompt = """${{ secrets.SYSTEM_PROMPT }}""" model_name = "${{ secrets.OPENAI_MODEL }}" - + # 처리된 파일과 라인 기록 (중복 방지) processed_files = set() # 각 파일을 기록 processed_lines = {} # 각 파일별로 라인을 기록하기 위한 딕셔너리로 수정 - + # GitHub API 호출 로그 print("Fetching changed files from GitHub API...") - + # 변경된 파일과 라인 정보를 가져오기 위한 GitHub API 호출 files_url = f"https://api.github.com/repos/${{ github.repository }}/pulls/${{ github.event.pull_request.number }}/files" headers = {"Authorization": f"token ${{ secrets.GITHUB_TOKEN }}"} @@ -61,35 +61,35 @@ jobs: except requests.exceptions.RequestException as e: print(f"Error fetching files: {e}") exit(1) - + if response.status_code == 200: print("Files fetched successfully. Analyzing changes...") files_changed = response.json() - + # .java 파일만 필터링 java_files = [file for file in files_changed if file['filename'].endswith('.java')] - + if not java_files: print("No .java files to review.") exit(0) - + for file in java_files: file_path = file['filename'] - + # 이미 처리한 파일은 건너뛰기 if file_path in processed_files: print(f"Skipping already processed file: {file_path}") continue - + print(f"Processing file: {file_path}") patch = file.get('patch', '') print(f"Analyzing patch for file: {file_path}") - + # 각 파일마다 중복 라인 처리를 위한 집합 생성 if file_path not in processed_lines: processed_lines[file_path] = set() - - # 전체 패치 내용을 GPT에게 전달 (삭제된 라인, 추가된 라인 구분 없이) + + # 전체 패치 내용을 GPT에게 전달 if patch: # 패치가 존재할 경우에만 처리 print(f"Calling GPT API for patch in file: {file_path}") try: @@ -104,50 +104,41 @@ jobs: except Exception as e: print(f"Error in GPT request: {e}") continue - + review_comment = gpt_response.choices[0].message.content print(f"GPT response received for file: {file_path}") print(f"Review comment: {review_comment}") - + # 변경된 파일과 라인에 리뷰 코멘트를 추가 - commit_id = "${{ github.sha }}" # 현재 PR에 맞는 commit SHA 값을 사용 - patch_lines = patch.split('\n') - position = 0 # position은 패치 파일에서의 상대적인 위치 - - # 패치에서 추가된 (+) 라인의 position을 추적 - for i, line in enumerate(patch_lines): - if line.startswith('+') and not line.startswith('+++'): - position = i + 1 # 변경된 라인의 위치를 추적 - break - + commit_id = file['sha'] # 파일의 sha 값을 사용 + line_number = file['patch'].split('\n').index(next(line for line in file['patch'].split('\n') if line.startswith('+'))) + 1 comment_body = { "body": review_comment, "path": file_path, - "position": position, # 패치에서 계산된 position 사용 - "side": "RIGHT", # 변경된 코드에 대한 코멘트를 추가할 경우 'RIGHT' - "commit_id": commit_id # 현재 커밋 ID를 명시적으로 설정 + "line": line_number, + "side": "RIGHT", + "commit_id": commit_id } - + # 코멘트를 추가하기 전 파일 경로와 위치를 로그로 출력 - print(f"Commenting on file: {file_path}, position: {position}") - + print(f"Commenting on file: {file_path}, line: {line_number}") + comment_url = f"https://api.github.com/repos/${{ github.repository }}/pulls/${{ github.event.pull_request.number }}/comments" response = requests.post(comment_url, headers=headers, data=json.dumps(comment_body)) - + # 응답 상태 확인 if response.status_code == 201: print(f"Comment posted successfully for file: {file_path}") else: print(f"Failed to post comment. Status code: {response.status_code}, Response: {response.text}") - - + # 각 파일을 처리한 후 파일 이름을 기록 processed_files.add(file_path) - + else: print(f"Unexpected status code: {response.status_code}") exit(1) - + # 최종 리뷰 요약 코멘트 추가 final_comment = "### 최종 리뷰 요약: .java 파일에 대한 모든 변경 사항을 검토 완료했습니다." comment_url = f"https://api.github.com/repos/${{ github.repository }}/issues/${{ github.event.pull_request.number }}/comments" @@ -155,4 +146,3 @@ jobs: print("Final review comment posted.") exit(0) EOF - From 7acad3fafe6739bbf691e3fdb26f65cc1cbe161c Mon Sep 17 00:00:00 2001 From: suhee Date: Sat, 19 Oct 2024 16:37:44 +0900 Subject: [PATCH 32/34] fix: Modify code-review.yml --- .github/workflows/code-review.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/code-review.yml b/.github/workflows/code-review.yml index bb9c970..6e2bcb7 100644 --- a/.github/workflows/code-review.yml +++ b/.github/workflows/code-review.yml @@ -110,8 +110,8 @@ jobs: print(f"Review comment: {review_comment}") # 변경된 파일과 라인에 리뷰 코멘트를 추가 - commit_id = file['sha'] # 파일의 sha 값을 사용 - line_number = file['patch'].split('\n').index(next(line for line in file['patch'].split('\n') if line.startswith('+'))) + 1 + commit_id = file.get('sha') # 파일의 sha 값을 사용 + line_number = file.get('patch).split('\n').index(next(line for line in file['patch'].split('\n') if line.startswith('+'))) + 1 comment_body = { "body": review_comment, "path": file_path, From d05eea0ea6d4ca55b38d8b19838e58ee9612d728 Mon Sep 17 00:00:00 2001 From: suhee Date: Sat, 19 Oct 2024 16:39:10 +0900 Subject: [PATCH 33/34] fix: Modify code-review.yml --- .github/workflows/code-review.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/code-review.yml b/.github/workflows/code-review.yml index 6e2bcb7..1b2460c 100644 --- a/.github/workflows/code-review.yml +++ b/.github/workflows/code-review.yml @@ -111,7 +111,7 @@ jobs: # 변경된 파일과 라인에 리뷰 코멘트를 추가 commit_id = file.get('sha') # 파일의 sha 값을 사용 - line_number = file.get('patch).split('\n').index(next(line for line in file['patch'].split('\n') if line.startswith('+'))) + 1 + line_number = file.get('patch').split('\n').index(next(line for line in file['patch'].split('\n') if line.startswith('+'))) + 1 comment_body = { "body": review_comment, "path": file_path, From 6e45dda7674ede9fef10ab10bf6cb1f1a1a0156f Mon Sep 17 00:00:00 2001 From: suhee Date: Sat, 19 Oct 2024 16:41:00 +0900 Subject: [PATCH 34/34] fix: Modify code-review.yml --- .github/workflows/code-review.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/code-review.yml b/.github/workflows/code-review.yml index 1b2460c..bc6e1fa 100644 --- a/.github/workflows/code-review.yml +++ b/.github/workflows/code-review.yml @@ -110,7 +110,7 @@ jobs: print(f"Review comment: {review_comment}") # 변경된 파일과 라인에 리뷰 코멘트를 추가 - commit_id = file.get('sha') # 파일의 sha 값을 사용 + commit_id = "${{ github.event.pull_request.head.sha }}" line_number = file.get('patch').split('\n').index(next(line for line in file['patch'].split('\n') if line.startswith('+'))) + 1 comment_body = { "body": review_comment,