-
Notifications
You must be signed in to change notification settings - Fork 519
Expand file tree
/
Copy pathbuild.gradle.kts
More file actions
396 lines (318 loc) · 12.3 KB
/
build.gradle.kts
File metadata and controls
396 lines (318 loc) · 12.3 KB
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
@file:Suppress("UnstableApiUsage")
import nl.javadude.gradle.plugins.license.LicenseExtension
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
plugins {
id("org.openrewrite.build.language-library")
id("org.openrewrite.build.moderne-source-available-license")
id("jvm-test-suite")
id("publishing")
}
dependencies {
api(project(":rewrite-core"))
api(project(":rewrite-java"))
api(project(":rewrite-toml"))
api("org.jetbrains:annotations:latest.release")
api("com.fasterxml.jackson.core:jackson-annotations")
implementation("io.moderne:jsonrpc:latest.integration")
implementation(project(":rewrite-maven"))
compileOnly(project(":rewrite-test"))
testImplementation(project(":rewrite-test"))
testImplementation("io.moderne:jsonrpc:latest.integration")
testRuntimeOnly(project(":rewrite-java-21"))
}
tasks.withType<Javadoc>().configureEach {
(options as StandardJavadocDocletOptions).addStringOption("Xdoclint:none", "-quiet")
exclude("**/Py.java")
}
// Python-specific build tasks
val pythonDir = projectDir.resolve("rewrite")
val venvDir = pythonDir.resolve(".venv")
val isWindows = System.getProperty("os.name").lowercase().contains("windows")
val pythonExe = if (isWindows) venvDir.resolve("Scripts/python.exe") else venvDir.resolve("bin/python")
val pipExe = if (isWindows) venvDir.resolve("Scripts/pip.exe") else venvDir.resolve("bin/pip")
// Find system Python
fun findPython(): String {
val candidates = if (isWindows) {
listOf("python", "python3", "py")
} else {
listOf("python3", "python")
}
for (cmd in candidates) {
try {
val process = ProcessBuilder(cmd, "--version")
.redirectErrorStream(true)
.start()
if (process.waitFor() == 0) {
return cmd
}
} catch (e: Exception) {
// Command not found, try next
}
}
throw GradleException("Python 3 not found. Please install Python 3.10+ and ensure it's on your PATH.")
}
val pythonSetupVenv by tasks.registering(Exec::class) {
group = "python"
description = "Create Python virtual environment"
onlyIf { !venvDir.exists() }
workingDir = pythonDir
commandLine(findPython(), "-m", "venv", ".venv")
doFirst {
logger.lifecycle("Creating Python virtual environment in ${venvDir}")
}
}
val pythonUpgradePip by tasks.registering(Exec::class) {
group = "python"
description = "Upgrade pip in virtual environment"
dependsOn(pythonSetupVenv)
onlyIf { venvDir.exists() }
workingDir = pythonDir
commandLine(pythonExe.absolutePath, "-m", "pip", "install", "--upgrade", "pip")
doFirst {
logger.lifecycle("Upgrading pip in virtual environment")
}
}
val pythonInstall by tasks.registering(Exec::class) {
group = "python"
description = "Install Python package in development mode"
dependsOn(pythonUpgradePip)
workingDir = pythonDir
commandLine(pipExe.absolutePath, "install", "-e", ".[dev]")
// Re-run if pyproject.toml changes
inputs.file(pythonDir.resolve("pyproject.toml"))
doFirst {
logger.lifecycle("Installing Python package with pip")
}
}
testing {
suites {
register<JvmTestSuite>("integTest") {
useJUnitJupiter()
dependencies {
implementation(project())
implementation(project(":rewrite-java-21"))
implementation(project(":rewrite-test"))
implementation("org.assertj:assertj-core:latest.release")
implementation("org.junit.platform:junit-platform-suite-api")
runtimeOnly("org.junit.platform:junit-platform-suite-engine")
}
}
register<JvmTestSuite>("py2CompatibilityTest") {
useJUnitJupiter()
dependencies {
implementation(project())
implementation(project(":rewrite-test"))
implementation(project(":rewrite-java-21"))
implementation("org.assertj:assertj-core:latest.release")
implementation("io.moderne:jsonrpc:latest.integration")
}
targets {
all {
testTask.configure {
// Include the main test classes so common tests run with the Python 2 parser
testClassesDirs += sourceSets["test"].output.classesDirs
classpath += sourceSets["test"].runtimeClasspath
systemProperty("rewrite.python.version", "2")
useJUnitPlatform {
excludeTags("python3")
}
shouldRunAfter(tasks.named("test"))
}
}
}
}
}
}
val pytestTest by tasks.registering(Exec::class) {
group = "verification"
description = "Run Python pytest tests"
dependsOn(pythonInstall)
workingDir = pythonDir
commandLine(pythonExe.absolutePath, "-m", "pytest", "tests/", "-v")
inputs.dir(pythonDir.resolve("src"))
inputs.dir(pythonDir.resolve("tests"))
inputs.file(pythonDir.resolve("pyproject.toml"))
}
tasks.named("check") {
dependsOn(testing.suites.named("py2CompatibilityTest"))
dependsOn(pytestTest)
}
// Run tests serially to avoid issues with concurrent Python RPC processes
// The Python RPC server uses ThreadLocal, but test state can interfere
// when multiple tests run rapidly on the same thread
tasks.withType<Test> {
// Ensure Python venv is set up before running tests
dependsOn(pythonInstall)
maxParallelForks = 1
// Add timeout to identify hanging tests - tests that hang will fail with timeout
systemProperty("junit.jupiter.execution.timeout.default", "30s")
// Show test names as they run
testLogging {
events("started", "passed", "failed", "skipped")
showStandardStreams = true
}
}
// Note: Python IDE support is configured via the standalone module at:
// .idea/modules/rewrite-python-src/rewrite-python-src.iml
// This is separate from Gradle because IntelliJ's Gradle integration doesn't support Python source roots.
// ============================================
// Version Resource (for RPC version pinning)
// ============================================
// Generate a PEP 440 compliant version for CI builds
// Snapshots use .dev suffix: 8.71.0.dev20260112145318
// Releases use clean version: 8.71.0
val pythonVersion: String = if (System.getenv("CI") != null) {
project.version.toString().replace(
"-SNAPSHOT",
".dev${LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"))}"
)
} else {
project.version.toString().replace("-SNAPSHOT", ".dev0")
}
// Write version.txt resource so PythonRewriteRpc can pin the pip package version
val generateVersionTxt by tasks.registering {
group = "python"
description = "Generate META-INF/version.txt for RPC version pinning"
val versionTxt = file("src/main/resources/META-INF/version.txt")
inputs.property("version", pythonVersion)
outputs.file(versionTxt)
doLast {
versionTxt.parentFile.mkdirs()
versionTxt.writeText(pythonVersion)
}
}
listOf("sourcesJar", "processResources", "licenseMain", "assemble").forEach {
tasks.named(it) {
dependsOn(generateVersionTxt)
}
}
// ============================================
// Python Publishing Tasks (PyPI)
// ============================================
// Task to update version in pyproject.toml
val pythonUpdateVersion by tasks.registering {
group = "python"
description = "Update version in pyproject.toml"
dependsOn(pythonSetupVenv)
val pyprojectFile = pythonDir.resolve("pyproject.toml")
inputs.property("version", pythonVersion)
outputs.file(pyprojectFile)
doLast {
val content = pyprojectFile.readText()
val updated = content.replace(
Regex("""version\s*=\s*"[^"]*""""),
"""version = "$pythonVersion""""
)
pyprojectFile.writeText(updated)
logger.lifecycle("Updated pyproject.toml version to $pythonVersion")
}
}
// Task to install build dependencies
val pythonInstallBuildDeps by tasks.registering(Exec::class) {
group = "python"
description = "Install Python build and publish dependencies"
dependsOn(pythonUpgradePip)
workingDir = pythonDir
commandLine(pipExe.absolutePath, "install", "build>=1.0.0", "twine>=5.0.0")
doFirst {
logger.lifecycle("Installing Python build dependencies (build, twine)")
}
}
// Task to build Python distribution (wheel + sdist)
val pythonBuild by tasks.registering(Exec::class) {
group = "python"
description = "Build Python distribution packages"
dependsOn(pythonUpdateVersion, pythonInstallBuildDeps)
workingDir = pythonDir
commandLine(pythonExe.absolutePath, "-m", "build")
inputs.dir(pythonDir.resolve("src"))
inputs.file(pythonDir.resolve("pyproject.toml"))
outputs.dir(pythonDir.resolve("dist"))
doFirst {
// Clean previous builds
pythonDir.resolve("dist").deleteRecursively()
logger.lifecycle("Building Python distribution packages")
}
}
// Task to create .pypirc for authentication
val setupPypirc by tasks.registering {
group = "python"
description = "Create .pypirc file for PyPI authentication"
doLast {
if (project.hasProperty("pypiToken")) {
val pypirc = pythonDir.resolve(".pypirc")
pypirc.writeText("""
[pypi]
username = __token__
password = ${project.property("pypiToken")}
""".trimIndent())
logger.lifecycle("Created .pypirc for PyPI authentication")
} else {
logger.warn("No pypiToken property found, skipping .pypirc creation")
}
}
}
// Task to publish to PyPI
val pythonPublish by tasks.registering(Exec::class) {
group = "python"
description = "Publish Python package to PyPI"
dependsOn(pythonBuild, setupPypirc)
workingDir = pythonDir
commandLine(
pythonExe.absolutePath, "-m", "twine", "upload",
"--config-file", ".pypirc",
"dist/*"
)
doFirst {
logger.lifecycle("Publishing Python package to PyPI (version: $pythonVersion)")
}
}
// Wire into the main publish task
tasks.named("publish") {
dependsOn(pythonPublish)
}
// ============================================
// Python Test Support Tasks
// ============================================
// Task to generate classpath file for Java RPC server testing
val generateTestClasspath by tasks.registering {
group = "python"
description = "Generate classpath file for Java RPC server (used by Python tests)"
val outputFile = pythonDir.resolve("test-classpath.txt")
outputs.file(outputFile)
// Depend on jar tasks to ensure jars exist
dependsOn(tasks.named("testClasses"))
dependsOn(tasks.named("jar"))
doLast {
// Combine compile and test runtime classpaths to get all dependencies
val classpath = (
configurations.getByName("runtimeClasspath").files +
configurations.getByName("testRuntimeClasspath").files +
tasks.named("compileJava").get().outputs.files +
tasks.named("processResources").get().outputs.files
).distinctBy { it.absolutePath }
.joinToString(File.pathSeparator) { it.absolutePath }
outputFile.writeText(classpath)
logger.lifecycle("Generated test classpath to ${outputFile.absolutePath}")
}
}
// Task to print test classpath to stdout (useful for setting env vars)
val printTestClasspath by tasks.registering {
group = "python"
description = "Print the test classpath (for use with REWRITE_PYTHON_CLASSPATH env var)"
dependsOn(tasks.named("testClasses"))
doLast {
val classpath = (
configurations.getByName("runtimeClasspath").files +
configurations.getByName("testRuntimeClasspath").files +
tasks.named("compileJava").get().outputs.files +
tasks.named("processResources").get().outputs.files
).distinctBy { it.absolutePath }
.joinToString(File.pathSeparator) { it.absolutePath }
println(classpath)
}
}
extensions.configure<LicenseExtension> {
exclude("**/version.txt")
}