이미 SonarQube 서버가 활성화되어 있다는 전제로 쓰인 글이다.
기본 요구 사항
- Maven 3.x
- SonarQube 서버에서 지원하는 Java 버전 (또는 그 이상)
시스템 설정
Maven의 settings.xml에 SonarQube 서버 주소 및 다른 정보를 설정해 줘야 한다.
settings.xml은 Maven 실행 시 필요한 설정 중, 특정 프로젝트에 포함되거나 일반 사용자에게 배포하면 안 되는 값들을 설정하기 위해 사용한다.
settings.xml 파일 위치는 다음과 같다. 없으면 만들면 된다.
${maven.home}/conf/settings.xml: 글로벌 설정${user.home}/.m2/settings.xml: 사용자 설정. 둘 다 존재한다면, 사용자 설정 우선으로 병합됨
<settings>
<pluginGroups>
<pluginGroup>org.sonarsource.scanner.maven</pluginGroup>
</pluginGroups>
<profiles>
<profile>
<id>sonar</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<!-- Optional URL to server. Default value is http://localhost:9000 -->
<sonar.host.url>
<!-- SonarQube 서버 주소 -->
</sonar.host.url>
<sonar.login>
<!-- 필수 X, SonarQube 분석 위한 authentication token -->
</sonar.login>
</properties>
</profile>
</profiles>
</settings>
분석 실행
정적 분석을 진행하고 싶은 프로젝트의 디렉터리(pom.xml이 있는 곳)에서 Maven goal sonar:sonar를 실행한다.
mvn clean verify sonar:sonar [-Dsonar.login=myAuthenticationToken]
clean: 기존 프로젝트 빌드 삭제verify: 테스트 등 프로젝트에 대한 검증 과정 수행.verify를 수행하기 위해.class파일이 필요하기 때문에 명시하지 않아도 Maven이 알아서 먼저compile과정을 수행함sonar:sonar: SonarQube 정적 분석 실행
명령어 파라미터로 authentication token을 넣어줄 수도 있긴 한데, settings.xml에 넣어두는 게 더 편해서 난 그렇게 했다.
Troubleshooting
ERROR: Your project contains .java files, please provide compiled classes with sonar.java.binaries property, or exclude them from the analysis with sonar.exclusions property.
곧장 mvn sonar:sonar를 실행했을 때 뜬 에러.
SonarQube 정적 분석을 위한 Java .class 파일이 없기 때문에 뜨는 에러이다. 실제로 실행되는 코드가 무엇인지, 프로젝트의 dependency는 어떻게 되는지 등 분석하기 위해 Java .class 파일이 꼭 필요하다.
compile 과정을 거친 후 분석하면 해당 에러는 뜨지 않는다.
mvn과 mvnw 차이
맨날 Gradle만 쓰다가 옛날 코드를 보면서 Maven을 오랜만에 봤는데, 내 컴퓨터에서 mvn 명령어가 실행되지 않아 처음에 당황했다.
mvn은 시스템 내 Maven이 설치되어 있을 때 (PATH 변수로 설정되어 실행할 수 있을 때) 사용하는 명령어이다.mvnw(Maven Wrapper)는 Maven이 설치되어 있지 않더라도 실행할 수 있게 하는 명령어이다.mvnw최초 실행 시 자동으로 프로젝트 내.m2/wrapper에 프로젝트에 맞는 Maven 버전을 설치하고, 이후에는 미리 설치된 Maven 버전으로 실행한다.