├── .gitignore
├── README.md
├── build.gradle.kts
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle.kts
└── src
├── main
└── kotlin
│ └── com
│ └── y9san9
│ └── kds
│ ├── KDataStorage.kt
│ └── utils
│ ├── FileUtils.kt
│ └── JsonUtils.kt
└── test
└── kotlin
└── com
└── y9san9
└── kds
└── Main.kt
/.gitignore:
--------------------------------------------------------------------------------
1 | /data/
2 | /.gradle/
3 | /.idea/
4 | /build/
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | # About
4 | Kotlin Data Storage (KDS) - class that generates the json file and stores the data into there. You can use it as android SharedPreferences.
5 |
6 | You can create a property by `property(defaultValue)` delegate.
7 |
8 | KDS generates map `property name to property value` and then stores it into the file via Gson.
9 | # Example
10 | ```kotlin
11 | class SomeClass(val someValue: String)
12 |
13 | // Defining the KDS model
14 | object AppData : KDataStorage() {
15 | val launches by property(0)
16 | val count by property(100)
17 | val available by property(625)
18 | val someClass by property()
19 | }
20 |
21 | fun main() {
22 | // To edit the data, use the commit method (else if you will try to edit data, TransactionError will be thrown)
23 | AppData.commit {
24 | launches++
25 | }
26 |
27 | // To clear all data, use the clear method
28 | AppData.clear()
29 |
30 | // To clear a single property use the clearProperty method and pass name of the property that you want to delete (if you try to delete a non-existent property, ClearingError will be thrown)
31 | AppData.clearProperty("count")
32 |
33 | // To clear several properties, use the clearProperties method and pass their names (if you try to delete a non-existent properties, ClearingError will be thrown)
34 | AppData.clearProperties("someClass", "available")
35 |
36 | // You can use toString method to convert the Storage to String
37 | println(AppData.toString())
38 |
39 | // You can get the data from anywhere
40 | println("Total launches ${AppData.launches}")
41 | }
42 | ```
43 | Besides, check [it](https://github.com/y9san9/kotlin-data-storage/blob/master/src/test/kotlin/com/y9san9/kds/Main.kt)
44 | # Quick start [](https://jitpack.io/#y9san9/kotlin-data-storage)
45 | Import the library with jitpack:
46 | ## Gradle
47 | ```gradle
48 | repositories {
49 | maven { url "https://jitpack.io" } // Connecting jitpack to import github repos
50 | }
51 |
52 | dependencies {
53 | implementation 'com.github.y9san9:kotlin-data-storage:-SNAPSHOT'
54 | }
55 | ```
56 | ## Pro way (Kotlin Gradle DSL)
57 | Add these 2 functions to top of your build.gradle.kts file:
58 | ```kotlin
59 | /**
60 | * Import github repo; first add [jitpack] to repos
61 | * @param repo username/repo; e.g. y9san9/kotlogram-wrapper
62 | */
63 | fun DependencyHandlerScope.github(repo: String, tag: String = "-SNAPSHOT") = implementation(
64 | repo.split("/").let { (username, repo) ->
65 | "com.github.${username}:${repo}:${tag}"
66 | }
67 | )
68 |
69 | /**
70 | * Jitpack maven
71 | */
72 | fun RepositoryHandler.jitpack() = maven("https://jitpack.io")
73 | ```
74 | Then, use pretty easy implementation code:
75 | ```kotlin
76 | repositories {
77 | jitpack()
78 | }
79 |
80 | dependencies {
81 | github("y9san9/kotlin-data-storage")
82 | }
83 | ```
--------------------------------------------------------------------------------
/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | kotlin("jvm") version "1.3.72"
3 | maven
4 | }
5 |
6 | group = "com.y9san9.kds"
7 | version = "1.0"
8 |
9 | repositories {
10 | mavenCentral()
11 | }
12 |
13 | dependencies {
14 | implementation(kotlin("stdlib-jdk8"))
15 | implementation(kotlin("reflect"))
16 | implementation("com.google.code.gson:gson:2.8.6")
17 | }
18 |
19 | configure {
20 | sourceCompatibility = JavaVersion.VERSION_1_8
21 | }
22 |
23 | val fatJar = task("fatJar", type = Jar::class) {
24 | @Suppress("UnstableApiUsage")
25 | manifest {
26 | attributes["Implementation-Title"] = "kotlogram-wrapper"
27 | }
28 | from(configurations.runtimeClasspath.get().map { if (it.isDirectory) it else zipTree(it) })
29 | with(tasks.jar.get() as CopySpec)
30 | }
31 |
32 | tasks {
33 | "build" {
34 | dependsOn(fatJar)
35 | }
36 | }
37 |
38 | tasks {
39 | compileKotlin {
40 | kotlinOptions.jvmTarget = "1.8"
41 | }
42 | compileTestKotlin {
43 | kotlinOptions.jvmTarget = "1.8"
44 | }
45 | }
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | kotlin.code.style=official
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/y9san9/kotlin-data-storage/8e4bed353426b959d72f154ff1a33b2d169e333c/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.1-bin.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 | # Determine the Java command to use to start the JVM.
86 | if [ -n "$JAVA_HOME" ] ; then
87 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
88 | # IBM's JDK on AIX uses strange locations for the executables
89 | JAVACMD="$JAVA_HOME/jre/sh/java"
90 | else
91 | JAVACMD="$JAVA_HOME/bin/java"
92 | fi
93 | if [ ! -x "$JAVACMD" ] ; then
94 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
95 |
96 | Please set the JAVA_HOME variable in your environment to match the
97 | location of your Java installation."
98 | fi
99 | else
100 | JAVACMD="java"
101 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
102 |
103 | Please set the JAVA_HOME variable in your environment to match the
104 | location of your Java installation."
105 | fi
106 |
107 | # Increase the maximum file descriptors if we can.
108 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
109 | MAX_FD_LIMIT=`ulimit -H -n`
110 | if [ $? -eq 0 ] ; then
111 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
112 | MAX_FD="$MAX_FD_LIMIT"
113 | fi
114 | ulimit -n $MAX_FD
115 | if [ $? -ne 0 ] ; then
116 | warn "Could not set maximum file descriptor limit: $MAX_FD"
117 | fi
118 | else
119 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
120 | fi
121 | fi
122 |
123 | # For Darwin, add options to specify how the application appears in the dock
124 | if $darwin; then
125 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
126 | fi
127 |
128 | # For Cygwin or MSYS, switch paths to Windows format before running java
129 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
130 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
131 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
132 | JAVACMD=`cygpath --unix "$JAVACMD"`
133 |
134 | # We build the pattern for arguments to be converted via cygpath
135 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
136 | SEP=""
137 | for dir in $ROOTDIRSRAW ; do
138 | ROOTDIRS="$ROOTDIRS$SEP$dir"
139 | SEP="|"
140 | done
141 | OURCYGPATTERN="(^($ROOTDIRS))"
142 | # Add a user-defined pattern to the cygpath arguments
143 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
144 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
145 | fi
146 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
147 | i=0
148 | for arg in "$@" ; do
149 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
150 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
151 |
152 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
153 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
154 | else
155 | eval `echo args$i`="\"$arg\""
156 | fi
157 | i=`expr $i + 1`
158 | done
159 | case $i in
160 | 0) set -- ;;
161 | 1) set -- "$args0" ;;
162 | 2) set -- "$args0" "$args1" ;;
163 | 3) set -- "$args0" "$args1" "$args2" ;;
164 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
165 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
166 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
167 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
168 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
169 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
170 | esac
171 | fi
172 |
173 | # Escape application args
174 | save () {
175 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
176 | echo " "
177 | }
178 | APP_ARGS=`save "$@"`
179 |
180 | # Collect all arguments for the java command, following the shell quoting and substitution rules
181 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
182 |
183 | exec "$JAVACMD" "$@"
184 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
33 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
34 |
35 | @rem Find java.exe
36 | if defined JAVA_HOME goto findJavaFromJavaHome
37 |
38 | set JAVA_EXE=java.exe
39 | %JAVA_EXE% -version >NUL 2>&1
40 | if "%ERRORLEVEL%" == "0" goto init
41 |
42 | echo.
43 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
44 | echo.
45 | echo Please set the JAVA_HOME variable in your environment to match the
46 | echo location of your Java installation.
47 |
48 | goto fail
49 |
50 | :findJavaFromJavaHome
51 | set JAVA_HOME=%JAVA_HOME:"=%
52 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
53 |
54 | if exist "%JAVA_EXE%" goto init
55 |
56 | echo.
57 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
58 | echo.
59 | echo Please set the JAVA_HOME variable in your environment to match the
60 | echo location of your Java installation.
61 |
62 | goto fail
63 |
64 | :init
65 | @rem Get command-line arguments, handling Windows variants
66 |
67 | if not "%OS%" == "Windows_NT" goto win9xME_args
68 |
69 | :win9xME_args
70 | @rem Slurp the command line arguments.
71 | set CMD_LINE_ARGS=
72 | set _SKIP=2
73 |
74 | :win9xME_args_slurp
75 | if "x%~1" == "x" goto execute
76 |
77 | set CMD_LINE_ARGS=%*
78 |
79 | :execute
80 | @rem Setup the command line
81 |
82 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
83 |
84 | @rem Execute Gradle
85 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
86 |
87 | :end
88 | @rem End local scope for the variables with windows NT shell
89 | if "%ERRORLEVEL%"=="0" goto mainEnd
90 |
91 | :fail
92 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
93 | rem the _cmd.exe /c_ return code!
94 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
95 | exit /b 1
96 |
97 | :mainEnd
98 | if "%OS%"=="Windows_NT" endlocal
99 |
100 | :omega
101 |
--------------------------------------------------------------------------------
/settings.gradle.kts:
--------------------------------------------------------------------------------
1 | rootProject.name = "kotlin-data-file"
--------------------------------------------------------------------------------
/src/main/kotlin/com/y9san9/kds/KDataStorage.kt:
--------------------------------------------------------------------------------
1 | package com.y9san9.kds
2 |
3 | import com.y9san9.kds.utils.fromJson
4 | import com.y9san9.kds.utils.refresh
5 | import com.y9san9.kds.utils.toJson
6 | import java.io.File
7 | import kotlin.reflect.KProperty
8 |
9 | private val dataDir = File(System.getProperty("user.dir"), "data")
10 |
11 | fun T.commit(transaction: T.() -> Unit) {
12 | beginTransaction()
13 | transaction()
14 | endTransaction()
15 | }
16 |
17 | open class KDataStorage(source: File? = null) {
18 | constructor(name: String, dir: File = dataDir) : this(File(dir, "$name.json"))
19 |
20 | private val source = (source ?: File(dataDir, "${this::class.simpleName?.toLowerCase()}.json"))
21 | .apply { refresh(defaultFileText = "{}") }
22 |
23 | /**
24 | * always true inside [commit] block
25 | */
26 | private var transaction = false
27 | private val variableValuesMap = load()
28 |
29 | internal fun beginTransaction() {
30 | transaction = true
31 | }
32 |
33 | internal fun endTransaction() = commit().apply {
34 | transaction = false
35 | }
36 |
37 | private fun commit() = source.writeText(variableValuesMap.toJson())
38 | private fun load() = source.readText().fromJson>()
39 |
40 | fun clear() {
41 | source.delete()
42 | variableValuesMap.clear()
43 | }
44 |
45 | fun clearProperty(property: String) = clearProperties(property)
46 |
47 | fun clearProperties(vararg propertiesToClear: String) = commit {
48 | propertiesToClear.forEach {
49 | if (it in variableValuesMap.keys)
50 | variableValuesMap.remove(it)
51 | else throw ClearingError(it)
52 | }
53 | }
54 |
55 | override fun toString() = variableValuesMap.toString()
56 |
57 | @Suppress("DEPRECATION")
58 | inline fun property(default: T = null as T) = property(default) { it.fromJson() }
59 |
60 | @Deprecated("That is an internal call, do not use it", ReplaceWith("property(default)"))
61 | fun property(default: T, jsonConverter: (String) -> T) = object : Delegate {
62 | /**
63 | * @throws TransactionError if there is no transaction in context
64 | * Usage:
65 | * kDataFile.commit {
66 | * variable = ...
67 | * }
68 | */
69 | override operator fun setValue(thisRef: KDataStorage, property: KProperty<*>, value: T) =
70 | if (transaction)
71 | variableValuesMap[property.name] = value.toJson()
72 | else throw TransactionError
73 |
74 | override operator fun getValue(thisRef: KDataStorage, property: KProperty<*>): T {
75 | return jsonConverter(variableValuesMap[property.name] ?: return default)
76 | }
77 | }
78 | }
79 |
80 | interface Delegate {
81 | operator fun setValue(thisRef: KDataStorage, property: KProperty<*>, value: T)
82 | operator fun getValue(thisRef: KDataStorage, property: KProperty<*>): T
83 | }
84 |
85 | object TransactionError : Throwable("No transaction in the context")
86 | class ClearingError(property: String) : Throwable("No such property in the storage: $property")
--------------------------------------------------------------------------------
/src/main/kotlin/com/y9san9/kds/utils/FileUtils.kt:
--------------------------------------------------------------------------------
1 | package com.y9san9.kds.utils
2 |
3 | import java.io.File
4 |
5 | internal fun File.refresh(directory: Boolean = false, defaultFileText: String = "") = when {
6 | exists() -> Unit
7 | directory -> mkdirs().let { }
8 | else -> {
9 | parentFile.mkdirs()
10 | createNewFile()
11 | writeText(defaultFileText)
12 | }
13 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/y9san9/kds/utils/JsonUtils.kt:
--------------------------------------------------------------------------------
1 | package com.y9san9.kds.utils
2 |
3 | import com.google.gson.reflect.TypeToken
4 | import com.google.gson.Gson
5 | import com.google.gson.GsonBuilder
6 |
7 | val gson = GsonBuilder()
8 | .create()!!
9 |
10 | fun Any?.toJson() = gson.toJson(this)!!
11 | inline fun String.fromJson(): T = gson.fromJson(this, object : TypeToken() {}.type)
--------------------------------------------------------------------------------
/src/test/kotlin/com/y9san9/kds/Main.kt:
--------------------------------------------------------------------------------
1 | package com.y9san9.kds
2 |
3 | data class MyDataClass(
4 | val testString: String,
5 | val testBoolean: Boolean
6 | )
7 |
8 | object Test : KDataStorage() {
9 | var name by property()
10 | var id by property(0)
11 | var data by property()
12 | var list by property(mutableListOf())
13 | }
14 |
15 | fun main() {
16 | Test.commit {
17 | data = MyDataClass("asd", false)
18 | id = 123
19 | name = "asdasd"
20 | }
21 | Test.clearProperties("data", "id")
22 | println(Test.toString())
23 | println(Test.data)
24 | println(Test.id)
25 | }
--------------------------------------------------------------------------------