forked from smithy-lang/smithy-rs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CodegenTestCommon.kt
266 lines (240 loc) · 9.14 KB
/
CodegenTestCommon.kt
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
import org.gradle.api.Project
import org.gradle.api.tasks.Exec
import org.gradle.kotlin.dsl.extra
import org.gradle.kotlin.dsl.register
import java.io.File
/**
* This file contains common functionality shared across the build scripts for the
* `codegen-client-test` and `codegen-server-test` modules.
*/
data class CodegenTest(
val service: String,
val module: String,
val extraConfig: String? = null,
val imports: List<String> = emptyList(),
)
fun generateImports(imports: List<String>): String = if (imports.isEmpty()) {
""
} else {
"\"imports\": [${imports.map { "\"$it\"" }.joinToString(", ")}],"
}
private fun generateSmithyBuild(projectDir: String, pluginName: String, tests: List<CodegenTest>): String {
val projections = tests.joinToString(",\n") {
"""
"${it.module}": {
${generateImports(it.imports)}
"plugins": {
"$pluginName": {
"runtimeConfig": {
"relativePath": "$projectDir/rust-runtime"
},
"service": "${it.service}",
"module": "${it.module}",
"moduleVersion": "0.0.1",
"moduleDescription": "test",
"moduleAuthors": ["protocoltest@example.com"]
${it.extraConfig ?: ""}
}
}
}
""".trimIndent()
}
return """
{
"version": "1.0",
"projections": {
$projections
}
}
""".trimIndent()
}
enum class Cargo(val toString: String) {
CHECK("cargoCheck"),
TEST("cargoTest"),
DOCS("cargoDoc"),
CLIPPY("cargoClippy"),
}
private fun generateCargoWorkspace(pluginName: String, tests: List<CodegenTest>) =
"""
[workspace]
members = [
${tests.joinToString(",") { "\"${it.module}/$pluginName\"" }}
]
""".trimIndent()
/**
* Filter the service integration tests for which to generate Rust crates in [allTests] using the given [properties].
*/
private fun codegenTests(properties: PropertyRetriever, allTests: List<CodegenTest>): List<CodegenTest> {
val modulesOverride = properties.get("modules")?.split(",")?.map { it.trim() }
val ret = if (modulesOverride != null) {
println("modulesOverride: $modulesOverride")
allTests.filter { modulesOverride.contains(it.module) }
} else {
allTests
}
require(ret.isNotEmpty()) {
"None of the provided module overrides (`$modulesOverride`) are valid test services (`${allTests.map {
it.module
}}`)"
}
return ret
}
val AllCargoCommands = listOf(Cargo.CHECK, Cargo.TEST, Cargo.CLIPPY, Cargo.DOCS)
/**
* Filter the Cargo commands to be run on the generated Rust crates using the given [properties].
* The list of Cargo commands that is run by default is defined in [AllCargoCommands].
*/
fun cargoCommands(properties: PropertyRetriever): List<Cargo> {
val cargoCommandsOverride = properties.get("cargoCommands")?.split(",")?.map { it.trim() }?.map {
when (it) {
"check" -> Cargo.CHECK
"test" -> Cargo.TEST
"doc" -> Cargo.DOCS
"clippy" -> Cargo.CLIPPY
else -> throw IllegalArgumentException("Unexpected Cargo command `$it` (valid commands are `check`, `test`, `doc`, `clippy`)")
}
}
val ret = if (cargoCommandsOverride != null) {
println("cargoCommandsOverride: $cargoCommandsOverride")
AllCargoCommands.filter { cargoCommandsOverride.contains(it) }
} else {
AllCargoCommands
}
require(ret.isNotEmpty()) {
"None of the provided cargo commands (`$cargoCommandsOverride`) are valid cargo commands (`${AllCargoCommands.map {
it.toString
}}`)"
}
return ret
}
fun Project.registerGenerateSmithyBuildTask(
rootProject: Project,
pluginName: String,
allCodegenTests: List<CodegenTest>,
) {
val properties = PropertyRetriever(rootProject, this)
this.tasks.register("generateSmithyBuild") {
description = "generate smithy-build.json"
outputs.file(project.projectDir.resolve("smithy-build.json"))
allCodegenTests.flatMap { it.imports }.forEach { inputs.file(project.projectDir.resolve(it)) }
doFirst {
project.projectDir.resolve("smithy-build.json")
.writeText(
generateSmithyBuild(
rootProject.projectDir.absolutePath,
pluginName,
codegenTests(properties, allCodegenTests),
),
)
// If this is a rebuild, cache all the hashes of the generated Rust files. These are later used by the
// `modifyMtime` task.
project.extra[previousBuildHashesKey] = project.buildDir.walk()
.filter { it.isFile }
.map {
getChecksumForFile(it) to it.lastModified()
}
.toMap()
}
}
}
fun Project.registerGenerateCargoWorkspaceTask(
rootProject: Project,
pluginName: String,
allCodegenTests: List<CodegenTest>,
workingDirUnderBuildDir: String,
) {
val properties = PropertyRetriever(rootProject, this)
project.tasks.register("generateCargoWorkspace") {
description = "generate Cargo.toml workspace file"
doFirst {
project.buildDir.resolve("$workingDirUnderBuildDir/Cargo.toml")
.writeText(generateCargoWorkspace(pluginName, codegenTests(properties, allCodegenTests)))
}
}
}
fun Project.registerGenerateCargoConfigTomlTask(
outputDir: File,
) {
this.tasks.register("generateCargoConfigToml") {
description = "generate `.cargo/config.toml`"
doFirst {
outputDir.resolve(".cargo").mkdir()
outputDir.resolve(".cargo/config.toml")
.writeText(
"""
[build]
rustflags = ["--deny", "warnings"]
""".trimIndent(),
)
}
}
}
const val previousBuildHashesKey = "previousBuildHashes"
fun Project.registerModifyMtimeTask() {
// Cargo uses `mtime` (among other factors) to determine whether a compilation unit needs a rebuild. While developing,
// it is likely that only a small number of the generated crate files are modified across rebuilds. This task compares
// the hashes of the newly generated files with the (previously cached) old ones, and restores their `mtime`s if the
// hashes coincide.
// Debugging tip: it is useful to run with `CARGO_LOG=cargo::core::compiler::fingerprint=trace` to learn why Cargo
// determines a compilation unit needs a rebuild.
// For more information see https://github.com/awslabs/smithy-rs/issues/1412.
this.tasks.register("modifyMtime") {
description = "modify Rust files' `mtime` if the contents did not change"
dependsOn("generateSmithyBuild")
doFirst {
if (!project.extra.has(previousBuildHashesKey)) {
println("No hashes from a previous build exist because `generateSmithyBuild` is up to date, skipping `mtime` fixups")
} else {
@Suppress("UNCHECKED_CAST")
val previousBuildHashes: Map<String, Long> = project.extra[previousBuildHashesKey] as Map<String, Long>
project.buildDir.walk()
.filter { it.isFile }
.map {
getChecksumForFile(it) to it
}
.forEach { (currentHash, currentFile) ->
previousBuildHashes[currentHash]?.also { oldMtime ->
println("Setting `mtime` of $currentFile back to `$oldMtime` because its hash `$currentHash` remained unchanged after a rebuild.")
currentFile.setLastModified(oldMtime)
}
}
}
}
}
}
fun Project.registerCargoCommandsTasks(
outputDir: File,
defaultRustDocFlags: String,
) {
val dependentTasks =
listOfNotNull(
"assemble",
"generateCargoConfigToml",
this.tasks.findByName("modifyMtime")?.let { "modifyMtime" },
)
this.tasks.register<Exec>(Cargo.CHECK.toString) {
dependsOn(dependentTasks)
workingDir(outputDir)
commandLine("cargo", "check", "--lib", "--tests", "--benches", "--all-features")
}
this.tasks.register<Exec>(Cargo.TEST.toString) {
dependsOn(dependentTasks)
workingDir(outputDir)
commandLine("cargo", "test", "--all-features")
}
this.tasks.register<Exec>(Cargo.DOCS.toString) {
dependsOn(dependentTasks)
workingDir(outputDir)
environment("RUSTDOCFLAGS", defaultRustDocFlags)
commandLine("cargo", "doc", "--no-deps", "--document-private-items")
}
this.tasks.register<Exec>(Cargo.CLIPPY.toString) {
dependsOn(dependentTasks)
workingDir(outputDir)
commandLine("cargo", "clippy")
}
}