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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
|
#!/usr/bin/env kotlin
@file:DependsOn("com.github.ajalt.clikt:clikt-jvm:3.5.2")
@file:DependsOn("me.alllex.parsus:parsus-jvm:0.4.0")
@file:DependsOn("org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.7.3")
import Release_main.SemVer.Companion.SemVer
import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.parameters.options.flag
import com.github.ajalt.clikt.parameters.options.option
import java.io.File
import java.util.concurrent.TimeUnit.MINUTES
import kotlin.system.exitProcess
import kotlin.time.Duration.Companion.seconds
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import me.alllex.parsus.parser.*
import me.alllex.parsus.token.literalToken
import me.alllex.parsus.token.regexToken
try {
Release.main(args)
exitProcess(0)
} catch (ex: Exception) {
println("${ex::class.simpleName}: ${ex.message}")
exitProcess(1)
}
/**
* Release a new version.
*
* Requires:
* * [gh cli](https://cli.github.com/manual/gh)
* * [kotlin](https://kotlinlang.org/docs/command-line.html)
* * [git](https://git-scm.com/)
*/
// based on https://github.com/apollographql/apollo-kotlin/blob/v4.0.0-dev.2/scripts/release.main.kts
object Release : CliktCommand() {
private val skipGitValidation by option(
"--skip-git-validation",
help = "skips git status validation"
).flag(default = false)
override fun run() {
echo("Current Dokkatoo version is $dokkatooVersion")
echo("git dir is ${Git.rootDir}")
val startBranch = Git.currentBranch()
validateGitStatus(startBranch)
val releaseVersion = semverPrompt(
text = "version to release?",
default = dokkatooVersion.copy(snapshot = false),
) {
if (it.snapshot) {
echo("versionToRelease must not be a snapshot version, but was $it")
}
!it.snapshot
}
val nextVersion = semverPrompt(
text = "post-release version?",
default = releaseVersion.incrementMinor(snapshot = true),
)
updateVersionCreatePR(releaseVersion)
// switch back to the main branch
Git.switch(startBranch)
Git.pull(startBranch)
// Tag the release
createAndPushTag(releaseVersion)
confirm("Publish plugins to Gradle Plugin Portal?", abort = true)
Gradle.publishPlugins()
// Bump the version to the next snapshot
updateVersionCreatePR(nextVersion)
// Go back and pull the changes
Git.switch(startBranch)
Git.pull(startBranch)
echo("Released version $releaseVersion")
}
private fun validateGitStatus(startBranch: String) {
if (skipGitValidation) {
echo("skipping git status validation")
return
}
check(Git.status().isEmpty()) {
"git repo is not clean. Stash or commit changes before making a release."
}
check(dokkatooVersion.snapshot) {
"Current version must be a SNAPSHOT, but was $dokkatooVersion"
}
check(startBranch == "main") {
"Must be on the main branch to make a release, but current branch is $startBranch"
}
}
/**
* @param[validate] returns `null` if the provided SemVer is valid, or else an error message
* explaining why it is invalid.
*/
private tailrec fun semverPrompt(
text: String,
default: SemVer,
validate: (candidate: SemVer) -> Boolean = { true },
): SemVer {
val response = prompt(
text = text,
default = default.toString(),
requireConfirmation = true,
) {
SemVer.of(it)
}
return if (response == null || !validate(response)) {
if (response == null) echo("invalid SemVer")
semverPrompt(text, default, validate)
} else {
response
}
}
private fun updateVersionCreatePR(version: SemVer) {
// checkout a release branch
val releaseBranch = "release/v$version"
echo("checkout out new branch...")
Git.switch(releaseBranch, create = true)
// update the version & run tests
dokkatooVersion = version
echo("running Gradle check...")
Gradle.check()
// commit and push
echo("committing...")
Git.commit("release $version")
echo("pushing...")
Git.push(releaseBranch)
// create a new PR
echo("creating PR...")
GitHub.createPr(releaseBranch)
confirm("Merge the PR for branch $releaseBranch?", abort = true)
mergeAndWait(releaseBranch)
echo("$releaseBranch PR merged")
}
private fun createAndPushTag(version: SemVer) {
// Tag the release
require(dokkatooVersion == version) {
"tried to create a tag, but project version does not match provided version. Expected $version but got $dokkatooVersion"
}
val tagName = "v$version"
Git.tag(tagName)
confirm("Push tag $tagName?", abort = true)
Git.push(tagName)
echo("Tag pushed")
confirm("Publish plugins to Gradle Plugin Portal?", abort = true)
Gradle.publishPlugins()
}
private val buildGradleKts: File by lazy {
val rootDir = Git.rootDir
File("$rootDir/build.gradle.kts").apply {
require(exists()) { "could not find build.gradle.kts in $rootDir" }
}
}
/** Read/write the version set in the root `build.gradle.kts` file */
private var dokkatooVersion: SemVer
get() {
val rawVersion = Gradle.dokkatooVersion()
return SemVer(rawVersion)
}
set(value) {
val updatedFile = buildGradleKts.useLines { lines ->
lines.joinToString(separator = "\n", postfix = "\n") { line ->
if (line.startsWith("version = ")) {
"version = \"${value}\""
} else {
line
}
}
}
buildGradleKts.writeText(updatedFile)
}
private fun mergeAndWait(branchName: String): Unit = runBlocking {
GitHub.autoMergePr(branchName)
echo("Waiting for the PR to be merged...")
while (GitHub.prState(branchName) != "MERGED") {
delay(1.seconds)
echo(".", trailingNewline = false)
}
}
}
private abstract class CliTool {
protected fun runCommand(
cmd: String,
dir: File? = Git.rootDir,
logOutput: Boolean = true,
): String {
val args = parseSpaceSeparatedArgs(cmd)
val process = ProcessBuilder(args).apply {
redirectOutput(ProcessBuilder.Redirect.PIPE)
redirectInput(ProcessBuilder.Redirect.PIPE)
redirectErrorStream(true)
if (dir != null) directory(dir)
}.start()
val processOutput = process.inputStream
.bufferedReader()
.lineSequence()
.onEach { if (logOutput) println("\t$it") }
.joinToString("\n")
.trim()
process.waitFor(10, MINUTES)
val exitCode = process.exitValue()
if (exitCode != 0) {
error("command '$cmd' failed:\n${processOutput}")
}
return processOutput
}
private data class ProcessResult(
val exitCode: Int,
val output: String,
)
companion object {
private fun parseSpaceSeparatedArgs(argsString: String): List<String> {
val parsedArgs = mutableListOf<String>()
var inQuotes = false
var currentCharSequence = StringBuilder()
fun saveArg(wasInQuotes: Boolean) {
if (wasInQuotes || currentCharSequence.isNotBlank()) {
parsedArgs.add(currentCharSequence.toString())
currentCharSequence = StringBuilder()
}
}
argsString.forEach { char ->
if (char == '"') {
inQuotes = !inQuotes
// Save value which was in quotes.
if (!inQuotes) {
saveArg(true)
}
} else if (char.isWhitespace() && !inQuotes) {
// Space is separator
saveArg(false)
} else {
currentCharSequence.append(char)
}
}
if (inQuotes) {
error("No close-quote was found in $currentCharSequence.")
}
saveArg(false)
return parsedArgs
}
}
}
/** git commands */
private object Git : CliTool() {
val rootDir = File(runCommand("git rev-parse --show-toplevel", dir = null))
init {
require(rootDir.exists()) { "could not determine root git directory" }
}
fun switch(branch: String, create: Boolean = false): String {
return runCommand(
buildString {
append("git switch ")
if (create) append("--create ")
append(branch)
}
)
}
fun commit(message: String): String = runCommand("git commit -a -m \"$message\"")
fun currentBranch(): String = runCommand("git symbolic-ref --short HEAD")
fun pull(ref: String): String = runCommand("git pull origin $ref")
fun push(ref: String): String = runCommand("git push origin $ref")
fun status(): String {
runCommand("git fetch --all")
return runCommand("git status --porcelain=v2")
}
fun tag(tag: String): String {
return runCommand("git tag $tag")
}
}
/** GitHub commands */
private object GitHub : CliTool() {
init {
setRepo("adamko-dev/dokkatoo")
}
fun setRepo(repo: String): String =
runCommand("gh repo set-default $repo")
fun prState(branchName: String): String =
runCommand("gh pr view $branchName --json state --jq .state", logOutput = false)
fun createPr(branch: String): String =
runCommand("gh pr create --head $branch --fill")
fun autoMergePr(branch: String): String =
runCommand("gh pr merge $branch --squash --auto --delete-branch")
fun waitForPrChecks(branch: String): String =
runCommand("gh pr checks $branch --watch --interval 30")
}
/** GitHub commands */
private object Gradle : CliTool() {
val gradlew: String
init {
val osName = System.getProperty("os.name").lowercase()
gradlew = if ("win" in osName) "./gradlew.bat" else "./gradlew"
}
fun stopDaemons(): String = runCommand("$gradlew --stop")
fun dokkatooVersion(): String {
stopDaemons()
return runCommand("$gradlew :dokkatooVersion --quiet --no-daemon")
}
fun check(): String {
stopDaemons()
return runCommand("$gradlew check --no-daemon")
}
fun publishPlugins(): String {
stopDaemons()
return runCommand("$gradlew publishPlugins --no-daemon --no-configuration-cache")
}
}
private data class SemVer(
val major: Int,
val minor: Int,
val patch: Int,
val snapshot: Boolean,
) {
fun incrementMinor(snapshot: Boolean): SemVer =
copy(minor = minor + 1, snapshot = snapshot)
override fun toString(): String =
"$major.$minor.$patch" + if (snapshot) "-SNAPSHOT" else ""
companion object {
fun SemVer(input: String): SemVer =
SemVerParser.parseEntire(input).getOrElse { error ->
error("provided version to release must be SemVer X.Y.Z, but got error while parsing: $error")
}
fun of(input: String): SemVer? =
SemVerParser.parseEntire(input).getOrElse { return null }
fun isValid(input: String): Boolean =
try {
SemVerParser.parseEntireOrThrow(input)
true
} catch (ex: ParseException) {
false
}
}
private object SemVerParser : Grammar<SemVer>() {
private val dotSeparator by literalToken(".")
private val dashSeparator by literalToken("-")
/** Non-negative number that is either 0, or does not start with 0 */
private val number: Parser<Int> by regexToken("""0|[1-9]\d*""").map { it.text.toInt() }
private val snapshot by -dashSeparator * literalToken("SNAPSHOT")
override val root: Parser<SemVer> by parser {
val major = number()
dotSeparator()
val minor = number()
dotSeparator()
val patch = number()
val snapshot = checkPresent(snapshot)
SemVer(
major = major,
minor = minor,
patch = patch,
snapshot = snapshot,
)
}
}
}
|