ITNEXT

ITNEXT is a platform for IT developers & software engineers to share knowledge, connect, collaborate, learn and experience next-gen technologies.

Follow publication

Write custom Android/Kotlin linting rules like a Psi-chic!

Jason Low
ITNEXT
Published in
10 min readFeb 27, 2021

Table of Contents

Preface

Chicken, or Egg?

Diving into the matrix

Get Psi-ched

Psi-Viewer

Image A
Image B

The Fun Part (Implementation)

Hol’ Up a Minute

Pre-setup

Setup

plugins {
id "kotlin"
id "java-library"
id "maven"
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:0.33.0"
compileOnly "com.pinterest.ktlint:ktlint-core:0.33.0"
testImplementation "junit:junit:4.12"
testImplementation "org.assertj:assertj-core:3.12.2"
testImplementation "com.pinterest.ktlint:ktlint-core:0.33.0"
testImplementation "com.pinterest.ktlint:ktlint-test:0.33.0"
}
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
}
The third image is how your module directory should look like at this point.

The Good Stuff

class CustomRuleSetProvider : RuleSetProvider {
override fun get() = RuleSet(
"custom-rule-set",
TodoCommentRule(),
)
}
class TodoCommentRule : Rule("todo-comment") {
override fun visit(
node: ASTNode,
autoCorrect: Boolean,
emit: (
offset: Int,
errorMessage: String,
canBeAutoCorrected: Boolean
) -> Unit
) {
if (node.elementType == EOL_COMMENT) {
val commentText = node.text
if (commentText.contains("TODO")) {
val keywordIndex = commentText.indexOf("TODO")

if (keywordIndex > 0) {
val keywordCountOffset = keywordIndex + "TODO".length
val noColonAfter = commentText[keywordCountOffset].toString() != ":"

if (noColonAfter) {
emit(
node.startOffset,
"TODO should have a ':' immediately after",
true
)
}
}
}
}
}
}

Wrap Up

References

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Published in ITNEXT

ITNEXT is a platform for IT developers & software engineers to share knowledge, connect, collaborate, learn and experience next-gen technologies.

Written by Jason Low

https://twitter.com/jasonlowdh Full-time Android developer. I write about anything Android/software development, tech, and life’s musings.

Responses (1)