fun setupProject()

in plugin/src/functionalTest/kotlin/com/android/gradle/replicator/Fixtures.kt [132:212]


fun setupProject(
    type: BuildFileType,
    traceOffset: Int,
    plugins: List<PluginInfo>,
    buildscript: (() -> String)?
): ProjectSetup {
    // Setup the test build
    val projectDir = File("build/functionalTest/${getName(traceOffset)}")
    if (projectDir.exists()) {
        projectDir.deleteRecursively()
    }
    projectDir.mkdirs()
    projectDir.resolve(type.settingsFile()).writeText("")
    val buildFile = projectDir.resolve(type.buidFile())

    val buildScriptBlock = if (buildscript != null) {
        when (type) {
            BuildFileType.GROOVY ->
                """
buildscript {
${buildscript()}
}
                """
            BuildFileType.KTS ->
                """
buildscript {
${buildscript()}
}
                """
        }
    } else ""

    val customPlugins = plugins.map {
        val versionStr = if (it.version != null) {
            " version \"${it.version}\""
        } else ""

        val applyStr = if (it.apply == false) {
            "apply false"
        } else ""

        val keyword = if (it.kotlin) "kotlin" else "id"

        "    $keyword(\"${it.id}\")$versionStr$applyStr"
    }.joinToString(separator = "\n")

    buildFile.writeText("""
$buildScriptBlock
plugins {
    id("com.android.gradle.project.replicator")
$customPlugins
}
        """)

    // Run the build
    val runner = GradleRunner.create()
    runner.forwardOutput()
    runner.withPluginClasspath()
    runner.withArguments("getStructure", "--stacktrace")

    val property: String? = System.getProperty("agp.classpath")
    property?.let {
        val newCP = File(it).readLines().map { File(it) }
        val oldCP = runner.pluginClasspath
        runner.withPluginClasspath(newCP + oldCP)
    }

    val env = runner.environment
    val newEnv = mutableMapOf<String, String>().also {
        it["ANDROID_SDK_ROOT"] = System.getenv("ANDROID_SDK_ROOT")
    }
    env?.let { newEnv.putAll(it) }
    runner.withEnvironment(newEnv)

    runner.withProjectDir(projectDir)

    return ProjectSetup(
        projectDir = projectDir,
        buildFile = buildFile,
        runner = runner)
}