fixes envvar Option[T] decoder

This commit is contained in:
jangko 2020-10-28 16:17:22 +07:00 committed by zah
parent f4087c1789
commit b961fbe7b4
3 changed files with 29 additions and 8 deletions

View File

@ -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])

View File

@ -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):

View File

@ -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()