/
Nexus.kt
282 lines (231 loc) · 9.57 KB
/
Nexus.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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
package com.vanniktech.maven.publish.nexus
import java.io.IOException
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
class Nexus(
private val baseUrl: String,
private val username: String,
password: String,
) {
private val service by lazy {
val okHttpClient = OkHttpClient.Builder()
.addInterceptor(NexusOkHttpInterceptor(username, password))
.connectTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.build()
val retrofit = Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create())
.client(okHttpClient)
.baseUrl(baseUrl)
.build()
retrofit.create(NexusService::class.java)
}
private fun getProfiles(): List<StagingProfile>? {
val stagingProfilesResponse = service.getStagingProfiles().execute()
if (!stagingProfilesResponse.isSuccessful) {
throw IOException("Cannot get stagingProfiles for account $username: ${stagingProfilesResponse.errorBody()?.string()}")
}
return stagingProfilesResponse.body()?.data
}
private fun findStagingProfile(group: String): StagingProfile {
val allProfiles = getProfiles() ?: emptyList()
if (allProfiles.isEmpty()) {
throw IllegalArgumentException("No staging profiles found in account $username. Make sure you called \"./gradlew publish\".")
}
val candidateProfiles = allProfiles.filter { group == it.name || group.startsWith(it.name) }
if (candidateProfiles.isEmpty()) {
throw IllegalArgumentException(
"No matching staging profile found in account $username. It is expected that the account contains a staging " +
"profile that matches or is the start of $group." +
"Available profiles are: ${allProfiles.joinToString(separator = ", ") { it.name }}"
)
}
if (candidateProfiles.size > 1) {
throw IllegalArgumentException(
"More than 1 matching staging profile found in account $username. " +
"Available profiles are: ${allProfiles.joinToString(separator = ", ") { it.name }}"
)
}
return candidateProfiles[0]
}
private fun createStagingRepository(group: String, profile: StagingProfile): String {
println("Creating repository in profile: ${profile.name}")
val response = service.createRepository(profile.id, CreateRepositoryInput(CreateRepositoryInputData("Repository for $group"))).execute()
if (!response.isSuccessful) {
throw IOException("Cannot create repository: ${response.errorBody()?.string()}")
}
val id = response.body()?.data?.stagedRepositoryId
if (id == null) {
throw IOException("Did not receive created repository")
}
println("Created staging repository $id")
return id
}
fun createRepositoryForGroup(group: String): String {
val profile = findStagingProfile(group)
return createStagingRepository(group, profile)
}
private fun getProfileRepositories(): List<Repository>? {
val profileRepositoriesResponse = service.getProfileRepositories().execute()
if (!profileRepositoriesResponse.isSuccessful) {
throw IOException("Cannot get profileRepositories for account $username: ${profileRepositoriesResponse.errorBody()?.string()}")
}
return profileRepositoriesResponse.body()?.data
}
private fun findStagingRepository(): Repository {
val allRepositories = getProfileRepositories() ?: emptyList()
if (allRepositories.isEmpty()) {
throw IllegalArgumentException(
"No matching staging repository found in account $username. You can can explicitly choose one by " +
"passing it as an option like this \"./gradlew closeAndReleaseRepository --repository=comexample-123\". " +
"Available repositories are: ${allRepositories.joinToString(separator = ", ") { it.repositoryId }}"
)
}
if (allRepositories.size > 1) {
throw IllegalArgumentException(
"More than 1 matching staging repository found in account $username. You can can explicitly choose " +
"one by passing it as an option like this \"./gradlew closeAndReleaseRepository --repository comexample-123\". " +
"Available repositories are: ${allRepositories.joinToString(separator = ", ") { it.repositoryId }}"
)
}
return allRepositories[0]
}
private fun getStagingRepository(repositoryId: String): Repository {
val repositoryResponse = service.getRepository(repositoryId).execute()
if (!repositoryResponse.isSuccessful) {
throw IOException("Cannot get repository with id $repositoryId for account $username: ${repositoryResponse.errorBody()?.string()}")
}
val repository = repositoryResponse.body()
if (repository == null) {
throw IOException("Could not get repository with id $repositoryId for account $username")
}
return repository
}
private fun closeStagingRepository(stagingRepository: Repository) {
val repositoryId = stagingRepository.repositoryId
if (stagingRepository.type == "closed") {
if (stagingRepository.transitioning) {
waitForClose(stagingRepository.repositoryId)
} else {
println("Repository $repositoryId already closed")
}
return
}
if (stagingRepository.type != "open") {
throw IllegalArgumentException("Repository $repositoryId is of type '${stagingRepository.type}' and not 'open'")
}
println("Closing repository: $repositoryId")
val response = service.closeRepository(TransitionRepositoryInput(TransitionRepositoryInputData(listOf(repositoryId)))).execute()
if (!response.isSuccessful) {
throw IOException("Cannot close repository: ${response.errorBody()?.string()}")
}
waitForClose(repositoryId)
println("Repository $repositoryId closed")
}
private fun waitForClose(repositoryId: String) {
val startMillis = System.currentTimeMillis()
val waitingChars = listOf(
PROGRESS_1,
PROGRESS_2,
PROGRESS_3,
PROGRESS_4,
PROGRESS_5,
PROGRESS_6,
PROGRESS_7
)
var i = 0
while (true) {
if (System.currentTimeMillis() - startMillis > CLOSE_TIMEOUT_MILLIS) {
throw IOException("Timeout waiting for repository close")
}
print("\r${waitingChars[i++ % waitingChars.size]} waiting for close...")
System.out.flush()
Thread.sleep(CLOSE_WAIT_INTERVAL_MILLIS)
val repository = try {
getStagingRepository(repositoryId)
} catch (e: IOException) {
System.err.println("Exception trying to get repository status: ${e.message}")
null
} catch (e: TimeoutException) {
System.err.println("Exception trying to get repository status: ${e.message}")
null
}
if (repository?.type == "closed" && !repository.transitioning) {
break
}
if (repository?.type == "open" && !repository.transitioning && repository.notifications > 0) {
val properties = try {
val response = service.getRepositoryActivity(repositoryId).execute()
if (response.isSuccessful) {
response.body()?.find { it.name == "close" }
?.events?.find { it.name == "ruleFailed" }
?.properties?.filter { it.name == "failureMessage" }
} else {
emptyList()
}
} catch (_: IOException) {
emptyList()
}
if (properties.isNullOrEmpty()) {
val url = baseUrl.toHttpUrl().newBuilder("/#stagingRepositories").toString()
throw IOException("Closing the repository failed. ${repository.notifications} messages are available on $url")
} else {
val message = properties.joinToString("\n") { it.value }
throw IOException("Closing the repository failed with the following errors:\n$message")
}
}
}
}
fun closeCurrentStagingRepository(): String {
val stagingRepository = findStagingRepository()
closeStagingRepository(stagingRepository)
return stagingRepository.repositoryId
}
fun closeStagingRepository(repositoryId: String) {
val stagingRepository = getStagingRepository(repositoryId)
closeStagingRepository(stagingRepository)
}
fun releaseStagingRepository(repositoryId: String) {
println("Releasing repository: $repositoryId")
val response = service.releaseRepository(
TransitionRepositoryInput(
TransitionRepositoryInputData(
stagedRepositoryIds = listOf(repositoryId),
autoDropAfterRelease = true
)
)
).execute()
if (!response.isSuccessful) {
throw IOException("Cannot release repository: ${response.errorBody()?.string()}")
}
println("Repository $repositoryId released")
}
fun dropStagingRepository(repositoryId: String) {
val response = service.dropRepository(
TransitionRepositoryInput(
TransitionRepositoryInputData(
stagedRepositoryIds = listOf(repositoryId)
)
)
).execute()
if (!response.isSuccessful) {
throw IOException("Cannot drop repository: ${response.errorBody()?.string()}")
}
}
companion object {
private const val PROGRESS_1 = "\u2839"
private const val PROGRESS_2 = "\u2838"
private const val PROGRESS_3 = "\u2834"
private const val PROGRESS_4 = "\u2826"
private const val PROGRESS_5 = "\u2807"
private const val PROGRESS_6 = "\u280F"
private const val PROGRESS_7 = "\u2819"
private const val CLOSE_TIMEOUT_MILLIS = 15 * 60 * 1000L
private const val CLOSE_WAIT_INTERVAL_MILLIS = 10_000L
}
}