Compare commits

...

69 Commits

Author SHA1 Message Date
bad9a53fdb update dependencies 2024-10-06 12:28:48 +06:00
0bce7bd60a fix of #488 2024-10-06 12:25:42 +06:00
2f70a1cfb4 solution of #489 2024-10-01 20:30:45 +06:00
bfb6e738ee add debouncedBy extension 2024-09-26 23:50:57 +06:00
c7ad9aae07 start 0.22.5 2024-09-26 23:17:00 +06:00
fecd719239 Merge pull request #491 from InsanusMokrassar/0.22.4
0.22.4
2024-09-25 22:53:53 +06:00
18d6ac31b5 update exposed 2024-09-25 22:09:50 +06:00
d8dbebfc7e start 0.22.4 2024-09-25 21:03:18 +06:00
16463d0eb9 Merge pull request #487 from InsanusMokrassar/0.22.3
0.22.3
2024-09-20 13:27:16 +06:00
837cac644d add extensions in JS 2024-09-20 13:14:50 +06:00
e83e0a8535 update dependencies 2024-09-20 12:44:10 +06:00
2e309c31a6 start 0.22.3 2024-09-20 12:18:17 +06:00
625db02651 Merge pull request #479 from InsanusMokrassar/0.22.2
0.22.2
2024-08-30 20:57:10 +06:00
e3144c08c1 update dependencies 2024-08-30 20:48:34 +06:00
40e25970ad start 0.22.2 2024-08-30 20:46:07 +06:00
4ccb8a8d11 Merge pull request #477 from InsanusMokrassar/0.22.1
0.22.1
2024-08-29 15:02:34 +06:00
26d1c3d9ef update dependencies 2024-08-29 14:49:29 +06:00
cc8fe7b001 start 0.22.1 2024-08-29 14:14:20 +06:00
4601eab864 update gradle scripts to improve performance of configuration 2024-08-27 18:57:59 +06:00
1ee9c88ffd Merge pull request #459 from InsanusMokrassar/0.22.0
0.22.0
2024-08-11 16:51:30 +06:00
7feac213f6 update android code version 2024-08-11 16:51:09 +06:00
c75a9c0f61 update dependencies 2024-08-11 16:44:08 +06:00
afd0c9784f Update libs.versions.toml 2024-08-11 12:41:30 +06:00
f1ddbea06e update android version 2024-08-09 23:06:50 +06:00
42bf3cd4e3 update kotlin-poet 2024-08-09 22:21:53 +06:00
27f5549f56 improve tests of repos 2024-08-09 21:58:09 +06:00
b0569f8421 add tests for cruds 2024-08-09 19:22:32 +06:00
8d86f29325 Revert "small change in FullKeyValuesCacheRepoTests and FullKeyValueCacheRepoTests"
This reverts commit 3db8d2291e.
2024-08-07 16:50:13 +06:00
aeca32498a Revert "Update build.yml"
This reverts commit ab0b3a8f0d.
2024-08-07 16:50:13 +06:00
e8232664f3 update delay on creating tests in cache 2024-08-07 16:50:13 +06:00
efa869f91a Update build.yml 2024-08-07 16:50:13 +06:00
dbff3d7cf1 small change in FullKeyValuesCacheRepoTests and FullKeyValueCacheRepoTests 2024-08-07 16:50:13 +06:00
9e70f73684 upgrade kotlin 2024-08-07 16:50:13 +06:00
9f2f0de0c4 add check of emptiness in map reslozations of KV/KVs repos 2024-08-07 16:50:13 +06:00
bf293a8f8f fix of tests 2024-08-07 16:50:13 +06:00
5fbc1a132f improvements in SmartRWLocker and breaking of FullKeyValueCacheRepo tests 2024-08-07 16:50:13 +06:00
36093b9741 fix of full caches initial actualization and realize MapKeyValuesRepo methods getAll 2024-08-07 16:50:13 +06:00
8713fb04c5 small change in MapWriteKeyValuesRepo.set and remove duration of FullKeyValuesCacheRepoTests.creatingWorksProperly 2024-08-07 16:50:13 +06:00
ea82a59f31 update gradle wrapper version 2024-08-07 16:50:13 +06:00
18f67cd4f2 small improvement of test data in Full Cache tests 2024-08-07 16:50:13 +06:00
120e7228c7 add FullKeyValuesCacheRepoTests and small rewrite of MapWriteKeyValuesRepo.set(Map<Key, List<Value>>) function 2024-08-07 16:50:13 +06:00
892fa90c37 start add cache repos tests 2024-08-07 16:50:13 +06:00
491dac5bf0 update exposed 2024-08-07 16:50:13 +06:00
2ab06fbafd change version 2024-08-07 16:50:11 +06:00
e68735d061 Revert "migrations onto new libraries"
This reverts commit 647cd7d7b4.
2024-08-07 16:46:49 +06:00
9ba4d98c30 migrations onto new libraries 2024-08-07 16:46:49 +06:00
19bbfd4916 downgrade kotlin and fix build 2024-08-07 16:46:49 +06:00
d94cd7ea94 some fixes 2024-08-07 16:46:49 +06:00
0dd8f41eb0 update dependencies 2024-08-07 16:46:49 +06:00
f1ab5ab51f update kotlinx serialization 2024-08-07 16:46:49 +06:00
a8056f3120 update dependencies 2024-08-07 16:46:49 +06:00
09c0cdebb5 update dependencies 2024-08-07 16:46:49 +06:00
629d7c7a82 temporal project in upgrade 2024-08-07 16:46:49 +06:00
a0dd1aec3d trying to update to new compose 2024-08-07 16:46:49 +06:00
17d6377902 Merge pull request #466 from InsanusMokrassar/0.21.6
0.21.6
2024-07-26 19:16:13 +06:00
ad401105a1 fixes in ksp sealed generator 2024-07-26 17:17:11 +06:00
4913e99c2e start 0.21.6 2024-07-26 16:40:30 +06:00
16b97029cf Merge pull request #465 from InsanusMokrassar/0.21.5
0.21.5
2024-07-25 02:48:27 +06:00
481130c9bb fill changelog 2024-07-25 02:30:10 +06:00
698ed6718d improve sealed workaround generation 2024-07-25 02:27:33 +06:00
d164813bb4 Revert "start moving to kotlinx-io"
This reverts commit 52157ee0e7.
2024-07-25 01:20:32 +06:00
52157ee0e7 start moving to kotlinx-io 2024-07-24 00:34:49 +06:00
877b62fe5d start 0.21.5 2024-07-24 00:06:18 +06:00
d823a02971 Merge pull request #464 from InsanusMokrassar/0.21.4
add additional targets with natives support
2024-07-16 17:58:02 +06:00
e950056e3b add additional targets with natives support 2024-07-16 17:18:26 +06:00
70014ba233 Merge pull request #463 from InsanusMokrassar/0.21.4
0.21.4
2024-07-16 14:23:41 +06:00
4425f24a20 add support of native platforms in common compose and coroutines compose 2024-07-16 14:16:08 +06:00
410964a44b start 0.21.4 2024-07-16 14:02:36 +06:00
30389e8536 Merge pull request #462 from InsanusMokrassar/0.21.3
0.21.3
2024-07-15 16:33:28 +06:00
133 changed files with 6214 additions and 3117 deletions

2
.gitignore vendored
View File

@@ -1,4 +1,5 @@
.idea
.kotlin
out/*
*.iml
target
@@ -17,5 +18,6 @@ publishing.sh
local.*
local/
**/*.local.*
.kotlin/

View File

