Skip to content

Commit

Permalink
Tweak config and exception (#91)
Browse files Browse the repository at this point in the history
### What's done:

* Changed config name to TomlConfig
* Set deprecated for current KtomlConf
* Modified exception classes and change `field` to `property` as the latter is preferred in Kotlin
* Changed `TomlSerializationException` to `TomlDecodingException`
* Migrated to TomlConfig
  • Loading branch information
Peanutz_OwO authored Jan 15, 2022
1 parent d953779 commit cc6e05a
Show file tree
Hide file tree
Showing 36 changed files with 391 additions and 373 deletions.
10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,12 @@ So we decided to support this format for the `kotlinx` serialization library.
As this young and big project [is needed](https://github.com/Kotlin/kotlinx.serialization/issues/1092) by the Kotlin community, we need your help.
We will be glad if you will test `ktoml` or contribute to this project.
In case you don't have much time for this - at least spend 5 seconds to give us a star to attract other contributors!

**Thanks!** :pray:

### Acknowledgement
Special thanks to those devoted who help us maintain and improve the project: @NightEule5, @Peanuuutz, @petertrr, @Olivki and @edrd-f.

## Supported platforms
All the code is written in Kotlin **common** module. This means that it can be built for each and every Kotlin native platform.
However, to reduce the scope, ktoml now supports only the following platforms:
Expand Down Expand Up @@ -168,10 +172,10 @@ val resultFromList = TomlFileReader.partiallyDecodeFromFile<MyClass>(serializer(

```kotlin
import com.akuleshov7.ktoml.parsers.TomlParser
import com.akuleshov7.ktoml.KtomlConf
import com.akuleshov7.ktoml.TomlConfig
/* ========= */
var tomlAST = TomlParser(KtomlConf()).parseStringsToTomlTree(/* list with toml strings */)
tomlAST = TomlParser(KtomlConf()).parseString(/* the string that you want to parse */)
var tomlAST = TomlParser(TomlConfig()).parseStringsToTomlTree(/* list with toml strings */)
tomlAST = TomlParser(TomlConfig()).parseString(/* the string that you want to parse */)
tomlAST.prettyPrint()
```
</details>
Expand Down
27 changes: 0 additions & 27 deletions ktoml-core/src/commonMain/kotlin/com/akuleshov7/ktoml/KtomlConf.kt

This file was deleted.

43 changes: 22 additions & 21 deletions ktoml-core/src/commonMain/kotlin/com/akuleshov7/ktoml/Toml.kt
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package com.akuleshov7.ktoml

import com.akuleshov7.ktoml.decoders.TomlMainDecoder
import com.akuleshov7.ktoml.exceptions.MissingRequiredFieldException
import com.akuleshov7.ktoml.exceptions.MissingRequiredPropertyException
import com.akuleshov7.ktoml.parsers.TomlParser
import com.akuleshov7.ktoml.tree.TomlFile
import com.akuleshov7.ktoml.writers.TomlWriter
Expand All @@ -25,7 +25,7 @@ import kotlinx.serialization.modules.SerializersModule
*/
@OptIn(ExperimentalSerializationApi::class)
public open class Toml(
private val config: KtomlConf = KtomlConf(),
private val config: TomlConfig = TomlConfig(),
override val serializersModule: SerializersModule = EmptySerializersModule
) : StringFormat {
// parser and writer are created once after the creation of the class, to reduce
Expand Down Expand Up @@ -57,15 +57,16 @@ public open class Toml(
*
* @param toml list with strings in toml format
* @param deserializer deserialization strategy
* @param ktomlConf
* @param config
* @return deserialized object of type T
*/
public fun <T> decodeFromString(
deserializer: DeserializationStrategy<T>,
toml: List<String>,
ktomlConf: KtomlConf): T {
val parsedToml = tomlParser.parseStringsToTomlTree(toml, ktomlConf)
return TomlMainDecoder.decode(deserializer, parsedToml, config)
config: TomlConfig
): T {
val parsedToml = tomlParser.parseStringsToTomlTree(toml, config)
return TomlMainDecoder.decode(deserializer, parsedToml, this.config)
}

/**
Expand All @@ -79,17 +80,17 @@ public open class Toml(
* @param deserializer deserialization strategy
* @param toml request-string in toml format with '\n' or '\r\n' separation
* @param tomlTableName fully qualified name of the toml table (it should be the full name - a.b.c.d)
* @param ktomlConf
* @param config
* @return deserialized object of type T
*/
public fun <T> partiallyDecodeFromString(
deserializer: DeserializationStrategy<T>,
toml: String,
tomlTableName: String,
ktomlConf: KtomlConf = KtomlConf()
config: TomlConfig = TomlConfig()
): T {
val fakeFileNode = generateFakeTomlStructureForPartialParsing(toml, tomlTableName, ktomlConf, TomlParser::parseString)
return TomlMainDecoder.decode(deserializer, fakeFileNode, config)
val fakeFileNode = generateFakeTomlStructureForPartialParsing(toml, tomlTableName, config, TomlParser::parseString)
return TomlMainDecoder.decode(deserializer, fakeFileNode, this.config)
}

/**
Expand All @@ -103,41 +104,41 @@ public open class Toml(
* @param deserializer deserialization strategy
* @param toml list of strings with toml input
* @param tomlTableName fully qualified name of the toml table (it should be the full name - a.b.c.d)
* @param ktomlConf
* @param config
* @return deserialized object of type T
*/
public fun <T> partiallyDecodeFromString(
deserializer: DeserializationStrategy<T>,
toml: List<String>,
tomlTableName: String,
ktomlConf: KtomlConf = KtomlConf()
config: TomlConfig = TomlConfig()
): T {
val fakeFileNode = generateFakeTomlStructureForPartialParsing(
toml.joinToString("\n"),
tomlTableName,
ktomlConf,
config,
TomlParser::parseString,
)
return TomlMainDecoder.decode(deserializer, fakeFileNode, config)
return TomlMainDecoder.decode(deserializer, fakeFileNode, this.config)
}

// ================== other ===============
@Suppress("TYPE_ALIAS")
private fun generateFakeTomlStructureForPartialParsing(
toml: String,
tomlTableName: String,
ktomlConf: KtomlConf = KtomlConf(),
config: TomlConfig = TomlConfig(),
parsingFunction: (TomlParser, String) -> TomlFile
): TomlFile {
val parsedToml = parsingFunction(TomlParser(config), toml)
val parsedToml = parsingFunction(TomlParser(this.config), toml)
.findTableInAstByName(tomlTableName, tomlTableName.count { it == '.' } + 1)
?: throw MissingRequiredFieldException(
"Table with <$tomlTableName> name is missing in the toml input. " +
?: throw MissingRequiredPropertyException(
"Cannot find table with name <$tomlTableName> in the toml input. " +
"Not able to decode this toml part."
)

// adding a fake file node to restore the structure and parse only the part of te toml
val fakeFileNode = TomlFile(ktomlConf)
val fakeFileNode = TomlFile(config)
parsedToml.children.forEach {
fakeFileNode.appendChild(it)
}
Expand All @@ -147,9 +148,9 @@ public open class Toml(

/**
* The default instance of [Toml] with the default configuration.
* See [KtomlConf] for the list of the default options
* See [TomlConfig] for the list of the default options
* ThreadLocal annotation is used here for caching.
*/
@ThreadLocal
public companion object Default : Toml(KtomlConf())
public companion object Default : Toml(TomlConfig())
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
@file:Suppress("HEADER_MISSING_IN_NON_SINGLE_CLASS_FILE", "MISSING_KDOC_TOP_LEVEL")

package com.akuleshov7.ktoml

@Deprecated(
message = "Class name changed for convention.",
replaceWith = ReplaceWith("TomlConfig", "com.akuleshov7.ktoml.TomlConfig")
)
public class KtomlConf(
ignoreUnknownNames: Boolean = false,
emptyValuesAllowed: Boolean = true,
escapedQuotesInLiteralStringsAllowed: Boolean = true
) : TomlConfig(
ignoreUnknownNames,
emptyValuesAllowed,
escapedQuotesInLiteralStringsAllowed
)

/**
* @property ignoreUnknownNames - a control to allow/prohibit unknown names during the deserialization
* @property allowEmptyValues - a control to allow/prohibit empty values: a = # comment
* @property allowEscapedQuotesInLiteralStrings - a control to allow/prohibit escaping of single quotes in literal strings
* @property indentation
*/
public open class TomlConfig(
public val ignoreUnknownNames: Boolean = false,
public val allowEmptyValues: Boolean = true,
public val allowEscapedQuotesInLiteralStrings: Boolean = true,
public val indentation: Indentation = Indentation.FOUR_SPACES,
) {
/**
* @property value
*/
public enum class Indentation(public val value: String) {
FOUR_SPACES(" "),
NONE(""),
TAB("\t"),
TWO_SPACES(" "),
;
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package com.akuleshov7.ktoml.decoders

import com.akuleshov7.ktoml.exceptions.IllegalTomlTypeException
import com.akuleshov7.ktoml.exceptions.TomlCastException
import com.akuleshov7.ktoml.exceptions.CastException
import com.akuleshov7.ktoml.exceptions.IllegalTypeException
import com.akuleshov7.ktoml.tree.TomlKeyValue
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.encoding.AbstractDecoder
Expand Down Expand Up @@ -29,10 +29,10 @@ public abstract class TomlAbstractDecoder : AbstractDecoder() {

private fun invalidType(typeName: String, requiredType: String): Nothing {
val keyValue = decodeKeyValue()
throw IllegalTomlTypeException(
throw IllegalTypeException(
"<$typeName> type is not allowed by toml specification," +
" use <$requiredType> instead" +
" (field = ${keyValue.key.content}; value = ${keyValue.value.content})", keyValue.lineNo
" (key = ${keyValue.key.content}; value = ${keyValue.value.content})", keyValue.lineNo
)
}

Expand All @@ -41,7 +41,7 @@ public abstract class TomlAbstractDecoder : AbstractDecoder() {
try {
return keyValue.value.content as T
} catch (e: ClassCastException) {
throw TomlCastException(
throw CastException(
"Cannot decode the key [${keyValue.key.content}] with the value [${keyValue.value.content}]" +
" with the provided type [${T::class}]. Please check the type in your Serializable class or it's nullability",
keyValue.lineNo
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.akuleshov7.ktoml.decoders

import com.akuleshov7.ktoml.KtomlConf
import com.akuleshov7.ktoml.TomlConfig
import com.akuleshov7.ktoml.tree.TomlKeyValue
import com.akuleshov7.ktoml.tree.TomlKeyValueArray
import com.akuleshov7.ktoml.tree.TomlKeyValuePrimitive
Expand All @@ -14,13 +14,13 @@ import kotlinx.serialization.modules.SerializersModule

/**
* @property rootNode
* @property ktomlConf
* @property config
*/
@ExperimentalSerializationApi
@Suppress("UNCHECKED_CAST")
public class TomlArrayDecoder(
private val rootNode: TomlKeyValueArray,
private val ktomlConf: KtomlConf,
private val config: TomlConfig,
) : TomlAbstractDecoder() {
private var nextElementIndex = 0
private val list = rootNode.value.content as List<TomlValue>
Expand All @@ -46,7 +46,7 @@ public class TomlArrayDecoder(
currentPrimitiveElementOfArray,
rootNode.lineNo,
rootNode.key.content,
ktomlConf
config
)
)
return nextElementIndex++
Expand Down
Loading

0 comments on commit cc6e05a

Please sign in to comment.