Coder Social home page Coder Social logo

devalves1993 / diktat Goto Github PK

View Code? Open in Web Editor NEW

This project forked from saveourtool/diktat

0.0 1.0 0.0 6.21 MB

Strict coding standard for Kotlin and a custom set of rules for detecting code smells, code style issues and bugs

Home Page: https://analysis-dev.github.io/diktat/

License: MIT License

Shell 0.03% Java 0.10% Kotlin 90.38% TeX 9.49% Makefile 0.01%

diktat's Introduction

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 and a collection of Kotlin code style rules implemented as AST visitors on the top of KTlint. It can be used for detecting and autofixing code smells in CI/CD process. The full list of available supported rules and inspections can be found here.

Now diKTat was already added to the lists of static analysis tools, to kotlin-awesome and to kompar. Thanks to the community for this support!

See first

Codestyle Inspections Examples Demo White Paper Groups of Inspections

Why should I use diktat in my CI/CD?

There are several tools like detekt and ktlint that are doing static analysis. Why do I need diktat?

First of all - actually you can combine diktat with any other static analyzers. And diKTat is even using ktlint framework for parsing the code into the AST. Main features of diktat are the following:

  1. More inspections. It has 100+ inspections that are tightly coupled with it's Codestyle.

  2. Unique Inspections that are missing in other linters.

  3. Highly configurable. Each and every inspection can be configured or suppressed.

  4. Strict detailed Codestyle that you can adopt and use in your project.

Run as CLI-application

Download and install binaries:
  1. Install KTlint manually: here

OR use curl:

# another option is "brew install ktlint"

curl -sSLO https://github.com/pinterest/ktlint/releases/download/0.43.2/ktlint && chmod a+x ktlint
  1. Load diKTat manually: here

OR use curl:

$ curl -sSLO https://github.com/cqfn/diKTat/releases/download/v1.1.0/diktat-1.1.0.jar
Run diktat:
  1. Finally, run KTlint (with diKTat injected) to check your '*.kt' files in 'dir/your/dir':
$ ./ktlint -R diktat.jar --disabled_rules=standard "dir/your/dir/**/*.kt"

To autofix all code style violations use -F option.

Run with Maven using diktat-maven-plugin

❗ If you are using Java 16+, you need to add --add-opens java.base/java.util=ALL-UNNAMED flag to the JVM. For more information, see: pinterest/ktlint#1195 This can be done by setting MAVEN_OPTS variable:

export MAVEN_OPTS="--add-opens java.base/java.util=ALL-UNNAMED"

This plugin is available since version 0.1.3. You can see how it is configured in our project for self-checks: pom.xml. If you use it and encounter any problems, feel free to open issues on github.

Add this plugin to your pom.xml:
            <plugin>
                <groupId>org.cqfn.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.

Run with Gradle using diktat-gradle-plugin

Requires a gradle version no lower than 5.3.

This plugin is available since version 0.1.5. You can see how the plugin is configured in our examples: build.gradle.kts.

Add this plugin to your `build.gradle.kts`:
plugins {
    id("org.cqfn.diktat.diktat-gradle-plugin") version "1.1.0"
}

Or use buildscript syntax:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.cqfn.diktat:diktat-gradle-plugin:1.1.0")
    }
}

apply(plugin = "org.cqfn.diktat.diktat-gradle-plugin")

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 diktat extension has different reporters. You can specify json, html, sarif, plain (default) or your own custom reporter (it should be added as a dependency into diktat configuration):

diktat {
    // since 1.1.0 to keep in line with maven properties
    reporter = "json" // "html", "json", "plain" (default), "sarif"
    // before 1.1.0
    // reporterType = "json" // "html", "json", "plain" (default), "sarif"
}

You can also specify an output.

diktat {
    // since 1.1.0 (reporterType for old versions)
    reporter = "json"
    output = "someFile.json"
}

You can run diktat checks using task diktatCheck and automatically fix errors with tasks 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("1.1.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>1.1.0</version> <!-- optional -->
  <configFile>full/path/to/diktat-analysis.yml</configFile> <!-- optional, configuration file path -->
</diktat>

GitHub Native Integration

We suggest everyone to use common "sarif" format as a reporter (reporterType) 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 }}

Customizations via diktat-analysis.yml

In KTlint, rules can be configured via .editorconfig, but this does not give a chance to customize or enable/disable each and every rule independently. That is why 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

For example:

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

    }
}
Suppress groups of inspections 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:

java -jar ktlint -R dikat.jar --baseline=diktat-baseline.xml **/*.kt

or with corresponding configuration options in maven or gradle plugins. Baseline report is intended to be added into the VCS, but it can be removed and re-generated later, if needed.

Contribution

See our Contributing Policy and Code of Conduct

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.