Project Icon

diktat

严格的Kotlin代码规范与自动修复工具

diKTat是一款严格的Kotlin代码规范工具,基于KTlint开发。它提供100多项代码风格检查和自动修复功能,可集成到CI/CD流程中检测和修复代码异味。diKTat具有独特的检查项、高度可配置性和详细的代码风格指南,适合需要执行统一编码标准的团队使用。工具支持Maven、Gradle等构建系统,并能与GitHub Actions集成,提供原生问题报告。

Build and test deteKT static analysis diKTat code style codecov

Releases Maven Central FOSSA Status Chat on Telegram

Hits-of-Code Lines of code GitHub repo size Awesome Kotlin Badge

DiKTat is a strict coding standard for Kotlin, consisting of a collection of Kotlin code style rules implemented as Abstract Syntax Tree (AST) visitors built on top of KTlint. It serves the purpose of detecting and automatically fixing code smells in the Continuous Integration/Continuous Deployment (CI/CD) process. You can find the comprehensive list of supported rules and inspections here.

DiKTat has gained recognition and has been added to the lists of static analysis tools, kotlin-awesome, and kompar. We extend our gratitude to the community for this support!

See first

Why Choose DiKTat for CI/CD?

While there are other tools like detekt and ktlint performing static analysis, you might wonder why DiKTat is necessary. Here are the key reasons:

  1. More Inspections: DiKTat boasts over 100 inspections tightly coupled with its Codestyle.

  2. Unique Inspections: DiKTat introduces unique inspections not found in other linters.

  3. Highly Configurable: Every inspection is highly configurable, allowing customization and suppression. Check configuration options and suppression.

  4. Strict Codestyle: DiKTat enforces a detailed Codestyle that can be adopted and applied in your project.

Run as CLI-application

Download binary

  1. Download diKTat manually: here

    OR use curl:

    curl -sSLO https://github.com/saveourtool/diktat/releases/download/v2.0.0/diktat && chmod a+x diktat
    

For Windows only. Download diKTat.cmd manually: here

Run diKTat

Finally, run KTlint (with diKTat injected) to check your '*.kt' files in 'dir/your/dir':

$ ./diktat "dir/your/dir/**/*.kt"

On Windows

diktat.bat "dir/your/dir/**/*.kt"

To autofix all code style violations, use --mode fix option.

Run with Maven using diktat-maven-plugin

You can see how it is configured in our examples:

Add this plugin to your pom.xml:
            <plugin>
                <groupId>com.saveourtool.diktat</groupId>
                <artifactId>diktat-maven-plugin</artifactId>
                <version>${diktat.version}</version>
                <executions>
                    <execution>
                        <id>diktat</id>
                        <phase>none</phase>
                        <goals>
                            <goal>check</goal>
                            <goal>fix</goal>
                        </goals>
                        <configuration>
                            <inputs>
                                <input>${project.basedir}/src/main/kotlin</input>
                                <input>${project.basedir}/src/test/kotlin</input>
                            </inputs>
                            <diktatConfigFile>diktat-analysis.yml</diktatConfigFile>
                           <excludes>
                              <exclude>${project.basedir}/src/test/kotlin/excluded</exclude>
                           </excludes>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

To run diktat in only-check mode use command $ mvn diktat:check@diktat. To run diktat in autocorrect mode use command $ mvn diktat:fix@diktat.

Requesting a specific Maven executionId on the command line (the trailing diktat in the above example) may be essential in these cases:

  • In your pom.xml, you have multiple executions with different configurations (e. g.: multiple rule sets):

    <executions>
    
        <execution>
            <id>diktat-basic</id>
            <configuration>
                <diktatConfigFile>diktat-analysis.yml</diktatConfigFile>
            </configuration>
        </execution>
    
        <execution>
            <id>diktat-advanced</id>
            <configuration>
                <diktatConfigFile>diktat-analysis-advanced.yml</diktatConfigFile>
            </configuration>
        </execution>
    
    </executions>
    
  • Your YAML file with DiKTat rules has a non-default name and/or resides in a non-default location:

    <executions>
        <execution>
            <id>diktat</id>
            <configuration>
                <diktatConfigFile>/non/default/rule-set-file.yml</diktatConfigFile>
            </configuration>
        </execution>
    </executions>
    
    • You can omit the diktatConfigFile or if it points to non-existed file then DiKTat runs with default configuration.

If you omit the executionId:

$ mvn diktat:check

