GitLab pipeline with static code analysis — detekt (kotlin)

Rushabh Shah
2 min readMar 22, 2021

Have you ever tried static code analysis for your project? Not yet!! you should have a hands-on it!

Many of the developers might try it for linting purposes. But what if we can make it automated!! Sounds good!!

I am going to explain detekt tool for kotlin static code analysis with gitlab automated pipelines.

What is detekt ??

Kotlin specific linting tool that can enforce codebase documentation, give hints about code blocks, and enforce formatting standards!

Step : 1 Add detekt in your project:

Modify your app-level build.gradle file as below. Add detekt plugin.

plugins {
id 'com.android.application'
id 'kotlin-android'
id "io.gitlab.arturbosch.detekt" version "1.16.0"
}

Step: 2 Add below in app-level build.gradle file dependancies. (formatting checks)

dependencies {
.
.
detekt("io.gitlab.arturbosch.detekt:detekt-formatting:1.16.0")
detekt("io.gitlab.arturbosch.detekt:detekt-cli:1.16.0")
}

Other ways for adding can be found here.

Sync file with Gradle. Then run,

$ ./gradlew task

You can see a list of gradle tasks, including the brand new detekt ones running in the terminal. Run below command to see the full report!!

$ ./gradlew detekt

Detekt Configuration File

Detekt configuration file is highly configurable. Detekt uses a yaml style configuration file for various things. Sample file.

Run the below command to generate a config file.

$ ./gradlew detektGenerateConfig

Open the newly generated file in <project-root>/config/detekt/detekt.yml to start modifying it.

More related to the config file can be found here.

Android Studio Gradle Plugin for detekt : https://plugins.jetbrains.com/plugin/10761-detekt

GitLab Integration:

We can enforce static code checks defined in detekt.yml as precheck before merge request.

First, create .gitlab-ci.yml file at the root of your project folder. Add below content in it.

before_script:
- export GRADLE_USER_HOME=$(pwd)/.gradle
- chmod +x ./gradlew

cache:
key: ${CI_PROJECT_ID}
paths:
- .gradle/
stages:
- build

assembleDebug:
image: jangrewe/gitlab-ci-android
stage: build
only:
- merge_requests
script:
- ./gradlew detekt

Commit and push this file to your repository. And voila!!

Now, whenever any merge request created, first a pipeline will run and code will be analyzed.

❣️ A supporter is worth 1000 followers!! ❣️

❤❤ Hey 👋. Enjoying reading my post, please show some LOVE! ❤❤

Bonus:
For enforcing that, Only allow merge requests to be merged if the pipeline succeeds. In your GitLab repository, (maintainer access needed)

  1. Navigate to your project’s Settings > General page.
  2. Expand the Merge requests section.
  3. In the Merge checks subsection, select the Pipelines must succeed checkbox.
  4. Press Save for the changes to take effect.

If you like SMASH the CLAP 👏 Button and DISAPPEAR it from Medium.

--

--

Rushabh Shah

Android & Flutter Developer with zeal to new learning everyday