@@ -1,5 +1,99 @@
# Changelog
## 0.22.5
* `Versions`:
* `Compose`: `1.7.0-beta02` -> `1.7.0-rc01`
* `SQLite`: `3.46.1.2` -> `3.46.1.3`
* `AndroidXFragment`: `1.8.3` -> `1.8.4`
* `Common`:
* Add extension `withReplacedAt`/`withReplaced` ([#489](https://github.com/InsanusMokrassar/MicroUtils/issues/489))
* `Coroutines`:
* Add extension `Flow.debouncedBy`
* `Ktor`:
* `Server`:
* Add `KtorApplicationConfigurator.Routing.Static` as solution for [#488](https://github.com/InsanusMokrassar/MicroUtils/issues/488)
## 0.22.4
* `Versions`:
* `Exposed`: `0.54.0` -> `0.55.0`
* `SQLite`: `3.46.1.0` -> `3.46.1.2`
## 0.22.3
* `Versions`:
* `Serialization`: `1.7.2` -> `1.7.3`
* `Coroutines`: `1.8.1` -> `1.9.0`
* `Compose`: `1.7.0-alpha03` -> `1.7.0-beta02`
* `Koin`: `3.5.6` -> `4.0.0`
* `Okio`: `3.9.0` -> `3.9.1`
* `AndroidFragment`: `1.8.2` -> `1.8.3`
* `androidx.compose.material3:material3` has been replaced with `org.jetbrains.compose.material3:material3`
* `Common`:
* `JS`:
* Add several useful extensions
* `Compose`:
* `JS`:
* Add several useful extensions
## 0.22.2
* `Versions`:
* `Exposed`: `0.53.0` -> `0.54.0`
* `SQLite`: `3.46.0.1` -> `3.46.1.0`
## 0.22.1
* `Versions`:
* `Kotlin`: `2.0.10` -> `2.0.20`
* `Serialization`: `1.7.1` -> `1.7.2`
* `KSLog`: `1.3.5` -> `1.3.6`
* `Compose`: `1.7.0-alpha02` -> `1.7.0-alpha03`
* `Ktor`: `2.3.11` -> `2.3.12`
## 0.22.0
**THIS UPDATE CONTAINS BREAKING CHANGES ACCORDING TO UPDATE UP TO KOTLIN 2.0**
* `Versions`:
* `Kotlin`: `1.9.23` -> `2.0.10`
* `Serialization`: `1.6.3` -> `1.7.1`
* `KSLog`: `1.3.4` -> `1.3.5`
* `Compose`: `1.6.2` -> `1.7.0-alpha02`
* `Exposed`: `0.50.1` -> `0.53.0`
* `AndroidAppCompat`: `1.6.1` -> `1.7.0`
* `AndroidFragment`: `1.7.1` -> `1.8.2`
## 0.21.6
* `KSP`:
* `Sealed`:
* Fixes in generation
## 0.21.5
* `KSP`:
* Add utility functions `KSClassDeclaration.findSubClasses`
* `Sealed`:
* Improve generation
## 0.21.4
* `Common`:
* `Compose`:
* Add support of mingw, linux, arm64 targets
* `Coroutines`:
* `Compose`:
* Add support of mingw, linux, arm64 targets
* `Koin`:
* Add support of mingw, linux, arm64 targets
* `KSP`:
* `ClassCasts`:
* Add support of mingw, linux, arm64 targets
* `Sealed`:
* Add support of mingw, linux, arm64 targets
## 0.21.3
* `Colors`:

View File

@@ -4,7 +4,7 @@ plugins {
id "com.android.library"
}
apply from: "$mppAndroidProjectPresetPath"
apply from: "$mppAndroidProject"
kotlin {
sourceSets {

View File

@@ -4,7 +4,7 @@ plugins {
id "com.android.library"
}
apply from: "$mppAndroidProjectPresetPath"
apply from: "$mppAndroidProject"
kotlin {
sourceSets {

View File

@@ -3,9 +3,10 @@ plugins {
id "org.jetbrains.kotlin.plugin.serialization"
id "com.android.library"
alias(libs.plugins.jb.compose)
alias(libs.plugins.kt.jb.compose)
}
apply from: "$mppProjectWithSerializationAndComposePresetPath"
apply from: "$mppProjectWithSerializationAndCompose"
kotlin {
sourceSets {

View File

@@ -4,7 +4,7 @@ plugins {
id "com.android.library"
}
apply from: "$mppAndroidProjectPresetPath"
apply from: "$mppAndroidProject"
kotlin {
sourceSets {

View File

@@ -3,15 +3,16 @@ plugins {
id "org.jetbrains.kotlin.plugin.serialization"
id "com.android.library"
alias(libs.plugins.jb.compose)
alias(libs.plugins.kt.jb.compose)
}
apply from: "$mppProjectWithSerializationAndComposePresetPath"
apply from: "$mppProjectWithSerializationAndCompose"
kotlin {
sourceSets {
androidMain {
dependencies {
api libs.android.compose.material3
api libs.jb.compose.material3
}
}
}

View File

@@ -29,15 +29,6 @@ allprojects {
maven { url "https://maven.pkg.jetbrains.space/public/p/compose/dev" }
maven { url "https://nexus.inmo.dev/repository/maven-releases/" }
}
// temporal crutch until legacy tests will be stabled or legacy target will be removed
if (it != rootProject.findProject("docs")) {
tasks.whenTaskAdded { task ->
if(task.name == "jsLegacyBrowserTest" || task.name == "jsLegacyNodeTest") {
task.enabled = false
}
}
}
}
apply from: "./extensions.gradle"

View File

@@ -4,7 +4,7 @@ plugins {
id "com.android.library"
}
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64ProjectPresetPath"
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64Project"
kotlin {
sourceSets {

View File

@@ -4,4 +4,4 @@ plugins {
id "com.android.library"
}
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64ProjectPresetPath"
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64Project"

View File

@@ -4,7 +4,7 @@ plugins {
id "com.android.library"
}
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64ProjectPresetPath"
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64Project"
kotlin {
sourceSets {

View File

@@ -3,9 +3,10 @@ plugins {
id "org.jetbrains.kotlin.plugin.serialization"
id "com.android.library"
alias(libs.plugins.jb.compose)
alias(libs.plugins.kt.jb.compose)
}
apply from: "$mppProjectWithSerializationAndComposePresetPath"
apply from: "$mppComposeJvmJsAndroidLinuxMingwLinuxArm64Project"
kotlin {
sourceSets {

View File

@@ -0,0 +1,19 @@
package dev.inmo.micro_utils.common.compose
import org.jetbrains.compose.web.dom.AttrBuilderContext
import org.w3c.dom.Element
operator fun <T : Element> AttrBuilderContext<T>?.plus(
other: AttrBuilderContext<T>?
) = when (this) {
null -> other ?: {}
else -> when (other) {
null -> this ?: {}
else -> {
{
invoke(this)
other(this)
}
}
}
}

View File

@@ -0,0 +1,22 @@
package dev.inmo.micro_utils.common.compose
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.DisposableEffectResult
import androidx.compose.runtime.DisposableEffectScope
import org.jetbrains.compose.web.attributes.AttrsScope
import org.jetbrains.compose.web.dom.ElementScope
import org.w3c.dom.Element
/**
* This function must be called in the context of your tag content. It works like default [AttrsScope.ref],
* but able to be used several times. Uses [DisposableEffect] under the hood
*/
@Composable
fun <T : Element> ElementScope<T>.ref(
block: DisposableEffectScope.(T) -> DisposableEffectResult
) {
DisposableEffect(0) {
block(scopeElement)
}
}

View File

@@ -0,0 +1,11 @@
package dev.inmo.micro_utils.common.compose
import org.jetbrains.compose.web.dom.AttrBuilderContext
fun tagClasses(vararg classnames: String): AttrBuilderContext<*> = {
classes(*classnames)
}
fun tagId(id: String): AttrBuilderContext<*> = {
id(id)
}

View File

@@ -8,7 +8,7 @@ private inline fun <T> getObject(
additional: MutableList<T>,
iterator: Iterator<T>
): T? = when {
additional.isNotEmpty() -> additional.removeFirst()
additional.isNotEmpty() -> additional.removeAt(0)
iterator.hasNext() -> iterator.next()
else -> null
}

View File

@@ -0,0 +1,5 @@
package dev.inmo.micro_utils.common
fun <T> Iterable<T>.withReplacedAt(i: Int, block: (T) -> T): List<T> = take(i) + block(elementAt(i)) + drop(i + 1)
fun <T> Iterable<T>.withReplaced(t: T, block: (T) -> T): List<T> = withReplacedAt(indexOf(t), block)

View File

@@ -0,0 +1,21 @@
package dev.inmo.micro_utils.common
import kotlin.test.Test
import kotlin.test.assertEquals
class WithReplacedTest {
@Test
fun testReplaced() {
val data = 0 until 10
val testData = Int.MAX_VALUE
for (i in 0 until data.last) {
val withReplaced = data.withReplacedAt(i) {
testData
}
val dataAsMutableList = data.toMutableList()
dataAsMutableList[i] = testData
assertEquals(withReplaced, dataAsMutableList.toList())
}
}
}

View File

@@ -0,0 +1,13 @@
package dev.inmo.micro_utils.common
import kotlinx.browser.window
fun copyToClipboard(text: String): Boolean {
return runCatching {
window.navigator.clipboard.writeText(
text
)
}.onFailure {
it.printStackTrace()
}.isSuccess
}

View File

@@ -0,0 +1,29 @@
package dev.inmo.micro_utils.common
import kotlinx.browser.window
import org.w3c.files.Blob
import org.w3c.files.BlobPropertyBag
import kotlin.js.json
external class ClipboardItem(data: dynamic)
inline fun Blob.convertToClipboardItem(): ClipboardItem {
val itemData: dynamic = json(this.type to this)
return ClipboardItem(itemData)
}
suspend fun copyImageURLToClipboard(imageUrl: String): Boolean {
return runCatching {
val response = window.fetch(imageUrl).await()
val blob = response.blob().await()
val data = arrayOf(
Blob(
arrayOf(blob),
BlobPropertyBag("image/png")
).convertToClipboardItem()
).asDynamic()
window.navigator.clipboard.write(data)
}.onFailure {
it.printStackTrace()
}.isSuccess
}

View File

@@ -4,7 +4,7 @@ plugins {
id "com.android.library"
}
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64ProjectPresetPath"
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64Project"
kotlin {
sourceSets {

View File

@@ -3,9 +3,10 @@ plugins {
id "org.jetbrains.kotlin.plugin.serialization"
id "com.android.library"
alias(libs.plugins.jb.compose)
alias(libs.plugins.kt.jb.compose)
}
apply from: "$mppProjectWithSerializationAndComposePresetPath"
apply from: "$mppComposeJvmJsAndroidLinuxMingwLinuxArm64Project"
kotlin {
sourceSets {

View File

@@ -0,0 +1,40 @@
package dev.inmo.micro_utils.coroutines
import kotlinx.coroutines.Job
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlin.jvm.JvmInline
import kotlin.time.Duration
@JvmInline
private value class DebouncedByData<T>(
val millisToData: Pair<Long, T>
)
fun <T> Flow<T>.debouncedBy(timeout: (T) -> Long, markerFactory: (T) -> Any?): Flow<T> = channelFlow {
val jobs = mutableMapOf<Any?, Job>()
val mutex = Mutex()
subscribe(this) {
mutex.withLock {
val marker = markerFactory(it)
lateinit var job: Job
job = async {
delay(timeout(it))
mutex.withLock {
if (jobs[marker] === job) {
this@channelFlow.send(it)
jobs.remove(marker)
}
}
}
jobs[marker] ?.cancel()
jobs[marker] = job
}
}
}
fun <T> Flow<T>.debouncedBy(timeout: Long, markerFactory: (T) -> Any?): Flow<T> = debouncedBy({ timeout }, markerFactory)
fun <T> Flow<T>.debouncedBy(timeout: Duration, markerFactory: (T) -> Any?): Flow<T> = debouncedBy({ timeout.inWholeMilliseconds }, markerFactory)

View File

@@ -13,7 +13,7 @@ import kotlin.contracts.contract
* * [unlockWrite] will just unlock [writeMutex]
*/
class SmartRWLocker(private val readPermits: Int = Int.MAX_VALUE, writeIsLocked: Boolean = false) {
private val _readSemaphore = SmartSemaphore.Mutable(permits = readPermits, acquiredPermits = 0)
private val _readSemaphore = SmartSemaphore.Mutable(permits = readPermits, acquiredPermits = if (writeIsLocked) readPermits else 0)
private val _writeMutex = SmartMutex.Mutable(locked = writeIsLocked)
val readSemaphore: SmartSemaphore.Immutable = _readSemaphore.immutable()

View File

@@ -0,0 +1,42 @@
import dev.inmo.micro_utils.coroutines.debouncedBy
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class DebouncedByTests {
@Test
fun testThatParallelDebouncingWorksCorrectly() = runTest {
val dataToMarkerFactories = listOf(
1 to 0,
2 to 1,
3 to 2,
4 to 0,
5 to 1,
6 to 2,
7 to 0,
8 to 1,
9 to 2,
)
val collected = mutableListOf<Int>()
dataToMarkerFactories.asFlow().debouncedBy(10L) {
it.second
}.collect {
when (it.second) {
0 -> assertEquals(7, it.first)
1 -> assertEquals(8, it.first)
2 -> assertEquals(9, it.first)
else -> error("wtf")
}
collected.add(it.first)
}
val expectedList = listOf(7, 8, 9)
assertEquals(expectedList, collected)
assertTrue { collected.containsAll(expectedList) }
assertTrue { expectedList.containsAll(collected) }
}
}

View File

@@ -4,7 +4,7 @@ plugins {
id "com.android.library"
}
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64ProjectPresetPath"
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64Project"
kotlin {
sourceSets {

View File

@@ -130,4 +130,4 @@ tasks.dokkaHtml {
}
}
apply from: "$defaultAndroidSettingsPresetPath"
apply from: "$defaultAndroidSettings"

View File

@@ -1,42 +1,32 @@
allprojects {
ext {
projectByName = { name ->
for (subproject in rootProject.subprojects) {
if (subproject.name == name) {
return subproject
}
}
return null
}
File templatesFolder = new File("$rootProject.projectDir.absolutePath${File.separatorChar}gradle${File.separatorChar}templates")
internalProject = { name ->
// if (releaseMode) {
// "$group:$name:$version"
// } else {
// projectByName("$name")
// }
projectByName("$name")
}
Map properties = new HashMap<String, String>()
releaseMode = (project.hasProperty('RELEASE_MODE') && project.property('RELEASE_MODE') == "true") || System.getenv('RELEASE_MODE') == "true"
// String compilerPluginVersionFromProperties = (String) project.properties["compose.kotlinCompilerPluginVersion"]
// String compilerPluginVersionFromLibrariesVersions = libs.versions.compose.kotlin.get()
// composePluginKotlinVersion = compilerPluginVersionFromProperties
// if (compilerPluginVersionFromProperties == null) {
// composePluginKotlinVersion = compilerPluginVersionFromLibrariesVersions
// }
mppProjectWithSerializationPresetPath = "${rootProject.projectDir.absolutePath}/mppJvmJsAndroidProject.gradle"
mppProjectWithSerializationAndComposePresetPath = "${rootProject.projectDir.absolutePath}/mppProjectWithSerializationAndCompose.gradle"
mppJavaProjectPresetPath = "${rootProject.projectDir.absolutePath}/mppJavaProject.gradle"
mppJvmJsLinuxMingwProjectPresetPath = "${rootProject.projectDir.absolutePath}/mppJvmJsLinuxMingwProject.gradle"
mppJvmJsLinuxMingwLinuxArm64ProjectPresetPath = "${rootProject.projectDir.absolutePath}/mppJvmJsLinuxMingwLinuxArm64Project.gradle"
mppJvmJsAndroidLinuxMingwLinuxArm64ProjectPresetPath = "${rootProject.projectDir.absolutePath}/mppJvmJsAndroidLinuxMingwLinuxArm64Project.gradle"
mppAndroidProjectPresetPath = "${rootProject.projectDir.absolutePath}/mppAndroidProject.gradle"
defaultAndroidSettingsPresetPath = "${rootProject.projectDir.absolutePath}/defaultAndroidSettings.gradle"
publishGradlePath = "${rootProject.projectDir.absolutePath}/publish.gradle"
publishJvmOnlyPath = "${rootProject.projectDir.absolutePath}/jvm.publish.gradle"
if (templatesFolder.exists() && templatesFolder.isDirectory()) {
templatesFolder.listFiles().each {
properties[it.name - ".gradle"] = it.absolutePath
}
}
properties["projectByName"] = { name ->
for (subproject in rootProject.subprojects) {
if (subproject.name == name) {
return subproject
}
}
return null
}
properties["internalProject"] = { name ->
projectByName("$name")
}
allprojects {
ext {
releaseMode = (project.hasProperty('RELEASE_MODE') && project.property('RELEASE_MODE') == "true") || System.getenv('RELEASE_MODE') == "true"
properties.forEach { k, v ->
it[k] = v
}
}
}

View File

@@ -4,7 +4,7 @@ plugins {
id "com.android.library"
}
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64ProjectPresetPath"
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64Project"
kotlin {
sourceSets {

View File

@@ -4,7 +4,7 @@ plugins {
id "com.android.library"
}
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64ProjectPresetPath"
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64Project"
kotlin {
sourceSets {

View File

@@ -15,5 +15,5 @@ crypto_js_version=4.1.1
# Project data
group=dev.inmo
version=0.21.3
android_code_version=262
version=0.22.5
android_code_version=271

View File

@@ -1,45 +1,47 @@
[versions]
kt = "1.9.23"
kt-serialization = "1.6.3"
kt-coroutines = "1.8.1"
kt = "2.0.20"
kt-serialization = "1.7.3"
kt-coroutines = "1.9.0"
kslog = "1.3.4"
kslog = "1.3.6"
jb-compose = "1.6.2"
jb-exposed = "0.50.1"
jb-compose = "1.7.0-rc01"
jb-exposed = "0.55.0"
jb-dokka = "1.9.20"
sqlite = "3.46.1.3"
korlibs = "5.4.0"
uuid = "0.8.4"
ktor = "2.3.11"
ktor = "2.3.12"
gh-release = "2.5.2"
koin = "3.5.6"
koin = "4.0.0"
okio = "3.9.0"
okio = "3.9.1"
ksp = "1.9.23-1.0.20"
kotlin-poet = "1.16.0"
ksp = "2.0.20-1.0.25"
kotlin-poet = "1.18.1"
versions = "0.51.0"
android-gradle = "8.2.0"
android-gradle = "8.2.2"
dexcount = "4.0.0"
android-coreKtx = "1.13.1"
android-recyclerView = "1.3.2"
android-appCompat = "1.6.1"
android-fragment = "1.7.1"
android-espresso = "3.5.1"
android-test = "1.1.5"
android-compose-material3 = "1.2.1"
android-appCompat = "1.7.0"
android-fragment = "1.8.4"
android-espresso = "3.6.1"
android-test = "1.2.1"
android-compose-material3 = "1.3.0"
android-props-minSdk = "21"
android-props-compileSdk = "34"
android-props-buildTools = "34.0.0"
android-props-compileSdk = "35"
android-props-buildTools = "35.0.0"
[libraries]
@@ -52,6 +54,7 @@ kt-serialization-cbor = { module = "org.jetbrains.kotlinx:kotlinx-serialization-
kt-coroutines = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "kt-coroutines" }
kt-coroutines-android = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-android", version.ref = "kt-coroutines" }
kt-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "kt-coroutines" }
kt-coroutines-debug = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-debug", version.ref = "kt-coroutines" }
ktor-io = { module = "io.ktor:ktor-io", version.ref = "ktor" }
@@ -79,12 +82,14 @@ koin = { module = "io.insert-koin:koin-core", version.ref = "koin" }
jb-exposed = { module = "org.jetbrains.exposed:exposed-core", version.ref = "jb-exposed" }
jb-exposed-jdbc = { module = "org.jetbrains.exposed:exposed-jdbc", version.ref = "jb-exposed" }
sqlite = { module = "org.xerial:sqlite-jdbc", version.ref = "sqlite" }
jb-compose-material3 = { module = "org.jetbrains.compose.material3:material3", version.ref = "jb-compose" }
android-coreKtx = { module = "androidx.core:core-ktx", version.ref = "android-coreKtx" }
android-recyclerView = { module = "androidx.recyclerview:recyclerview", version.ref = "android-recyclerView" }
android-appCompat-resources = { module = "androidx.appcompat:appcompat-resources", version.ref = "android-appCompat" }
android-compose-material3 = { module = "androidx.compose.material3:material3", version.ref = "android-compose-material3" }
android-fragment = { module = "androidx.fragment:fragment", version.ref = "android-fragment" }
android-espresso = { module = "androidx.test.espresso:espresso-core", version.ref = "android-espresso" }
android-test-junit = { module = "androidx.test.ext:junit", version.ref = "android-test" }
@@ -113,5 +118,6 @@ buildscript-android-dexcount = { module = "com.getkeepsafe.dexcount:dexcount-gra
[plugins]
jb-compose = { id = "org.jetbrains.compose", version.ref = "jb-compose" }
kt-jb-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kt" }
versions = { id = "com.github.ben-manes.versions", version.ref = "versions" }

View File

@@ -6,6 +6,7 @@ android {
defaultConfig {
minSdkVersion libs.versions.android.props.minSdk.get().toInteger()
compileSdkVersion libs.versions.android.props.compileSdk.get().toInteger()
targetSdkVersion libs.versions.android.props.compileSdk.get().toInteger()
versionCode "${android_code_version}".toInteger()
versionName "$version"

View File

@@ -1,7 +1,7 @@
project.version = "$version"
project.group = "$group"
apply from: "$publishGradlePath"
apply from: "$publish"
kotlin {
androidTarget {
@@ -29,7 +29,7 @@ kotlin {
}
}
apply from: "$defaultAndroidSettingsPresetPath"
apply from: "$defaultAndroidSettings"
java {
sourceCompatibility = JavaVersion.VERSION_17

View File

@@ -1,7 +1,7 @@
project.version = "$version"
project.group = "$group"
apply from: "$publishGradlePath"
apply from: "$publish"
kotlin {
jvm {
@@ -12,8 +12,20 @@ kotlin {
}
}
js (IR) {
browser()
nodejs()
browser {
testTask {
useMocha {
timeout = "60000"
}
}
}
nodejs {
testTask {
useMocha {
timeout = "60000"
}
}
}
}
androidTarget {
publishAllLibraryVariants()
@@ -25,11 +37,13 @@ kotlin {
}
linuxX64()
mingwX64()
linuxArm64()
sourceSets {
commonMain {
dependencies {
implementation kotlin('stdlib')
implementation compose.runtime
api libs.kt.serialization
}
}
@@ -40,40 +54,53 @@ kotlin {
implementation libs.kt.coroutines.test
}
}
jvmTest {
dependencies {
implementation kotlin('test-junit')
}
}
jsTest {
dependencies {
implementation kotlin('test-js')
implementation kotlin('test-junit')
}
}
androidUnitTest {
dependencies {
implementation kotlin('test-junit')
implementation libs.android.test.junit
implementation libs.android.espresso
implementation compose.uiTest
}
}
androidInstrumentedTest {
dependencies {
implementation kotlin('test-junit')
implementation libs.android.test.junit
implementation libs.android.espresso
}
}
mingwX64Test {
jvmMain {
dependencies {
implementation kotlin('test-junit')
implementation compose.desktop.currentOs
}
}
linuxX64Test {
jvmTest {
dependencies {
implementation kotlin('test-junit')
implementation compose.uiTest
}
}
jsMain {
dependencies {
implementation compose.web.core
}
}
jsTest {
dependencies {
implementation kotlin('test-js')
}
}
nativeMain.dependsOn commonMain
linuxX64Main.dependsOn nativeMain
mingwX64Main.dependsOn nativeMain
linuxArm64Main.dependsOn nativeMain
androidMain.dependsOn jvmMain
}
}
apply from: "$defaultAndroidSettingsPresetPath"
apply from: "$defaultAndroidSettings"
java {
sourceCompatibility = JavaVersion.VERSION_17

View File

@@ -1,7 +1,7 @@
project.version = "$version"
project.group = "$group"
apply from: "$publishGradlePath"
apply from: "$publish"
kotlin {
jvm {

View File

@@ -1,7 +1,7 @@
project.version = "$version"
project.group = "$group"
apply from: "$publishGradlePath"
apply from: "$publish"
kotlin {
jvm {
@@ -12,8 +12,20 @@ kotlin {
}
}
js (IR) {
browser()
nodejs()
browser {
testTask {
useMocha {
timeout = "60000"
}
}
}
nodejs {
testTask {
useMocha {
timeout = "60000"
}
}
}
}
androidTarget {
publishAllLibraryVariants()
@@ -36,7 +48,7 @@ kotlin {
}
commonTest {
dependencies {
implementation kotlin('test-common')
implementation kotlin('test')
implementation kotlin('test-annotations-common')
implementation libs.kt.coroutines.test
}
@@ -57,7 +69,6 @@ kotlin {
jsTest {
dependencies {
implementation kotlin('test-js')
implementation kotlin('test-junit')
}
}
nativeMain.dependsOn commonMain
@@ -69,7 +80,7 @@ kotlin {
}
}
apply from: "$defaultAndroidSettingsPresetPath"
apply from: "$defaultAndroidSettings"
java {
sourceCompatibility = JavaVersion.VERSION_17

View File

@@ -1,7 +1,7 @@
project.version = "$version"
project.group = "$group"
apply from: "$publishGradlePath"
apply from: "$publish"
kotlin {
jvm {
@@ -12,8 +12,20 @@ kotlin {
}
}
js (IR) {
browser()
nodejs()
browser {
testTask {
useMocha {
timeout = "60000"
}
}
}
nodejs {
testTask {
useMocha {
timeout = "60000"
}
}
}
}
linuxX64()
mingwX64()
@@ -41,17 +53,6 @@ kotlin {
jsTest {
dependencies {
implementation kotlin('test-js')
implementation kotlin('test-junit')
}
}
mingwX64Test {
dependencies {
implementation kotlin('test-junit')
}
}
linuxX64Test {
dependencies {
implementation kotlin('test-junit')
}
}

View File

@@ -1,7 +1,7 @@
project.version = "$version"
project.group = "$group"
apply from: "$publishGradlePath"
apply from: "$publish"
kotlin {
jvm {
@@ -12,8 +12,20 @@ kotlin {
}
}
js (IR) {
browser()
nodejs()
browser {
testTask {
useMocha {
timeout = "60000"
}
}
}
nodejs {
testTask {
useMocha {
timeout = "60000"
}
}
}
}
androidTarget {
publishAllLibraryVariants()
@@ -58,7 +70,6 @@ kotlin {
jsTest {
dependencies {
implementation kotlin('test-js')
implementation kotlin('test-junit')
}
}
androidUnitTest {
@@ -69,17 +80,10 @@ kotlin {
implementation compose.uiTest
}
}
androidInstrumentedTest {
dependencies {
implementation kotlin('test-junit')
implementation libs.android.test.junit
implementation libs.android.espresso
}
}
}
}
apply from: "$defaultAndroidSettingsPresetPath"
apply from: "$defaultAndroidSettings"
java {
sourceCompatibility = JavaVersion.VERSION_17

View File

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

View File

@@ -4,7 +4,7 @@ plugins {
id "com.android.library"
}
apply from: "$mppProjectWithSerializationPresetPath"
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64Project"
kotlin {
sourceSets {

View File

@@ -2,7 +2,7 @@ plugins {
id "org.jetbrains.kotlin.jvm"
}
apply from: "$publishJvmOnlyPath"
apply from: "$publish_jvm"
repositories {
mavenCentral()

View File

@@ -5,7 +5,7 @@ plugins {
id "com.google.devtools.ksp"
}
apply from: "$mppProjectWithSerializationPresetPath"
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64Project"
kotlin {

View File

@@ -4,4 +4,4 @@ plugins {
id "com.android.library"
}
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64ProjectPresetPath"
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64Project"

View File

@@ -2,7 +2,7 @@ plugins {
id "org.jetbrains.kotlin.jvm"
}
apply from: "$publishJvmOnlyPath"
apply from: "$publish_jvm"
repositories {
mavenCentral()

View File

@@ -5,7 +5,7 @@ plugins {
id "com.google.devtools.ksp"
}
apply from: "$mppProjectWithSerializationPresetPath"
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64Project"
kotlin {

View File

@@ -2,7 +2,7 @@ plugins {
id "org.jetbrains.kotlin.jvm"
}
apply from: "$publishJvmOnlyPath"
apply from: "$publish_jvm"
repositories {
mavenCentral()

View File

@@ -0,0 +1,30 @@
package dev.inmo.micro_ksp.generator
import com.google.devtools.ksp.getAllSuperTypes
import com.google.devtools.ksp.symbol.KSAnnotated
import com.google.devtools.ksp.symbol.KSClassDeclaration
import com.google.devtools.ksp.symbol.KSDeclarationContainer
import com.google.devtools.ksp.symbol.KSFile
fun KSClassDeclaration.findSubClasses(subSymbol: KSAnnotated): Sequence<KSClassDeclaration> {
return when (subSymbol) {
is KSClassDeclaration -> if (subSymbol.getAllSuperTypes().map { it.declaration }.contains(this)) {
sequenceOf(subSymbol)
} else {
sequenceOf()
}
else -> sequenceOf()
} + if (subSymbol is KSDeclarationContainer) {
subSymbol.declarations.flatMap {
findSubClasses(it)
}
} else {
sequenceOf()
}
}
fun KSClassDeclaration.findSubClasses(files: Sequence<KSAnnotated>): Sequence<KSClassDeclaration> {
return files.flatMap {
findSubClasses(it)
}
}

View File

@@ -4,4 +4,4 @@ plugins {
id "com.android.library"
}
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64ProjectPresetPath"
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64Project"

View File

@@ -2,7 +2,7 @@ plugins {
id "org.jetbrains.kotlin.jvm"
}
apply from: "$publishJvmOnlyPath"
apply from: "$publish_jvm"
repositories {
mavenCentral()

View File

@@ -6,7 +6,6 @@ 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.AnnotationSpec
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.CodeBlock
import com.squareup.kotlinpoet.FileSpec
@@ -16,18 +15,35 @@ 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.findSubClasses
import dev.inmo.micro_ksp.generator.writeFile
import dev.inmo.microutils.kps.sealed.GenerateSealedWorkaround
import java.io.File
class Processor(
private val codeGenerator: CodeGenerator
) : SymbolProcessor {
private fun KSClassDeclaration.resolveSubclasses(): List<KSClassDeclaration> {
return (getSealedSubclasses().flatMap {
it.resolveSubclasses()
}.ifEmpty {
sequenceOf(this)
}).toList()
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)
@@ -35,7 +51,11 @@ class Processor(
ksClassDeclaration: KSClassDeclaration,
resolver: Resolver
) {
val subClasses = ksClassDeclaration.resolveSubclasses().distinct()
val annotation = ksClassDeclaration.getAnnotationsByType(GenerateSealedWorkaround::class).first()
val subClasses = ksClassDeclaration.resolveSubclasses(
searchIn = resolver.getAllFiles(),
allowNonSealed = annotation.includeNonSealedSubTypes
).distinct()
val subClassesNames = subClasses.filter {
when (it.classKind) {
ClassKind.ENUM_ENTRY,
@@ -51,7 +71,7 @@ class Processor(
(it.getAnnotationsByType(GenerateSealedWorkaround.Order::class).firstOrNull()) ?.order ?: 0
}.map {
it.toClassName()
}
}.toList()
val className = ksClassDeclaration.toClassName()
val setType = Set::class.asTypeName().parameterizedBy(
ksClassDeclaration.toClassName()

View File

@@ -5,7 +5,7 @@ plugins {
id "com.google.devtools.ksp"
}
apply from: "$mppProjectWithSerializationPresetPath"
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64Project"
kotlin {

View File

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

View File

@@ -4,7 +4,7 @@ plugins {
id "com.android.library"
}
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64ProjectPresetPath"
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64Project"
kotlin {
sourceSets {

View File

@@ -4,7 +4,7 @@ plugins {
id "com.android.library"
}
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64ProjectPresetPath"
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64Project"
kotlin {
sourceSets {

View File

@@ -3,7 +3,7 @@ plugins {
id "org.jetbrains.kotlin.plugin.serialization"
}
apply from: "$mppJavaProjectPresetPath"
apply from: "$mppJavaProject"
kotlin {
sourceSets {

View File

@@ -1,7 +1,101 @@
package dev.inmo.micro_utils.ktor.server.configurators
import io.ktor.server.application.Application
import io.ktor.server.application.*
import io.ktor.server.http.content.*
import io.ktor.server.plugins.cachingheaders.*
import io.ktor.server.plugins.statuspages.*
import io.ktor.server.routing.*
import io.ktor.server.sessions.*
import kotlinx.serialization.Contextual
import kotlinx.serialization.Serializable
import java.io.File
interface KtorApplicationConfigurator {
@Serializable
class Routing(
private val elements: List<@Contextual Element>
) : KtorApplicationConfigurator {
fun interface Element { operator fun Route.invoke() }
private val rootInstaller = Element {
elements.forEach {
it.apply { invoke() }
}
}
override fun Application.configure() {
pluginOrNull(io.ktor.server.routing.Routing) ?.apply {
rootInstaller.apply { invoke() }
} ?: install(io.ktor.server.routing.Routing) {
rootInstaller.apply { invoke() }
}
}
/**
* @param pathToFolder Contains [Pair]s where firsts are paths in urls and seconds are folders file paths
* @param pathToResource Contains [Pair]s where firsts are paths in urls and seconds are packages in resources
*/
class Static(
private val pathToFolder: List<Pair<String, String>> = emptyList(),
private val pathToResource: List<Pair<String, String>> = emptyList(),
) : Element {
override fun Route.invoke() {
pathToFolder.forEach {
staticFiles(
it.first,
File(it.second)
)
}
pathToResource.forEach {
staticResources(
it.first,
it.second
)
}
}
}
}
class StatusPages(
private val elements: List<@Contextual Element>
) : KtorApplicationConfigurator {
fun interface Element { operator fun StatusPagesConfig.invoke() }
override fun Application.configure() {
install(StatusPages) {
elements.forEach {
it.apply { invoke() }
}
}
}
}
class Sessions(
private val elements: List<@Contextual Element>
) : KtorApplicationConfigurator {
fun interface Element { operator fun SessionsConfig.invoke() }
override fun Application.configure() {
install(Sessions) {
elements.forEach {
it.apply { invoke() }
}
}
}
}
class CachingHeaders(
private val elements: List<@Contextual Element>
) : KtorApplicationConfigurator {
fun interface Element { operator fun CachingHeadersConfig.invoke() }
override fun Application.configure() {
install(CachingHeaders) {
elements.forEach {
it.apply { invoke() }
}
}
}
}
fun Application.configure()
}

View File

@@ -4,4 +4,4 @@ plugins {
id "com.android.library"
}
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64ProjectPresetPath"
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64Project"

File diff suppressed because one or more lines are too long

View File

@@ -22,17 +22,24 @@ private const val baseClassSerializerAnnotationName = "@Serializable(${baseClass
@Serializable
private data class LanguageCode(
@SerialName("alpha2")
val tag: String,
@SerialName("English")
val title: String
)
val title: String,
@SerialName("alpha2")
val alpha: String? = null,
@SerialName("alpha3-b")
val alpha2: String? = null,
@SerialName("alpha3-t")
val alpha3: String? = null,
) {
val tag: String
get() = alpha ?: alpha2 ?: alpha3!!
}
fun String.adaptAsTitle() = if (first().isDigit()) {
fun String.adaptAsTitle() = (if (first().isDigit()) {
"L$this"
} else {
this
}
}).replace(".", "_").replace("'", "_")
fun String.normalized() = Normalizer.normalize(this, Normalizer.Form.NFD).replace(Regex("[^\\p{ASCII}]"), "")
@@ -73,7 +80,10 @@ data class Tag(
val title: String,
val tag: String,
val subtags: List<Tag>
)
) {
val adaptedTitle
get() = title.adaptAsTitle()
}
private fun printLanguageCodeAndTags(
tag: Tag,
@@ -81,17 +91,19 @@ private fun printLanguageCodeAndTags(
indents: String = " "
): String = if (tag.subtags.isEmpty()) {
"""${indents}${baseClassSerializerAnnotationName}
${indents}object ${tag.title} : ${parent ?.title ?: baseClassName}() { override val code: String = "${tag.tag}"${parent ?.let { parent -> "; override val parentLang: ${parent.title} get() = ${parent.title};" } ?: ""} }"""
${indents}object ${tag.adaptedTitle} : ${parent ?.adaptedTitle ?: baseClassName} { override val code: String = "${tag.tag}"${parent ?.let { parent -> "; override val parentLang: ${parent.adaptedTitle} get() = ${parent.adaptedTitle}" } ?: ""}; override fun toString() = code }"""
} else {
"""
${indents}${baseClassSerializerAnnotationName}
${indents}sealed class ${tag.title} : ${parent ?.title ?: baseClassName}() {
${indents} override val code: String = "${tag.tag}"${parent ?.let { parent -> "\n${indents} override val parentLang: ${parent.title} get() = ${parent.title};" } ?: ""}
${indents}sealed interface ${tag.adaptedTitle} : ${parent ?.adaptedTitle ?: baseClassName} {
${tag.subtags.joinToString("\n") { printLanguageCodeAndTags(it, tag, "${indents} ") }}
${indents} ${baseClassSerializerAnnotationName}
${indents} companion object : ${tag.title}()
${indents} companion object : ${tag.adaptedTitle} {
${indents} override val code: String = "${tag.tag}"${parent ?.let { parent -> "\n${indents} override val parentLang: ${parent.adaptedTitle} get() = ${parent.adaptedTitle};" } ?: ""}
${indents} override fun toString() = code
${indents} }
${indents}}
"""
}
@@ -105,23 +117,22 @@ import kotlinx.serialization.Serializable
* https://datahub.io/core/language-codes/ files (base and tags) and create the whole hierarchy using it.
*/
${baseClassSerializerAnnotationName}
sealed class $baseClassName {
abstract val code: String
open val parentLang: $baseClassName?
get() = null
open val withoutDialect: String
sealed interface $baseClassName {
val code: String
val parentLang: $baseClassName?
get() = code.split("-").takeIf { it.size > 1 } ?.first() ?.let(::$unknownBaseClassName)
val withoutDialect: String
get() = parentLang ?.code ?: code
${tags.joinToString("\n") { printLanguageCodeAndTags(it, indents = " ") } }
$baseClassSerializerAnnotationName
data class $unknownBaseClassName (override val code: String) : $baseClassName() {
data class $unknownBaseClassName (override val code: String) : $baseClassName {
override val parentLang = code.dropLastWhile { it != '-' }.removeSuffix("-").takeIf { it.length > 0 } ?.let(::$unknownBaseClassName)
}
@Deprecated("Renamed", ReplaceWith("$baseClassName.$unknownBaseClassName", "${if (prePackage.isNotEmpty()) "$prePackage." else ""}$baseClassName.$unknownBaseClassName"))
val $oldUnknownBaseClassName = $unknownBaseClassName
override fun toString() = code
val $oldUnknownBaseClassName
get() = $unknownBaseClassName
}
@Deprecated("Renamed", ReplaceWith("$baseClassName", "${if (prePackage.isNotEmpty()) "$prePackage." else ""}$baseClassName"))
typealias $oldBaseClassName = $baseClassName
@@ -133,7 +144,7 @@ fun createStringConverterCode(tags: List<Tag>, prePackage: String): String {
pretitle: String = baseClassName,
indents: String = " "
): String {
val currentTitle = "$pretitle.${tag.title}"
val currentTitle = "$pretitle.${tag.adaptedTitle}"
return """${indents}$currentTitle.code -> $currentTitle${if (tag.subtags.isNotEmpty()) tag.subtags.joinToString("\n", "\n") { createDeserializeVariantForTag(it, currentTitle, indents) } else ""}"""
}
fun createInheritorVariantForTag(
@@ -141,7 +152,7 @@ fun createStringConverterCode(tags: List<Tag>, prePackage: String): String {
pretitle: String = baseClassName,
indents: String = " "
): String {
val currentTitle = "$pretitle.${tag.title}"
val currentTitle = "$pretitle.${tag.adaptedTitle}"
val subtags = if (tag.subtags.isNotEmpty()) {
tag.subtags.joinToString(",\n", ",\n") { createInheritorVariantForTag(it, currentTitle, "$indents ") }
} else {
@@ -155,7 +166,7 @@ fun createStringConverterCode(tags: List<Tag>, prePackage: String): String {
indents: String = " ",
codeSuffix: String = ""
): String {
val currentTitle = "$pretitle.${tag.title}"
val currentTitle = "$pretitle.${tag.adaptedTitle}"
val subtags = if (tag.subtags.isNotEmpty()) {
tag.subtags.joinToString(",\n", ",\n") { createInheritorVariantForMapForTag(it, currentTitle, "$indents ", codeSuffix) }
} else {
@@ -266,7 +277,7 @@ suspend fun main(vararg args: String) {
File(outputFolder, "LanguageCodes.kt").apply {
delete()
createNewFile()
writeText(targetPackagePrefix + buildKtFileContent(tags, targetPackage ?: ""))
writeText("@file:Suppress(\"SERIALIZER_TYPE_INCOMPATIBLE\")\n\n" + targetPackagePrefix + buildKtFileContent(tags, targetPackage ?: ""))
}
File(outputFolder, "StringToLanguageCodes.kt").apply {

File diff suppressed because one or more lines are too long

View File

@@ -4,4 +4,4 @@ plugins {
id "com.android.library"
}
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64ProjectPresetPath"
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64Project"

View File

@@ -4,4 +4,4 @@ plugins {
id "com.android.library"
}
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64ProjectPresetPath"
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64Project"

View File

@@ -4,7 +4,7 @@ plugins {
id "com.android.library"
}
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64ProjectPresetPath"
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64Project"
kotlin {
sourceSets {

View File

@@ -3,7 +3,7 @@ plugins {
id "org.jetbrains.kotlin.plugin.serialization"
}
apply from: "$mppJavaProjectPresetPath"
apply from: "$mppJavaProject"
kotlin {
sourceSets {

View File

@@ -4,7 +4,7 @@ plugins {
id "com.android.library"
}
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64ProjectPresetPath"
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64Project"
kotlin {
sourceSets {

View File

@@ -3,7 +3,7 @@ plugins {
id "org.jetbrains.kotlin.plugin.serialization"
}
apply from: "$mppJavaProjectPresetPath"
apply from: "$mppJavaProject"
kotlin {
sourceSets {

View File

@@ -4,7 +4,7 @@ plugins {
id "com.android.library"
}
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64ProjectPresetPath"
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64Project"
kotlin {
sourceSets {

View File

@@ -98,7 +98,7 @@ open class FullCRUDCacheRepo<ObjectType, IdType, InputValueType>(
kvCache: KeyValueRepo<IdType, ObjectType>,
scope: CoroutineScope = CoroutineScope(Dispatchers.Default),
skipStartInvalidate: Boolean = false,
locker: SmartRWLocker = SmartRWLocker(),
locker: SmartRWLocker = SmartRWLocker(writeIsLocked = !skipStartInvalidate),
idGetter: (ObjectType) -> IdType
) : FullReadCRUDCacheRepo<ObjectType, IdType>(
parentRepo,
@@ -116,10 +116,23 @@ open class FullCRUDCacheRepo<ObjectType, IdType, InputValueType>(
CRUDRepo<ObjectType, IdType, InputValueType> {
init {
if (!skipStartInvalidate) {
scope.launchSafelyWithoutExceptions { invalidate() }
scope.launchSafelyWithoutExceptions {
if (locker.writeMutex.isLocked) {
initialInvalidate()
} else {
invalidate()
}
}
}
}
protected open suspend fun initialInvalidate() {
try {
kvCache.actualizeAll(parentRepo, locker = null)
} finally {
locker.unlockWrite()
}
}
override suspend fun invalidate() {
actualizeAll()
}

View File

@@ -126,26 +126,40 @@ fun <Key, Value> WriteKeyValueRepo<Key, Value>.caching(
) = FullWriteKeyValueCacheRepo(this, kvCache, scope)
open class FullKeyValueCacheRepo<Key,Value>(
protected open val parentRepo: KeyValueRepo<Key, Value>,
override val parentRepo: KeyValueRepo<Key, Value>,
kvCache: KeyValueRepo<Key, Value>,
scope: CoroutineScope = CoroutineScope(Dispatchers.Default),
skipStartInvalidate: Boolean = false,
locker: SmartRWLocker = SmartRWLocker()
) : FullWriteKeyValueCacheRepo<Key,Value>(parentRepo, kvCache, scope),
locker: SmartRWLocker = SmartRWLocker(writeIsLocked = !skipStartInvalidate),
) : //FullWriteKeyValueCacheRepo<Key,Value>(parentRepo, kvCache, scope),
KeyValueRepo<Key,Value>,
ReadKeyValueRepo<Key, Value> by FullReadKeyValueCacheRepo(
WriteKeyValueRepo<Key,Value> by parentRepo,
FullReadKeyValueCacheRepo<Key, Value>(
parentRepo,
kvCache,
locker
) {
init {
if (!skipStartInvalidate) {
scope.launchSafelyWithoutExceptions { invalidate() }
scope.launchSafelyWithoutExceptions {
if (locker.writeMutex.isLocked) {
initialInvalidate()
} else {
invalidate()
}
}
}
}
override suspend fun unsetWithValues(toUnset: List<Value>) = parentRepo.unsetWithValues(toUnset)
protected open suspend fun initialInvalidate() {
try {
kvCache.actualizeAll(parentRepo, locker = null)
} finally {
locker.unlockWrite()
}
}
override suspend fun invalidate() {
kvCache.actualizeAll(parentRepo, locker)
}
@@ -154,6 +168,28 @@ open class FullKeyValueCacheRepo<Key,Value>(
parentRepo.clear()
kvCache.clear()
}
override suspend fun set(toSet: Map<Key, Value>) {
locker.withWriteLock {
parentRepo.set(toSet)
kvCache.set(
toSet.filter {
parentRepo.contains(it.key)
}
)
}
}
override suspend fun unset(toUnset: List<Key>) {
locker.withWriteLock {
parentRepo.unset(toUnset)
kvCache.unset(
toUnset.filter {
!parentRepo.contains(it)
}
)
}
}
}
fun <Key, Value> KeyValueRepo<Key, Value>.fullyCached(

View File

@@ -10,6 +10,7 @@ import dev.inmo.micro_utils.pagination.utils.*
import dev.inmo.micro_utils.repos.*
import dev.inmo.micro_utils.repos.cache.util.ActualizeAllClearMode
import dev.inmo.micro_utils.repos.cache.util.actualizeAll
import dev.inmo.micro_utils.repos.pagination.maxPagePagination
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
@@ -65,6 +66,42 @@ open class FullReadKeyValuesCacheRepo<Key,Value>(
)
}
override suspend fun getAll(k: Key, reversed: Boolean): List<Value> {
return doOrTakeAndActualizeWithWriteLock(
{
get(k) ?.optionallyReverse(reversed).optionalOrAbsentIfNull
},
{ getAll(k, reversed) },
{ kvCache.set(k, it.optionallyReverse(reversed)) }
)
}
override suspend fun getAll(reverseLists: Boolean): Map<Key, List<Value>> {
return doOrTakeAndActualizeWithWriteLock(
{
getAll().takeIf { it.isNotEmpty() } ?.let {
if (reverseLists) {
it.mapValues { it.value.reversed() }
} else {
it
}
}.optionalOrAbsentIfNull
},
{ getAll(reverseLists) },
{
kvCache.set(
it.let {
if (reverseLists) {
it.mapValues { it.value.reversed() }
} else {
it
}
}
)
}
)
}
override suspend fun keys(pagination: Pagination, reversed: Boolean): PaginationResult<Key> {
return doOrTakeAndActualize(
{
@@ -163,17 +200,23 @@ fun <Key, Value> WriteKeyValuesRepo<Key, Value>.caching(
) = FullWriteKeyValuesCacheRepo(this, kvCache, scope, locker)
open class FullKeyValuesCacheRepo<Key,Value>(
protected open val parentRepo: KeyValuesRepo<Key, Value>,
override val parentRepo: KeyValuesRepo<Key, Value>,
kvCache: KeyValueRepo<Key, List<Value>>,
scope: CoroutineScope = CoroutineScope(Dispatchers.Default),
skipStartInvalidate: Boolean = false,
locker: SmartRWLocker = SmartRWLocker(),
) : FullWriteKeyValuesCacheRepo<Key, Value>(parentRepo, kvCache, scope, locker),
KeyValuesRepo<Key, Value>,
ReadKeyValuesRepo<Key, Value> by FullReadKeyValuesCacheRepo(parentRepo, kvCache, locker) {
locker: SmartRWLocker = SmartRWLocker(writeIsLocked = !skipStartInvalidate),
) : KeyValuesRepo<Key, Value>,
FullReadKeyValuesCacheRepo<Key, Value>(parentRepo, kvCache, locker),
WriteKeyValuesRepo<Key, Value> by parentRepo {
init {
if (!skipStartInvalidate) {
scope.launchSafelyWithoutExceptions { invalidate() }
scope.launchSafelyWithoutExceptions {
if (locker.writeMutex.isLocked) {
initialInvalidate()
} else {
invalidate()
}
}
}
}
@@ -185,16 +228,75 @@ open class FullKeyValuesCacheRepo<Key,Value>(
}
}
protected open suspend fun initialInvalidate() {
try {
kvCache.actualizeAll(parentRepo, locker = null)
} finally {
locker.unlockWrite()
}
}
override suspend fun invalidate() {
kvCache.actualizeAll(parentRepo, locker = locker)
}
override suspend fun set(toSet: Map<Key, List<Value>>) {
super<KeyValuesRepo>.set(toSet)
locker.withWriteLock {
parentRepo.set(toSet)
kvCache.set(
toSet.filter {
parentRepo.contains(it.key)
}
)
}
}
override suspend fun removeWithValue(v: Value) {
super<FullWriteKeyValuesCacheRepo>.removeWithValue(v)
override suspend fun add(toAdd: Map<Key, List<Value>>) {
locker.withWriteLock {
parentRepo.add(toAdd)
toAdd.forEach {
val filtered = it.value.filter { v ->
parentRepo.contains(it.key, v)
}.ifEmpty {
return@forEach
}
kvCache.set(
it.key,
(kvCache.get(it.key) ?: emptyList()) + filtered
)
}
}
}
override suspend fun remove(toRemove: Map<Key, List<Value>>) {
locker.withWriteLock {
parentRepo.remove(toRemove)
toRemove.forEach {
val filtered = it.value.filter { v ->
!parentRepo.contains(it.key, v)
}.ifEmpty {
return@forEach
}.toSet()
val resultList = (kvCache.get(it.key) ?: emptyList()) - filtered
if (resultList.isEmpty()) {
kvCache.unset(it.key)
} else {
kvCache.set(
it.key,
resultList
)
}
}
}
}
override suspend fun clear(k: Key) {
locker.withWriteLock {
parentRepo.clear(k)
if (parentRepo.contains(k)) {
return@withWriteLock
}
kvCache.unset(k)
}
}
}

View File

@@ -0,0 +1,142 @@
package full
import com.benasher44.uuid.uuid4
import dev.inmo.micro_utils.repos.MapCRUDRepo
import dev.inmo.micro_utils.repos.MapKeyValueRepo
import dev.inmo.micro_utils.repos.cache.full.FullCRUDCacheRepo
import dev.inmo.micro_utils.repos.create
import dev.inmo.micro_utils.repos.deleteById
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class FullCRUDCacheRepoTests {
data class New(
val data: String
)
data class Registered(
val id: String,
val data: String
)
@Test
fun creatingWorksProperly() = runTest {
val testData = (0 until 1000).map {
("$it-" + uuid4().toString())
}
val updatedTestData = (0 until 1000).map {
("$it-" + uuid4().toString())
}
val kvCache = MapKeyValueRepo<String, Registered>()
val crudRepo = MapCRUDRepo<Registered, String, New>(
{ new, id, old ->
Registered(id, new.data)
}
) {
val id = uuid4().toString()
id to Registered(id, it.data)
}
val cacheRepo = FullCRUDCacheRepo(
crudRepo,
kvCache,
idGetter = { it.id }
)
val registereds = testData.map {
val created = cacheRepo.create(New(it)).first()
assertEquals(it, created.data)
assertEquals(kvCache.get(created.id), created)
assertEquals(crudRepo.getById(created.id), created)
created
}
cacheRepo.getAll().forEach { (id, value) ->
assertTrue {
registereds.first {
it.id == id
} == value
}
}
val updatedRegistereds = registereds.mapIndexed { i, it ->
val updated = cacheRepo.update(it.id, New(updatedTestData[i])) ?: error("Unable to update data for $it")
assertEquals(updatedTestData[i], updated.data)
assertEquals(kvCache.get(updated.id), updated)
assertEquals(crudRepo.getById(updated.id), updated)
updated
}
cacheRepo.getAll().forEach { (id, value) ->
assertTrue {
updatedRegistereds.first {
it.id == id
} == value
}
}
}
@Test
fun precachingWorksProperly() = runTest {
val testData = (0 until 1000).map {
(it.toString() + uuid4().toString())
}
val kvCache = MapKeyValueRepo<String, Registered>()
val crudRepo = MapCRUDRepo<Registered, String, New>(
{ new, id, old ->
Registered(id, new.data)
}
) {
val id = uuid4().toString()
id to Registered(id, it.data)
}
val registereds = crudRepo.create(testData.map { New(it) })
val cacheRepo = FullCRUDCacheRepo(
crudRepo,
kvCache,
idGetter = { it.id }
)
cacheRepo.getAll().forEach { (id, value) ->
assertTrue {
registereds.first {
it.id == id
} == value
}
}
}
@Test
fun removingWorksProperly() = runTest {
val testData = (0 until 1000).map {
(it.toString() + uuid4().toString())
}
val kvCache = MapKeyValueRepo<String, Registered>()
val crudRepo = MapCRUDRepo<Registered, String, New>(
{ new, id, old ->
Registered(id, new.data)
}
) {
val id = uuid4().toString()
id to Registered(id, it.data)
}
val registereds = crudRepo.create(testData.map { New(it) })
val cacheRepo = FullCRUDCacheRepo(
crudRepo,
kvCache,
idGetter = { it.id }
)
registereds.forEach {
val id = it.id
assertTrue {
cacheRepo.getAll()[id] == it
}
cacheRepo.deleteById(id)
assertFalse {
cacheRepo.contains(id)
}
}
assertEquals(0, cacheRepo.count())
}
}

View File

@@ -0,0 +1,92 @@
package full
import com.benasher44.uuid.uuid4
import dev.inmo.micro_utils.repos.*
import dev.inmo.micro_utils.repos.cache.full.FullKeyValueCacheRepo
import korlibs.time.seconds
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class FullKeyValueCacheRepoTests {
@Test
fun creatingWorksProperly() = runTest(timeout = 120.seconds) {
val testData = (0 until 1000).associate {
("$it-" + uuid4().toString()) to "$it-" + uuid4().toString()
}
val updatedTestData = testData.keys.associateWith {
"$it-" + uuid4().toString()
}
val kvCache = MapKeyValueRepo<String, String>()
val kvRepo = MapKeyValueRepo<String, String>()
val cacheRepo = FullKeyValueCacheRepo(
kvRepo,
kvCache
)
testData.forEach {
cacheRepo.set(it.key, it.value)
assertEquals(it.value, cacheRepo.get(it.key))
assertEquals(it.value, kvRepo.get(it.key))
assertEquals(it.value, kvCache.get(it.key))
}
updatedTestData.forEach {
cacheRepo.set(it.key, it.value)
assertEquals(cacheRepo.get(it.key), it.value)
assertEquals(kvRepo.get(it.key), it.value)
assertEquals(kvCache.get(it.key), it.value)
}
}
@Test
fun precachingWorksProperly() = runTest {
val testData = (0 until 1000).associate {
(it.toString() + uuid4().toString()) to uuid4().toString()
}
val kvCache = MapKeyValueRepo<String, String>()
val kvRepo = MapKeyValueRepo<String, String>()
kvRepo.set(testData)
val cacheRepo = FullKeyValueCacheRepo(
kvRepo,
kvCache
)
cacheRepo.getAll().forEach { (id, value) ->
assertTrue {
testData[id] == value
}
}
}
@Test
fun unsettingWorksProperly() = runTest {
val testData = (0 until 1000).associate {
(it.toString() + uuid4().toString()) to uuid4().toString()
}
val kvCache = MapKeyValueRepo<String, String>()
val kvRepo = MapKeyValueRepo<String, String>()
kvRepo.set(testData)
val cacheRepo = FullKeyValueCacheRepo(
kvRepo,
kvCache
)
testData.forEach {
val id = it.key
assertTrue {
cacheRepo.getAll()[id] == it.value
}
cacheRepo.unset(id)
assertFalse {
cacheRepo.contains(id)
}
}
assertEquals(0, cacheRepo.count())
}
}

View File

@@ -0,0 +1,58 @@
package full
import com.benasher44.uuid.uuid4
import dev.inmo.micro_utils.repos.*
import dev.inmo.micro_utils.repos.cache.full.FullKeyValuesCacheRepo
import dev.inmo.micro_utils.repos.pagination.maxPagePagination
import korlibs.time.days
import korlibs.time.seconds
import korlibs.time.years
import kotlinx.coroutines.test.runTest
import kotlin.test.*
class FullKeyValuesCacheRepoTests {
@Test
fun creatingWorksProperly() = runTest(timeout = 120.seconds) {
val testData = (0 until 1000).associate {
("$it-" + uuid4().toString()) to (0 until 1000).map {
"$it-" + uuid4().toString()
}.sorted()
}
val updatedTestData = testData.keys.associateWith {
(0 until 1000).map {
"$it-" + uuid4().toString()
}.sorted()
}
val addedData = testData.keys.associateWith {
"$it-" + uuid4().toString()
}
val kvCache = MapKeyValueRepo<String, List<String>>()
val kvRepo = MapKeyValuesRepo<String, String>()
val cacheRepo = FullKeyValuesCacheRepo(
kvRepo,
kvCache
)
testData.forEach {
cacheRepo.set(it.key, it.value)
assertContentEquals(it.value, cacheRepo.getAll(it.key))
assertContentEquals(it.value, kvRepo.getAll(it.key))
assertContentEquals(it.value, kvCache.get(it.key) ?.sorted())
}
updatedTestData.forEach {
cacheRepo.set(it.key, it.value)
assertContentEquals(it.value, cacheRepo.getAll(it.key))
assertContentEquals(it.value, kvRepo.getAll(it.key))
assertContentEquals(it.value, kvCache.get(it.key) ?.sorted())
}
addedData.forEach {
cacheRepo.add(it.key, it.value)
assertTrue(cacheRepo.contains(it.key, it.value))
assertTrue(kvRepo.contains(it.key, it.value))
assertTrue(kvCache.get(it.key) !!.contains(it.value))
}
}
}

View File

@@ -4,7 +4,7 @@ plugins {
id "com.android.library"
}
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64ProjectPresetPath"
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64Project"
kotlin {
sourceSets {

View File

@@ -1,8 +1,12 @@
plugins {
id "org.jetbrains.kotlin.multiplatform"
id "org.jetbrains.kotlin.plugin.serialization"
id "com.android.library"
}
project.version = "$version"
project.group = "$group"
apply from: "$publishGradlePath"
kotlin {
jvm {
compilations.main {
@@ -15,6 +19,13 @@ kotlin {
browser()
nodejs()
}
androidTarget {
compilations.all {
kotlinOptions {
jvmTarget = "17"
}
}
}
linuxX64()
mingwX64()
linuxArm64()
@@ -24,28 +35,23 @@ kotlin {
dependencies {
implementation kotlin('stdlib')
api libs.kt.serialization
}
}
commonTest {
dependencies {
implementation kotlin('test-common')
implementation kotlin('test-annotations-common')
implementation libs.kt.coroutines.test
api kotlin('test')
api kotlin('test-annotations-common')
api libs.kt.coroutines.test
api project(":micro_utils.repos.common")
}
}
jvmTest {
jvmMain {
dependencies {
implementation kotlin('test-junit')
}
}
jsTest {
jsMain {
dependencies {
implementation kotlin('test-js')
implementation kotlin('test-junit')
}
}
nativeMain.dependsOn commonMain
linuxX64Main.dependsOn nativeMain
mingwX64Main.dependsOn nativeMain
@@ -55,7 +61,9 @@ kotlin {
}
}
apply from: "$defaultAndroidSettings"
java {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
}

View File

@@ -0,0 +1,82 @@
package dev.inmo.micro_utils.repos.common.tests
import com.benasher44.uuid.uuid4
import dev.inmo.micro_utils.repos.CRUDRepo
import dev.inmo.micro_utils.repos.create
import dev.inmo.micro_utils.repos.deleteById
import korlibs.time.seconds
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.Serializable
import kotlin.test.*
abstract class CommonCRUDRepoTests : CommonRepoTests<CRUDRepo<CommonCRUDRepoTests.Registered, String, CommonCRUDRepoTests.New>>() {
@Serializable
data class New(
val data: String
)
@Serializable
data class Registered(
val id: String,
val data: String
)
@Test
fun creatingWorksProperly() = runTest(timeout = 120.seconds) {
val crudRepo = repoCreator()
val testData = (0 until testSequencesSize).map {
("$it-" + uuid4().toString())
}
val updatedTestData = (0 until 1000).map {
("$it-" + uuid4().toString())
}
val registereds = testData.map {
val created = crudRepo.create(New(it)).first()
assertEquals(it, created.data)
assertEquals(crudRepo.getById(created.id), created)
created
}
crudRepo.getAll().forEach { (id, value) ->
assertTrue {
registereds.first {
it.id == id
} == value
}
}
val updatedRegistereds = registereds.mapIndexed { i, it ->
val updated = crudRepo.update(it.id, New(updatedTestData[i])) ?: error("Unable to update data for $it")
assertEquals(updatedTestData[i], updated.data)
assertEquals(crudRepo.getById(updated.id), updated)
updated
}
crudRepo.getAll().forEach { (id, value) ->
assertTrue {
updatedRegistereds.first {
it.id == id
} == value
}
}
}
@Test
fun removingWorksProperly() = runTest {
val crudRepo = repoCreator()
val testData = (0 until testSequencesSize).map {
(it.toString() + uuid4().toString())
}
val registereds = crudRepo.create(testData.map { New(it) })
registereds.forEach {
val id = it.id
assertTrue {
crudRepo.getAll()[id] == it
}
crudRepo.deleteById(id)
assertFalse {
crudRepo.contains(id)
}
}
assertEquals(0, crudRepo.count())
}
}

View File

@@ -0,0 +1,55 @@
package dev.inmo.micro_utils.repos.common.tests
import com.benasher44.uuid.uuid4
import dev.inmo.micro_utils.repos.*
import korlibs.time.seconds
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
abstract class CommonKeyValueRepoTests : CommonRepoTests<KeyValueRepo<String, String>>() {
@Test
fun creatingWorksProperly() = runTest(timeout = 120.seconds) {
val repo = repoCreator()
val testData = (0 until testSequencesSize).associate {
("$it-" + uuid4().toString()) to "$it-" + uuid4().toString()
}
val updatedTestData = testData.keys.associateWith {
"$it-" + uuid4().toString()
}
testData.forEach {
repo.set(it.key, it.value)
assertEquals(it.value, repo.get(it.key))
}
updatedTestData.forEach {
repo.set(it.key, it.value)
assertEquals(repo.get(it.key), it.value)
}
}
@Test
fun unsettingWorksProperly() = runTest {
val repo = repoCreator()
val testData = (0 until testSequencesSize).associate {
(it.toString() + uuid4().toString()) to uuid4().toString()
}
repo.set(testData)
testData.forEach {
val id = it.key
assertTrue {
repo.getAll()[id] == it.value
}
repo.unset(id)
assertFalse {
repo.contains(id)
}
}
assertEquals(0, repo.count())
}
}

View File

@@ -0,0 +1,49 @@
package dev.inmo.micro_utils.repos.common.tests
import com.benasher44.uuid.uuid4
import dev.inmo.micro_utils.repos.*
import korlibs.time.seconds
import kotlinx.coroutines.joinAll
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.runTest
import kotlin.test.*
abstract class CommonKeyValuesRepoTests : CommonRepoTests<KeyValuesRepo<String, String>>() {
@Test
fun creatingWorksProperly() = runTest(timeout = 120.seconds) {
val repo = repoCreator()
val testData = (0 until testSequencesSize).associate {
("$it-" + uuid4().toString()) to (0 until 1000).map {
"$it-" + uuid4().toString()
}.sorted()
}
val updatedTestData = testData.keys.associateWith {
(0 until 1000).map {
"$it-" + uuid4().toString()
}.sorted()
}
val addedData = testData.keys.associateWith {
"$it-" + uuid4().toString()
}
updatedTestData.map {
launch {
repo.set(it.key, it.value)
assertContentEquals(it.value.sorted(), repo.getAll(it.key).sorted())
}
}.joinAll()
updatedTestData.map {
launch {
repo.set(it.key, it.value)
val all = repo.getAll(it.key)
assertContentEquals(it.value.sorted(), all.sorted())
}
}.joinAll()
addedData.forEach {
repo.add(it.key, it.value)
assertTrue(repo.contains(it.key, it.value))
}
}
}

View File

@@ -0,0 +1,6 @@
package dev.inmo.micro_utils.repos.common.tests
abstract class CommonRepoTests<T> {
protected open val testSequencesSize = 1000
protected abstract val repoCreator: suspend () -> T
}

View File

@@ -3,7 +3,7 @@ plugins {
id "org.jetbrains.kotlin.plugin.serialization"
}
apply from: "$mppJavaProjectPresetPath"
apply from: "$mppJavaProject"
kotlin {
sourceSets {
@@ -14,5 +14,12 @@ kotlin {
api internalProject("micro_utils.pagination.exposed")
}
}
jvmTest {
dependencies {
api libs.sqlite
api libs.jb.exposed.jdbc
api project(":micro_utils.repos.common.tests")
}
}
}
}

View File

@@ -52,9 +52,9 @@ abstract class AbstractExposedWriteCRUDRepo<ObjectType, IdType, InputValueType>(
*
* @return In case when id for the model has been created new [IdType] should be returned
*/
protected open fun createAndInsertId(value: InputValueType, it: InsertStatement<Number>): IdType? = null
protected open fun createAndInsertId(value: InputValueType, it: UpdateBuilder<Int>): IdType? = null
protected open fun insert(value: InputValueType, it: InsertStatement<Number>) {
protected open fun insert(value: InputValueType, it: UpdateBuilder<Int>) {
val id = createAndInsertId(value, it)
update(id, value, it as UpdateBuilder<Int>)
}

View File

@@ -23,11 +23,11 @@ abstract class AbstractExposedKeyValueRepo<Key, Value>(
override val onValueRemoved: Flow<Key> = _onValueRemoved.asSharedFlow()
protected abstract fun update(k: Key, v: Value, it: UpdateBuilder<Int>)
protected abstract fun insertKey(k: Key, v: Value, it: InsertStatement<Number>)
protected abstract fun insertKey(k: Key, v: Value, it: UpdateBuilder<Int>)
protected open fun insert(k: Key, v: Value, it: InsertStatement<Number>) {
protected open fun insert(k: Key, v: Value, it: UpdateBuilder<Int>) {
insertKey(k, v, it)
update(k, v, it as UpdateBuilder<Int>)
update(k, v, it)
}
override suspend fun set(toSet: Map<Key, Value>) {

View File

@@ -5,6 +5,7 @@ import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.*
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.statements.InsertStatement
import org.jetbrains.exposed.sql.statements.UpdateBuilder
import org.jetbrains.exposed.sql.transactions.transaction
abstract class AbstractExposedKeyValuesRepo<Key, Value>(
@@ -26,7 +27,7 @@ abstract class AbstractExposedKeyValuesRepo<Key, Value>(
override val onDataCleared: Flow<Key>
get() = _onDataCleared.asSharedFlow()
protected abstract fun insert(k: Key, v: Value, it: InsertStatement<Number>)
protected abstract fun insert(k: Key, v: Value, it: UpdateBuilder<Int>)
override suspend fun add(toAdd: Map<Key, List<Value>>) {
transaction(database) {
@@ -48,6 +49,28 @@ abstract class AbstractExposedKeyValuesRepo<Key, Value>(
}.forEach { _onNewValue.emit(it) }
}
override suspend fun set(toSet: Map<Key, List<Value>>) {
if (toSet.isEmpty()) return
val prepreparedData = toSet.flatMap { (k, vs) ->
vs.map { v ->
k to v
}
}
transaction(database) {
deleteWhere {
selectByIds(it, toSet.keys.toList())
}
batchInsert(
prepreparedData,
) { (k, v) ->
insert(k, v, this)
}.map {
it.asKey to it.asObject
}
}.forEach { _onNewValue.emit(it) }
}
override suspend fun remove(toRemove: Map<Key, List<Value>>) {
transaction(database) {
toRemove.keys.flatMap { k ->

View File

@@ -83,8 +83,8 @@ abstract class AbstractExposedReadKeyValuesRepo<Key, Value>(
}
}
override suspend fun getAll(k: Key, reverseLists: Boolean): List<Value> = transaction(database) {
val query = if (reverseLists) {
override suspend fun getAll(k: Key, reversed: Boolean): List<Value> = transaction(database) {
val query = if (reversed) {
selectAll().where { selectById(k) }.orderBy(keyColumn, SortOrder.DESC)
} else {
selectAll().where { selectById(k) }

View File

@@ -0,0 +1,21 @@
package full
import com.benasher44.uuid.uuid4
import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.transactions.transactionManager
import org.sqlite.JDBC
import java.io.File
import java.sql.Connection
fun filename() = "${uuid4()}.local.sql".also {
val file = File(it)
file.createNewFile()
file.deleteOnExit()
}
fun createDatabase(filename: String) = Database.connect(
url = "jdbc:sqlite:$filename",
driver = JDBC::class.qualifiedName!!
).also {
it.transactionManager.defaultIsolationLevel = Connection.TRANSACTION_SERIALIZABLE
it.connector().close()
}

View File

@@ -0,0 +1,62 @@
package full
import com.benasher44.uuid.uuid4
import dev.inmo.micro_utils.repos.CRUDRepo
import dev.inmo.micro_utils.repos.common.tests.CommonCRUDRepoTests
import dev.inmo.micro_utils.repos.exposed.AbstractExposedCRUDRepo
import dev.inmo.micro_utils.repos.exposed.initTable
import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.ISqlExpressionBuilder
import org.jetbrains.exposed.sql.Op
import org.jetbrains.exposed.sql.ResultRow
import org.jetbrains.exposed.sql.statements.InsertStatement
import org.jetbrains.exposed.sql.statements.UpdateBuilder
import java.io.File
import kotlin.test.AfterTest
import kotlin.test.BeforeTest
class ExposedCRUDRepoTests : CommonCRUDRepoTests() {
class Repo(override val database: Database) : AbstractExposedCRUDRepo<Registered, String, New>() {
val idColumn = text("_id")
val dataColumn = text("data")
override val primaryKey: PrimaryKey = PrimaryKey(idColumn)
override val ResultRow.asId: String
get() = get(idColumn)
override val ResultRow.asObject: Registered
get() = Registered(
asId,
get(dataColumn)
)
override val selectById: ISqlExpressionBuilder.(String) -> Op<Boolean> = { idColumn.eq(it) }
init {
initTable()
}
override fun update(id: String?, value: New, it: UpdateBuilder<Int>) {
it[idColumn] = id ?: uuid4().toString()
it[dataColumn] = value.data
}
override fun InsertStatement<Number>.asObject(value: New): Registered {
return Registered(
get(idColumn),
get(dataColumn)
)
}
}
val filename = filename()
var database: Database? = null
override val repoCreator: suspend () -> CRUDRepo<Registered, String, New> = { Repo(database!!) }
@BeforeTest
fun beforeTest() {
database = createDatabase(filename)
}
@AfterTest
fun afterTest() {
database = null
File(filename).delete()
}
}

View File

@@ -0,0 +1,56 @@
package full
import dev.inmo.micro_utils.repos.KeyValueRepo
import dev.inmo.micro_utils.repos.common.tests.CommonKeyValueRepoTests
import dev.inmo.micro_utils.repos.exposed.initTable
import dev.inmo.micro_utils.repos.exposed.keyvalue.AbstractExposedKeyValueRepo
import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.ISqlExpressionBuilder
import org.jetbrains.exposed.sql.Op
import org.jetbrains.exposed.sql.ResultRow
import org.jetbrains.exposed.sql.statements.UpdateBuilder
import java.io.File
import kotlin.test.AfterTest
import kotlin.test.BeforeTest
class ExposedKeyValueRepoTests : CommonKeyValueRepoTests() {
class Repo(override val database: Database) : AbstractExposedKeyValueRepo<String, String>(database) {
override val keyColumn = text("_id")
val dataColumn = text("data")
override val primaryKey: PrimaryKey = PrimaryKey(keyColumn)
override val ResultRow.asKey: String
get() = get(keyColumn)
override val selectByValue: ISqlExpressionBuilder.(String) -> Op<Boolean> = { dataColumn.eq(it) }
override val ResultRow.asObject: String
get() = get(dataColumn)
override val selectById: ISqlExpressionBuilder.(String) -> Op<Boolean> = { keyColumn.eq(it) }
init {
initTable()
}
override fun update(k: String, v: String, it: UpdateBuilder<Int>) {
it[keyColumn] = k
it[dataColumn] = v
}
override fun insertKey(k: String, v: String, it: UpdateBuilder<Int>) {
it[keyColumn] = k
}
}
val filename = filename()
var database: Database? = null
@BeforeTest
fun beforeTest() {
database = createDatabase(filename)
}
@AfterTest
fun afterTest() {
database = null
File(filename).delete()
}
override val repoCreator: suspend () -> KeyValueRepo<String, String> = { Repo(database!!) }
}

View File

@@ -0,0 +1,52 @@
package full
import dev.inmo.micro_utils.repos.KeyValuesRepo
import dev.inmo.micro_utils.repos.common.tests.CommonKeyValuesRepoTests
import dev.inmo.micro_utils.repos.exposed.initTable
import dev.inmo.micro_utils.repos.exposed.onetomany.AbstractExposedKeyValuesRepo
import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.ISqlExpressionBuilder
import org.jetbrains.exposed.sql.Op
import org.jetbrains.exposed.sql.ResultRow
import org.jetbrains.exposed.sql.statements.UpdateBuilder
import java.io.File
import kotlin.test.AfterTest
import kotlin.test.BeforeTest
class ExposedKeyValuesRepoTests : CommonKeyValuesRepoTests() {
override val testSequencesSize: Int = 100
class Repo(override val database: Database) : AbstractExposedKeyValuesRepo<String, String>(database) {
override val keyColumn = text("_id")
val dataColumn = text("data")
override val ResultRow.asKey: String
get() = get(keyColumn)
override val selectByValue: ISqlExpressionBuilder.(String) -> Op<Boolean> = { dataColumn.eq(it) }
override val ResultRow.asObject: String
get() = get(dataColumn)
override val selectById: ISqlExpressionBuilder.(String) -> Op<Boolean> = { keyColumn.eq(it) }
init {
initTable()
}
override fun insert(k: String, v: String, it: UpdateBuilder<Int>) {
it[keyColumn] = k
it[dataColumn] = v
}
}
val filename = filename()
var database: Database? = null
@BeforeTest
fun beforeTest() {
database = createDatabase(filename)
}
@AfterTest
fun afterTest() {
database = null
File(filename).delete()
}
override val repoCreator: suspend () -> KeyValuesRepo<String, String> = { Repo(database!!) }
}

View File

@@ -2,7 +2,7 @@ plugins {
id "org.jetbrains.kotlin.jvm"
}
apply from: "$publishJvmOnlyPath"
apply from: "$publish_jvm"
repositories {
mavenCentral()

View File

@@ -5,7 +5,7 @@ plugins {
id "com.google.devtools.ksp"
}
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64ProjectPresetPath"
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64Project"
kotlin {

View File

@@ -4,7 +4,7 @@ plugins {
id "com.android.library"
}
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64ProjectPresetPath"
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64Project"
kotlin {
sourceSets {
@@ -14,5 +14,10 @@ kotlin {
api internalProject("micro_utils.coroutines")
}
}
commonTest {
dependencies {
api project(":micro_utils.repos.common.tests")
}
}
}
}

View File

@@ -24,7 +24,9 @@ class ReadMapKeyValueRepo<Key, Value>(
) : ReadKeyValueRepo<Key, Value> {
constructor(map: Map<Key, Value> = emptyMap()) : this(map, SmartRWLocker())
override suspend fun get(k: Key): Value? = locker.withReadAcquire { map[k] }
override suspend fun get(k: Key): Value? = locker.withReadAcquire {
map[k]
}
override suspend fun values(
pagination: Pagination,
@@ -100,11 +102,13 @@ class WriteMapKeyValueRepo<Key, Value>(
constructor(map: MutableMap<Key, Value> = mutableMapOf()) : this(map, SmartRWLocker())
override suspend fun set(toSet: Map<Key, Value>) {
if (toSet.isEmpty()) return
locker.withWriteLock { map.putAll(toSet) }
toSet.forEach { (k, v) -> _onNewValue.emit(k to v) }
}
override suspend fun unset(toUnset: List<Key>) {
if (toUnset.isEmpty()) return
locker.withWriteLock {
toUnset.mapNotNull { k ->
map.remove(k) ?.let { _ -> k }

View File

@@ -4,6 +4,7 @@ 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.pagination.*
import dev.inmo.micro_utils.pagination.utils.optionallyReverse
import dev.inmo.micro_utils.pagination.utils.paginate
import dev.inmo.micro_utils.pagination.utils.reverse
import kotlinx.coroutines.flow.*
@@ -33,6 +34,20 @@ class MapReadKeyValuesRepo<Key, Value>(
)
}
override suspend fun getAll(k: Key, reversed: Boolean): List<Value> {
return locker.withReadAcquire { map[k] ?.optionallyReverse(reversed) ?: return emptyList() }
}
override suspend fun getAll(reverseLists: Boolean): Map<Key, List<Value>> {
return locker.withReadAcquire {
if (reverseLists) {
map.mapValues { it.value.reversed() }
} else {
map.toMap()
}
}
}
override suspend fun keys(pagination: Pagination, reversed: Boolean): PaginationResult<Key> {
val keys = locker.withReadAcquire {
map.keys
@@ -108,7 +123,24 @@ class MapWriteKeyValuesRepo<Key, Value>(
}
}
override suspend fun set(toSet: Map<Key, List<Value>>) {
if (toSet.isEmpty()) return
locker.withWriteLock {
map.putAll(
toSet.mapValues { it.value.toMutableList() }
)
}
toSet.forEach { (k, v) ->
v.forEach {
_onNewValue.emit(k to it)
}
}
}
override suspend fun remove(toRemove: Map<Key, List<Value>>) {
if (toRemove.isEmpty()) return
val removed = mutableListOf<Pair<Key, Value>>()
val cleared = mutableListOf<Key>()
locker.withWriteLock {

Some files were not shown because too many files have changed in this diff Show More