forked from niv/neverwinter.nim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnwn_ssf.nim
76 lines (59 loc) · 2.2 KB
/
nwn_ssf.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import shared, neverwinter/ssf, parsecsv
const SupportedFormatsSimple = ["ssf", "csv"]
const SupportedFormats = {
"ssf": @["ssf"],
"csv": @["csv"]
}.toTable
let args = DOC """
Convert SSF tables to/from various formats.
Supported input/output formats: """ & SupportedFormatsSimple.join(", ") & """
Notes:
* Input and output default to stdin/stdout respectively ("-").
* You cannot pipe the input file into itself (this will result in a
zero-length file).
Usage:
$0 [options]
$USAGE
Options:
-i IN Input file [default: -]
-l INFORMAT Input format [default: autodetect]
-o OUT Output file [default: -]
-k OUTFORMAT Output format [default: autodetect]
--csv-separator SEP What to use as separator for CSV cells [default: ,]
$OPT
"""
let inputfile = $args["-i"]
let outputfile = $args["-o"]
let informat = ensureValidFormat($args["-l"], inputfile, SupportedFormats)
let outformat = ensureValidFormat($args["-k"], outputfile, SupportedFormats)
let input = if $args["-i"] == "-": newFileStream(stdin) else: openFileStream($args["-i"])
let output = if $args["-o"] == "-": newFileStream(stdout) else: openFileStream($args["-o"], fmWrite)
proc readCsv(s: Stream): SsfRoot =
result = newSsf()
var p: CsvParser
p.open(input = s, filename = inputfile, separator = ($args["--csv-separator"])[0])
while p.readRow():
var e = SsfEntry()
let idx = p.row[0].parseInt.StrRef
e.resref = p.row[1].strip(leading = true, trailing = true, chars = Whitespace)
e.strref = uint32 p.row[2].parseUInt()
result.entries.add(e)
p.close()
proc writeCsv(s: Stream, ssf: SsfRoot) =
proc quote(s: string): string =
"\"" & s.replace("\"", "\"\"") & "\""
for idx, e in ssf.entries:
s.writeLine([
$idx,
if e.resref != "": e.resref.quote() else: "",
$e.strref
].join(($args["--csv-separator"])[0..0]))
var state: SsfRoot
case informat:
of "ssf": state = input.readSsf()
of "csv": state = input.readCsv()
else: quit("Unsupported informat: " & informat)
case outformat:
of "ssf": output.writeSsf(state)
of "csv": output.writeCsv(state)
else: quit("Unsupported outformat: " & outformat)