-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathbuild.gradle.kts
389 lines (337 loc) · 14.4 KB
/
build.gradle.kts
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
import com.jetbrains.rd.gradle.dependencies.kotlinVersion
import groovy.json.JsonBuilder
import groovy.json.JsonSlurper
import okhttp3.MultipartBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import org.gradle.api.tasks.testing.logging.TestExceptionFormat
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import java.util.*
import kotlin.time.Duration
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.seconds
import kotlin.time.toJavaDuration
buildscript {
dependencies {
classpath("com.squareup.okhttp3:okhttp:4.12.0")
}
project.extra.apply {
val repoRoot = rootProject.projectDir
set("repoRoot", repoRoot)
set("cppRoot", File(repoRoot, "rd-cpp"))
set("ktRoot", File(repoRoot, "rd-kt"))
set("csRoot", File(repoRoot, "rd-net"))
}
}
plugins {
base
id("me.filippov.gradle.jvm.wrapper") version "0.14.0"
}
allprojects {
plugins.apply("maven-publish")
configurations.all {
resolutionStrategy {
force("org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion")
force("org.jetbrains.kotlin:kotlin-reflect:$kotlinVersion")
force("org.jetbrains.kotlin:kotlin-runtime:$kotlinVersion")
force("org.jetbrains.kotlin:kotlin-stdlib-js:$kotlinVersion")
}
}
repositories {
mavenCentral()
}
tasks {
withType<Test> {
testLogging {
showStandardStreams = true
exceptionFormat = TestExceptionFormat.FULL
}
}
withType<KotlinCompile> {
compilerOptions {
jvmTarget.set(JvmTarget.JVM_17)
}
}
withType<JavaCompile> {
targetCompatibility = "17"
}
}
}
val clean by tasks.getting(Delete::class) {
delete(rootProject.buildDir)
}
if (System.getenv("TEAMCITY_VERSION") == null) {
version = "SNAPSHOT"
}
tasks {
val nuGetTargetDir = buildDir.resolve("artifacts").resolve("nuget")
val publishingGroup = "publishing"
val dotNetBuild by registering(Exec::class) {
group = publishingGroup
executable = projectDir.resolve("rd-net").resolve("dotnet.cmd").canonicalPath
args("build", "/p:Configuration=Release", "/p:PackageVersion=$version", projectDir.resolve("rd-net").resolve("Rd.sln").canonicalPath)
environment("DOTNET_NOLOGO", "1")
environment("DOTNET_CLI_TELEMETRY_OPTOUT", "1")
}
val packNuGetLifetimes by registering(Exec::class) {
group = publishingGroup
dependsOn(dotNetBuild)
executable = project.projectDir.resolve("rd-net").resolve("dotnet.cmd").canonicalPath
args("pack", "--include-symbols", "/p:Configuration=Release", "/p:PackageVersion=$version", projectDir.resolve("rd-net").resolve("Lifetimes").resolve("Lifetimes.csproj").canonicalPath)
environment("DOTNET_NOLOGO", "1")
environment("DOTNET_CLI_TELEMETRY_OPTOUT", "1")
}
val copyNuGetLifetimes by registering(Copy::class) {
group = publishingGroup
dependsOn(packNuGetLifetimes)
from("${projectDir.resolve("rd-net").resolve("Lifetimes").resolve("bin").resolve("Release").canonicalPath}${File.separator}")
include("*.nupkg")
include("*.snupkg")
into(buildDir.resolve("artifacts").resolve("nuget"))
}
val packDotNetRdFramework by registering(Exec::class) {
group = publishingGroup
dependsOn(dotNetBuild)
executable = project.projectDir.resolve("rd-net").resolve("dotnet.cmd").canonicalPath
args("pack", "--include-symbols", "/p:Configuration=Release", "/p:PackageVersion=$version", projectDir.resolve("rd-net").resolve("RdFramework").resolve("RdFramework.csproj").canonicalPath)
environment("DOTNET_NOLOGO", "1")
environment("DOTNET_CLI_TELEMETRY_OPTOUT", "1")
}
val copyNuGetRdFramework by registering(Copy::class) {
group = publishingGroup
dependsOn(packDotNetRdFramework)
from("${projectDir.resolve("rd-net").resolve("RdFramework").resolve("bin").resolve("Release").canonicalPath}${File.separator}")
include("*.nupkg")
include("*.snupkg")
into(buildDir.resolve("artifacts").resolve("nuget"))
}
val packDotNetRdFrameworkReflection by registering(Exec::class) {
group = publishingGroup
dependsOn(dotNetBuild)
executable = project.projectDir.resolve("rd-net").resolve("dotnet.cmd").canonicalPath
args("pack", "--include-symbols", "/p:Configuration=Release", "/p:PackageVersion=$version", projectDir.resolve("rd-net").resolve("RdFramework.Reflection").resolve("RdFramework.Reflection.csproj").canonicalPath)
environment("DOTNET_NOLOGO", "1")
environment("DOTNET_CLI_TELEMETRY_OPTOUT", "1")
}
val copyNuGetRdFrameworkReflection by registering(Copy::class) {
group = publishingGroup
dependsOn(packDotNetRdFrameworkReflection)
from("${projectDir.resolve("rd-net").resolve("RdFramework.Reflection").resolve("bin").resolve("Release").canonicalPath}${File.separator}")
include("*.nupkg")
include("*.snupkg")
into(buildDir.resolve("artifacts").resolve("nuget"))
}
val cleanupArtifacts by registering {
group = publishingGroup
doLast {
if (nuGetTargetDir.exists()) {
nuGetTargetDir.deleteRecursively()
}
}
}
val createNuGetPackages by registering {
group = publishingGroup
dependsOn(cleanupArtifacts, copyNuGetLifetimes, copyNuGetRdFramework, copyNuGetRdFrameworkReflection)
}
fun enableNuGetPublishing(url: String, apiKey: String) {
val args = mutableListOf<Any>(
project.projectDir.resolve("rd-net").resolve("dotnet.cmd").canonicalPath,
"nuget",
"push",
"--source", url,
"--api-key", apiKey
)
for (file in nuGetTargetDir.listFiles()?.filter { it.extension == "nupkg" } ?: emptyList()) {
exec {
val argsForCurrentFile = (args + file).toTypedArray()
commandLine(*argsForCurrentFile)
}
}
}
val publishNuGet by registering {
group = publishingGroup
dependsOn(createNuGetPackages)
val deployToNuGetOrg = rootProject.extra["deployNuGetToNuGetOrg"].toString().toBoolean()
val deployToInternal = rootProject.extra["deployNuGetToInternal"].toString().toBoolean()
doLast {
if (deployToNuGetOrg) {
val nuGetOrgApiKey = rootProject.extra["nuGetOrgApiKey"].toString()
enableNuGetPublishing("https://api.nuget.org/v3/index.json", nuGetOrgApiKey)
}
if (deployToInternal) {
val internalFeedUrl = rootProject.extra["internalNuGetFeedUrl"].toString()
val internalFeedApiKey = rootProject.extra["internalDeployKey"].toString()
enableNuGetPublishing(internalFeedUrl, internalFeedApiKey)
}
}
}
val packSonatypeCentralBundle by registering(Zip::class) {
group = publishingGroup
dependsOn(
":rd-core:publishAllPublicationsToArtifactsRepository",
":rd-framework:publishAllPublicationsToArtifactsRepository",
":rd-gen:publishAllPublicationsToArtifactsRepository",
":rd-swing:publishAllPublicationsToArtifactsRepository",
":rd-text:publishAllPublicationsToArtifactsRepository"
)
from(layout.buildDirectory.dir("artifacts/maven"))
archiveFileName.set("bundle.zip")
destinationDirectory.set(layout.buildDirectory)
}
fun base64Auth(userName: String, accessToken: String): String =
Base64.getEncoder().encode("$userName:$accessToken".toByteArray()).toString(Charsets.UTF_8)
fun deployToCentralPortal(
bundleFile: File,
uriBase: String,
isUserManaged: Boolean,
deploymentName: String,
userName: String,
accessToken: String
): String {
// https://central.sonatype.org/publish/publish-portal-api/#uploading-a-deployment-bundle
val publishingType = if (isUserManaged) "USER_MANAGED" else "AUTOMATIC"
val uri = uriBase.trimEnd('/') + "/api/v1/publisher/upload?name=$deploymentName&publishingType=$publishingType"
val base64Auth = base64Auth(userName, accessToken)
println("Sending request to $uri...")
val client = OkHttpClient()
val request = Request.Builder()
.url(uri)
.header("Authorization", "Bearer $base64Auth")
.post(
MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("bundle", bundleFile.name, bundleFile.asRequestBody())
.build()
)
.build()
val response = client.newCall(request).execute()
val statusCode = response.code
println("Upload status code: $statusCode")
val uploadResult = response.body!!.string()
println("Upload result: $uploadResult")
if (statusCode == 201) {
return uploadResult
} else {
error("Upload error to Central repository. Status code $statusCode.")
}
}
fun waitForUploadToSucceed(
uriBase: String,
deploymentId: String,
isUserManaged: Boolean,
userName: String,
accessToken: String,
maxTimeout: Duration,
minTimeBetweenAttempts: Duration
) {
val uri = uriBase.trimEnd('/') + "/api/v1/publisher/status?id=$deploymentId"
val base64Auth = base64Auth(userName, accessToken)
var timeSpent = Duration.ZERO
var attemptNumber = 1
var terminatingState = false
println("Polling for deployment status for $maxTimeout: $uri")
while (timeSpent < maxTimeout) {
val remainingTime = maxTimeout - timeSpent
println("Polling attempt ${attemptNumber++}, remaining time ${remainingTime}.")
val client = OkHttpClient().newBuilder()
.callTimeout(remainingTime.toJavaDuration())
.build()
val beforeMs = System.currentTimeMillis()
try {
val request = Request.Builder()
.url(uri)
.header("Authorization", "Bearer $base64Auth")
.post("".toRequestBody())
.build()
val response = client.newCall(request).execute()
val code = response.code
if (code != 200) {
error("Response code $code: ${response.body?.string()}")
}
val jsonResult = JsonSlurper().parse(response.body?.bytes() ?: error("Empty response body.")) as Map<*, *>
val state = jsonResult["deploymentState"]
println("Current state: $state.")
when(state) {
"PENDING", "VALIDATING", "PUBLISHING" -> {}
"VALIDATED" -> {
terminatingState = true
if (isUserManaged) {
println("Validated successfully.")
return
}
error("State error: deployment is not user managed, but signals it requires a UI interaction.")
}
"PUBLISHED" -> {
terminatingState = true
if (!isUserManaged) {
println("Published successfully.")
return
}
error("State error: deployment is user managed, but signals it has been published.")
}
"FAILED" -> {
terminatingState = true
// The documentation provides no type information for the errors field, so we have to treat
// them as opaque.
val errors = jsonResult["errors"]
val errorsAsString = JsonBuilder(errors).toPrettyString()
error("Deployment failed. Errors: $errorsAsString")
}
else -> logger.warn("Unknown deployment state: $state")
}
} catch (e: Exception) {
if (terminatingState) {
throw e
}
logger.warn("Error during HTTP request: ${e.message}")
} finally {
val afterMs = System.currentTimeMillis()
var attemptTime = (afterMs - beforeMs).coerceAtLeast(0L).milliseconds
if (attemptTime < minTimeBetweenAttempts) {
val sleepTime = minTimeBetweenAttempts - attemptTime
Thread.sleep(sleepTime.inWholeMilliseconds)
attemptTime = minTimeBetweenAttempts
}
timeSpent += attemptTime
}
}
}
val publishMavenToCentralPortal by registering {
group = publishingGroup
dependsOn(packSonatypeCentralBundle)
doLast {
val uriBase = rootProject.extra["centralPortalUrl"] as String
val userName = rootProject.extra["centralPortalUserName"] as String
val accessToken = rootProject.extra["centralPortalToken"] as String
val isUserManaged = false
val deploymentId = deployToCentralPortal(
bundleFile = packSonatypeCentralBundle.get().archiveFile.get().asFile,
uriBase,
isUserManaged,
deploymentName = "rd-$version",
userName,
accessToken
)
waitForUploadToSucceed(
uriBase,
deploymentId,
isUserManaged,
userName,
accessToken,
maxTimeout = 60.minutes,
minTimeBetweenAttempts = 5.seconds
)
}
}
named("publish") {
dependsOn(publishNuGet)
val deployToCentral = rootProject.extra["deployMavenToCentralPortal"].toString().toBoolean()
if (deployToCentral) {
dependsOn(publishMavenToCentralPortal)
}
}
}