nim-confutils/confutils/envvar/writer.nim

56 lines
1.5 KiB
Nim
Raw Normal View History

2020-10-22 07:18:08 +00:00
import
typetraits, options, tables, os,
serialization, ./utils
2020-10-22 07:18:08 +00:00
type
EnvvarWriter* = object
prefix: string
key: seq[string]
proc init*(T: type EnvvarWriter, prefix: string): T =
result.prefix = prefix
proc writeValue*(w: var EnvvarWriter, value: auto) =
mixin enumInstanceSerializedFields, writeValue, writeFieldIMPL
# TODO: reduce allocation
when value is string:
2020-10-22 07:18:08 +00:00
let key = constructKey(w.prefix, w.key)
os.putEnv(key, value)
2020-10-22 07:18:08 +00:00
elif value is (SomePrimitives or range):
let key = constructKey(w.prefix, w.key)
setValue(key, value)
2020-10-22 07:18:08 +00:00
elif value is Option:
if value.isSome:
w.writeValue value.get
elif value is (seq or array or openArray):
when uTypeIsPrimitives(type value):
let key = constructKey(w.prefix, w.key)
setValue(key, value)
elif uTypeIsRecord(type value):
let key = w.key[^1]
for i in 0..<value.len:
w.key[^1] = key & $i
w.writeValue(value[i])
else:
const typeName = typetraits.name(value.type)
{.fatal: "Failed to convert to Envvar array an unsupported type: " & typeName.}
elif value is (object or tuple):
type RecordType = type value
w.key.add ""
value.enumInstanceSerializedFields(fieldName, field):
type FieldType = type field
w.key[^1] = fieldName
w.writeFieldIMPL(FieldTag[RecordType, fieldName, FieldType], field, value)
discard w.key.pop()
else:
const typeName = typetraits.name(value.type)
{.fatal: "Failed to convert to Envvar an unsupported type: " & typeName.}