status-im / nim-confutils

Simplified handling of command line options and config files
Apache License 2.0
63 stars 16 forks source link

Environment variables example #56

Closed kamilchm closed 2 years ago

kamilchm commented 2 years ago

Hi! Is there a working example of how to use environment variables to populate options? You mention using it by default in https://github.com/status-im/nim-confutils#handling-of-environment-variables-and-config-files, but I can't find any usage of the envTable in the code. I tried using it by setting an env var in the form of {PROGRAM_NAME}_{OPTION_NAME} but it doesn't seem to load it.

jangko commented 2 years ago

Hi @kamilchm, please take a look into this test file. https://github.com/status-im/nim-confutils/blob/master/tests/test_config_file.nim it shows how to use config file, env var, and windows reg.

you need to register the secondary sources first: https://github.com/status-im/nim-confutils/blob/40c6f0b378a34d4812e410e9d6762e21f059de4c/tests/test_config_file.nim#L194

and also overloading readValue for non standard types, for example:

proc readValue(r: var EnvvarReader,
  value: var (InputFile | InputDir | OutFile | OutDir | ValidatorKeyPath)) =
  type T = type value
  value = r.readValue(string).T

proc readValue(r: var EnvvarReader, value: var ValidIpAddress) =
  value = ValidIpAddress.init(r.readValue(string))

proc readValue(r: var EnvvarReader, value: var Port) =
  value = r.readValue(int).Port

proc readValue(r: var EnvvarReader, value: var GraffitiBytes) =
  value = hexToByteArray[value.len](r.readValue(string))

and then use confutils the usual way.

you'll probably see confusing error messages during compilation, usually that is because you don't provide required readValue for specific types e.g. distinct types. I suggest start with a simple config using standard data types, and then add more types when you need it.

don't forget to import confutils/envvar/envvar_serialization

kamilchm commented 2 years ago

Thanks @jangko! It works after I registered Envvar as a secondary source like you showed.