-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.gradle.kts
397 lines (361 loc) · 15.2 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
390
391
392
393
394
395
/*
* Copyright 2023-2024 onseok
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("DSL_SCOPE_VIOLATION")
import com.android.build.gradle.LibraryExtension
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.runBlocking
import org.gradle.nativeplatform.platform.internal.DefaultNativePlatform
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import java.net.HttpURLConnection
import java.net.URL
import java.util.Properties
import java.util.concurrent.Executors
plugins {
// alias(libs.plugins.jetbrains.compose).apply(false)
alias(libs.plugins.compose.compiler).apply(false)
// id(libs.plugins.android.application.get().pluginId).apply(false)
// id(libs.plugins.android.library.get().pluginId).apply(false)
// id(libs.plugins.kotlin.multiplatform.get().pluginId).apply(false)
alias(libs.plugins.android.application).apply(false)
alias(libs.plugins.android.library).apply(false)
alias(libs.plugins.kotlin.multiplatform).apply(false)
alias(libs.plugins.dokka)
id("maven-publish")
}
allprojects {
configurations.all {
resolutionStrategy {
/*eachDependency {
if (requested.group == "org.jetbrains.kotlin") {
useVersion(libs.versions.kotlin.get())
}else if (requested.group.startsWith("org.jetbrains.compose")||requested.group.startsWith("androidx.compose")) {
useVersion(libs.versions.compose.plugin.get())
} else if (requested.group.startsWith("org.jetbrains.kotlinx") && requested.name.startsWith("kotlinx-coroutines")) {
useVersion(libs.versions.coroutines.bom.get())
}
}*/
// preferProjectModules的作用是优先使用项目中的模块,而不是从远程仓库中下载
// preferProjectModules()
/* // cacheDynamicVersionsFor的作用是缓存动态版本,避免每次构建都去下载
cacheDynamicVersionsFor(0, TimeUnit.SECONDS)
// cacheChangingModulesFor的作用是缓存变化的模块,避免每次构建都去下载
cacheChangingModulesFor(0, TimeUnit.SECONDS)
// failOnVersionConflict的作用是当版本冲突时,抛出异常
// failOnVersionConflict()*/
}
}
tasks.withType<KotlinCompile>().all {
compilerOptions {
freeCompilerArgs.add("-Xopt-in=kotlin.RequiresOptIn")
freeCompilerArgs.add("-Xexpect-actual-classes")
}
}
}
val javaVersion = JavaVersion.toVersion(libs.versions.jvmTarget.get())
check(JavaVersion.current().isCompatibleWith(javaVersion)) {
"This project needs to be run with Java ${javaVersion.getMajorVersion()} or higher (found: ${JavaVersion.current()})."
}
buildscript {
dependencies {
val dokkaVersion = libs.versions.dokka.get()
classpath("org.jetbrains.dokka:dokka-base:$dokkaVersion")
classpath("org.jetbrains.compose:compose-gradle-plugin:${libs.versions.compose.plugin.get()}")
}
}
allprojects {
val properties = Properties().apply {
runCatching { rootProject.file("local.properties") }
.getOrNull()
.takeIf { it?.exists() ?: false }
?.reader()
?.use(::load)
}
val environment: Map<String, String?> = System.getenv()
val myExtra = mutableMapOf<String, Any>()
myExtra["githubToken"] = properties["github.token"] as? String
?: environment["GITHUB_TOKEN"] ?: ""
val libs = rootDir.resolve("gradle/libs.versions.toml")
val map = hashMapOf<String, String>()
libs.useLines {
it.forEach { line ->
if (line.contains("=") && line.replace(" ", "").startsWith("#").not()) {
val (key, value) = line.split("=")
map[key.replace(" ", "").removeSurrounding("\"")] =
value.replace(" ", "").removeSurrounding("\"")
}
}
}
val jvmTarget = map["jvmTarget"] ?: "11"
val repo = rootDir.name
val rootProjectName = rootProject.name.lowercase()
.replace("compose-", "")
.replace("compose_", "")
.replace("compose", "")
val mavenAuthor = "vickyleu"
val mavenGroup = "com.$mavenAuthor.$rootProjectName"
val mVersion = "1.0.2"
if (project.subprojects.isNotEmpty()) return@allprojects
val currentName = project.name
.replace("$rootProjectName-", "")
.replace("${rootProjectName}_", "")
if (rootProject.name == currentName) {
return@allprojects
}
if (project.name.contains("composeApp") || project.name.contains("sample") || project.parent?.name?.contains("sample") == true) {
return@allprojects
}
println("currentName: ${project.parent?.name} - ${project.name}")
val mGroup = mavenGroup
project.apply(plugin = "org.jetbrains.dokka")
project.apply(plugin = "maven-publish")
project.afterEvaluate {
if (project.extensions.findByName("android") != null) {
val ext = project.extensions.findByType<LibraryExtension>()
?: project.extensions.findByType<com.android.build.gradle.AppExtension>()
if (ext != null && ext is LibraryExtension) {
} else {
return@afterEvaluate
}
} else {
return@afterEvaluate
}
tasks.withType<PublishToMavenRepository> {
val isMac = DefaultNativePlatform.getCurrentOperatingSystem().isMacOsX
onlyIf {
isMac.also {
if (!isMac) logger.error(
"""
Publishing the library requires macOS to be able to generate iOS artifacts.
Run the task on a mac or use the project GitHub workflows for publication and release.
""",
)
}
}
}
val javadocJar by tasks.registering(Jar::class) {
dependsOn(tasks.dokkaHtml)
from(tasks.dokkaHtml.flatMap(org.jetbrains.dokka.gradle.DokkaTask::outputDirectory))
archiveClassifier = "javadoc"
}
publishing {
val projectName = repo
repositories {
maven {
name = "GitHubPackages"
url = uri("https://maven.pkg.github.com/$mavenAuthor/${projectName}")
credentials {
username = "$mavenAuthor"
password = myExtra["githubToken"]?.toString()
}
}
}
afterEvaluate {
publications.withType<MavenPublication> {
artifact(javadocJar)
version = mVersion
groupId = mGroup
if (artifactId.startsWith("${rootProjectName}-${currentName}")) {
artifactId =
artifactId.replace("${rootProjectName}-${currentName}", currentName)
}
artifactId=artifactId.lowercase()
println("artifactId: $artifactId \"${rootProjectName}-${currentName}\"")
pom {
url = "https://github.com/$mavenAuthor/${projectName}"
name = projectName
description = """
Visit the project on GitHub to learn more.
""".trimIndent()
inceptionYear = "2024"
licenses {
license {
name = "Apache-2.0 License"
url = "http://www.apache.org/licenses/LICENSE-2.0.txt"
}
}
developers {
developer {
id = "arnaudgiuliani"
name = "Arnaud Giuliani"
email = "[email protected]"
roles = listOf("Mobile Developer")
timezone = "GMT+8"
}
}
contributors {
// contributor {}
}
scm {
tag = "HEAD"
url = "https://github.com/$mavenAuthor/${projectName}"
connection = "scm:git:github.com/$mavenAuthor/${projectName}.git"
developerConnection =
"scm:git:ssh://github.com/$mavenAuthor/${projectName}.git"
}
issueManagement {
system = "GitHub"
url = "https://github.com/$mavenAuthor/${projectName}/issues"
}
ciManagement {
system = "GitHub Actions"
url = "https://github.com/$mavenAuthor/${projectName}/actions"
}
}
}
}
}
tasks.dokkaHtml {
// outputDirectory = layout.buildDirectory.get().resolve("dokka")
offlineMode = false
moduleName = currentName
dokkaSourceSets {
configureEach {
reportUndocumented = true
noAndroidSdkLink = false
noStdlibLink = false
noJdkLink = false
jdkVersion = jvmTarget.toInt()
}
}
}
tasks.withType(AbstractPublishToMaven::class).configureEach {
dependsOn(tasks.withType(Sign::class))
}
}
}
tasks.register("deletePackages") {
val libs = rootDir.resolve("gradle/libs.versions.toml")
val map = hashMapOf<String, String>()
libs.useLines {
it.forEach { line ->
if (line.contains("=") && line.startsWith("#").not()) {
val (key, value) = line.split("=")
map[
key
.replace(" ", "").removeSurrounding("\""),
] =
value
.replace(" ", "").removeSurrounding("\"")
}
}
}
val rootProjectName = rootDir.name.lowercase()
.replace("compose_", "")
.replace("compose-", "")
.replace("compose", "")
val mavenAuthor = "vickyleu"
val mavenGroup = "com.$mavenAuthor.$rootProjectName"
group = "publishing"
description = "Delete all packages in the GitHub Packages registry"
val keyword = "${mavenGroup}"
println("keyword: $keyword")
val properties = Properties().apply {
runCatching { rootProject.file("local.properties") }
.getOrNull()
.takeIf { it?.exists() ?: false }
?.reader()
?.use(::load)
}
// For information about signing.* properties,
// see comments on signing { ... } block below
val environment: Map<String, String?> = System.getenv()
val myExtra = mutableMapOf<String, Any>()
myExtra["githubToken"] = properties["github.token"] as? String
?: environment["GITHUB_TOKEN"] ?: ""
val headers = mapOf(
"Accept" to "application/vnd.github.v3+json",
"Authorization" to "Bearer ${myExtra["githubToken"]}",
"X-GitHub-Api-Version" to "2022-11-28",
)
doLast {
runBlocking {
val executor = Executors.newFixedThreadPool(10)
val scope = CoroutineScope(executor.asCoroutineDispatcher())
val fetchJobs = packageTypes.flatMap { packageType ->
visibilityTypes.map { visibility ->
scope.async {
fetchPackages(packageType, visibility, headers)
}
}
}
fetchJobs.awaitAll().forEach { packages ->
allPackages.addAll(packages)
}
val deleteJobs = allPackages.filter { pkg ->
val packageName = pkg["name"] as String
packageName.contains(keyword)
}.map { pkg ->
val packageType = pkg["package_type"] as String
val packageName = pkg["name"] as String
scope.async {
deletePackage(packageType, packageName, headers)
}
}
try {
deleteJobs.awaitAll()
executor.shutdown()
} catch (e: Exception) {
println("删除包失败: ${e.message}")
}
}
}
}
val packageTypes = listOf("npm", "maven", "docker", "container")
val visibilityTypes = listOf("public", "private", "internal")
val allPackages = mutableListOf<Map<String, Any>>()
fun fetchPackages(
packageType: String,
visibility: String,
headers: Map<String, String>,
): List<Map<String, Any>> {
val packages = mutableListOf<Map<String, Any>>()
var page = 1
while (true) {
val url =
URL("https://api.github.com/user/packages?package_type=$packageType&visibility=$visibility&page=$page&per_page=100")
val connection = url.openConnection() as HttpURLConnection
headers.forEach { (key, value) -> connection.setRequestProperty(key, value) }
if (connection.responseCode == 200) {
val response = connection.inputStream.bufferedReader().use { it.readText() }
val batch: List<Map<String, Any>> = jacksonObjectMapper().readValue(response)
if (batch.isEmpty()) break
packages.addAll(batch)
page++
} else {
println("获取$packageType ($visibility) 包列表失败,错误代码: ${connection.responseCode} ${connection.responseMessage}")
println(connection.inputStream.bufferedReader().use { it.readText() })
break
}
}
return packages
}
fun deletePackage(packageType: String, packageName: String, headers: Map<String, String>) {
val url = URL("https://api.github.com/user/packages/$packageType/$packageName")
val connection = url.openConnection() as HttpURLConnection
connection.requestMethod = "DELETE"
headers.forEach { (key, value) -> connection.setRequestProperty(key, value) }
if (connection.responseCode == 204 || connection.responseCode == 200) {
println("$packageName 删除成功")
} else {
println("$packageName 删除失败,错误代码: ${connection.responseCode}")
println(connection.inputStream.bufferedReader().use { it.readText() })
}
}