— the plug-in will use the default configuration and search for diktat-analysis.yml file in the project directory (you can still customize the rule sets by editing the YAML file).

Run with Gradle using diktat-gradle-plugin

Requires a gradle version no lower than 7.0

You can see how the plugin is configured in our examples:

Add this plugin to your `build.gradle.kts`:
plugins {
    id("com.saveourtool.diktat") version "2.0.0"
}

Note If you want to apply the plugin to multi-module projects"

import com.saveourtool.diktat.plugin.gradle.DiktatGradlePlugin

plugins {
    id("com.saveourtool.diktat") version "2.0.0" apply false
}

allprojects {
    apply<DiktatGradlePlugin>()
}

You can then configure diktat using diktat extension:

diktat {
    inputs {
        include("src/**/*.kt")  // path matching this pattern (per PatternFilterable) that will be checked by diktat
        exclude("src/test/kotlin/excluded/**")  // path matching this pattern will not be checked by diktat
    }
    debug = true  // turn on debug logging
}

Also in diktat extension you can configure different reporters and their output. You can specify json, html, sarif, plain (default). If output is set, it should be a file path. If not set, results will be printed to stdout. You can specify multiple reporters. If no reporter is specified, plain will be used with stdout as output.

diktat {
    reporters {
        plain()
        json()
        html {
            output = file("someFile.html")
        }
        // checkstyle()
        // sarif()
        // gitHubActions()
    }
}

You can run diktat checks using task ./gradlew diktatCheck and automatically fix errors with task ./gradlew diktatFix.

Run with Spotless

Spotless is a linter aggregator.

Gradle

Diktat can be run via spotless-gradle-plugin since version 5.10.0

Add this plugin to your build.gradle.kts
plugins {
   id("com.diffplug.spotless") version "5.10.0"
}

spotless {
   kotlin {
      diktat()
   }
   kotlinGradle {
      diktat()
   }
}
You can provide a version and configuration path manually as configFile.
spotless {
   kotlin {
      diktat("2.0.0").configFile("full/path/to/diktat-analysis.yml")
   }
}

Maven

Diktat can be run via spotless-maven-plugin since version 2.8.0

Add this plugin to your pom.xml
<plugin>
   <groupId>com.diffplug.spotless</groupId>
   <artifactId>spotless-maven-plugin</artifactId>
   <version>${spotless.version}</version>
   <configuration>
      <kotlin>
         <diktat />
      </kotlin>
   </configuration>
</plugin>
You can provide a version and configuration path manually as configFile
<diktat>
  <version>2.0.0</version> <!-- optional -->
  <configFile>full/path/to/diktat-analysis.yml</configFile> <!-- optional, configuration file path -->
</diktat>

GitHub Integration

We suggest everyone to use common "sarif" format as a reporter in CI/CD. GitHub has an integration with SARIF format and provides you a native reporting of diktat issues in Pull Requests.

img.png

Github Integration 1) Add the following configuration to your project's setup for GitHub Actions:

Gradle Plugin:

    githubActions = true

Maven Plugin (pom.xml):

    <githubActions>true</githubActions>

Maven Plugin (cli options):

mvn -B diktat:check@diktat -Ddiktat.githubActions=true
  1. Add the following code to your GitHub Action to upload diktat SARIF report (after it was generated):
      - name: Upload SARIF to Github using the upload-sarif action
        uses: github/codeql-action/upload-sarif@v1
        if: ${{ always() }}
        with:
          sarif_file: ${{ github.workspace }}

Note: codeql-action/upload-sarif limits the number of uploaded files at 15. If your project has more than 15 subprojects, the limit will be exceeded and the step will fail. To solve this issue one can merge SARIF reports.

diktat-gradle-plugin provides this capability with mergeDiktatReports task. This task aggregates reports of all diktat tasks of all Gradle project, which produce SARIF reports, and outputs the merged report into root project's build directory. Then this single file can be used as an input for GitHub action:

with:
    sarif_file: build/reports/diktat/diktat-merged.sarif

Customizations via diktat-analysis.yml

In Diktat we have supported diktat-analysis.yml that can be easily changed and help in customization of your own rule set. It has simple fields: name — name of the rule, enabled (true/false) — to enable or disable that rule (all rules are enabled by the default), configuration — a simple map of some extra unique configurations for this particular rule. For example:

- name: HEADER_MISSING_OR_WRONG_COPYRIGHT
  # all rules are enabled by the default. To disable add 'enabled: false' to the config.
  enabled: true
  configuration:
    isCopyrightMandatory: true
    copyrightText: Copyright (c) Jeff Lebowski, 2012-2020. All rights reserved.

