Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add some protections to work with gradle composite builds #11

Merged
merged 3 commits into from
Dec 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions build-scripts/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ plugins {
`kotlin-dsl`
}

group = "ru.vladislavsumin"

dependencies {
// Мы хотим получать доступ к libs из наших convention плагинов, но гредл на текущий момент не умеет прокидывать
// version catalogs. Поэтому используем костыль отсюда - https://github.com/gradle/gradle/issues/15383
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package ru.vladislavsumin.configuration

import org.gradle.api.Project
import ru.vladislavsumin.utils.isDslAccessors
import kotlin.reflect.KClass

/**
Expand All @@ -11,23 +13,33 @@ import kotlin.reflect.KClass
*/
@Suppress("UnnecessaryAbstractClass") // Создавать этот класс напрямую не имеет смысла
abstract class Configuration(
private val basePath: String,
@PublishedApi
internal val project: Project,
@PublishedApi
internal val basePath: String,
private val propertyProvider: PropertyProvider,
) {
/**
* Конструктор для создания дочерней секции пропертей относительно родительской.
* @param relativePath путь, который будет добавлен к пути родителя для получения финального пути этой конфигурации.
*/
constructor(relativePath: String, parent: Configuration) : this(
parent.project,
"${parent.basePath}.$relativePath",
parent.propertyProvider,
)

protected inline fun <reified T : Any> property(relativePath: String, defaultValue: T): T =
propertyOrNull(relativePath, T::class) ?: defaultValue

protected inline fun <reified T : Any> property(relativePath: String): T =
propertyOrNull(relativePath, T::class)!!
protected inline fun <reified T : Any> property(relativePath: String): T {
val prop = propertyOrNull(relativePath, T::class)
return when {
prop != null -> prop
project.isDslAccessors -> fakeDefaultValue()
else -> error("Property $basePath.$relativePath is required but not set")
}
}

protected inline fun <reified T : Any> propertyOrNull(relativePath: String): T? =
propertyOrNull(relativePath, T::class)
Expand All @@ -51,6 +63,16 @@ abstract class Configuration(
else -> Error("Unsupported cast to ${kClass.simpleName}")
} as T
}

@PublishedApi
internal inline fun <reified T : Any> fakeDefaultValue(): T {
return when (T::class) {
String::class -> ""
Boolean::class -> false
Integer::class -> 0
else -> Error("Unsupported cast to ${T::class.simpleName}")
} as T
}
}

fun interface PropertyProvider {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,11 @@ import org.gradle.kotlin.dsl.findByType
* Файл пропертей проекта, содержит dsl для доступа к любым проперти используемым при сборке.
*/
@Suppress("UnnecessaryAbstractClass")
open class ProjectConfiguration(propertyProvider: PropertyProvider) :
Configuration("ru.vs", propertyProvider) {
open class ProjectConfiguration(project: Project, propertyProvider: PropertyProvider) :
Configuration(project, "ru.vs", propertyProvider) {

val version = property("version", "0.0.1")
val basePackage = property<String>("basePackage")
val core = CoreConfiguration()
val signing = Signing()
val sonatype = Sonatype()
Expand Down Expand Up @@ -60,6 +61,7 @@ val Project.projectConfiguration: ProjectConfiguration
get() = rootProject.extensions.findByType()
?: rootProject.extensions.create(
ProjectConfiguration::class.java.simpleName,
project,
propertyProvider,
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,27 @@ package ru.vladislavsumin.convention.android

import ru.vladislavsumin.configuration.projectConfiguration
import ru.vladislavsumin.utils.android
import ru.vladislavsumin.utils.protectFromDslAccessors

/**
* Базовая настройка android плагина без привязки к конкретной имплементации (application/library/итд).
*/

val configuration = project.projectConfiguration

android {
setCompileSdkVersion(configuration.core.android.compileSdk)
protectFromDslAccessors {
android {
setCompileSdkVersion(configuration.core.android.compileSdk)

defaultConfig {
minSdk = configuration.core.android.minSdk
targetSdk = configuration.core.android.targetSdk
}
defaultConfig {
minSdk = configuration.core.android.minSdk
targetSdk = configuration.core.android.targetSdk
}

compileOptions {
val version = JavaVersion.toVersion(configuration.core.jvmVersion)
sourceCompatibility = version
targetCompatibility = version
compileOptions {
val version = JavaVersion.toVersion(configuration.core.jvmVersion)
sourceCompatibility = version
targetCompatibility = version
}
}
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
package ru.vladislavsumin.convention.android

import ru.vladislavsumin.configuration.projectConfiguration
import ru.vladislavsumin.utils.android
import ru.vladislavsumin.utils.fullName
import ru.vladislavsumin.utils.protectFromDslAccessors

/**
* Устанавливает базовый namespace для android модулей вида ru.vladislavsumin.***, где *** заменяются на полное имя проекта.
*/

android {
namespace = "ru.vladislavsumin.${project.fullName()}"
protectFromDslAccessors {
android {
namespace = "${project.projectConfiguration.basePackage}.${project.fullName()}"
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
package ru.vladislavsumin.convention.publication

import ru.vladislavsumin.configuration.projectConfiguration
import ru.vladislavsumin.utils.fullName

/**
* Устанавливает группу проекта основываясь на его пути
*/

group = "ru.vladislavsumin.${project.parent!!.fullName()}"
group = "${project.projectConfiguration.basePackage}.${project.parent!!.fullName()}"
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package ru.vladislavsumin.utils

import org.gradle.api.Project

/**
* Защита от выполнения кода при генерации kotlin dsl при использовании composite builds содержащих convention плагины.
*/
inline fun Project.protectFromDslAccessors(block: () -> Unit) {
if (!isDslAccessors) {
block()
}
}

val Project.isDslAccessors: Boolean get() = name == "gradle-kotlin-dsl-accessors"
3 changes: 3 additions & 0 deletions gradle.properties
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
# Project
ru.vs.basePackage=ru.vladislavsumin

# Kotlin
kotlin.code.style=official

Expand Down