Skip to content

Commit

Permalink
fixes envvar Option[T] decoder
Browse files Browse the repository at this point in the history
  • Loading branch information
jangko authored and zah committed Oct 29, 2020
1 parent f4087c1 commit b961fbe
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 8 deletions.
2 changes: 1 addition & 1 deletion confutils/envvar/envvar_serialization.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand Down
11 changes: 4 additions & 7 deletions confutils/envvar/reader.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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):
Expand Down
24 changes: 24 additions & 0 deletions tests/test_envvar.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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()

0 comments on commit b961fbe

Please sign in to comment.