/
config.nim
58 lines (54 loc) · 1.49 KB
/
config.nim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import parsecfg, streams, strutils, os
type
TConfig* = object
title*: string
url*: string
author*: string
numRssEntries*: int
proc initConfig(): TConfig =
result.title = ""
result.url = ""
result.author = ""
result.numRssEntries = 10
proc validateConfig(config: TConfig) =
template ra(field: string) =
raise newException(EInvalidValue,
"You need to specify the '$1' field in the config." % field)
if config.title == "":
ra("title")
if config.author == "":
ra("author")
if config.url == "":
ra("url")
if config.numRssEntries < 0:
raise newException(EInvalidValue,
"The numRssEntries value can't be negative.")
proc parseConfig*(filename: string): TConfig =
if not filename.existsFile:
raise newException(EInvalidValue, "Missing '" & filename & "'")
result = initConfig()
var file = newFileStream(filename, fmRead)
var cfg: TCfgParser
open(cfg, file, filename)
while true:
let ev = cfg.next()
case ev.kind
of cfgSectionStart:
raise newException(EInvalidValue, "No sections supported.")
of cfgKeyValuePair, cfgOption:
case ev.key.normalize
of "title":
result.title = ev.value
of "url":
result.url = ev.value
of "author":
result.author = ev.value
of "numrssentries":
result.numRssEntries = ev.value.parseInt
of cfgError:
raise newException(EInvalidValue, ev.msg)
of cfgEof:
break
cfg.close()
file.close()
validateConfig(result)