├── .editorconfig ├── .github ├── CODEOWNERS └── workflows │ ├── publish.yml │ └── warning-check.yml ├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── SECURITY.md ├── build.gradle.kts ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle.kts └── src └── main └── kotlin └── com └── doist └── gradle ├── KotlinWarningBaselineExtension.kt ├── KotlinWarningBaselinePlugin.kt ├── collector └── WarningFileCollector.kt ├── convertor └── PathSeparatorConvertor.kt ├── ext ├── FileExt.kt └── IterableExt.kt ├── spec └── TaskInGraphSpec.kt └── task ├── CheckKotlinWarningBaselineTask.kt ├── RemoveKotlinWarningBaselineTask.kt └── WriteKotlinWarningBaselineTask.kt /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | end_of_line = lf 6 | indent_size = 4 7 | indent_style = space 8 | insert_final_newline = true 9 | max_line_length = 100 10 | tab_width = 4 11 | -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @Doist/android 2 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish 2 | 3 | on: 4 | push: 5 | tags: [ v* ] 6 | 7 | jobs: 8 | check: 9 | runs-on: ubuntu-latest 10 | timeout-minutes: 60 11 | steps: 12 | - uses: actions/checkout@v4 13 | - uses: actions/setup-java@v2 14 | with: 15 | java-version: '11' 16 | distribution: 'adopt' 17 | - run: ./gradlew check 18 | 19 | publish: 20 | needs: check 21 | runs-on: ubuntu-latest 22 | timeout-minutes: 60 23 | steps: 24 | - uses: actions/checkout@v4 25 | - uses: actions/setup-java@v2 26 | with: 27 | java-version: '11' 28 | distribution: 'adopt' 29 | - id: get_tag_version 30 | run: echo "VERSION=${GITHUB_REF#refs/tags/v}" >> $GITHUB_OUTPUT 31 | - run: ./gradlew assemble 32 | - run: ./gradlew publishPlugins -Pgradle.publish.key=${{ secrets.GRADLE_PUBLISH_KEY }} -Pgradle.publish.secret=${{ secrets.GRADLE_PUBLISH_SECRET }} 33 | env: 34 | ORG_GRADLE_PROJECT_version: ${{ steps.get_tag_version.outputs.VERSION }} 35 | shell: bash 36 | 37 | release: 38 | needs: publish 39 | runs-on: ubuntu-latest 40 | timeout-minutes: 60 41 | steps: 42 | - uses: actions/checkout@v4 43 | - uses: actions/create-release@v1 44 | env: 45 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 46 | with: 47 | tag_name: ${{ github.ref }} 48 | release_name: ${{ github.ref }} 49 | -------------------------------------------------------------------------------- /.github/workflows/warning-check.yml: -------------------------------------------------------------------------------- 1 | name: Warning check 2 | 3 | on: 4 | pull_request: 5 | branches: 6 | - main 7 | 8 | concurrency: 9 | group: warning-check-${{ github.ref }} 10 | cancel-in-progress: true 11 | 12 | jobs: 13 | warning-check: 14 | runs-on: ubuntu-latest 15 | 16 | timeout-minutes: 60 17 | steps: 18 | - name: Checkout repo 19 | uses: actions/checkout@v4 20 | 21 | - name: Setup Java 22 | uses: actions/setup-java@v2 23 | with: 24 | distribution: "adopt" 25 | java-version: "11" 26 | 27 | - name: Check warning baseline 28 | run: ./gradlew checkKotlinWarningBaseline 29 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | .idea 3 | build 4 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | This file documents all notable changes, following the [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) format. 4 | 5 | ## Unreleased 6 | 7 | ## 1.0.0 - 2021-12-23 8 | 9 | ### Added 10 | - Public release 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Doist 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Kotlin Warning Baseline Gradle Plugin 2 | 3 | This plugin adds tasks to control kotlin warnings in the project with the help of baseline or without it. Typical usage of the plugin would be checking that PR doesn't introduce new warnings (for example [github action](.github/workflows/warning-check.yml)) or running it locally to catch new deprecations after dependencies update. 4 | 5 | Currently, plugin supports: Kotlin JVM, Kotlin Multiplatform and Android projects. 6 | 7 | ## Usage 8 | 9 | Run: 10 | ```shell 11 | ./gradlew checkKotlinWarningBaseline 12 | ``` 13 | and receive error in case of new warnings: 14 | ``` 15 | FAILURE: Build failed with an exception. 16 | * What went wrong: 17 | Execution failed for task ':checkKotlinWarningBaseline'. 18 | > Found 3 warnings behind baseline: 19 | .../src/main/kotlin/com/doist/gradle/KotlinWarningBaselinePlugin.kt: (3, 30): 'TaskInGraphSpec' is deprecated. 20 | .../src/main/kotlin/com/doist/gradle/KotlinWarningBaselinePlugin.kt: (69, 72): 'TaskInGraphSpec' is deprecated. 21 | .../src/main/kotlin/com/doist/gradle/KotlinWarningBaselinePlugin.kt: (70, 72): 'TaskInGraphSpec' is deprecated. 22 | ``` 23 | 24 | ### Notes 25 | 26 | - Warnings are differentiated by plugin based on path to `kt` file, warning position in code (line, symbol) and warning message. So if you update code above warning position, it will change position of the warning, and you'll have to update warning baseline. 27 | - When collecting of warnings is running, plugin makes `clean` and temporarily disables Gradle Build Cache for Kotlin compile tasks. So running `writeKotlinWarningBaseline` or `checkKotlinWarningBaseline` leads to **full build**. 28 | 29 | ## Setup 30 | 31 | ```kotlin 32 | plugins { 33 | id("com.doist.gradle.kotlin-warning-baseline") version "1.0.0" 34 | } 35 | 36 | // Optional configuration. 37 | kotlinWarningBaseline { 38 | // Option to change name of warning baseline file. 39 | // Default: "warning-baseline.txt" 40 | baselineFileName = "..." 41 | 42 | // Option to disable new line at the end of the baseline files. 43 | // Default: true 44 | insertFinalNewline = true | false 45 | 46 | // Option to skip some Kotlin compile tasks for collecting of warnings. 47 | // Default: undefined. 48 | skipIf { task -> ... } 49 | } 50 | ``` 51 | 52 | Also see plugin page in [Gradle Plugin Portal](https://plugins.gradle.org/plugin/com.doist.gradle.kotlin-warning-baseline) 53 | 54 | ## Tasks 55 | 56 | - `writeKotlinWarningBaseline` Create or update warning baseline files for each source set in project/module. If there is no warnings in project/module, files won't be created/updated. 57 | - `checkKotlinWarningBaseline` Check that all warnings are in warning baseline files for each source set in project/module. 58 | - `removeKotlinWarningBaseline` Remove all warning baselines files in project/module. 59 | 60 | ## Release 61 | 62 | To release a new version, ensure `CHANGELOG.md` is up-to-date, and push the corresponding tag (e.g., `v1.2.3`). GitHub Actions handles the rest. 63 | 64 | ## Licence 65 | 66 | Released under the [MIT License](https://opensource.org/licenses/MIT). 67 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Supported versions 4 | 5 | At the moment, we only officially support the latest version of the project with security updates. 6 | 7 | ## Reporting a vulnerability 8 | 9 | Please report any vulnerabilities by [opening an issue]({repository-url}/issues/new) and including as many details as you can. We will prioritize security reports above other issues. 10 | 11 | We don't currently offer a bounty for OSS vulnerabilities, but if it affects [one of the eligible targets, you might qualify for a reward](https://todoist.com/help/articles/doist-bug-bounty-policy). 12 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | `kotlin-dsl` 3 | `java-gradle-plugin` 4 | id("maven-publish") 5 | id("com.gradle.plugin-publish").version("0.16.0") 6 | id("com.doist.gradle.kotlin-warning-baseline").version("+") 7 | } 8 | 9 | repositories { 10 | mavenCentral() 11 | } 12 | group = "com.doist.gradle" 13 | version = property("version") as String 14 | 15 | dependencies { 16 | compileOnly("org.jetbrains.kotlin:kotlin-gradle-plugin") 17 | } 18 | 19 | val pluginName = "KotlinWarningBaseline" 20 | 21 | gradlePlugin { 22 | plugins.register(pluginName) { 23 | id = "${project.group}.${project.name}" 24 | implementationClass = "com.doist.gradle.KotlinWarningBaselinePlugin" 25 | } 26 | isAutomatedPublishing = true 27 | } 28 | 29 | pluginBundle { 30 | website = "https://github.com/Doist/kotlin-warning-baseline" 31 | vcsUrl = "https://github.com/Doist/kotlin-warning-baseline.git" 32 | 33 | plugins.getByName(pluginName) { 34 | displayName = "Kotlin Warning Baseline Plugin" 35 | description = "This plugin adds tasks to control kotlin warnings in the project with the help of baseline or without it" 36 | tags = listOf( 37 | "analysis", 38 | "baseline", 39 | "check", 40 | "code quality", 41 | "kotlin", 42 | "verification", 43 | "warnings" 44 | ) 45 | } 46 | 47 | mavenCoordinates { 48 | groupId = project.group.toString() 49 | artifactId = project.name 50 | version = project.version.toString() 51 | } 52 | } 53 | 54 | tasks.named("wrapper") { 55 | distributionType = Wrapper.DistributionType.ALL 56 | } 57 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | kotlin.code.style=official 2 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Doist/kotlin-warning-baseline/00f685d7b6d156bf50106a722bc5880340e12630/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.2-all.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "kotlin-warning-baseline" 2 | -------------------------------------------------------------------------------- /src/main/kotlin/com/doist/gradle/KotlinWarningBaselineExtension.kt: -------------------------------------------------------------------------------- 1 | package com.doist.gradle 2 | 3 | import org.gradle.api.Task 4 | import org.gradle.api.specs.Spec 5 | 6 | open class KotlinWarningBaselineExtension { 7 | var baselineFileName: String = "warning-baseline.txt" 8 | var insertFinalNewline: Boolean = true 9 | 10 | internal val skipSpecs = mutableSetOf>() 11 | 12 | fun skipIf(spec: Spec) { 13 | skipSpecs.add(spec) 14 | } 15 | 16 | inline fun skipIf(crossinline spec: (Task) -> Boolean) { 17 | skipIf(Spec { spec(it) }) 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/kotlin/com/doist/gradle/KotlinWarningBaselinePlugin.kt: -------------------------------------------------------------------------------- 1 | package com.doist.gradle 2 | 3 | import com.doist.gradle.collector.WarningFileCollector 4 | import com.doist.gradle.convertor.PathSeparatorConvertor 5 | import com.doist.gradle.spec.TaskInGraphSpec 6 | import com.doist.gradle.task.CheckKotlinWarningBaselineTask 7 | import com.doist.gradle.task.RemoveKotlinWarningBaselineTask 8 | import com.doist.gradle.task.WriteKotlinWarningBaselineTask 9 | import org.gradle.api.GradleException 10 | import org.gradle.api.Plugin 11 | import org.gradle.api.Project 12 | import org.gradle.kotlin.dsl.create 13 | import org.gradle.kotlin.dsl.findByType 14 | import org.gradle.kotlin.dsl.withType 15 | import org.jetbrains.kotlin.gradle.dsl.KotlinProjectExtension 16 | import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet 17 | import org.jetbrains.kotlin.gradle.tasks.AbstractKotlinCompile 18 | import java.io.File 19 | 20 | class KotlinWarningBaselinePlugin : Plugin { 21 | override fun apply(target: Project) = with(target) { 22 | val extension = extensions.create("kotlinWarningBaseline") 23 | afterEvaluate { configure(extension) } 24 | } 25 | 26 | private fun Project.configure(extension: KotlinWarningBaselineExtension) { 27 | val kotlinExtension = extensions.findByType() 28 | ?: throw GradleException("Kotlin not configured in project $this.") 29 | val baselines = kotlinExtension.sourceSets.associate { 30 | val sourceSetRoot = it.findRootDirectory() 31 | sourceSetRoot to File(sourceSetRoot, extension.baselineFileName) 32 | } 33 | val pathConvertor = PathSeparatorConvertor() 34 | 35 | val kotlinTaskMap = tasks.withType>() 36 | .filter { task -> extension.skipSpecs.none { it.isSatisfiedBy(task) } } 37 | .associateWith { File(buildDir, "kotlin-warnings/${it.name}.txt") } 38 | .onEach { (task, file) -> 39 | val collector = WarningFileCollector(task, file, pathConvertor, baselines.keys) 40 | gradle.taskGraph.addTaskExecutionListener(collector) 41 | } 42 | 43 | val clean = tasks.getByName("clean") 44 | 45 | val check = tasks.create("checkKotlinWarningBaseline") { 46 | group = "verification" 47 | description = "Check that all warnings are in warning baseline files." 48 | 49 | warningFiles.set(kotlinTaskMap.values) 50 | baselineFiles.set(baselines.values) 51 | this.pathConvertor.set(pathConvertor) 52 | 53 | dependsOn(kotlinTaskMap.keys + clean) 54 | mustRunAfter(clean) 55 | } 56 | val write = tasks.create("writeKotlinWarningBaseline") { 57 | group = "verification" 58 | description = "Create or update warning baseline files for each source set." 59 | 60 | warningPostfix.set(extension.warningPostfix) 61 | warningFiles.set(kotlinTaskMap.values) 62 | baselineFiles.set(baselines.values) 63 | 64 | dependsOn(kotlinTaskMap.keys + clean) 65 | mustRunAfter(clean) 66 | } 67 | tasks.create("removeKotlinWarningBaseline") { 68 | group = "verification" 69 | description = "Remove all warning baseline files." 70 | 71 | baselineFiles.set(baselines.values) 72 | } 73 | 74 | tasks.getByName("check").dependsOn(check) 75 | 76 | kotlinTaskMap.keys.forEach { task -> 77 | task.outputs.doNotCacheIf("Task graph has ${check.name}.", TaskInGraphSpec(check)) 78 | task.outputs.doNotCacheIf("Task graph has ${write.name}.", TaskInGraphSpec(write)) 79 | } 80 | } 81 | 82 | private fun KotlinSourceSet.findRootDirectory(): File { 83 | var parent: File? = kotlin.sourceDirectories.firstOrNull()?.parentFile 84 | while (parent != null && parent.name != name) { 85 | parent = parent.parentFile 86 | } 87 | return parent ?: throw GradleException( 88 | "Can't find root directory for sources set $name in ${kotlin.sourceDirectories.asPath}" 89 | ) 90 | } 91 | 92 | private val KotlinWarningBaselineExtension.warningPostfix 93 | get() = when { 94 | insertFinalNewline -> "\n" 95 | else -> "" 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/main/kotlin/com/doist/gradle/collector/WarningFileCollector.kt: -------------------------------------------------------------------------------- 1 | package com.doist.gradle.collector 2 | 3 | import com.doist.gradle.convertor.PathSeparatorConvertor 4 | import com.doist.gradle.ext.create 5 | import org.gradle.api.Task 6 | import org.gradle.api.execution.TaskExecutionListener 7 | import org.gradle.api.logging.StandardOutputListener 8 | import org.gradle.api.tasks.TaskState 9 | import java.io.File 10 | 11 | class WarningFileCollector( 12 | private val task: Task, 13 | private val file: File, 14 | private val pathConvertor: PathSeparatorConvertor, 15 | sourceSets: Set 16 | ) : TaskExecutionListener { 17 | private val prefixSet = 18 | sourceSets.mapTo(mutableSetOf()) { "w: ${it.parent}${File.separatorChar}" } 19 | 20 | private val outputListener = StandardOutputListener { line -> 21 | for (prefix in prefixSet) { 22 | if (line.startsWith(prefix)) { 23 | file.takeIf { !it.exists() }?.create() 24 | file.appendText("${pathConvertor.toUnix(line.removePrefix(prefix))}\n") 25 | break 26 | } 27 | } 28 | } 29 | 30 | override fun beforeExecute(task: Task) { 31 | if (task == this.task) { 32 | task.logging.addStandardOutputListener(outputListener) 33 | } 34 | } 35 | 36 | override fun afterExecute(task: Task, state: TaskState) { 37 | if (task == this.task) { 38 | task.logging.removeStandardOutputListener(outputListener) 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/kotlin/com/doist/gradle/convertor/PathSeparatorConvertor.kt: -------------------------------------------------------------------------------- 1 | package com.doist.gradle.convertor 2 | 3 | import org.apache.tools.ant.taskdefs.condition.Os 4 | 5 | private const val WINDOWS_SEPARATOR = "\\\\" 6 | private const val UNIX_SEPARATOR = "/" 7 | 8 | fun PathSeparatorConvertor() = when { 9 | Os.isFamily(Os.FAMILY_WINDOWS) -> WindowsToUnixPathSeparatorConvertor() 10 | else -> KeepAsIsPathSeparatorConvertor() 11 | } 12 | 13 | interface PathSeparatorConvertor { 14 | fun toUnix(text: CharSequence): CharSequence 15 | 16 | fun toPlatform(text: CharSequence): CharSequence 17 | } 18 | 19 | private class WindowsToUnixPathSeparatorConvertor : PathSeparatorConvertor { 20 | // Finds each "\" before ".kt" if they're separated by letters/digits/underscores. 21 | // 22 | // E.g. only the first two "\" characters will be found in 23 | // "w: C:\work\Composer.kt: (1, 1): \Deprecated\ in \Java\" line. The rest are behind ".kt". 24 | private val findWindowsSeparatorsRegex = """(?<=(\w|:))?\\(?=(\w|\\)*\.kt)""".toRegex() 25 | 26 | // Finds each "/" before ".kt" if they're separated by letters/digits/underscores. 27 | private val findUnixSeparatorsRegex = """(?<=(\w|:))?/(?=(\w|/)*\.kt)""".toRegex() 28 | 29 | override fun toUnix(text: CharSequence) = 30 | text.replace(findWindowsSeparatorsRegex, UNIX_SEPARATOR) 31 | 32 | override fun toPlatform(text: CharSequence) = 33 | text.replace(findUnixSeparatorsRegex, WINDOWS_SEPARATOR) 34 | } 35 | 36 | private class KeepAsIsPathSeparatorConvertor : PathSeparatorConvertor { 37 | override fun toUnix(text: CharSequence) = text 38 | 39 | override fun toPlatform(text: CharSequence) = text 40 | } 41 | -------------------------------------------------------------------------------- /src/main/kotlin/com/doist/gradle/ext/FileExt.kt: -------------------------------------------------------------------------------- 1 | package com.doist.gradle.ext 2 | 3 | import org.gradle.api.GradleException 4 | import java.io.File 5 | 6 | fun File.create() { 7 | if (!parentFile.exists() && !parentFile.mkdirs()) { 8 | throw GradleException("Can't create parent file: $this.") 9 | } 10 | if (!createNewFile()) { 11 | throw GradleException("Can't create file: $this.") 12 | } 13 | } 14 | 15 | fun File.readWarningLines() = takeIf(File::exists) 16 | ?.readLines() 17 | ?.filterNot { it.isEmpty() || it.startsWith("#") } 18 | ?: emptyList() 19 | -------------------------------------------------------------------------------- /src/main/kotlin/com/doist/gradle/ext/IterableExt.kt: -------------------------------------------------------------------------------- 1 | package com.doist.gradle.ext 2 | 3 | import java.io.File 4 | 5 | fun Iterable.readSetOfLines(): Set = flatMapTo(mutableSetOf()) { 6 | it.takeIf(File::exists)?.readLines() ?: emptyList() 7 | } 8 | 9 | fun Iterable.filterByBaseline(baseline: File): List = filter { 10 | it.startsWith("${baseline.parentFile.name}/") 11 | } 12 | -------------------------------------------------------------------------------- /src/main/kotlin/com/doist/gradle/spec/TaskInGraphSpec.kt: -------------------------------------------------------------------------------- 1 | package com.doist.gradle.spec 2 | 3 | import org.gradle.api.Task 4 | import org.gradle.api.specs.Spec 5 | 6 | class TaskInGraphSpec(private val task: Task) : Spec { 7 | override fun isSatisfiedBy(element: Task) = element.project.gradle.taskGraph.hasTask(task) 8 | } 9 | -------------------------------------------------------------------------------- /src/main/kotlin/com/doist/gradle/task/CheckKotlinWarningBaselineTask.kt: -------------------------------------------------------------------------------- 1 | package com.doist.gradle.task 2 | 3 | import com.doist.gradle.convertor.PathSeparatorConvertor 4 | import com.doist.gradle.ext.filterByBaseline 5 | import com.doist.gradle.ext.readSetOfLines 6 | import com.doist.gradle.ext.readWarningLines 7 | import org.gradle.api.DefaultTask 8 | import org.gradle.api.GradleException 9 | import org.gradle.api.provider.ListProperty 10 | import org.gradle.api.provider.Property 11 | import org.gradle.api.tasks.Input 12 | import org.gradle.api.tasks.InputFiles 13 | import org.gradle.api.tasks.TaskAction 14 | import java.io.File 15 | 16 | abstract class CheckKotlinWarningBaselineTask : DefaultTask() { 17 | @get:InputFiles 18 | abstract val warningFiles: ListProperty 19 | 20 | @get:InputFiles 21 | abstract val baselineFiles: ListProperty 22 | 23 | @get:Input 24 | abstract val pathConvertor: Property 25 | 26 | @TaskAction 27 | fun write() { 28 | val pathConvertor = pathConvertor.get() 29 | val warningSet = warningFiles.get().readSetOfLines() 30 | val diff = baselineFiles.get().flatMap { baselineFile -> 31 | val baseline = baselineFile.readWarningLines() 32 | val current = warningSet.filterByBaseline(baselineFile) 33 | (current - baseline).map { 34 | val parentFile = baselineFile.parentFile 35 | pathConvertor.toPlatform(it).toString() 36 | .replaceFirst(parentFile.name, parentFile.absolutePath) 37 | } 38 | } 39 | if (diff.isNotEmpty()) { 40 | val text = diff.joinToString( 41 | prefix = "Found ${diff.size} warnings behind baseline:\n", 42 | separator = "\n" 43 | ) 44 | throw GradleException(text) 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/kotlin/com/doist/gradle/task/RemoveKotlinWarningBaselineTask.kt: -------------------------------------------------------------------------------- 1 | package com.doist.gradle.task 2 | 3 | import org.gradle.api.DefaultTask 4 | import org.gradle.api.provider.ListProperty 5 | import org.gradle.api.tasks.InputFiles 6 | import org.gradle.api.tasks.TaskAction 7 | import java.io.File 8 | 9 | abstract class RemoveKotlinWarningBaselineTask : DefaultTask() { 10 | @get:InputFiles 11 | abstract val baselineFiles: ListProperty 12 | 13 | @TaskAction 14 | fun remove() = baselineFiles.get().forEach(File::delete) 15 | } 16 | -------------------------------------------------------------------------------- /src/main/kotlin/com/doist/gradle/task/WriteKotlinWarningBaselineTask.kt: -------------------------------------------------------------------------------- 1 | package com.doist.gradle.task 2 | 3 | import com.doist.gradle.ext.create 4 | import com.doist.gradle.ext.filterByBaseline 5 | import com.doist.gradle.ext.readSetOfLines 6 | import org.gradle.api.DefaultTask 7 | import org.gradle.api.provider.ListProperty 8 | import org.gradle.api.provider.Property 9 | import org.gradle.api.tasks.Input 10 | import org.gradle.api.tasks.InputFiles 11 | import org.gradle.api.tasks.TaskAction 12 | import java.io.File 13 | 14 | abstract class WriteKotlinWarningBaselineTask : DefaultTask() { 15 | @get:Input 16 | abstract val warningPostfix: Property 17 | 18 | @get:InputFiles 19 | abstract val warningFiles: ListProperty 20 | 21 | @get:InputFiles 22 | abstract val baselineFiles: ListProperty 23 | 24 | @TaskAction 25 | fun write() { 26 | val postfix = warningPostfix.get() 27 | val warningSet = warningFiles.get().readSetOfLines() 28 | baselineFiles.get().forEach { file -> 29 | val warnings = warningSet.filterByBaseline(file) 30 | file.takeIf { warnings.isNotEmpty() }?.run { 31 | val text = warnings.sorted().joinToString( 32 | prefix = """ 33 | # This file was automatically generated by Kotlin Warning Baseline Plugin 34 | # and should not be edited manually. 35 | 36 | 37 | """.trimIndent(), 38 | separator = "\n", 39 | postfix = postfix 40 | ) 41 | if (!exists()) { 42 | println("create baseline file: $this") 43 | create() 44 | writeText(text) 45 | } else if (text != readText()) { 46 | println("update baseline file: $this") 47 | writeText(text) 48 | } 49 | } 50 | } 51 | } 52 | } 53 | --------------------------------------------------------------------------------