Note, that you can specify and put diktat-analysis.yml that contains configuration of diktat in the parent directory of your project on the same level where build.gradle/pom.xml is stored.
See default configuration in diktat-analysis.yml
Also see the list of all rules supported by diKTat.

Suppress warnings/inspections

Suppress warnings on individual code blocks In addition to enabling/disabling warning globally via config file (`enable = false`), you can suppress warnings by adding `@Suppress` annotation on individual code blocks or `@file:Suppress()` annotation on a file-level.

For example:

@Suppress("FUNCTION_NAME_INCORRECT_CASE")
class SomeClass {
    fun methODTREE(): String {

    }
}
Disable all inspections on selected code blocks Also you can suppress **all** warnings by adding `@Suppress("diktat")` annotation on individual code blocks.

For example:

@Suppress("diktat")
class SomeClass {
    fun methODTREE(): String {

    }
}
ignoreAnnotated: disable inspections on blocks with predefined annotation In the `diktat-analysis.yml` file for each inspection it is possible to define a list of annotations that will cause disabling of the inspection on that particular code block:
- name: HEADER_NOT_BEFORE_PACKAGE
  enabled: true
  ignoreAnnotated: [MyAnnotation, Compose, Controller]
Suppress groups of inspections by chapters It is easy to suppress even groups of inspections in diKTat.

These groups are linked to chapters of Codestyle.

To disable chapters, you will need to add the following configuration to common configuration (- name: DIKTAT_COMMON):

    disabledChapters: "1, 2, 3"

Mapping of inspections to chapters can be found in Groups of Inspections.

Running against the baseline

When setting up code style analysis on a large existing project, one often doesn't have an ability to fix all findings at once. To allow gradual adoption, diktat and ktlint support baseline mode. When running ktlint for the first time with active baseline, the baseline file will be generated. It is a xml file with a complete list of findings by the tool. On later invocations, only the findings that are not in the baseline file will be reported. Baseline can be activated with CLI flag:

./diktat --baseline=diktat-baseline.xml
项目侧边栏1项目侧边栏2
推荐项目
Project Cover

豆包MarsCode

豆包 MarsCode 是一款革命性的编程助手,通过AI技术提供代码补全、单测生成、代码解释和智能问答等功能,支持100+编程语言,与主流编辑器无缝集成,显著提升开发效率和代码质量。

Project Cover

AI写歌

Suno AI是一个革命性的AI音乐创作平台,能在短短30秒内帮助用户创作出一首完整的歌曲。无论是寻找创作灵感还是需要快速制作音乐,Suno AI都是音乐爱好者和专业人士的理想选择。

Project Cover

白日梦AI

白日梦AI提供专注于AI视频生成的多样化功能,包括文生视频、动态画面和形象生成等,帮助用户快速上手,创造专业级内容。

Project Cover

有言AI

有言平台提供一站式AIGC视频创作解决方案,通过智能技术简化视频制作流程。无论是企业宣传还是个人分享,有言都能帮助用户快速、轻松地制作出专业级别的视频内容。

Project Cover

Kimi

Kimi AI助手提供多语言对话支持,能够阅读和理解用户上传的文件内容,解析网页信息,并结合搜索结果为用户提供详尽的答案。无论是日常咨询还是专业问题,Kimi都能以友好、专业的方式提供帮助。

Project Cover

讯飞绘镜

讯飞绘镜是一个支持从创意到完整视频创作的智能平台,用户可以快速生成视频素材并创作独特的音乐视频和故事。平台提供多样化的主题和精选作品,帮助用户探索创意灵感。

Project Cover

讯飞文书

讯飞文书依托讯飞星火大模型,为文书写作者提供从素材筹备到稿件撰写及审稿的全程支持。通过录音智记和以稿写稿等功能,满足事务性工作的高频需求,帮助撰稿人节省精力,提高效率,优化工作与生活。

Project Cover

阿里绘蛙

绘蛙是阿里巴巴集团推出的革命性AI电商营销平台。利用尖端人工智能技术,为商家提供一键生成商品图和营销文案的服务,显著提升内容创作效率和营销效果。适用于淘宝、天猫等电商平台,让商品第一时间被种草。

Project Cover

AIWritePaper论文写作

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

投诉举报邮箱: service@vectorlightyear.com
@2024 懂AI·鲁ICP备2024100362号-6·鲁公网安备37021002001498号