add copy method to descriptors

This commit is contained in:
Alexander Nozik 2020-12-20 18:22:50 +03:00
parent 1f773cc230
commit 702589f7b3
3 changed files with 18 additions and 2 deletions

View File

@ -5,6 +5,7 @@
- Yaml meta format based on yaml.kt - Yaml meta format based on yaml.kt
- `Path` builders - `Path` builders
- Special ValueType for lists - Special ValueType for lists
- `copy` method to descriptors
### Changed ### Changed
- `ListValue` and `DoubleArrayValue` implement `Iterable`. - `ListValue` and `DoubleArrayValue` implement `Iterable`.

View File

@ -94,7 +94,11 @@ public class Config() : AbstractMutableMeta<Config>(), ObservableItemProvider {
public operator fun Config.get(token: NameToken): MetaItem<Config>? = items[token] public operator fun Config.get(token: NameToken): MetaItem<Config>? = items[token]
public fun Meta.asConfig(): Config = this as? Config ?: Config().also { builder -> /**
* Create a mutable copy of this [Meta]. The copy is created event if initial [Meta] is a [Config].
* Listeners are not preserved
*/
public fun Meta.toConfig(): Config = Config().also { builder ->
this.items.mapValues { entry -> this.items.mapValues { entry ->
val item = entry.value val item = entry.value
builder[entry.key.asName()] = when (item) { builder[entry.key.asName()] = when (item) {
@ -102,4 +106,9 @@ public fun Meta.asConfig(): Config = this as? Config ?: Config().also { builder
is MetaItem.NodeItem -> MetaItem.NodeItem(item.node.asConfig()) is MetaItem.NodeItem -> MetaItem.NodeItem(item.node.asConfig())
} }
} }
} }
/**
* Return this [Meta] as [Config] if it is [Config] and create a new copy otherwise
*/
public fun Meta.asConfig(): Config = this as? Config ?: toConfig()

View File

@ -38,6 +38,8 @@ public sealed class ItemDescriptor(public val config: Config) {
*/ */
public var indexKey: String by config.string(DEFAULT_INDEX_KEY) public var indexKey: String by config.string(DEFAULT_INDEX_KEY)
public abstract fun copy(): ItemDescriptor
public companion object{ public companion object{
public const val DEFAULT_INDEX_KEY: String = "@index" public const val DEFAULT_INDEX_KEY: String = "@index"
} }
@ -180,6 +182,8 @@ public class NodeDescriptor(config: Config = Config()) : ItemDescriptor(config)
value(name.toName(), block) value(name.toName(), block)
} }
override fun copy(): NodeDescriptor = NodeDescriptor(config.toConfig())
public companion object { public companion object {
internal val ITEM_KEY: Name = "item".asName() internal val ITEM_KEY: Name = "item".asName()
@ -281,6 +285,8 @@ public class ValueDescriptor(config: Config = Config()) : ItemDescriptor(config)
public fun allow(vararg v: Any) { public fun allow(vararg v: Any) {
this.allowedValues = v.map { Value.of(it) } this.allowedValues = v.map { Value.of(it) }
} }
override fun copy(): ValueDescriptor = ValueDescriptor(config.toConfig())
} }
/** /**