Compare commits

..

2 Commits

Author SHA1 Message Date
ef9828d817 update dependencies 2025-01-10 08:34:56 +06:00
d1a5bdd04d start 0.24.1 2025-01-10 08:22:56 +06:00
57 changed files with 105 additions and 1075 deletions

View File

@@ -1,48 +1,5 @@
# Changelog
## 0.24.6
* `Versions`:
* `KSLog`: `1.4.0` -> `1.4.1`
* `Exposed`: `0.58.0` -> `0.59.0`
* `SQLite`: `3.48.0.0` -> `3.49.0.0`
* `AndroidFragment`: `1.8.5` -> `1.8.6`
* `Coroutines`:
* Safely functions has been replaced with `Logging` variations (resolve of [#541](https://github.com/InsanusMokrassar/MicroUtils/issues/541))
* `KSP`:
* `Variations`:
* Module has been created
## 0.24.5
* `Versions`:
* `Kotlin`: `2.1.0` -> `2.1.10`
* `SQLite`: `3.47.2.0` -> `3.48.0.0`
* `Koin`: `4.0.1` -> `4.0.2`
* `Android RecyclerView`: `1.3.2` -> `1.4.0`
## 0.24.4
* `Repos`:
* `Exposed`:
* Improve `CommonExposedRepo.selectByIds`
* `FSM`:
* Fixes and improvements
## 0.24.3
* `Ksp`:
* `Sealed`:
* Fixes in processing of `GenerateSealedTypesWorkaround` annotations
## 0.24.2
* `Versions`:
* `Exposed`: `0.57.0` -> `0.58.0`
* `Ksp`:
* `Sealed`:
* Add annotation `GenerateSealedTypesWorkaround` which allow to generate `subtypes` lists
## 0.24.1
* `Versions`:

View File

@@ -11,7 +11,6 @@ kotlin {
commonMain {
dependencies {
api libs.kt.coroutines
api libs.kslog
}
}
jsMain {

View File

@@ -41,4 +41,4 @@ class ContextSafelyExceptionHandler(
) : CoroutineContext.Element {
override val key: CoroutineContext.Key<*>
get() = ContextSafelyExceptionHandlerKey
}
}

View File

@@ -2,7 +2,6 @@
package dev.inmo.micro_utils.coroutines
import dev.inmo.kslog.common.KSLog
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.sync.Mutex
@@ -17,45 +16,6 @@ inline fun <T> Flow<T>.subscribe(scope: CoroutineScope, noinline block: suspend
* Use [subscribe], but all [block]s will be called inside of [safely] function.
* Use [onException] to set up your reaction for [Throwable]s
*/
inline fun <T> Flow<T>.subscribeLogging(
scope: CoroutineScope,
noinline errorMessageBuilder: T.(Throwable) -> Any = { "Something web wrong" },
logger: KSLog = KSLog,
noinline block: suspend (T) -> Unit
) = subscribe(scope) {
it.runCatchingLogging(
errorMessageBuilder,
logger
) {
block(it)
}.getOrThrow()
}
/**
* Use [subscribeSafelyWithoutExceptions], but all exceptions will be passed to [defaultSafelyExceptionHandler]
*/
inline fun <T> Flow<T>.subscribeLoggingDropExceptions(
scope: CoroutineScope,
noinline errorMessageBuilder: T.(Throwable) -> Any = { "Something web wrong" },
logger: KSLog = KSLog,
noinline block: suspend (T) -> Unit
) = subscribe(scope) {
it.runCatchingLogging(
errorMessageBuilder,
logger
) {
block(it)
}
}
/**
* Use [subscribe], but all [block]s will be called inside of [safely] function.
* Use [onException] to set up your reaction for [Throwable]s
*/
@Deprecated(
"Will be removed soon due to replacement by subscribeLogging",
ReplaceWith("this.subscribeLogging(scope = scope, block = block)")
)
inline fun <T> Flow<T>.subscribeSafely(
scope: CoroutineScope,
noinline onException: ExceptionHandler<Unit> = defaultSafelyExceptionHandler,
@@ -69,10 +29,6 @@ inline fun <T> Flow<T>.subscribeSafely(
/**
* Use [subscribeSafelyWithoutExceptions], but all exceptions will be passed to [defaultSafelyExceptionHandler]
*/
@Deprecated(
"Will be removed soon due to replacement by subscribeLoggingDropExceptions",
ReplaceWith("this.subscribeLoggingDropExceptions(scope = scope, block = block)")
)
inline fun <T> Flow<T>.subscribeSafelyWithoutExceptions(
scope: CoroutineScope,
noinline onException: ExceptionHandler<T?> = defaultSafelyWithoutExceptionHandlerWithNull,
@@ -86,10 +42,6 @@ inline fun <T> Flow<T>.subscribeSafelyWithoutExceptions(
/**
* Use [subscribeSafelyWithoutExceptions], but all exceptions inside of [safely] will be skipped
*/
@Deprecated(
"Will be removed soon due to replacement by subscribeLoggingDropExceptions",
ReplaceWith("this.subscribeLoggingDropExceptions(scope = scope, block = block)")
)
inline fun <T> Flow<T>.subscribeSafelySkippingExceptions(
scope: CoroutineScope,
noinline block: suspend (T) -> Unit

View File

@@ -15,7 +15,7 @@ private class SubscribeAsyncReceiver<T>(
get() = dataChannel
init {
scope.launchLoggingDropExceptions {
scope.launchSafelyWithoutExceptions {
for (data in dataChannel) {
output(data)
}

View File

@@ -15,10 +15,6 @@ import kotlin.coroutines.coroutineContext
*
* @return [Result] with result of [block] if no exceptions or [Result] from [onException] execution
*/
@Deprecated(
"This function become redundant since coroutines correctly handling throwing exceptions",
replaceWith = ReplaceWith("runCatching(block).replaceIfFailure { onException(it) }")
)
suspend inline fun <T> runCatchingSafely(
onException: ExceptionHandler<T>,
block: suspend () -> T
@@ -33,10 +29,6 @@ suspend inline fun <T> runCatchingSafely(
}
}
@Deprecated(
"This function become redundant since coroutines correctly handling throwing exceptions",
replaceWith = ReplaceWith("runCatching(block).replaceIfFailure { onException(it) }")
)
suspend inline fun <T, R> R.runCatchingSafely(
onException: ExceptionHandler<T>,
block: suspend R.() -> T
@@ -47,18 +39,10 @@ suspend inline fun <T, R> R.runCatchingSafely(
/**
* Launching [runCatchingSafely] with [defaultSafelyExceptionHandler] as `onException` parameter
*/
@Deprecated(
"This function become redundant since coroutines correctly handling throwing exceptions",
replaceWith = ReplaceWith("runCatching(block).replaceIfFailure { defaultSafelyExceptionHandler(it) }")
)
suspend inline fun <T> runCatchingSafely(
block: suspend () -> T
): Result<T> = runCatchingSafely(defaultSafelyExceptionHandler, block)
@Deprecated(
"This function become redundant since coroutines correctly handling throwing exceptions",
replaceWith = ReplaceWith("runCatching(block).replaceIfFailure { defaultSafelyExceptionHandler(it) }")
)
suspend inline fun <T, R> R.runCatchingSafely(
block: suspend R.() -> T
): Result<T> = runCatchingSafely<T> {
@@ -89,9 +73,6 @@ suspend fun contextSafelyExceptionHandler() = coroutineContext[ContextSafelyExce
* After all, will be called [withContext] method with created [ContextSafelyExceptionHandler] and block which will call
* [safely] method with [safelyExceptionHandler] as onException parameter and [block] as execution block
*/
@Deprecated(
"This function become redundant since coroutines correctly handling throwing exceptions",
)
suspend fun <T> safelyWithContextExceptionHandler(
contextExceptionHandler: ExceptionHandler<Unit>,
safelyExceptionHandler: ExceptionHandler<T> = defaultSafelyExceptionHandler,
@@ -113,10 +94,6 @@ suspend fun <T> safelyWithContextExceptionHandler(
*
* @see runCatchingSafely
*/
@Deprecated(
"This function become redundant since coroutines correctly handling throwing exceptions",
replaceWith = ReplaceWith("runCatching(block).replaceIfFailure { onException(it) }.getOrThrow()")
)
suspend inline fun <T> safely(
onException: ExceptionHandler<T>,
block: suspend () -> T
@@ -127,17 +104,9 @@ suspend inline fun <T> safely(
*
* @see runCatchingSafely
*/
@Deprecated(
"This function become redundant since coroutines correctly handling throwing exceptions",
replaceWith = ReplaceWith("runCatching(block).replaceIfFailure { defaultSafelyExceptionHandler(it) }.getOrThrow()")
)
suspend inline fun <T> safely(
block: suspend () -> T
): T = safely(defaultSafelyExceptionHandler, block)
@Deprecated(
"This function become redundant since coroutines correctly handling throwing exceptions",
replaceWith = ReplaceWith("runCatching(block).replaceIfFailure { defaultSafelyExceptionHandler(it) }.getOrThrow()")
)
suspend inline fun <T, R> R.safely(
block: suspend R.() -> T
): T = safely<T> { block() }
@@ -168,19 +137,11 @@ val defaultSafelyWithoutExceptionHandlerWithNull: ExceptionHandler<Nothing?> = {
* Shortcut for [safely] with exception handler, that as expected must return null in case of impossible creating of
* result from exception (instead of throwing it, by default always returns null)
*/
@Deprecated(
"This function become redundant since coroutines correctly handling throwing exceptions",
replaceWith = ReplaceWith("runCatching(block).replaceIfFailure { onException(it) }.getOrNull()")
)
suspend fun <T> safelyWithoutExceptions(
onException: ExceptionHandler<T> = defaultSafelyExceptionHandler,
block: suspend () -> T
): T? = runCatchingSafely(onException, block).getOrNull()
@Deprecated(
"This function become redundant since coroutines correctly handling throwing exceptions",
replaceWith = ReplaceWith("runCatching(block).replaceIfFailure { onException(it) }.getOrNull()")
)
suspend fun <T> runCatchingSafelyWithoutExceptions(
onException: ExceptionHandler<T?> = defaultSafelyExceptionHandler,
block: suspend () -> T

View File

@@ -1,55 +0,0 @@
package dev.inmo.micro_utils.coroutines
import dev.inmo.kslog.common.KSLog
import dev.inmo.kslog.common.e
import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
fun CoroutineScope.launchLogging(
errorMessageBuilder: CoroutineScope.(Throwable) -> Any = { "Something web wrong" },
logger: KSLog = KSLog,
context: CoroutineContext = EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> Unit
) = launch(context, start) {
runCatching { block() }.onFailure {
logger.e(it) { errorMessageBuilder(it) }
}.getOrThrow()
}
fun CoroutineScope.launchLoggingDropExceptions(
errorMessageBuilder: CoroutineScope.(Throwable) -> Any = { "Something web wrong" },
logger: KSLog = KSLog,
context: CoroutineContext = EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> Unit
) = launch(context, start) {
runCatching { block() }.onFailure {
logger.e(it) { errorMessageBuilder(it) }
} // just dropping exception
}
fun <T> CoroutineScope.asyncLogging(
errorMessageBuilder: CoroutineScope.(Throwable) -> Any = { "Something web wrong" },
logger: KSLog = KSLog,
context: CoroutineContext = EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> T
) = async(context, start) {
runCatching { block() }.onFailure {
logger.e(it) { errorMessageBuilder(it) }
}.getOrThrow()
}
fun <T> CoroutineScope.asyncLoggingDropExceptions(
errorMessageBuilder: CoroutineScope.(Throwable) -> Any = { "Something web wrong" },
logger: KSLog = KSLog,
context: CoroutineContext = EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> T
) = async(context, start) {
runCatching { block() }.onFailure {
logger.e(it) { errorMessageBuilder(it) }
}
}

View File

@@ -4,10 +4,6 @@ import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
@Deprecated(
"This method will be removed soon. Use launchLogging instead",
ReplaceWith("this.launchLogging(context = context, start = start, block = block)")
)
fun CoroutineScope.launchSafely(
context: CoroutineContext = EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
@@ -19,10 +15,6 @@ fun CoroutineScope.launchSafely(
}
}
@Deprecated(
"This method will be removed soon. Use launchLoggingDropExceptions instead",
ReplaceWith("this.launchLoggingDropExceptions(context = context, start = start, block = block)")
)
fun CoroutineScope.launchSafelyWithoutExceptions(
context: CoroutineContext = EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
@@ -34,10 +26,6 @@ fun CoroutineScope.launchSafelyWithoutExceptions(
}
}
@Deprecated(
"This method will be removed soon. Use asyncLogging instead",
ReplaceWith("this.asyncLogging(context = context, start = start, block = block)")
)
fun <T> CoroutineScope.asyncSafely(
context: CoroutineContext = EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
@@ -49,10 +37,6 @@ fun <T> CoroutineScope.asyncSafely(
}
}
@Deprecated(
"This method will be removed soon. Use asyncLoggingDropExceptions instead",
ReplaceWith("this.asyncLoggingDropExceptions(context = context, start = start, block = block)")
)
fun <T> CoroutineScope.asyncSafelyWithoutExceptions(
context: CoroutineContext = EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,

View File

@@ -1,3 +0,0 @@
package dev.inmo.micro_utils.coroutines
inline fun <T> Result<T>.replaceIfFailure(onException: (Throwable) -> T) = if (isSuccess) { this } else { runCatching { onException(exceptionOrNull()!!) } }

View File

@@ -1,12 +0,0 @@
package dev.inmo.micro_utils.coroutines
import dev.inmo.kslog.common.KSLog
import dev.inmo.kslog.common.e
inline fun <T, R> R.runCatchingLogging(
noinline errorMessageBuilder: R.(Throwable) -> Any = { "Something web wrong" },
logger: KSLog = KSLog,
block: R.() -> T
) = runCatching(block).onFailure {
logger.e(it) { errorMessageBuilder(it) }
}

View File

@@ -12,7 +12,6 @@ kotlin {
dependencies {
api project(":micro_utils.common")
api project(":micro_utils.coroutines")
api libs.kslog
}
}
}

View File

@@ -1,7 +1,5 @@
package dev.inmo.micro_utils.fsm.common
import dev.inmo.kslog.common.TagLogger
import dev.inmo.kslog.common.e
import dev.inmo.micro_utils.common.Optional
import dev.inmo.micro_utils.coroutines.*
import dev.inmo.micro_utils.fsm.common.utils.StateHandlingErrorHandler
@@ -70,7 +68,6 @@ open class DefaultStatesMachine <T: State>(
protected val handlers: List<CheckableHandlerHolder<in T, T>>,
protected val onStateHandlingErrorHandler: StateHandlingErrorHandler<T> = defaultStateHandlingErrorHandler()
) : StatesMachine<T> {
protected val logger = TagLogger(this::class.simpleName!!)
/**
* Will call [launchStateHandling] for state handling
*/
@@ -99,13 +96,7 @@ open class DefaultStatesMachine <T: State>(
statesJobsMutex.withLock {
statesJobs[actualState] ?.cancel()
statesJobs[actualState] = scope.launch {
runCatching {
performUpdate(actualState)
}.onFailure {
logger.e(it) {
"Unable to perform update of state from $actualState"
}
}.getOrThrow()
performUpdate(actualState)
}.also { job ->
job.invokeOnCompletion { _ ->
scope.launch {
@@ -128,10 +119,8 @@ open class DefaultStatesMachine <T: State>(
*/
override fun start(scope: CoroutineScope): Job {
val supervisorScope = scope.LinkedSupervisorScope()
supervisorScope.launchLoggingDropExceptions {
(statesManager.getActiveStates().asFlow() + statesManager.onStartChain).subscribeSafelyWithoutExceptions(
supervisorScope
) {
supervisorScope.launchSafelyWithoutExceptions {
(statesManager.getActiveStates().asFlow() + statesManager.onStartChain).subscribeSafelyWithoutExceptions(supervisorScope) {
supervisorScope.launch { performStateUpdate(Optional.absent(), it, supervisorScope) }
}
statesManager.onChainStateUpdated.subscribeSafelyWithoutExceptions(supervisorScope) {
@@ -142,7 +131,7 @@ open class DefaultStatesMachine <T: State>(
statesJobsMutex.withLock {
val stateInMap = statesJobs.keys.firstOrNull { stateInMap -> stateInMap == removedState }
if (stateInMap === removedState) {
statesJobs[stateInMap]?.cancel()
statesJobs[stateInMap] ?.cancel()
}
}
}

View File

@@ -9,12 +9,7 @@ interface StatesManager<T : State> {
/**
* It is expected, that [new] state will be saved in manager.
*
* If [new] context will not be equal to [old] one, it must do some check of availability for replacement
* of potentially exists state on [new] context. If this state can't be replaced, it will throw [IllegalStateException]
*
* @throws IllegalStateException - in case when [new] [State] can't be set
* Must set current set using [State.context]
*/
suspend fun update(old: T, new: T)

View File

@@ -1,6 +1,5 @@
package dev.inmo.micro_utils.fsm.common
import dev.inmo.kslog.common.e
import dev.inmo.micro_utils.common.*
import dev.inmo.micro_utils.fsm.common.utils.StateHandlingErrorHandler
import dev.inmo.micro_utils.fsm.common.utils.defaultStateHandlingErrorHandler
@@ -45,13 +44,7 @@ open class DefaultUpdatableStatesMachine<T : State>(
val job = previousState.mapOnPresented {
statesJobs.remove(it)
} ?.takeIf { it.isActive } ?: scope.launch {
runCatching {
performUpdate(actualState)
}.onFailure {
logger.e(it) {
"Unable to perform update of state up to $actualState"
}
}.getOrThrow()
performUpdate(actualState)
}.also { job ->
job.invokeOnCompletion { _ ->
scope.launch {

View File

@@ -1,11 +1,10 @@
package dev.inmo.micro_utils.fsm.common.managers
import dev.inmo.micro_utils.coroutines.SmartRWLocker
import dev.inmo.micro_utils.coroutines.withReadAcquire
import dev.inmo.micro_utils.coroutines.withWriteLock
import dev.inmo.micro_utils.fsm.common.State
import dev.inmo.micro_utils.fsm.common.StatesManager
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
/**
* Implement this repo if you want to use some custom repo for [DefaultStatesManager]
@@ -20,14 +19,6 @@ interface DefaultStatesManagerRepo<T : State> {
* NOT be removed
*/
suspend fun removeState(state: T)
/**
* Semantically, calls [removeState] and then [set]
*/
suspend fun removeAndSet(toRemove: T, toSet: T) {
removeState(toRemove)
set(toSet)
}
/**
* @return Current list of available and saved states
*/
@@ -67,7 +58,7 @@ open class DefaultStatesManager<T : State>(
protected val _onEndChain = MutableSharedFlow<T>(0)
override val onEndChain: Flow<T> = _onEndChain.asSharedFlow()
protected val internalLocker = SmartRWLocker()
protected val mapMutex = Mutex()
constructor(
repo: DefaultStatesManagerRepo<T>,
@@ -77,30 +68,28 @@ open class DefaultStatesManager<T : State>(
onUpdateContextsConflictResolver = onContextsConflictResolver
)
override suspend fun update(old: T, new: T) = internalLocker.withWriteLock {
override suspend fun update(old: T, new: T) = mapMutex.withLock {
val stateByOldContext: T? = repo.getContextState(old.context)
when {
stateByOldContext != old -> return@withWriteLock
old.context == new.context -> {
repo.removeAndSet(old, new)
stateByOldContext != old -> return@withLock
stateByOldContext == null || old.context == new.context -> {
repo.removeState(old)
repo.set(new)
_onChainStateUpdated.emit(old to new)
}
old.context != new.context -> {
else -> {
val stateOnNewOneContext = repo.getContextState(new.context)
if (stateOnNewOneContext == null || onUpdateContextsConflictResolver(old, new, stateOnNewOneContext)) {
stateOnNewOneContext ?.let { endChainWithoutLock(it) }
repo.removeAndSet(old, new)
repo.removeState(old)
repo.set(new)
_onChainStateUpdated.emit(old to new)
} else {
error(
"Unable to update state from $old to $new due to false answer from $onUpdateContextsConflictResolver and state on old context $stateOnNewOneContext"
)
}
}
}
}
override suspend fun startChain(state: T) = internalLocker.withWriteLock {
override suspend fun startChain(state: T) = mapMutex.withLock {
val stateOnContext = repo.getContextState(state.context)
if (stateOnContext == null || onStartContextsConflictResolver(stateOnContext, state)) {
stateOnContext ?.let {
@@ -119,13 +108,11 @@ open class DefaultStatesManager<T : State>(
}
override suspend fun endChain(state: T) {
internalLocker.withWriteLock {
mapMutex.withLock {
endChainWithoutLock(state)
}
}
override suspend fun getActiveStates(): List<T> = internalLocker.withReadAcquire {
repo.getStates()
}
override suspend fun getActiveStates(): List<T> = repo.getStates()
}

View File

@@ -1,59 +1,25 @@
package dev.inmo.micro_utils.fsm.repos.common
import dev.inmo.kslog.common.TagLogger
import dev.inmo.kslog.common.i
import dev.inmo.micro_utils.coroutines.SmartRWLocker
import dev.inmo.micro_utils.coroutines.withReadAcquire
import dev.inmo.micro_utils.coroutines.withWriteLock
import dev.inmo.micro_utils.fsm.common.State
import dev.inmo.micro_utils.fsm.common.managers.DefaultStatesManagerRepo
import dev.inmo.micro_utils.repos.*
import dev.inmo.micro_utils.repos.pagination.getAll
import dev.inmo.micro_utils.repos.unset
class KeyValueBasedDefaultStatesManagerRepo<T : State>(
private val keyValueRepo: KeyValueRepo<Any, T>
) : DefaultStatesManagerRepo<T> {
private val locker = SmartRWLocker()
private val logger = TagLogger("KeyValueBasedDefaultStatesManagerRepo")
override suspend fun set(state: T) {
locker.withWriteLock {
keyValueRepo.set(state.context, state)
logger.i { "Set ${state.context} value to $state" }
}
keyValueRepo.set(state.context, state)
}
override suspend fun removeState(state: T) {
locker.withWriteLock {
if (keyValueRepo.get(state.context) == state) {
keyValueRepo.unset(state.context)
logger.i { "Unset $state" }
}
if (keyValueRepo.get(state.context) == state) {
keyValueRepo.unset(state.context)
}
}
override suspend fun removeAndSet(toRemove: T, toSet: T) {
locker.withWriteLock {
when {
toRemove.context == toSet.context -> {
keyValueRepo.set(toSet.context, toSet)
}
else -> {
keyValueRepo.set(toSet.context, toSet)
keyValueRepo.unset(toRemove)
}
}
}
}
override suspend fun getStates(): List<T> = keyValueRepo.getAll { keys(it) }.map { it.second }
override suspend fun getContextState(context: Any): T? = keyValueRepo.get(context)
override suspend fun getStates(): List<T> = locker.withReadAcquire {
keyValueRepo.getAll { keys(it) }.map { it.second }
}
override suspend fun getContextState(context: Any): T? = locker.withReadAcquire {
keyValueRepo.get(context)
}
override suspend fun contains(context: Any): Boolean = locker.withReadAcquire {
keyValueRepo.contains(context)
}
override suspend fun contains(context: Any): Boolean = keyValueRepo.contains(context)
}

View File

@@ -15,5 +15,5 @@ crypto_js_version=4.1.1
# Project data
group=dev.inmo
version=0.24.6
android_code_version=286
version=0.24.1
android_code_version=280

View File

@@ -1,42 +1,43 @@
[versions]
kt = "2.1.10"
kt = "2.1.0"
kt-serialization = "1.8.0"
kt-coroutines = "1.10.1"
kslog = "1.4.1"
kslog = "1.4.0"
jb-compose = "1.7.3"
jb-exposed = "0.59.0"
jb-exposed = "0.57.0"
jb-dokka = "2.0.0"
sqlite = "3.49.0.0"
sqlite = "3.47.2.0"
korlibs = "5.4.0"
uuid = "0.8.4"
ktor = "3.1.0"
ktor = "3.0.3"
gh-release = "2.5.2"
koin = "4.0.2"
koin = "4.0.1"
okio = "3.10.2"
ksp = "2.1.10-1.0.29"
ksp = "2.1.0-1.0.29"
kotlin-poet = "1.18.1"
versions = "0.51.0"
android-gradle = "8.7.+"
android-gradle = "8.2.2"
dexcount = "4.0.0"
android-coreKtx = "1.15.0"
android-recyclerView = "1.4.0"
android-recyclerView = "1.3.2"
android-appCompat = "1.7.0"
android-fragment = "1.8.6"
android-fragment = "1.8.5"
android-espresso = "3.6.1"
android-test = "1.2.1"
android-compose-material3 = "1.3.0"
android-props-minSdk = "21"
android-props-compileSdk = "35"

View File

@@ -1,7 +1,3 @@
if (ext.getProperties()["do_publish"] == false) {
return
}
apply plugin: 'maven-publish'
task javadocsJar(type: Jar) {
@@ -23,29 +19,29 @@ publishing {
}
developers {
developer {
id = "InsanusMokrassar"
name = "Aleksei Ovsiannikov"
email = "ovsyannikov.alexey95@gmail.com"
}
developer {
id = "000Sanya"
name = "Syrov Aleksandr"
email = "000sanya.000sanya@gmail.com"
}
}
licenses {
license {
name = "Apache Software License 2.0"
url = "https://github.com/InsanusMokrassar/MicroUtils/blob/master/LICENSE"
}
}
}
repositories {
@@ -53,51 +49,51 @@ publishing {
maven {
name = "GithubPackages"
url = uri("https://maven.pkg.github.com/InsanusMokrassar/MicroUtils")
credentials {
username = project.hasProperty('GITHUBPACKAGES_USER') ? project.property('GITHUBPACKAGES_USER') : System.getenv('GITHUBPACKAGES_USER')
password = project.hasProperty('GITHUBPACKAGES_PASSWORD') ? project.property('GITHUBPACKAGES_PASSWORD') : System.getenv('GITHUBPACKAGES_PASSWORD')
}
}
}
if ((project.hasProperty('INMONEXUS_USER') || System.getenv('INMONEXUS_USER') != null) && (project.hasProperty('INMONEXUS_PASSWORD') || System.getenv('INMONEXUS_PASSWORD') != null)) {
maven {
name = "InmoNexus"
url = uri("https://nexus.inmo.dev/repository/maven-releases/")
credentials {
username = project.hasProperty('INMONEXUS_USER') ? project.property('INMONEXUS_USER') : System.getenv('INMONEXUS_USER')
password = project.hasProperty('INMONEXUS_PASSWORD') ? project.property('INMONEXUS_PASSWORD') : System.getenv('INMONEXUS_PASSWORD')
}
}
}
if ((project.hasProperty('SONATYPE_USER') || System.getenv('SONATYPE_USER') != null) && (project.hasProperty('SONATYPE_PASSWORD') || System.getenv('SONATYPE_PASSWORD') != null)) {
maven {
name = "sonatype"
url = uri("https://oss.sonatype.org/service/local/staging/deploy/maven2/")
credentials {
username = project.hasProperty('SONATYPE_USER') ? project.property('SONATYPE_USER') : System.getenv('SONATYPE_USER')
password = project.hasProperty('SONATYPE_PASSWORD') ? project.property('SONATYPE_PASSWORD') : System.getenv('SONATYPE_PASSWORD')
}
}
}
}
}
}
if (project.hasProperty("signing.gnupg.keyName")) {
apply plugin: 'signing'
signing {
useGpgCmd()
sign publishing.publications
}
task signAll {
tasks.withType(Sign).forEach {
dependsOn(it)

View File

@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.12.1-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@@ -5,8 +5,6 @@ plugins {
id "com.google.devtools.ksp"
}
ext.do_publish = false
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64Project"

View File

@@ -1,38 +1,28 @@
package dev.inmo.micro_ksp.generator
import com.google.devtools.ksp.symbol.KSClassDeclaration
import com.google.devtools.ksp.symbol.KSDeclaration
import com.google.devtools.ksp.symbol.KSFile
import com.google.devtools.ksp.symbol.KSFunctionDeclaration
import com.squareup.kotlinpoet.FileSpec
import java.io.File
fun KSDeclaration.writeFile(
fun KSClassDeclaration.writeFile(
prefix: String = "",
suffix: String = "",
relatedPath: String = "",
force: Boolean = false,
forceUppercase: Boolean = true,
fileSpecBuilder: () -> FileSpec
) {
val containingFile = containingFile!!
val simpleName = if (forceUppercase) {
val rawSimpleName = simpleName.asString()
rawSimpleName.replaceFirst(rawSimpleName.first().toString(), rawSimpleName.first().uppercase())
} else {
simpleName.asString()
}
File(
File(
File(containingFile.filePath).parent,
relatedPath
),
"$prefix${simpleName}$suffix.kt"
"$prefix${simpleName.asString()}$suffix.kt"
).takeIf { force || !it.exists() } ?.apply {
parentFile.mkdirs()
val fileSpec = fileSpecBuilder()
writer().use { writer ->
fileSpec.writeTo(writer)
fileSpecBuilder().writeTo(writer)
}
}
}
@@ -52,9 +42,8 @@ fun KSFile.writeFile(
"$prefix${fileName.dropLastWhile { it != '.' }.removeSuffix(".")}$suffix.kt"
).takeIf { force || !it.exists() } ?.apply {
parentFile.mkdirs()
val fileSpec = fileSpecBuilder()
writer().use { writer ->
fileSpec.writeTo(writer)
fileSpecBuilder().writeTo(writer)
}
}
}
}

View File

@@ -1,25 +0,0 @@
package dev.inmo.micro_ksp.generator
import com.google.devtools.ksp.KSTypeNotPresentException
import com.google.devtools.ksp.KSTypesNotPresentException
import com.google.devtools.ksp.KspExperimental
import com.google.devtools.ksp.symbol.KSType
import com.squareup.kotlinpoet.asClassName
import com.squareup.kotlinpoet.ksp.toClassName
import kotlin.reflect.KClass
@OptIn(KspExperimental::class)
inline fun convertToClassName(getter: () -> KClass<*>) = try {
getter().asClassName()
} catch (e: KSTypeNotPresentException) {
e.ksType.toClassName()
}
@OptIn(KspExperimental::class)
inline fun convertToClassNames(getter: () -> List<KClass<*>>) = try {
getter().map { it.asClassName() }
} catch (e: KSTypesNotPresentException) {
e.ksTypes.map {
it.toClassName()
}
}

View File

@@ -3,15 +3,9 @@ package dev.inmo.micro_utils.ksp.sealed.generator
import com.google.devtools.ksp.KspExperimental
import com.google.devtools.ksp.getAnnotationsByType
import com.google.devtools.ksp.symbol.KSClassDeclaration
import dev.inmo.micro_utils.ksp.sealed.GenerateSealedTypesWorkaround
import dev.inmo.micro_utils.ksp.sealed.GenerateSealedWorkaround
import dev.inmo.microutils.kps.sealed.GenerateSealedWorkaround as OldGenerateSealedWorkaround
@OptIn(KspExperimental::class)
val KSClassDeclaration.getGenerateSealedWorkaroundAnnotation
get() = (getAnnotationsByType(GenerateSealedWorkaround::class).firstOrNull() ?: getAnnotationsByType(OldGenerateSealedWorkaround::class).firstOrNull())
@OptIn(KspExperimental::class)
val KSClassDeclaration.getGenerateSealedTypesWorkaroundAnnotation
get() = getAnnotationsByType(GenerateSealedTypesWorkaround::class).firstOrNull()

View File

@@ -6,17 +6,21 @@ import com.google.devtools.ksp.processing.CodeGenerator
import com.google.devtools.ksp.processing.Resolver
import com.google.devtools.ksp.processing.SymbolProcessor
import com.google.devtools.ksp.symbol.*
import com.squareup.kotlinpoet.*
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.CodeBlock
import com.squareup.kotlinpoet.FileSpec
import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.KModifier
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.PropertySpec
import com.squareup.kotlinpoet.asTypeName
import com.squareup.kotlinpoet.ksp.toClassName
import dev.inmo.micro_ksp.generator.buildSubFileName
import dev.inmo.micro_ksp.generator.companion
import dev.inmo.micro_ksp.generator.findSubClasses
import dev.inmo.micro_ksp.generator.writeFile
import dev.inmo.micro_utils.ksp.sealed.GenerateSealedTypesWorkaround
import dev.inmo.micro_utils.ksp.sealed.GenerateSealedWorkaround
import java.io.File
import kotlin.reflect.KClass
class Processor(
private val codeGenerator: CodeGenerator
@@ -105,62 +109,6 @@ class Processor(
)
}
@OptIn(KspExperimental::class)
private fun FileSpec.Builder.generateSealedTypesWorkaround(
ksClassDeclaration: KSClassDeclaration,
resolver: Resolver
) {
val annotation = ksClassDeclaration.getGenerateSealedTypesWorkaroundAnnotation
val subClasses = ksClassDeclaration.resolveSubclasses(
searchIn = resolver.getAllFiles(),
allowNonSealed = annotation ?.includeNonSealedSubTypes ?: false
).distinct()
val subClassesNames = subClasses.filter {
it.getAnnotationsByType(GenerateSealedTypesWorkaround.Exclude::class).count() == 0
}.sortedBy {
(it.getAnnotationsByType(GenerateSealedTypesWorkaround.Order::class).firstOrNull()) ?.order ?: 0
}.map {
it.toClassName()
}.toList()
val className = ksClassDeclaration.toClassName()
val setType = Set::class.asTypeName().parameterizedBy(
KClass::class.asTypeName().parameterizedBy(
TypeVariableName(
"out ${ksClassDeclaration.asStarProjectedType().toClassName().simpleNames.joinToString(".")}",
)
)
)
addProperty(
PropertySpec.builder(
"subtypes",
setType
).apply {
modifiers.add(
KModifier.PRIVATE
)
initializer(
CodeBlock.of(
"""setOf(${subClassesNames.joinToString(",\n") { it.simpleNames.joinToString(".") + "::class" }})"""
)
)
}.build()
)
addFunction(
FunSpec.builder("subtypes").apply {
val companion = ksClassDeclaration.takeIf { it.isCompanionObject } ?.toClassName()
?: ksClassDeclaration.companion ?.toClassName()
?: ClassName(className.packageName, *className.simpleNames.toTypedArray(), "Companion")
receiver(companion)
returns(setType)
addCode(
CodeBlock.of(
"""return subtypes"""
)
)
}.build()
)
}
@OptIn(KspExperimental::class)
override fun process(resolver: Resolver): List<KSAnnotated> {
(resolver.getSymbolsWithAnnotation(GenerateSealedWorkaround::class.qualifiedName!!)).filterIsInstance<KSClassDeclaration>().forEach {
@@ -183,26 +131,6 @@ class Processor(
}.build()
}
}
(resolver.getSymbolsWithAnnotation(GenerateSealedTypesWorkaround::class.qualifiedName!!)).filterIsInstance<KSClassDeclaration>().forEach {
val prefix = (it.getGenerateSealedTypesWorkaroundAnnotation) ?.prefix ?.takeIf {
it.isNotEmpty()
} ?: it.buildSubFileName.replaceFirst(it.simpleName.asString(), "")
it.writeFile(prefix = prefix, suffix = "SealedTypesWorkaround") {
FileSpec.builder(
it.packageName.asString(),
"${it.simpleName.getShortName()}SealedTypesWorkaround"
).apply {
addFileComment(
"""
THIS CODE HAVE BEEN GENERATED AUTOMATICALLY
TO REGENERATE IT JUST DELETE FILE
ORIGINAL FILE: ${it.containingFile ?.fileName}
""".trimIndent()
)
generateSealedTypesWorkaround(it, resolver)
}.build()
}
}
return emptyList()
}

View File

@@ -5,8 +5,6 @@ plugins {
id "com.google.devtools.ksp"
}
ext.do_publish = false
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64Project"

View File

@@ -1,19 +1,14 @@
package dev.inmo.micro_utils.ksp.sealed.generator.test
import dev.inmo.micro_utils.ksp.sealed.GenerateSealedTypesWorkaround
import dev.inmo.micro_utils.ksp.sealed.GenerateSealedWorkaround
@GenerateSealedWorkaround
@GenerateSealedTypesWorkaround
sealed interface Test {
@GenerateSealedWorkaround.Order(2)
@GenerateSealedTypesWorkaround.Exclude
object A : Test
@GenerateSealedWorkaround.Exclude
@GenerateSealedTypesWorkaround.Order(2)
object B : Test
@GenerateSealedWorkaround.Order(0)
@GenerateSealedTypesWorkaround.Order(0)
object C : Test
// Required for successful sealed workaround generation

View File

@@ -1,12 +0,0 @@
// THIS CODE HAVE BEEN GENERATED AUTOMATICALLY
// TO REGENERATE IT JUST DELETE FILE
// ORIGINAL FILE: Test.kt
package dev.inmo.micro_utils.ksp.`sealed`.generator.test
import kotlin.collections.Set
import kotlin.reflect.KClass
private val subtypes: Set<KClass<out Test>> = setOf(Test.C::class,
Test.B::class)
public fun Test.Companion.subtypes(): Set<KClass<out Test>> = subtypes

View File

@@ -1,40 +0,0 @@
import dev.inmo.micro_utils.ksp.sealed.generator.test.subtypes
import dev.inmo.micro_utils.ksp.sealed.generator.test.values
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class TestTests {
@Test
fun testThatAfterCompilationTestWorkaroundsHaveCorrectValues() {
val correctValues = arrayOf(
dev.inmo.micro_utils.ksp.sealed.generator.test.Test.C,
dev.inmo.micro_utils.ksp.sealed.generator.test.Test.A,
)
val correctSubtypes = arrayOf(
dev.inmo.micro_utils.ksp.sealed.generator.test.Test.C::class,
dev.inmo.micro_utils.ksp.sealed.generator.test.Test.B::class,
)
assertEquals(
correctValues.size, dev.inmo.micro_utils.ksp.sealed.generator.test.Test.values().size
)
correctValues.forEachIndexed { index, value ->
assertTrue(
value === dev.inmo.micro_utils.ksp.sealed.generator.test.Test.values().elementAt(index)
)
}
assertEquals(
correctSubtypes.size, dev.inmo.micro_utils.ksp.sealed.generator.test.Test.subtypes().size
)
correctSubtypes.forEachIndexed { index, value ->
assertTrue(
value.qualifiedName != null
)
assertTrue(
value.qualifiedName === dev.inmo.micro_utils.ksp.sealed.generator.test.Test.subtypes().elementAt(index).qualifiedName
)
}
}
}

View File

@@ -1,15 +0,0 @@
package dev.inmo.micro_utils.ksp.sealed
@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.CLASS)
annotation class GenerateSealedTypesWorkaround(
val prefix: String = "",
val includeNonSealedSubTypes: Boolean = false,
) {
@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.CLASS)
annotation class Order(val order: Int)
@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.CLASS)
annotation class Exclude
}

View File

@@ -4,7 +4,7 @@ package dev.inmo.micro_utils.ksp.sealed
@Target(AnnotationTarget.CLASS)
annotation class GenerateSealedWorkaround(
val prefix: String = "",
val includeNonSealedSubTypes: Boolean = false,
val includeNonSealedSubTypes: Boolean = false
) {
@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.CLASS)

View File

@@ -1,7 +0,0 @@
plugins {
id "org.jetbrains.kotlin.multiplatform"
id "org.jetbrains.kotlin.plugin.serialization"
id "com.android.library"
}
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64Project"

View File

@@ -1,22 +0,0 @@
plugins {
id "org.jetbrains.kotlin.jvm"
}
apply from: "$publish_jvm"
repositories {
mavenCentral()
}
dependencies {
implementation libs.kt.stdlib
api project(":micro_utils.ksp.generator")
api project(":micro_utils.ksp.variations")
api libs.kotlin.poet
api libs.ksp
}
java {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}

View File

@@ -1,243 +0,0 @@
package dev.inmo.micro_utils.ksp.variations.generator
import com.google.devtools.ksp.KSTypeNotPresentException
import com.google.devtools.ksp.KspExperimental
import com.google.devtools.ksp.getAnnotationsByType
import com.google.devtools.ksp.processing.CodeGenerator
import com.google.devtools.ksp.processing.Resolver
import com.google.devtools.ksp.processing.SymbolProcessor
import com.google.devtools.ksp.symbol.*
import com.squareup.kotlinpoet.*
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.ksp.toAnnotationSpec
import com.squareup.kotlinpoet.ksp.toClassName
import com.squareup.kotlinpoet.ksp.toKModifier
import com.squareup.kotlinpoet.ksp.toTypeName
import dev.inmo.micro_ksp.generator.convertToClassName
import dev.inmo.micro_ksp.generator.convertToClassNames
import dev.inmo.micro_ksp.generator.findSubClasses
import dev.inmo.micro_ksp.generator.writeFile
import dev.inmo.micro_utils.ksp.variations.GenerateVariations
import dev.inmo.micro_utils.ksp.variations.GenerationVariant
import kotlin.math.pow
class Processor(
private val codeGenerator: CodeGenerator
) : SymbolProcessor {
private fun KSClassDeclaration.findSealedConnection(potentialSealedParent: KSClassDeclaration): Boolean {
val targetClassname = potentialSealedParent.qualifiedName ?.asString()
return superTypes.any {
val itAsDeclaration = it.resolve().declaration as? KSClassDeclaration ?: return@any false
targetClassname == (itAsDeclaration.qualifiedName ?.asString()) || (itAsDeclaration.getSealedSubclasses().any() && itAsDeclaration.findSealedConnection(potentialSealedParent))
}
}
private fun KSClassDeclaration.resolveSubclasses(
searchIn: Sequence<KSAnnotated>,
allowNonSealed: Boolean
): Sequence<KSClassDeclaration> {
return findSubClasses(searchIn).let {
if (allowNonSealed) {
it
} else {
it.filter {
it.findSealedConnection(this)
}
}
}
}
@OptIn(KspExperimental::class)
private fun FileSpec.Builder.generateVariations(
ksFunctionDeclaration: KSFunctionDeclaration,
resolver: Resolver
) {
val annotation = ksFunctionDeclaration.getAnnotationsByType(GenerateVariations::class).first()
val variations: List<Pair<List<GenerationVariant>, KSValueParameter>> = ksFunctionDeclaration.parameters.mapNotNull {
val variationAnnotations = it.getAnnotationsByType(GenerationVariant::class).toList()
variationAnnotations to it
}
val accumulatedGenerations = mutableSetOf<Pair<FunSpec, Map<String, String>>>()
val baseFunctionParameters = ksFunctionDeclaration.parameters.mapNotNull {
ParameterSpec
.builder(
it.name ?.asString() ?: return@mapNotNull null,
it.type.toTypeName(),
)
.apply {
if (it.isCrossInline) {
addModifiers(KModifier.CROSSINLINE)
}
if (it.isVal) {
addModifiers(KModifier.VALUE)
}
if (it.isNoInline) {
addModifiers(KModifier.NOINLINE)
}
if (it.isVararg) {
addModifiers(KModifier.VARARG)
}
it.annotations.forEach {
if (it.shortName.asString() == GenerationVariant::class.simpleName) return@forEach
addAnnotation(it.toAnnotationSpec(omitDefaultValues = false))
}
}
.build() to it.hasDefault
}
val baseFunctionFunSpecs = mutableListOf<Pair<FunSpec, Map<String, String>>>()
let {
var defaultParametersIndicator = 0u
val maxIndicator = baseFunctionParameters.filter { it.second }.foldIndexed(0u) { index, acc, _ ->
2.0.pow(index).toUInt() + acc
}
while (defaultParametersIndicator <= maxIndicator) {
var currentDefaultParameterIndex = 0u
val baseFunctionDefaults = mutableMapOf<String, String>()
val funSpec = FunSpec.builder(ksFunctionDeclaration.simpleName.asString()).apply {
modifiers.addAll(ksFunctionDeclaration.modifiers.mapNotNull { it.toKModifier() })
ksFunctionDeclaration.annotations.forEach {
if (it.shortName.asString() == GenerateVariations::class.simpleName) return@forEach
addAnnotation(it.toAnnotationSpec(omitDefaultValues = false))
}
ksFunctionDeclaration.extensionReceiver ?.let {
receiver(it.toTypeName())
}
ksFunctionDeclaration.returnType ?.let {
returns(it.toTypeName())
}
}
baseFunctionParameters.forEach { (parameter, hasDefault) ->
if (hasDefault) {
val shouldBeIncluded = (2.0.pow(currentDefaultParameterIndex.toInt()).toUInt()).and(defaultParametersIndicator) > 0u
currentDefaultParameterIndex++
if (!shouldBeIncluded) {
return@forEach
}
}
funSpec.addParameter(parameter)
val name = parameter.name
val defaultValueString = if (parameter.modifiers.contains(KModifier.VARARG)) {
"*$name"
} else {
"$name"
}
baseFunctionDefaults[parameter.name] = defaultValueString
}
baseFunctionFunSpecs.add(
funSpec.build() to baseFunctionDefaults.toMap()
)
defaultParametersIndicator++
}
}
variations.forEach { (variations, parameter) ->
(baseFunctionFunSpecs + accumulatedGenerations).forEach { (accumulatedGeneration, baseDefaults) ->
if ((parameter.name ?.asString() ?: "this") !in baseDefaults.keys) {
return@forEach
}
variations.forEach { variation ->
val defaults = mutableMapOf<String, String>()
accumulatedGenerations.add(
FunSpec.builder(accumulatedGeneration.name).apply {
modifiers.addAll(accumulatedGeneration.modifiers)
accumulatedGeneration.annotations.forEach {
addAnnotation(it)
}
accumulatedGeneration.receiverType ?.let {
receiver(it)
}
returns(accumulatedGeneration.returnType)
accumulatedGeneration.parameters.forEach {
val actualName = if (variation.argName.isEmpty()) it.name else variation.argName
parameters.add(
(if (it.name == (parameter.name ?.asString() ?: "this")) {
val type = convertToClassName { variation.type }
val genericTypes = convertToClassNames { variation.genericTypes.toList() }
ParameterSpec
.builder(
actualName,
if (genericTypes.isEmpty()) {
type
} else {
type.parameterizedBy(
*genericTypes.toTypedArray()
)
}
)
.apply {
addModifiers(it.modifiers)
val defaultValueString = """
with(${actualName}) {${
if (it.modifiers.contains(KModifier.VARARG)) {
"map { it.${variation.conversion} }.toTypedArray()"
} else {
"${variation.conversion}"
}
}}
""".trimIndent()
defaults[it.name] = defaultValueString
}
} else {
it.toBuilder().apply {
defaults[it.name] = it.name
}
})
.apply {
it.annotations.forEach {
addAnnotation(it)
}
}
.build()
)
}
val parameters = accumulatedGeneration.parameters.joinToString(", ") {
val itName = it.name
"""
$itName = ${defaults[itName] ?: baseDefaults[itName] ?: itName}
""".trimIndent()
}
addCode(
"""
return ${ksFunctionDeclaration.simpleName.asString()}(
$parameters
)
""".trimIndent()
)
}.build() to defaults.toMap()
)
}
}
}
accumulatedGenerations.forEach {
addFunction(it.first)
}
}
@OptIn(KspExperimental::class)
override fun process(resolver: Resolver): List<KSAnnotated> {
(resolver.getSymbolsWithAnnotation(GenerateVariations::class.qualifiedName!!)).filterIsInstance<KSFunctionDeclaration>().forEach {
val prefix = (it.getAnnotationsByType(GenerateVariations::class)).firstOrNull() ?.prefix ?.takeIf {
it.isNotEmpty()
} ?: it.simpleName.asString().replaceFirst(it.simpleName.asString(), "")
it.writeFile(prefix = prefix, suffix = "GeneratedVariation") {
FileSpec.builder(
it.packageName.asString(),
"${it.simpleName.getShortName().let { it.replaceFirst(it.first().toString(), it.first().uppercase()) }}GeneratedVariation"
).apply {
addFileComment(
"""
THIS CODE HAVE BEEN GENERATED AUTOMATICALLY
TO REGENERATE IT JUST DELETE FILE
ORIGINAL FILE: ${it.containingFile ?.fileName}
""".trimIndent()
)
generateVariations(it, resolver)
}.build()
}
}
return emptyList()
}
}

View File

@@ -1,11 +0,0 @@
package dev.inmo.micro_utils.ksp.variations.generator
import com.google.devtools.ksp.processing.SymbolProcessor
import com.google.devtools.ksp.processing.SymbolProcessorEnvironment
import com.google.devtools.ksp.processing.SymbolProcessorProvider
class Provider : SymbolProcessorProvider {
override fun create(environment: SymbolProcessorEnvironment): SymbolProcessor = Processor(
environment.codeGenerator
)
}

View File

@@ -1 +0,0 @@
dev.inmo.micro_utils.ksp.variations.generator.Provider

View File

@@ -1,30 +0,0 @@
plugins {
id "org.jetbrains.kotlin.multiplatform"
id "org.jetbrains.kotlin.plugin.serialization"
id "com.android.library"
id "com.google.devtools.ksp"
}
ext.do_publish = false
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64Project"
kotlin {
sourceSets {
commonMain {
dependencies {
implementation libs.kt.stdlib
api project(":micro_utils.ksp.variations")
}
}
}
}
dependencies {
add("kspCommonMainMetadata", project(":micro_utils.ksp.variations.generator"))
}
ksp {
}

View File

@@ -1,61 +0,0 @@
// THIS CODE HAVE BEEN GENERATED AUTOMATICALLY
// TO REGENERATE IT JUST DELETE FILE
// ORIGINAL FILE: SampleFun.kt
package dev.inmo.micro_utils.ksp.variations.generator.test
import kotlin.Boolean
import kotlin.Int
import kotlin.String
import kotlin.Unit
public suspend fun SimpleType.sample2(arg12: Int): Unit = sample2(
arg1 = with(arg12) {toString()}
)
public suspend fun SimpleType.sample2(arg12: Int, arg2: Int): Unit = sample2(
arg1 = with(arg12) {toString()}, arg2 = arg2
)
public suspend fun SimpleType.sample2(arg12: Int, arg3: Boolean): Unit = sample2(
arg1 = with(arg12) {toString()}, arg3 = arg3
)
public suspend fun SimpleType.sample2(
arg12: Int,
arg2: Int,
arg3: Boolean,
): Unit = sample2(
arg1 = with(arg12) {toString()}, arg2 = arg2, arg3 = arg3
)
public suspend fun SimpleType.sample2(arg22: String): Unit = sample2(
arg2 = with(arg22) {toInt()}
)
public suspend fun SimpleType.sample2(arg1: String, arg22: String): Unit = sample2(
arg1 = arg1, arg2 = with(arg22) {toInt()}
)
public suspend fun SimpleType.sample2(arg22: String, arg3: Boolean): Unit = sample2(
arg2 = with(arg22) {toInt()}, arg3 = arg3
)
public suspend fun SimpleType.sample2(
arg1: String,
arg22: String,
arg3: Boolean,
): Unit = sample2(
arg1 = arg1, arg2 = with(arg22) {toInt()}, arg3 = arg3
)
public suspend fun SimpleType.sample2(arg12: Int, arg22: String): Unit = sample2(
arg12 = arg12, arg2 = with(arg22) {toInt()}
)
public suspend fun SimpleType.sample2(
arg12: Int,
arg22: String,
arg3: Boolean,
): Unit = sample2(
arg12 = arg12, arg2 = with(arg22) {toInt()}, arg3 = arg3
)

View File

@@ -1,52 +0,0 @@
package dev.inmo.micro_utils.ksp.variations.generator.test
import dev.inmo.micro_utils.ksp.variations.GenerateVariations
import dev.inmo.micro_utils.ksp.variations.GenerationVariant
data class SimpleType(
val value: String
)
data class GenericType<T>(
val value: T
)
@GenerateVariations
fun sample(
@GenerationVariant(
SimpleType::class,
"value",
)
@GenerationVariant(
GenericType::class,
"value.toString()",
genericTypes = arrayOf(Int::class)
)
example: String = "12"
) = println(example)
@GenerateVariations
fun sampleVararg(
@GenerationVariant(
SimpleType::class,
"value",
)
vararg example: String = arrayOf("12")
) = println(example.joinToString())
@GenerateVariations
suspend fun SimpleType.sample2(
@GenerationVariant(
Int::class,
"toString()",
"arg12",
)
arg1: String = "1",
@GenerationVariant(
String::class,
"toInt()",
"arg22",
)
arg2: Int = 2,
arg3: Boolean = false
) = println(arg1)

View File

@@ -1,15 +0,0 @@
// THIS CODE HAVE BEEN GENERATED AUTOMATICALLY
// TO REGENERATE IT JUST DELETE FILE
// ORIGINAL FILE: SampleFun.kt
package dev.inmo.micro_utils.ksp.variations.generator.test
import kotlin.Int
import kotlin.Unit
public fun sample(example: SimpleType): Unit = sample(
example = with(example) {value}
)
public fun sample(example: GenericType<Int>): Unit = sample(
example = with(example) {value.toString()}
)

View File

@@ -1,10 +0,0 @@
// THIS CODE HAVE BEEN GENERATED AUTOMATICALLY
// TO REGENERATE IT JUST DELETE FILE
// ORIGINAL FILE: SampleFun.kt
package dev.inmo.micro_utils.ksp.variations.generator.test
import kotlin.Unit
public fun sampleVararg(vararg example: SimpleType): Unit = sampleVararg(
example = with(example) {map { it.value }.toTypedArray()}
)

View File

@@ -1,7 +0,0 @@
package dev.inmo.micro_utils.ksp.variations
@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.FUNCTION)
annotation class GenerateVariations(
val prefix: String = ""
)

View File

@@ -1,18 +0,0 @@
package dev.inmo.micro_utils.ksp.variations
import kotlin.reflect.KClass
/**
* @param argName New argument name. Default - empty - means "use default arg name"
* @param type Qualified class name, like "dev.inmo.micro_utils.ksp.variants.GenerationVariant"
* @param conversion Conversion string with `this`
*/
@Retention(AnnotationRetention.BINARY)
@Repeatable
@Target(AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.VALUE_PARAMETER)
annotation class GenerationVariant(
val type: KClass<*>,
val conversion: String,
val argName: String = "",
vararg val genericTypes: KClass<*>
)

View File

@@ -2,7 +2,7 @@ package dev.inmo.micro_utils.ktor.client
import dev.inmo.micro_utils.common.MPPFile
import dev.inmo.micro_utils.coroutines.LinkedSupervisorJob
import dev.inmo.micro_utils.coroutines.launchLoggingDropExceptions
import dev.inmo.micro_utils.coroutines.launchSafelyWithoutExceptions
import dev.inmo.micro_utils.ktor.common.TemporalFileId
import io.ktor.client.HttpClient
import io.ktor.client.content.*
@@ -27,7 +27,7 @@ suspend fun tempUpload(
val request = XMLHttpRequest()
request.responseType = XMLHttpRequestResponseType.TEXT
request.upload.onprogress = {
subscope.launchLoggingDropExceptions { onUpload.onProgress(it.loaded.toLong(), it.total.toLong()) }
subscope.launchSafelyWithoutExceptions { onUpload.onProgress(it.loaded.toLong(), it.total.toLong()) }
}
request.onload = {
if (request.status == 200.toShort()) {

View File

@@ -2,7 +2,7 @@ package dev.inmo.micro_utils.ktor.client
import dev.inmo.micro_utils.common.MPPFile
import dev.inmo.micro_utils.coroutines.LinkedSupervisorJob
import dev.inmo.micro_utils.coroutines.launchLoggingDropExceptions
import dev.inmo.micro_utils.coroutines.launchSafelyWithoutExceptions
import io.ktor.client.HttpClient
import io.ktor.client.content.*
import io.ktor.http.Headers
@@ -66,7 +66,7 @@ actual suspend fun <T> HttpClient.uniUpload(
}
request.responseType = XMLHttpRequestResponseType.TEXT
request.upload.onprogress = {
subscope.launchLoggingDropExceptions { onUpload.onProgress(it.loaded.toLong(), it.total.toLong()) }
subscope.launchSafelyWithoutExceptions { onUpload.onProgress(it.loaded.toLong(), it.total.toLong()) }
}
request.onload = {
if (request.status == 200.toShort()) {

View File

@@ -3,7 +3,7 @@ package dev.inmo.micro_utils.ktor.server
import com.benasher44.uuid.uuid4
import dev.inmo.micro_utils.common.FileName
import dev.inmo.micro_utils.common.MPPFile
import dev.inmo.micro_utils.coroutines.launchLoggingDropExceptions
import dev.inmo.micro_utils.coroutines.launchSafelyWithoutExceptions
import dev.inmo.micro_utils.ktor.common.DefaultTemporalFilesSubPath
import dev.inmo.micro_utils.ktor.common.TemporalFileId
import dev.inmo.micro_utils.ktor.server.configurators.ApplicationRoutingConfigurator
@@ -44,7 +44,7 @@ class TemporalFilesRoutingConfigurator(
filesMap: MutableMap<TemporalFileId, MPPFile>,
filesMutex: Mutex,
onNewFileFlow: Flow<TemporalFileId>
): Job = scope.launchLoggingDropExceptions {
): Job = scope.launchSafelyWithoutExceptions {
while (currentCoroutineContext().isActive) {
val filesWithCreationInfo = filesMap.mapNotNull { (fileId, file) ->
fileId to ((Files.getAttribute(file.toPath(), "creationTime") as? FileTime) ?.toMillis() ?: return@mapNotNull null)

View File

@@ -2,19 +2,19 @@ package dev.inmo.micro_utils.pagination
import org.jetbrains.exposed.sql.*
fun Query.paginate(with: Pagination, orderBy: Pair<Expression<*>, SortOrder>? = null) =
limit(with.size)
.offset(with.firstIndex.toLong())
.let {
if (orderBy != null) {
it.orderBy(
orderBy.first,
orderBy.second
)
} else {
it
}
fun Query.paginate(with: Pagination, orderBy: Pair<Expression<*>, SortOrder>? = null) = limit(
with.size,
with.firstIndex.toLong()
).let {
if (orderBy != null) {
it.orderBy(
orderBy.first,
orderBy.second
)
} else {
it
}
}
fun Query.paginate(with: Pagination, orderBy: Expression<*>?, reversed: Boolean = false) = paginate(
with,

View File

@@ -1,6 +1,6 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"extends": [
"config:recommended"
"config:base"
]
}

View File

@@ -2,7 +2,7 @@ package dev.inmo.micro_utils.repos.cache.full
import dev.inmo.micro_utils.common.*
import dev.inmo.micro_utils.coroutines.SmartRWLocker
import dev.inmo.micro_utils.coroutines.launchLoggingDropExceptions
import dev.inmo.micro_utils.coroutines.launchSafelyWithoutExceptions
import dev.inmo.micro_utils.coroutines.withReadAcquire
import dev.inmo.micro_utils.coroutines.withWriteLock
import dev.inmo.micro_utils.pagination.Pagination
@@ -116,7 +116,7 @@ open class FullCRUDCacheRepo<ObjectType, IdType, InputValueType>(
CRUDRepo<ObjectType, IdType, InputValueType> {
init {
if (!skipStartInvalidate) {
scope.launchLoggingDropExceptions {
scope.launchSafelyWithoutExceptions {
if (locker.writeMutex.isLocked) {
initialInvalidate()
} else {

View File

@@ -2,7 +2,7 @@ package dev.inmo.micro_utils.repos.cache.full
import dev.inmo.micro_utils.common.*
import dev.inmo.micro_utils.coroutines.SmartRWLocker
import dev.inmo.micro_utils.coroutines.launchLoggingDropExceptions
import dev.inmo.micro_utils.coroutines.launchSafelyWithoutExceptions
import dev.inmo.micro_utils.coroutines.withReadAcquire
import dev.inmo.micro_utils.coroutines.withWriteLock
import dev.inmo.micro_utils.pagination.Pagination
@@ -141,7 +141,7 @@ open class FullKeyValueCacheRepo<Key,Value>(
) {
init {
if (!skipStartInvalidate) {
scope.launchLoggingDropExceptions {
scope.launchSafelyWithoutExceptions {
if (locker.writeMutex.isLocked) {
initialInvalidate()
} else {

View File

@@ -2,7 +2,7 @@ package dev.inmo.micro_utils.repos.cache.full
import dev.inmo.micro_utils.common.*
import dev.inmo.micro_utils.coroutines.SmartRWLocker
import dev.inmo.micro_utils.coroutines.launchLoggingDropExceptions
import dev.inmo.micro_utils.coroutines.launchSafelyWithoutExceptions
import dev.inmo.micro_utils.coroutines.withReadAcquire
import dev.inmo.micro_utils.coroutines.withWriteLock
import dev.inmo.micro_utils.pagination.*
@@ -210,7 +210,7 @@ open class FullKeyValuesCacheRepo<Key,Value>(
WriteKeyValuesRepo<Key, Value> by parentRepo {
init {
if (!skipStartInvalidate) {
scope.launchLoggingDropExceptions {
scope.launchSafelyWithoutExceptions {
if (locker.writeMutex.isLocked) {
initialInvalidate()
} else {

View File

@@ -2,7 +2,7 @@ package dev.inmo.micro_utils.repos.cache.full.direct
import dev.inmo.micro_utils.common.*
import dev.inmo.micro_utils.coroutines.SmartRWLocker
import dev.inmo.micro_utils.coroutines.launchLoggingDropExceptions
import dev.inmo.micro_utils.coroutines.launchSafelyWithoutExceptions
import dev.inmo.micro_utils.coroutines.withReadAcquire
import dev.inmo.micro_utils.coroutines.withWriteLock
import dev.inmo.micro_utils.pagination.Pagination
@@ -82,7 +82,7 @@ open class DirectFullCRUDCacheRepo<ObjectType, IdType, InputValueType>(
CRUDRepo<ObjectType, IdType, InputValueType> {
init {
if (!skipStartInvalidate) {
scope.launchLoggingDropExceptions {
scope.launchSafelyWithoutExceptions {
if (locker.writeMutex.isLocked) {
initialInvalidate()
} else {

View File

@@ -1,7 +1,7 @@
package dev.inmo.micro_utils.repos.cache.full.direct
import dev.inmo.micro_utils.coroutines.SmartRWLocker
import dev.inmo.micro_utils.coroutines.launchLoggingDropExceptions
import dev.inmo.micro_utils.coroutines.launchSafelyWithoutExceptions
import dev.inmo.micro_utils.coroutines.withReadAcquire
import dev.inmo.micro_utils.coroutines.withWriteLock
import dev.inmo.micro_utils.pagination.Pagination
@@ -117,7 +117,7 @@ open class DirectFullKeyValueCacheRepo<Key, Value>(
DirectFullReadKeyValueCacheRepo<Key, Value>(parentRepo, kvCache, locker) {
init {
if (!skipStartInvalidate) {
scope.launchLoggingDropExceptions {
scope.launchSafelyWithoutExceptions {
if (locker.writeMutex.isLocked) {
initialInvalidate()
} else {

View File

@@ -2,7 +2,7 @@ package dev.inmo.micro_utils.repos.cache.full.direct
import dev.inmo.micro_utils.common.*
import dev.inmo.micro_utils.coroutines.SmartRWLocker
import dev.inmo.micro_utils.coroutines.launchLoggingDropExceptions
import dev.inmo.micro_utils.coroutines.launchSafelyWithoutExceptions
import dev.inmo.micro_utils.coroutines.withReadAcquire
import dev.inmo.micro_utils.coroutines.withWriteLock
import dev.inmo.micro_utils.pagination.*
@@ -145,7 +145,7 @@ open class DirectFullKeyValuesCacheRepo<Key,Value>(
WriteKeyValuesRepo<Key, Value> by parentRepo {
init {
if (!skipStartInvalidate) {
scope.launchLoggingDropExceptions {
scope.launchSafelyWithoutExceptions {
if (locker.writeMutex.isLocked) {
initialInvalidate()
} else {

View File

@@ -137,7 +137,7 @@ abstract class AbstractExposedWriteCRUDRepo<ObjectType, IdType, InputValueType>(
override suspend fun deleteById(ids: List<IdType>) {
onBeforeDelete(ids)
transaction(db = database) {
val deleted = deleteWhere { selectByIds(it, ids) }
val deleted = deleteWhere(null, null) { selectByIds(it, ids) }
if (deleted == ids.size) {
ids
} else {

View File

@@ -8,16 +8,8 @@ interface CommonExposedRepo<IdType, ObjectType> : ExposedRepo {
val selectById: ISqlExpressionBuilder.(IdType) -> Op<Boolean>
val selectByIds: ISqlExpressionBuilder.(List<IdType>) -> Op<Boolean>
get() = {
if (it.isEmpty()) {
Op.FALSE
} else {
var op = it.firstOrNull() ?.let { selectById(it) } ?: Op.FALSE
var i = 1
while (i < it.size) {
op = op.or(selectById(it[i]))
i++
}
op
}
it.foldRight<IdType, Op<Boolean>?>(null) { id, acc ->
acc ?.or(selectById(id)) ?: selectById(id)
} ?: Op.FALSE
}
}

View File

@@ -62,10 +62,6 @@ String[] includes = [
":ksp:classcasts:generator",
":ksp:classcasts:generator:test",
":ksp:variations",
":ksp:variations:generator",
":ksp:variations:generator:test",
":dokka"
]