### Simple Ktlint Plugin Setup (Groovy) Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/README.md Use this snippet for a straightforward setup of the Ktlint Gradle plugin. Ensure mavenCentral() is available to download KtLint. ```groovy plugins { id "org.jlleitschuh.gradle.ktlint" version "" } repositories { // Required to download KtLint mavenCentral() } ``` -------------------------------- ### Install Git Pre-commit Hook Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/_START_HERE.md Run this command to install the Ktlint check Git pre-commit hook. ```bash # Install git pre-commit hook ./gradlew addKtlintCheckGitPreCommitHook ``` -------------------------------- ### Simple Ktlint Plugin Setup (Kotlin) Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/README.md Use this snippet for a straightforward setup of the Ktlint Gradle plugin in a Kotlin build script. Ensure mavenCentral() is available to download KtLint. ```kotlin plugins { id("org.jlleitschuh.gradle.ktlint") version "" } repositories { // Required to download KtLint mavenCentral() } ``` -------------------------------- ### Complete Ktlint Configuration Example Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/GenerateReportsTask.md A comprehensive example demonstrating the configuration of the KtlintExtension with various options including console output, colored output, verbosity, ignoring failures, and setting up multiple reporter types. It also includes setting a custom report output directory for the GenerateReportsTask. ```kotlin configure { outputToConsole.set(true) coloredOutput.set(true) verbose.set(true) ignoreFailures.set(false) reporters { reporter(ReporterType.PLAIN) reporter(ReporterType.CHECKSTYLE) } } tasks.withType { reportsOutputDirectory.set( project.layout.buildDirectory.dir("lint-reports") ) } ``` -------------------------------- ### SemVer Version Comparison Example Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/types.md Example demonstrating how to use the SemVer type for comparing Ktlint versions to check for feature availability. Ensure SemVer is imported. ```kotlin val currentVersion = SemVer.parse("1.5.0") val minVersion = SemVer(0, 42, 0) if (currentVersion >= minVersion) { // SARIF reporter is available } ``` -------------------------------- ### Initial Setup Workflow Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/GenerateBaselineTask.md Steps to run ktlint checks, generate an initial baseline, and commit it. Subsequent checks will only report new violations. ```bash # Run checks to find all violations ./gradlew ktlintCheck # Create baseline for current state ./gradlew ktlintGenerateBaseline # Commit baseline to version control git add config/ktlint/baseline.xml git commit -m "Add ktlint baseline" # Now only new violations will fail the build ./gradlew ktlintCheck ``` -------------------------------- ### Console Output Example Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/GenerateReportsTask.md Shows the format for violations printed to the Gradle console when the `outputToConsole` option is enabled. ```text src/main/kotlin/Main.kt:5:20: Unexpected spaces src/main/kotlin/Utils.kt:12:1: Missing newline at end of file ``` -------------------------------- ### Full ktlint Configuration with Custom Reporters Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/CustomReporter.md A comprehensive example demonstrating the configuration of ktlint, including built-in reporters and multiple custom reporters with different dependency types. ```kotlin ktlint { version.set("1.5.0") reporters { // Built-in reporters reporter(ReporterType.PLAIN) reporter(ReporterType.CHECKSTYLE) // Custom reporters customReporters { register("csv") { reporterId = "csv-reporter" fileExtension = "csv" dependency = "com.example:csv-reporter:1.0.0" } register("markdown") { reporterId = "md-reporter" fileExtension = "md" dependency = project(":reporters:markdown") } register("slack") { fileExtension = "json" dependency = "com.example:slack-reporter:2.0.0" } } } } dependencies { ktlintReporter("com.example:csv-reporter:1.0.0") ktlintReporter("com.example:slack-reporter:2.0.0") } ``` -------------------------------- ### Configure Ktlint Source Files Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/configuration.md Specify the source files or directories that the Ktlint task should check. This example targets a specific task and provides source paths. ```kotlin tasks.named( "runKtlintCheckOverMainSourceSet" ) { source("src/main/kotlin", "src/main/java") } ``` -------------------------------- ### Checkstyle XML Report Example Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/GenerateReportsTask.md Example output format for a Checkstyle-compatible XML report generated by ktlint. This format is widely used by IDEs and CI tools for displaying linting errors. ```xml ``` -------------------------------- ### Plain Text Report Example Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/GenerateReportsTask.md Example output format for a plain text report generated by ktlint. It lists file paths, line numbers, column numbers, and error messages. ```text src/main/kotlin/Main.kt:1:1: Filename must match class or object declaration (cannot fix) src/main/kotlin/Main.kt:5:20: Unexpected spaces src/main/kotlin/Utils.kt:10:1: Missing newline at end of file ``` -------------------------------- ### Configure ktlint Reporters Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/ReporterType.md Example of configuring ktlint reporters within the ktlint block. Shows how to enable built-in reporters like PLAIN, CHECKSTYLE, and SARIF, and how to register custom reporters with specific file extensions and dependencies. ```kotlin ktlint { version.set("1.5.0") reporters { // Enable multiple reporters reporter(ReporterType.PLAIN) reporter(ReporterType.CHECKSTYLE) reporter(ReporterType.SARIF) // Add custom reporters customReporters { register("csv") { fileExtension = "csv" dependency = "com.example:csv-reporter:1.0.0" } } } } ``` -------------------------------- ### GitHub Actions Integration for Ktlint Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/OVERVIEW.md Set up a GitHub Actions workflow to run Ktlint checks. This example checks out the code, sets up Java, and executes the Gradle Ktlint task. ```yaml - uses: actions/checkout@v2 - uses: actions/setup-java@v2 with: java-version: 11 - run: ./gradlew ktlintCheck ``` -------------------------------- ### KtlintInstallGitHookTask Declaration Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/types.md Declaration for the KtlintInstallGitHookTask, used for installing git pre-commit hooks. It is marked as untracked as it's a utility task. ```kotlin @UntrackedTask(because = "Utility task used to install git hooks. Often only run once.") open class KtlintInstallGitHookTask @Inject constructor( objectFactory: ObjectFactory, projectLayout: ProjectLayout ) : DefaultTask() ``` -------------------------------- ### Ktlint Custom Reporter Example Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/README.md An example of a custom Ktlint reporter in Kotlin. Note that if the reporter writes to a file internally, task caching may not work correctly. ```kotlin class CsvReporter( private val out: PrintStream ) : Reporter { override fun onLintError(file: String, err: LintError, corrected: Boolean) { val line = "$file;${err.line};${err.col};${err.ruleId};${err.detail};$corrected" out.println(line) File("some_other_file.txt").write(line) // <-- Here!!! } } ``` -------------------------------- ### Install Ktlint Gradle Plugin Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/OVERVIEW.md Apply the ktlint-gradle plugin in your project's build script. Ensure you are using a compatible version. ```kotlin plugins { id("org.jlleitschuh.gradle.ktlint") version "14.2.0" } repositories { mavenCentral() } ``` -------------------------------- ### JSON Report Example Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/GenerateReportsTask.md Example output format for a JSON report generated by ktlint. This structured format is suitable for programmatic processing and integration with various tools. ```json [ { "file": "src/main/kotlin/Main.kt", "errors": [ { "line": 1, "column": 1, "message": "Filename must match class or object declaration (cannot fix)", "rule": "filename" }, { "line": 5, "column": 20, "message": "Unexpected spaces", "rule": "no-consecutive-spaces" } ] } ] ``` -------------------------------- ### Configure Ktlint Include/Exclude Patterns Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/configuration.md Set include and exclude patterns for a Ktlint task to control which files are linted. This example demonstrates chaining multiple include and exclude patterns. ```kotlin tasks.named( "runKtlintCheckOverMainSourceSet" ) { include("**/*.kt", "**/*.kts") exclude("**/generated/**", "**/build/**") } ``` -------------------------------- ### Configure Ktlint Plugin with Baseline Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/GenerateBaselineTask.md Configure the ktlint plugin to use a custom baseline file. This setup is part of the build script and applies to the entire project. ```kotlin plugins { id("org.jlleitschuh.gradle.ktlint") version "14.2.0" } repositories { mavenCentral() } configure { version.set("1.5.0") ignoreFailures.set(false) // Use custom baseline location baseline.set(file("lint-baseline.xml")) reporters { reporter(ReporterType.PLAIN) reporter(ReporterType.CHECKSTYLE) } } ``` -------------------------------- ### Apply KtlintPlugin to All Subprojects Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/KtlintPlugin.md Demonstrates how to apply the KtlintPlugin to all subprojects in a multi-module Gradle build using Kotlin DSL. Ensures each subproject gets its own independent task hierarchy. ```kotlin // root build.gradle.kts subprojects { apply(plugin = "org.jlleitschuh.gradle.ktlint") repositories { mavenCentral() } configure { version.set("1.5.0") } } ``` -------------------------------- ### Add Custom Rulesets and Reporters Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/configuration.md Use these configurations to add custom rulesets or reporters to your Ktlint setup. Ensure the specified coordinates are available in your project's dependencies. ```kotlin dependencies { // Add custom rulesets ktlintRuleset("com.github.username:custom-ruleset:1.0.0") // Add custom reporters ktlintReporter("com.example:csv-reporter:1.0.0") ktlintReporter("com.example:slack-reporter:2.0.0") } ``` -------------------------------- ### Minimal Custom Reporter Implementation Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/CustomReporter.md Implement the `Reporter` interface for custom lint error reporting. This example shows a basic CSV reporter that writes error details to an output stream. ```kotlin class CsvReporter( private val out: PrintStream ) : Reporter { override fun onLintError(file: String, err: LintError, corrected: Boolean) { out.println("$file;${err.line};${err.col};${err.ruleId};${err.detail};$corrected") } } ``` ```kotlin class CsvReporterProvider : ReporterProvider { override val id: String = "csv" override fun get(out: PrintStream, options: Map): Reporter { return CsvReporter(out) } } ``` -------------------------------- ### Run Ktlint Check on Sample Projects Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/README.md Use this command to run the current plugin snapshot on sample projects. This is useful for testing changes. ```bash ./gradlew ktlintCheck ``` -------------------------------- ### KtlintPlugin Apply Method Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/KtlintPlugin.md This is the main entry point for the KtlintPlugin. It initializes a PluginHolder and calls methods to add various ktlint-related tasks to the project. ```kotlin override fun apply(target: Project) { val holder = PluginHolder(target) holder.addKotlinScriptTasks() holder.addKtLintTasksToKotlinPlugin() holder.addGenerateBaselineTask() holder.addGitHookTasks() } ``` -------------------------------- ### Build the Ktlint Gradle Plugin Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/README.md Execute this command in the terminal to build the plugin. Ensure you are in the project root directory. ```bash ./plugin/gradlew build ``` -------------------------------- ### Get Current Exclude Patterns Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/BaseKtLintCheckTask.md The `getExcludes` method returns the current set of exclude patterns configured for the KtLint check task. ```kotlin fun getExcludes(): MutableSet ``` -------------------------------- ### Get Current Include Patterns Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/BaseKtLintCheckTask.md The `getIncludes` method returns the current set of include patterns configured for the KtLint check task. ```kotlin fun getIncludes(): MutableSet ``` -------------------------------- ### Load Reporters Task Execution Flow Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/LoadReportersTask.md Illustrates the steps involved in the loadKtlintReporters task, from discovering reporters to serializing them. ```text loadKtlintReporters ├─ Discover reporters from classpath ├─ Filter by ktlint version └─ Serialize to binary files ``` -------------------------------- ### Format Code Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/_START_HERE.md Execute this command to automatically format your code according to Ktlint rules. ```bash # Format code ./gradlew ktlintFormat ``` -------------------------------- ### Ktlint Plugin Configuration using Version Catalog (TOML) Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/README.md Configure the Ktlint plugin by adding entries to your libs.versions.toml file. This method centralizes version management. ```toml [versions] ktlint = "" [plugins] ktlint = { id = "org.jlleitschuh.gradle.ktlint", version.ref = "ktlint" } ``` -------------------------------- ### Upgrade Rules Workflow Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/GenerateBaselineTask.md Steps to upgrade the ktlint version, generate a new baseline for any new or changed rules, and review the differences. ```bash # Upgrade ktlint version ktlint { version.set("1.5.0") } # New rules or rule changes may create violations ./gradlew ktlintCheck # May fail with new violations # Decide: fix all or create new baseline ./gradlew ktlintGenerateBaseline # Review what changed git diff config/ktlint/baseline.xml ``` -------------------------------- ### Update Gradle Wrapper Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/CONTRIBUTING.md Run this command in the project root to update the main Gradle wrapper files. ```bash ./gradlew wrapper ``` -------------------------------- ### Configure Custom Reporter from Local JAR File Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/CustomReporter.md Register a custom reporter by providing a path to its JAR file. This method is suitable for standalone reporter JARs. ```kotlin ktlint { reporters { customReporters { register("custom") { fileExtension = "txt" dependency = files("libs/custom-reporter.jar") } } } } ``` -------------------------------- ### Generate Ktlint Baseline Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/configuration.md Execute the Gradle task to generate the Ktlint baseline file. ```bash ./gradlew ktlintGenerateBaseline ``` -------------------------------- ### Configure Ktlint for Snapshot Testing (Groovy) Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/README.md Add this configuration to your build script to test KtLint snapshots. It includes adding a snapshot repository and setting the version. ```groovy repositories { maven { url 'https://oss.sonatype.org/content/repositories/snapshots' } } ktlint { version = "0.41.0-SNAPSHOT" } ``` -------------------------------- ### Configuring Multiple Reporters Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/GenerateReportsTask.md Demonstrates how to configure multiple reporters within the Ktlint Gradle plugin to generate different report formats simultaneously. ```kotlin ktlint { reporters { reporter(ReporterType.PLAIN) reporter(ReporterType.CHECKSTYLE) reporter(ReporterType.JSON) } } ``` -------------------------------- ### Add Custom Ktlint Reporter Dependency Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/KtlintPlugin.md This Kotlin DSL snippet demonstrates how to add a custom reporter dependency for Ktlint in your Gradle build file. Replace the example coordinates with your reporter's actual coordinates. ```kotlin dependencies { ktlintReporter("com.example:csv-reporter:1.0.0") } ``` -------------------------------- ### Basic Ktlint Gradle Plugin Configuration Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/README.md Apply the Ktlint plugin and set its version. Ensure Maven Central is available for repository resolution. ```kotlin plugins { id("org.jlleitschuh.gradle.ktlint") version "14.2.0" } repositories { mavenCentral() } configure { version.set("1.5.0") } ``` -------------------------------- ### Exclude KtLint Configurations from Kotlin Version Pinning Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/README.md Prevent Gradle from pinning Kotlin versions for KtLint configurations to avoid compatibility issues. This snippet iterates through all configurations and applies a specific Kotlin version only when the configuration name does not start with 'ktlint'. ```kotlin configurations.all { if (!name.startsWith("ktlint")) { resolutionStrategy { eachDependency { // Force Kotlin to our version if (requested.group == "org.jetbrains.kotlin") { useVersion("1.3.72") } } } } } ``` -------------------------------- ### Configure Baseline in Root Project for Multi-Module Projects Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/GenerateBaselineTask.md Apply ktlint configuration to all subprojects, setting a common baseline file location for each module. ```kotlin subprojects { apply(plugin = "org.jlleitschuh.gradle.ktlint") configure { baseline.set(file("config/ktlint/baseline.xml")) } } ``` -------------------------------- ### Apply KtlintPlugin using Legacy Apply Method Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/KtlintPlugin.md Alternative method for applying the KtlintPlugin, typically used in older Gradle versions. Requires buildscript configuration. ```gradle buildscript { repositories { maven("https://plugins.gradle.org/m2/") } dependencies { classpath("org.jlleitschuh.gradle:ktlint-gradle:14.2.0") } } apply(plugin = "org.jlleitschuh.gradle.ktlint") ``` -------------------------------- ### Configure Custom Reporter from Local Project Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/CustomReporter.md Register a custom reporter by referencing a local Gradle project. This is useful for developing custom reporters alongside your main project. ```kotlin ktlint { reporters { customReporters { register("yaml") { fileExtension = "yml" dependency = project(":custom-reporters:yaml-reporter") } } } } ``` -------------------------------- ### Generate and Check Baseline with Gradle Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/GenerateBaselineTask.md Commands to generate the baseline file from current violations and then check the code against the generated baseline. The baseline is primarily for check-only workflows. ```bash # Generate baseline from current violations ./gradlew ktlintGenerateBaseline # Check against baseline (only new violations fail) ./gradlew ktlintCheck # View baseline file cat lint-baseline.xml ``` -------------------------------- ### Complete Ktlint Gradle Configuration Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/configuration.md This snippet shows a full configuration for the ktlint-gradle plugin. It includes setting the plugin version, enabling various output options, configuring custom editor settings, defining baseline files, and specifying custom reporters and rulesets. It also demonstrates how to filter files and configure task-specific settings like worker heap size and report output directories. ```kotlin plugins { id("org.jlleitschuh.gradle.ktlint") version "14.2.0" } repositories { mavenCentral() } configure { version.set("1.5.0") debug.set(false) verbose.set(false) android.set(false) outputToConsole.set(true) coloredOutput.set(true) outputColorName.set("") ignoreFailures.set(false) enableExperimentalRules.set(true) additionalEditorconfig.set(mapOf( "max_line_length" to "120", "indent_size" to "4" )) baseline.set(file("config/ktlint/baseline.xml")) relative.set(false) reporters { reporter(ReporterType.PLAIN) reporter(ReporterType.CHECKSTYLE) customReporters { register("csv") { fileExtension = "csv" dependency = "com.example:csv-reporter:1.0.0" } } } kotlinScriptAdditionalPaths { include(fileTree("scripts/")) } filter { exclude("**/generated/**") include("**/kotlin/**") } } dependencies { ktlintRuleset("com.github.username:custom-ruleset:1.0.0") ktlintReporter("com.example:csv-reporter:1.0.0") } tasks.withType { workerMaxHeapSize.set("512m") } tasks.withType { reportsOutputDirectory.set(project.layout.buildDirectory.dir("custom-reports")) } ``` -------------------------------- ### Configure Android SDK Location Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/README.md Add a local.properties file to the project root to specify the Android SDK location if the ANDROID_HOME environment variable is not defined. ```properties sdk.dir= ``` -------------------------------- ### include Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/BaseKtLintCheckTask.md Adds file inclusion patterns to the task. ```APIDOC ## include ### Description Adds file inclusion patterns. ### Method Overloads - `include(vararg includes: String): BaseKtLintCheckTask` - `include(includes: MutableIterable): BaseKtLintCheckTask` - `include(includeSpec: Spec): BaseKtLintCheckTask` - `include(includeSpec: Closure<*>): BaseKtLintCheckTask` ### Usage ```kotlin tasks.named("runKtlintCheckOverMainSourceSet") { include("**/*.kt") include { it.file.path.contains("app") } } ``` ``` -------------------------------- ### Configure KtLint Version from Properties File Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/configuration.md The plugin can read the KtLint version from a `ktlint-plugins.properties` file. This file takes precedence over inline version configuration. ```properties ktlint-version=1.5.0 ``` -------------------------------- ### Related Task Flow for Check/Format Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/LoadReportersTask.md Outlines the complete workflow for the ktlint check and format tasks, including dependencies on reporter loading. ```text ktlintCheck ├─ loadKtlintReporters ├─ runKtlintCheckOverMainSourceSet ├─ ktlintMainSourceSetCheck │ ├─ loadKtlintReporters (dependency) │ └─ GenerateReportsTask │ ├─ Read discovered errors │ ├─ Load serialized reporters │ └─ Generate reports └─ [build fails if violations found] ``` -------------------------------- ### Apply KtlintPlugin using Version Catalog Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/KtlintPlugin.md Integrate the KtlintPlugin using Gradle's version catalog for centralized dependency management. First, define the plugin in your TOML file. ```toml [plugins] ktlint = { id = "org.jlleitschuh.gradle.ktlint", version = "14.2.0" } ``` -------------------------------- ### Basic Ktlint Gradle Plugin Configuration Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/_START_HERE.md Configure the Ktlint Gradle plugin by applying the plugin, setting repositories, and defining extension properties like version and output. ```kotlin plugins { id("org.jlleitschuh.gradle.ktlint") version "14.2.0" } repositories { mavenCentral() } configure { version.set("1.5.0") outputToConsole.set(true) } ``` -------------------------------- ### KtlintPlugin with Custom Configuration Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/KtlintPlugin.md Configure the KtlintPlugin with custom settings such as ktlint version, output to console, reporter types, and file filtering. Also shows how to configure worker heap size for check tasks. ```kotlin plugins { id("org.jlleitschuh.gradle.ktlint") version "14.2.0" } repositories { mavenCentral() } configure { version.set("1.5.0") outputToConsole.set(true) reporters { reporter(ReporterType.PLAIN) reporter(ReporterType.CHECKSTYLE) } filter { exclude("**/generated/**") } } tasks.withType { workerMaxHeapSize.set("512m") } ``` -------------------------------- ### CustomReporter Configuration Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/INDEX.md Guidance on configuring custom reporters for Ktlint. ```APIDOC ## CustomReporter ### Description Configuration options for custom reporters. ### Requirements - Property definitions - Dependency notation - Service loader requirements - Configuration examples ``` -------------------------------- ### BaseKtLintCheckTask Configuration Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/INDEX.md Abstract base class for Ktlint check and format tasks, defining common source and pattern filtering configurations. ```APIDOC ## BaseKtLintCheckTask ### Description Abstract base class for check and format tasks, providing common configurations. ### Source Configuration - **setSource(files)**: Configures the source files to be processed. - **source(files)**: Alternative method for configuring source files. ### Pattern Filtering - **include(pattern)**: Includes files matching the given pattern. - **exclude(pattern)**: Excludes files matching the given pattern. ### Behavior - Incremental execution behavior - Worker configuration ``` -------------------------------- ### Configure BaseKtLintCheckTask Worker Heap and Source Filters Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/BaseKtLintCheckTask.md Configure the worker heap size and include/exclude source files for all BaseKtLintCheckTask instances. Useful for setting project-wide defaults. ```kotlin tasks.withType { // Set custom worker heap size for large projects workerMaxHeapSize.set("512m") // Filter to only include app source code include("**/src/main/kotlin/**") exclude("**/build/**") } ``` -------------------------------- ### Configure Ktlint for Snapshot Testing (Kotlin) Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/README.md Add this configuration to your Kotlin build script to test KtLint snapshots. It includes adding a snapshot repository and setting the version. ```kotlin repositories { maven("https://oss.sonatype.org/content/repositories/snapshots") } ktlint { version.set("0.41.0-SNAPSHOT") } ``` -------------------------------- ### Configure Specific Source Set Formatting Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/KtLintFormatTask.md Configure formatting for a specific source set, including excluding generated files. This allows fine-grained control over which files are formatted. ```kotlin tasks.named("runKtlintFormatOverMainSourceSet") { source("src/main/kotlin") // Don't format generated code exclude( "**/generated/**", "**/*.g.kt", "**/BuildConfig.kt" ) } ``` ```kotlin tasks.named("runKtlintFormatOverTestSourceSet") { source("src/test/kotlin") } ``` -------------------------------- ### Update Plugin Gradle Wrapper Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/CONTRIBUTING.md Run this command within the plugin directory to update its specific Gradle wrapper files. ```bash ./plugin/gradlew wrapper ``` -------------------------------- ### Generate Plugin Test Metadata Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/README.md Run this Gradle task to generate plugin test metadata, which is required before running tests in an IDE like IntelliJ IDEA. This should be run after any dependency changes. ```bash $ ./plugin/gradlew -p ./plugin pluginUnderTestMetadata ``` -------------------------------- ### KtlintExtension Configuration Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/INDEX.md Configuration options available through the KtlintExtension, which is the main entry point for customizing Ktlint behavior in Gradle. ```APIDOC ## KtlintExtension ### Description Main configuration extension class for the Ktlint Gradle plugin. ### Properties - **version** (string) - The Ktlint version to use. - **debug** (boolean) - Enable debug logging. - **verbose** (boolean) - Enable verbose logging. - **android** (boolean) - Enable Android-specific linting rules. - **outputToConsole** (boolean) - Whether to output reports to the console. ### Methods - **reporters()** - Configures the reporters to be used. - **filter()** - Configures file filtering rules. - **kotlinScriptAdditionalPaths()** - Specifies additional paths for Kotlin script analysis. ``` -------------------------------- ### Configure Ktlint Extension Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/README.md Use this block to configure the Ktlint plugin. Place your configuration settings within this block. ```kotlin configure { // configuration here } ``` -------------------------------- ### Configure Checkstyle Reporter Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/ReporterType.md Configures the ktlint task to use the Checkstyle XML reporter. This format is compatible with CI/CD systems and IDEs. ```gradle ktlint { reporters { reporter(ReporterType.CHECKSTYLE) } } ``` -------------------------------- ### Check Code Style Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/_START_HERE.md Run this command to check the code style of your project using Ktlint. ```bash # Check code style ./gradlew ktlintCheck ``` -------------------------------- ### Apply KtlintPlugin using Plugin DSL Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/KtlintPlugin.md Recommended way to apply the KtlintPlugin in your Gradle build script. Ensure you use the correct version. ```gradle plugins { id("org.jlleitschuh.gradle.ktlint") version "14.2.0" } ``` -------------------------------- ### Configure File Filters Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/configuration.md Define include and exclude patterns for files to be checked by Ktlint. This allows fine-grained control over which files are processed. ```kotlin ktlint { filter { exclude("**/generated/**") exclude("**/BuildConfig.kt") include("**/src/main/kotlin/**") } } ``` -------------------------------- ### Configure KtLintFormatTask Basic Usage Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/KtLintFormatTask.md Configure the KtLintFormatTask to set worker max heap size and specify source files with include/exclude patterns. This is useful for defining the scope of files to be formatted. ```kotlin tasks.named("runKtlintFormatOverMainSourceSet") { // Access inherited BaseKtLintCheckTask properties workerMaxHeapSize.set("512m") source("src/main/kotlin") include("**/*.kt") exclude("**/generated/**") } ``` -------------------------------- ### Configure KtLintCheckTask Basic Usage Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/KtLintCheckTask.md Configure the KtLintCheckTask for basic usage, setting worker heap size and specifying source files with include and exclude patterns. ```kotlin tasks.named("runKtlintCheckOverMainSourceSet") { // Access inherited BaseKtLintCheckTask properties workerMaxHeapSize.set("512m") source("src/main/kotlin") include("**/*.kt") exclude("**/generated/**") } ``` -------------------------------- ### source Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/BaseKtLintCheckTask.md Adds source files to be checked by this task. Multiple calls accumulate sources. ```APIDOC ## source ### Description Adds source files to be checked by this task. Multiple calls accumulate sources. ### Method `source(vararg sources: Any): BaseKtLintCheckTask` ### Parameters #### Path Parameters - **sources** (vararg Any) - Required - One or more file/directory paths. Evaluated per `Project.files()` semantics ### Usage ```kotlin tasks.named("runKtlintCheckOverMainSourceSet") { source("src/main/kotlin", "src/main/java") } ``` ``` -------------------------------- ### Configure Ktlint Plugin Version and Output Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/OVERVIEW.md Configure the ktlint plugin to set the ktlint version and enable console output for reports. This configuration should be placed within the 'build.gradle.kts' file. ```kotlin configure { version.set("1.5.0") outputToConsole.set(true) } ``` -------------------------------- ### Configure Ktlint Reports Output Directory Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/configuration.md Set the output directory for generated Ktlint report files. This allows customization of where reports are stored. ```kotlin tasks.withType { reportsOutputDirectory.set(project.layout.buildDirectory.dir("lint-reports")) } ``` -------------------------------- ### Add Source Files for KtLint Check Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/BaseKtLintCheckTask.md Use `source` to add one or more source files or directories to the KtLint check task. Multiple calls to this method will accumulate the sources. ```kotlin tasks.named("runKtlintCheckOverMainSourceSet") { source("src/main/kotlin", "src/main/java") } ``` -------------------------------- ### Legacy Ktlint Plugin Apply Method (Groovy) Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/README.md Use this legacy method for applying the Ktlint plugin across all Gradle versions. It requires explicit configuration in the buildscript block. ```groovy buildscript { repositories { maven { url "https://plugins.gradle.org/m2/" } } dependencies { classpath "org.jlleitschuh.gradle:ktlint-gradle:" } } repositories { // Required to download KtLint mavenCentral() } apply plugin: "org.jlleitschuh.gradle.ktlint" ``` -------------------------------- ### Configure Custom Reporters Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/types.md Register custom reporters by providing a name, file extension, and Gradle dependency. The `reporterId` defaults to the `name` and `fileExtension` defaults to `reporterId`. ```kotlin ktlint { reporters { customReporters { register("csv") { fileExtension = "csv" dependency = "com.example:csv-reporter:1.0.0" } } } } ``` -------------------------------- ### Configure KtLintFormatTask With Filters Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/KtLintFormatTask.md Apply specific include and exclude filters to the KtLintFormatTask to precisely control which directories and files are formatted. This helps in excluding build artifacts, generated code, and test files from the formatting process. ```kotlin tasks.named("runKtlintFormatOverMainSourceSet") { // Format specific directories only include("**/src/main/kotlin/**") // Skip generated and test files exclude( "**/build/**", "**/generated/**", "**/test/**" ) } ``` -------------------------------- ### KOTLIN_SCRIPT_TASK_NAME Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/KtLintFormatTask.md Predefined task name for formatting root-level Kotlin script files (.kts files in the project root). ```APIDOC ## KOTLIN_SCRIPT_TASK_NAME ### Description Predefined task name for formatting root-level Kotlin script files (.kts files in the project root). ### Value `"runKtlintFormatOverKotlinScripts"` ``` -------------------------------- ### Apply Ktlint Plugin using Version Catalog (Groovy) Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/README.md Apply the Ktlint plugin in your Groovy build script using the alias defined in your version catalog. Ensure mavenCentral() is available. ```groovy plugins { alias(libs.plugins.ktlint) } repositories { // Required to download KtLint mavenCentral() } ``` -------------------------------- ### Set Ktlint Baseline File Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/KtlintExtension.md Specify the path to a baseline file that tracks known ktlint issues. Issues listed in the baseline will not fail the build. ```kotlin ktlint { baseline.set(file("my-baseline.xml")) } ``` -------------------------------- ### Run Ktlint Check Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/OVERVIEW.md Execute the Ktlint check task. The first run checks all files, while subsequent runs only process changed files due to incremental execution. ```bash # First run - checks all files ./gradlew ktlintCheck # Subsequent runs - only changed files ./gradlew ktlintCheck ``` -------------------------------- ### Configure Plain Reporter Grouped by File Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/ReporterType.md Configures the ktlint task to use the plain text reporter, grouped and sorted by file path. Useful for organizing output in large projects. ```gradle ktlint { reporters { reporter(ReporterType.PLAIN_GROUP_BY_FILE) } } ``` -------------------------------- ### Gradual Compliance Workflow Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/GenerateBaselineTask.md Workflow for fixing violations, updating the baseline, and committing improvements incrementally. ```bash # Fix some violations manually vim src/main/kotlin/Main.kt # Update baseline to reflect improvements ./gradlew ktlintGenerateBaseline # Verify only the fixes are in baseline git diff config/ktlint/baseline.xml # Commit improvements git add src/main/kotlin/Main.kt config/ktlint/baseline.xml git commit -m "Fix ktlint violations in Main.kt" ``` -------------------------------- ### Generate Ktlint Baseline Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/README.md Run the `ktlintGenerateBaseline` task to generate a baseline file for your Gradle project. Note that format tasks ignore the baseline. ```groovy ktlintGenerateBaseline ``` -------------------------------- ### Add Ktlint Git Pre-commit Hooks Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/OVERVIEW.md Integrate Ktlint checks and formatting into your Git workflow by adding pre-commit hooks. Run the provided Gradle tasks to set them up. ```bash ./gradlew addKtlintCheckGitPreCommitHook ./gradlew addKtlintFormatGitPreCommitHook ``` -------------------------------- ### Add Kotlin Script Paths Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/configuration.md Specify additional directories containing Kotlin script files to be included in the Ktlint check. Use `include` with `fileTree` to add paths. ```kotlin ktlint { kotlinScriptAdditionalPaths { include(fileTree("scripts/")) include(fileTree("build-src/")) } } ``` -------------------------------- ### Enable Experimental Rules Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/KtlintExtension.md Activate experimental ktlint rules that are not yet stable. These rules are part of the ktlint experimental ruleset. ```kotlin ktlint { enableExperimentalRules.set(true) } ``` -------------------------------- ### Apply KtlintPlugin using Version Catalog Alias Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/KtlintPlugin.md Apply the KtlintPlugin in your build script by referencing its alias defined in the version catalog. ```gradle plugins { alias(libs.plugins.ktlint) } ``` -------------------------------- ### Configure Ktlint with Custom Reporters Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/README.md Set up custom reporters for Ktlint, including built-in types like PLAIN and CHECKSTYLE, and register a custom CSV reporter with its dependency. ```kotlin configure { reporters { reporter(ReporterType.PLAIN) reporter(ReporterType.CHECKSTYLE) customReporters { register("csv") { fileExtension = "csv" dependency = "com.example:csv-reporter:1.0.0" } } } } dependencies { ktlintReporter("com.example:csv-reporter:1.0.0") } ``` -------------------------------- ### Add Additional Kotlin Script Paths Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/KtlintExtension.md Provides additional file paths containing Kotlin script files (.kts) to be included in ktlint checking. Use this to ensure ktlint analyzes custom script files. ```kotlin ktlint { kotlinScriptAdditionalPaths { include(fileTree("scripts/")) } } ``` -------------------------------- ### Configure KtLintCheckTask for Main Source Set Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/KtLintCheckTask.md Configure a specific `KtLintCheckTask` for the main source set. This allows for custom source directory inclusion and exclusion patterns. ```kotlin tasks.named("runKtlintCheckOverMainSourceSet") { source("src/main/kotlin") exclude( "**/generated/**", "**/*Test.kt", "**/BuildConfig.kt" ) } ``` -------------------------------- ### Generate Baseline Violations Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/_START_HERE.md Use this command to generate a baseline file for known Ktlint violations in your project. ```bash # Generate baseline for known violations ./gradlew ktlintGenerateBaseline ``` -------------------------------- ### Detecting and Applying Ktlint to Kotlin Plugins Source: https://github.com/jlleitschuh/ktlint-gradle/blob/main/_autodocs/api-reference/KtlintPlugin.md This snippet demonstrates how the KtlintPlugin detects the application of different Kotlin plugins and applies the appropriate ktlint configurations. ```kotlin // Standard Kotlin plugin target.plugins.withId("kotlin", applyKtLint()) // Kotlin/JS plugin target.plugins.withId("org.jetbrains.kotlin.js", applyKtLint()) // Kotlin Multiplatform plugin target.plugins.withId( "org.jetbrains.kotlin.multiplatform", applyKtlintMultiplatform() ) // Android plugins target.plugins.withId("org.jetbrains.kotlin.android", applyKtLintToAndroid()) ```