代码格式化插件,包含各种语言
2 配置
3.1 在根目录gradle.kts中配置插件及使用参数
1
2
3
4
5
| plugins {
id 'com.android.application'
...
id("com.diffplug.spotless") version "6.15.0"
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
| allprojects {
// spotless 参数配置
apply(plugin = "com.diffplug.spotless")
configure<com.diffplug.gradle.spotless.SpotlessExtension> {
// kotlin 配置
kotlin {
target("**/*.kt")
targetExclude("$buildDir/**/*.kt", "spotless/*")
ktlint("0.48.2")
.userData(mapOf("android" to "true"))
.editorConfigOverride(
mapOf(
"ij_kotlin_allow_trailing_comma" to "false",
"ij_kotlin_allow_trailing_comma_on_call_site" to "false"
)
)
licenseHeaderFile(rootProject.file("spotless/copyright.kt"))
}
// java 配置
java {
target("**/*.java")
targetExclude("$buildDir/**/*.java", "spotless/*")
googleJavaFormat("1.8").aosp()
licenseHeaderFile(rootProject.file("spotless/copyright.java"))
}
// kts 配置
kotlinGradle {
target("**/*.kts")
targetExclude("$buildDir/**/*.kts", "spotless/*")
ktlint("0.48.2")
.editorConfigOverride(
mapOf(
"ij_kotlin_allow_trailing_comma" to "false",
"ij_kotlin_allow_trailing_comma_on_call_site" to "false"
)
)
licenseHeaderFile(rootProject.file("spotless/copyright.kts"), "(^(?![\\/ ]\\*).*$)")
}
// xml 配置
format("xml") {
target("**/*.xml")
targetExclude("**/build/**/*.xml", "spotless/*")
licenseHeaderFile(rootProject.file("spotless/copyright.xml"), "(<[^!?])")
}
}
// Configure Android projects
pluginManager.withPlugin("com.android.application") {
configureAndroidProject()
}
pluginManager.withPlugin("com.android.library") {
configureAndroidProject()
}
pluginManager.withPlugin("com.android.test") {
configureAndroidProject()
}
}
fun Project.configureAndroidProject() {
extensions.configure<com.android.build.gradle.BaseExtension> {
tasks.getByPath("preBuild").dependsOn("spotlessApply")
}
}
|
头文件配置
在根目录创建spotless目录,并放置各种语言的头文件
示例
copyright.java
1
2
3
4
5
| /*
* Copyright $YEAR Healer Corporation.
*/
|
copyright.kt
1
2
3
4
5
| /*
* Copyright $YEAR Healer Corporation.
*/
|
copyright.kts
1
2
3
4
5
| /*
* Copyright $YEAR Healer Corporation.
*/
|
copyright.xml
1
2
3
4
5
6
| <?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright $YEAR Healer Corporation.
-->
|
3.3. 运行检查代码格式错误
1
| ./gradlew spotlessCheck
|
3.4. 自动格式化代码
1
| ./gradlew spotlessApply
|
参考github: https://github.com/xuniyishifanchen/Wy/blob/master/build.gradle.kts