- Spring Boot 프로젝트에서 Github REST API로 Push 기능 구현하기2025년 05월 17일 00시 52분 32초에 업로드 된 글입니다.작성자: do_hyuk728x90반응형
이전 포스팅에서 Github과 연동하여 access token을 불러와 DB에 저장까지 마쳤다.
이제는 알고리즘 게시글의 내용을 특정 github 레포지토리에 push하는 기능을 만들어 보겠다.
push 기능을 구현하는데에는 크게 두 가지 방법이 있다.
첫 번째는 이전 포스팅과 같이 Github REST API를 직접 호출하는 방식이다.
GitHub REST API 설명서 - GitHub Docs
GitHub REST API를 사용하여 통합을 만들고, 데이터를 검색하고, 워크플로를 자동화합니다.
docs.github.com
두 번째로는 Java (hub4j/github-api)를 사용하는 것이다.
https://mvnrepository.com/artifact/org.kohsuke/github-api
해당 사이트에서 호환이 되는 버전을 선택해서 의존성 주입을 받으면 된다.
필자는 좀 더 사용하기 편한 두 번째 방법을 사용하였다.
의존성 주입
// Github API 사용을 위해 추가 implementation 'org.kohsuke:github-api:1.327'
Controller
프론트에서 Push 버튼을 통해 API를 호출했을 때
@PostMapping("/push/post/code") public ResponseEntity<String> push(@AuthenticationPrincipal UserDetails userDetails, @RequestBody GithubCodePushRequestDto requestDto) throws IOException { githubService.pushToGithub(userDetails.getUsername(), requestDto); return ResponseEntity.ok().body("Push to GitHub completed successfully."); }
Service
- Ori 라는 레포지토리가 있는지 확인하고 없으면 새로 생성
- (게시글 제목)/code.(사용 언어),
(게시글 제목)/description.md
디렉토리가 있으면 update, 없으면 새로 생성
@Transactional public void pushToGithub(String email, GithubCodePushRequestDto requestDto) throws IOException { String codePath = requestDto.title() + "/code." + requestDto.language(); String readmePath = requestDto.title() + "/description.md"; String githubToken = githubTokenRepository.findByEmail(email).orElseThrow( () -> new NotFoundException(ErrorCode.NOT_FOUND_GITHUB_TOKEN) ).getGithubToken(); GitHub github = new GitHubBuilder().withOAuthToken(githubToken).build(); GHRepository repo = getOrCreateRepository(github, getGithubName(github)); pushFile(repo, codePath, requestDto.code(), "Initial commit: code", "Updated code"); pushFile(repo, readmePath, requestDto.description(), "Initial commit: description", "Updated README"); } private GHRepository getOrCreateRepository(GitHub github, String username) throws IOException { try { return github.getRepository(username + "/" + REPO_NAME); } catch (GHFileNotFoundException e) { return github.createRepository(REPO_NAME) .description("Auto-created ori repo") .private_(false) .create(); } } private void pushFile(GHRepository repo, String path, String content, String initialMsg, String updateMsg) throws IOException { try { GHContent existing = repo.getFileContent(path, "main"); existing.update(content, updateMsg, "main"); } catch (GHFileNotFoundException e) { repo.createContent() .path(path) .message(initialMsg) .content(content) .commit(); } } private String getGithubName(GitHub github) throws IOException { return github.getMyself().getLogin(); }
결과
Ori repo가 생성되고 게시글이 push 됨 push 된 디렉토리 내부에 코드와 해설이 저장됨
해결해야 할 사항
현재 저장되는 경로에 code 파일의 형식이 사용 언어로 되어있는데 프론트에서는 java, c++, python으로 request를 보내준다.
java는 괜찮지만 python과 c++ 같은 경우를 그대로 쓸 경우 해당 언어에 대한 하이라이트가 적용되지 않을 거기 때문에
python -> py / c++ -> cpp 와 같이 매핑해줘야 할 로직을 짜야한다.
728x90반응형'포트폴리오 > AutoReview' 카테고리의 다른 글
🛠 GitHub 연동 기능 구현기 (5) 2025.05.15 Code Post에 북마크 기능 추가 (0) 2025.05.10 게시글 공개 여부 기능 추가 (0) 2025.05.08 [트러블 슈팅] Nginx 502 Bad Gateway 에러 발생 (0) 2025.04.29 검색 쿼리 개선 (LIKE -> Full Text Search) (0) 2025.04.23 댓글