SonarQube with pre commit hook ⚓
In this blog i’ll explain how to configure SonarQube to check for code quality by adding it to pre commit hook, so lets get started …
Point of adding sonarQube as pre commit hook is to let developers in teams check their code quality before pushing it to version control system (popular one: git)
There are just 3 simple steps to get it configured
1- Install sonarqube
There are 2 ways to install, first one via docker and other by installing zip file
First approach- Docker (Easy one)
docker run -d -p 9000:9000 -p 9092:9092 sonarqube
This command will install docker image and run it if not present locally to check if it ran successfully run below command and under image tab in one of your images you’ll see sonarqube,
(make sure you have docker installed on your machine)
docker ps
then open the browser hit localhost:9000 you will see homepage of sonarqube . To login just hit
username - admin and password- admin
Second Approach- By downloading sonarqube from official website and installing it, there is awesome blog on how to configure that, follow it and you will be able to install sonarQube
2- Install sonar scanner
Install sonar scanner for official website
3- Create file inside .git/hooks/
open your .git folder (generally hidden)
on linux machine hit ctrl H
on windows follow this
after opening .git folder open hooks and inside that folder create a file with name pre-commit and paste content specified below
#!/bin/bashchmod +x .git/hooks/pre-commitexport PATH="$PATH:YOUR_PATH_TO_SONAR_SCANNER_BIN"sonar-scanner -Dsonar.projectKey=YOUR_PROJECT_NAME -Dsonar.sources=. -Dsonar.host.url=http://localhost:9000 -Dsonar.qualitygate.wait=true
Note-
export command will work only in linux machine use set
for windows
change YOUR_PROJECT_NAME to your project name
change YOUR_PATH_TO_SONAR_SCANNER_BIN with the path of bin that you have downloaded earlier in step 2, sample on linux machine would be
export PATH="$PATH:/home/mypc/Downloads/sonar-scanner-cli-4.2.0.1873-linux/sonar-scanner-4.2.0.1873-linux/bin"
After all these step you should be able to use pre commit hook on your git(vcs) repository, check by commiting any files on git.
Conclusion- We must use some kind of tool to check our code quality either by sonarQube or by any other tool out there like flake8, pylint (for python)