CheckStyle로 코드 컨벤션 지키기

기록의 습작·2023년 3월 19일
0

어느날 우릐 프론트엔드팀에서

Javascript 의 husky 를 사용해서 커밋 시 코드 냄새를 잡아

이슈가 있다면 커밋을 못하게 만드는

아주 그냥 기개맥히는 기술을 도입하였다..!

그분들이 husky를 사용하는 모습을 보고 경악을 금치못한 나는

인텔리제이나 Gradle 에도 husky 같은 기술이 있는지 리서치하였고….

드디어!! (두둥)

Checkstyle 이란 기특한 놈을 찾아버렸다..!

CheckStyle은 코드 컨벤션을 맞추는데 도움을 주는 플러그인이다.

요놈을 잘 활용하면 commit을 하기 전에 (pre-commit) 컨벤션을 잘 지켰는지 확인하고, 잘 지키지 않았을 경우 수정하라는 메시지와 함께 commit이 되지 않도록 제한을 걸어줄 수 있다.

이제 한번 인텔리제이와 Git hook 을 사용해 해당 기능을 적용해보자!!


먼저 인텔리제이 Plugin 에서 다운로드를 받자 (참고로 이클립스에도 존재한다)

잘 설치가 되었다면 Settings → Tools 에 Checkstyle 가 생겼을 것이다!

CheckStyle 설치 후 formatter.xml 과 직접 규칙들을 정의한 checks.xml 파일 두개를 프로젝트 루트경로에 추가해준다!

인텔리제이에서 Settings를 통해 formatter.xml을 적용해줍니다.

추가로 checks.xml도 적용해줍니다.

이제 git hook 도 설정을 해줘야하는데

프로젝트 워크스페이스를 확인해보면 깃 연동이 되었을 경우 .git 폴더가 있을 것이다!!

여길 들어가보면

hooks 라는 폴더가 있는데 여기서 git hook 설정을 해줄 수 있드아!

먼저 위에 checkstyle.jar 파일을 해당 hooks 폴더 안에 추가해주어야 한다. (아래 경로에서 다운로드 가능)

Releases · checkstyle/checkstyle

이제 커밋 전 checkstyle 을 통해 내 코드를 검사할 목적이였기 때문에!

pre-commit.sample → pre-commit 으로 변경 후 해당 파일을 수정해주면 된다! (아래 코드는 내가 사용하고 있는 pre-commit file 이다)

#!/usr/bin/perl
#
# Pre-commit hook for running checkstyle on changed Java sources
#
# To use this you need:
# 1. checkstyle's jar file somewhere
# 2. a checkstyle XML check file somewhere
# 3. To configure git:
#   * git config --add checkstyle.jar <location of jar>
#   * git config --add checkstyle.checkfile <location of checkfile>
#   * git config --add java.command <path to java executale> [optional
#     defaults to assuming it's in your path]
# 4. Put this in your .git/hooks directory as pre-commit
#
# Now, when you commit, you will be disallowed from doing so
# until you pass your checkstyle checks.

$command = "git-diff-index --cached HEAD 2>&1 | sed 's/^:.*     //' | uniq";
open (FILES,$command . "|") || die "Cannot run '$command': $!\n";

$CONFIG_CHECK_FILE = "checkstyle.checkfile";
$CONFIG_JAR = "checkstyle.jar";
$CONFIG_JAVA = "java.command";

$check_file = `git config --get $CONFIG_CHECK_FILE`;
$checkstyle_jar = `git config --get $CONFIG_JAR`;
$java_command = `git config --get $CONFIG_JAVA`;

if (!$check_file || !$checkstyle_jar)
{
   die "You must configure checkstyle in your git config:\n"
   . "\t$CONFIG_CHECK_FILE - path to your checkstyle.xml file\n"
   . "\t$CONFIG_JAR - path to your checkstyle jar file\n"
   . "\t$CONFIG_JAVA - path to your java executable (optional)\n"
   ;
}

$java_command = "java" if (!$java_command);

chomp $check_file;
chomp $checkstyle_jar;
chomp $java_command;

$command = "$java_command -jar $checkstyle_jar -c $check_file";

@java_files = ();
@words = ();

foreach (<FILES>)
{
   chomp;
   @words = split(/ /, $_);
   $type = substr(@words[-1], 0, 1);

   if($type eq "D") {
      print "$type - delete \n";
   }else {
      print "$type - add or modify \n";
      next if (!(/\.java$/));
      push @java_files, $_;
      $command .= " ";
      $command .= $_;
   }
}
if ($#java_files >= 0)
{
   if (&run_and_log_system ($command))
   {
       print STDERR "Commit aborted.\n";
       exit -1;
   }
}

exit 0;

sub run_and_log_system
{
   ($cmd) = @_;

   system $cmd;
}

여기까지 왔다면 이제 거의 끝났다!!

해당 프로젝트 위치에서 터미널 (git bash) 를 열어서 아래 명령어를 두개 치면 진짜 끝!

git config --add checkstyle.jar {파일경로}/checkstyle-{버전}-all.jar
git config --add checkstyle.checkfile {파일경로}/custom_checks.xml

https://checkstyle.sourceforge.io/

  • Checkstyle site
  • 여기서 다양한 규칙들을 확인할 수 있다.
profile
GyUL의 Backend 개발일기

0개의 댓글