gib's blog

GitLab Code Quality: Your Best Friend

Necessity

Code quality management is something that needs to be dealt with as early as possible. Maintaining good code quality makes the code more clean, readable, and maintanable, as this source suggests.

Options

With that, at first our team had a few options to help us maintain our code quality, mainly:

SonarQube

We opted for SonarQube CSUI because the setup process was quite simple. All we needed to do was setup the GitLab pipeline as follows:

sonarqube-check:
  stage: analyze
  image:
    name: sonarsource/sonar-scanner-cli:latest
    entrypoint: ['']
  variables:
    SONAR_USER_HOME: '${CI_PROJECT_DIR}/.sonar' # Defines the location of the analysis task cache
    GIT_DEPTH: '0' # Tells git to fetch all the branches of the project, required by the analysis task
  cache:
    key: '${CI_JOB_NAME}'
    paths:
      - .sonar/cache
      - .yarn
  script:
    - yarn test --coverage
    - sonar-scanner -X -Dsonar.qualitygate.wait=true -Dsonar.projectKey=$SONAR_PROJECT_KEY -Dsonar.login=$SONAR_TOKEN
  allow_failure: true
  only:
    - main

We thought that we had code quality covered. However, there was an issue. Because the code quality checking runs only on the main branch, that means our team would need to merge our work and only then get our quality results. That is not really ideal. It would be nice to make some small changes and still get some feedback. But after some research, SonarQube would only work on the main branch.

We decided to find another code quality checker. It turns out that GitLab has its own code quality checker, named Code Quality. Since our team's codebases are hosted in GitLab, the checker suits our requirements perfectly. We added these lines in the CI configuration:

// the important part is the code_quality job for this context
sast:
  stage: test
  before_script:
    - ''
    
code_quality:
  stage: test
  before_script:
    - ''
  rules:
    - if: $CI_PIPELINE_SOURCE == 'merge_request_event'

include:
  - template: Security/SAST.gitlab-ci.yml
  - template: Code-Quality.gitlab-ci.yml

And with this, every time we make a merge request, GitLab will analyze our code and report the results to us, like this:

gib's blog

This means that before merging to the target branch, we get to see where our code has issues in terms of the quality. We can even customize the default settings, which makes the analyzer very flexible.

We even get the report on the Changes tab of the merge request. This really helps us locate the issue more efficiently.

gib's blog

Conclusion

All in all, GitLab's Code Quality really helps our team maintain our code quality.