From b961fbe7b4d315a4b3c27ac4d2e2ee857d9e7363 Mon Sep 17 00:00:00 2001 From: jangko Date: Wed, 28 Oct 2020 16:17:22 +0700 Subject: [PATCH] fixes envvar Option[T] decoder --- confutils/envvar/envvar_serialization.nim | 2 +- confutils/envvar/reader.nim | 11 ++++------- tests/test_envvar.nim | 24 +++++++++++++++++++++++ 3 files changed, 29 insertions(+), 8 deletions(-) diff --git a/confutils/envvar/envvar_serialization.nim b/confutils/envvar/envvar_serialization.nim index e0cd6ff..2c28ab1 100644 --- a/confutils/envvar/envvar_serialization.nim +++ b/confutils/envvar/envvar_serialization.nim @@ -43,7 +43,7 @@ template loadFile*(_: type Envvar, var reader = unpackArgs(init, [EnvvarReader, prefix, params]) reader.readValue(RecordType) -template saveFile*(Format: type, prefix: string, value: auto, params: varargs[untyped]) = +template saveFile*(_: type Envvar, prefix: string, value: auto, params: varargs[untyped]) = mixin init, WriterType, writeValue var writer = unpackArgs(init, [EnvvarWriter, prefix, params]) diff --git a/confutils/envvar/reader.nim b/confutils/envvar/reader.nim index dcf3e03..b251801 100644 --- a/confutils/envvar/reader.nim +++ b/confutils/envvar/reader.nim @@ -29,8 +29,6 @@ proc handleReadException*(r: EnvvarReader, proc init*(T: type EnvvarReader, prefix: string): T = result.prefix = prefix -template getUnderlyingType*[T](_: Option[T]): untyped = T - proc readValue*[T](r: var EnvvarReader, value: var T) {.raises: [SerializationError, ValueError, Defect].} = mixin readValue @@ -45,15 +43,14 @@ proc readValue*[T](r: var EnvvarReader, value: var T) getValue(key, value) elif T is Option: + template getUnderlyingType[T](_: Option[T]): untyped = T let key = constructKey(r.prefix, r.key) if existsEnv(key): - type uType = getUnderlyingType(value) - var outVal: uType + type uType = getUnderlyingType(value) when uType is string: value = some(os.getEnv(key)) - else: - r.readValue(outVal) - value = some(outVal) + else: + value = some(r.readValue(uType)) elif T is (seq or array): when uTypeIsPrimitives(T): diff --git a/tests/test_envvar.nim b/tests/test_envvar.nim index ecaace8..d1e2fd2 100644 --- a/tests/test_envvar.nim +++ b/tests/test_envvar.nim @@ -88,5 +88,29 @@ proc testEncoder() = check x.antennae.isNone check x.bumper.get() == "Chromium" +type + ValidIpAddress {.requiresInit.} = object + value: string + + TestObject = object + address: Option[ValidIpAddress] + +proc readValue(r: var EnvvarReader, value: var ValidIpAddress) = + r.readValue(value.value) + +proc writeValue(w: var EnvvarWriter, value: ValidIpAddress) = + w.writeValue(value.value) + +proc testOptionalFields() = + suite "optional fields test suite": + test "optional field with requiresInit pragma": + + var z = TestObject(address: some(ValidIpAddress(value: "1.2.3.4"))) + Envvar.saveFile(commonPrefix, z) + var x = Envvar.loadFile(commonPrefix, TestObject) + check x.address.isSome + check x.address.get().value == "1.2.3.4" + testUtils() testEncoder() +testOptionalFields()