|
1 | 1 | package com.ensody.buildlogic |
2 | 2 |
|
| 3 | +import com.android.build.gradle.internal.cxx.io.writeTextIfDifferent |
3 | 4 | import org.gradle.api.Project |
| 5 | +import org.gradle.kotlin.dsl.findByType |
| 6 | +import org.gradle.kotlin.dsl.get |
| 7 | +import org.jetbrains.kotlin.gradle.dsl.KotlinJvmExtension |
| 8 | +import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension |
| 9 | +import java.io.File |
4 | 10 |
|
5 | 11 | val Project.isRootProject get() = this == rootProject |
6 | 12 |
|
7 | | -fun shell(command: String): String { |
8 | | - val process = ProcessBuilder("/bin/bash", "-c", command).start() |
| 13 | +fun shell(command: String, workingDir: File? = null, inheritIO: Boolean = false): String { |
| 14 | + val processBuilder = ProcessBuilder("/bin/bash", "-c", command) |
| 15 | + workingDir?.let { processBuilder.directory(it) } |
| 16 | + processBuilder.redirectErrorStream(true) |
| 17 | + val process = processBuilder.start() |
9 | 18 | return process.inputStream.bufferedReader().readText().trim().also { |
10 | | - process.waitFor() |
| 19 | + val exitCode = process.waitFor() |
| 20 | + if (inheritIO) { |
| 21 | + println(it) |
| 22 | + } |
| 23 | + check(exitCode == 0) { "Process exit code was: $exitCode\nOriginal command: $command"} |
11 | 24 | } |
12 | 25 | } |
13 | 26 |
|
| 27 | +fun Project.withGeneratedBuildFile(category: String, path: String, sourceSet: String? = null, content: () -> String) { |
| 28 | + val generatedDir = file("${getGeneratedBuildFilesRoot()}/$category") |
| 29 | + extensions.findByType<KotlinJvmExtension>()?.apply { |
| 30 | + sourceSets[sourceSet ?: "main"].kotlin.srcDir(generatedDir) |
| 31 | + } ?: extensions.findByType<KotlinMultiplatformExtension>()?.apply { |
| 32 | + sourceSets[sourceSet ?: "commonMain"].kotlin.srcDir(generatedDir) |
| 33 | + } ?: error("Don't know how to add generated build file because project ${this.path} has unknown type") |
| 34 | + val outputPath = file("$generatedDir/$path") |
| 35 | + outputPath.writeTextIfDifferent(content().trimIndent().trimStart() + "\n") |
| 36 | + generatedFiles.getOrPut(this.path) { mutableSetOf() }.add(outputPath.normalize().absoluteFile) |
| 37 | +} |
| 38 | + |
| 39 | +internal val generatedFiles = mutableMapOf<String, MutableSet<File>>() |
| 40 | + |
| 41 | +internal fun File.withParents(): List<File> = |
| 42 | + buildList { |
| 43 | + add(this@withParents) |
| 44 | + while (true) { |
| 45 | + add(last().parentFile ?: break) |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | +internal fun Project.getGeneratedBuildFilesRoot(): File = |
| 50 | + file("$projectDir/build/generated/source/build-logic") |
| 51 | + |
14 | 52 | internal fun Project.detectProjectVersion(): String = |
15 | 53 | System.getenv("OVERRIDE_VERSION")?.takeIf { it.isNotBlank() } |
16 | 54 | ?: shell("git tag --points-at HEAD").split("\n").filter { |
|
0 commit comments