-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxpModel.nim
More file actions
76 lines (55 loc) · 1.76 KB
/
Copy pathxpModel.nim
File metadata and controls
76 lines (55 loc) · 1.76 KB
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 os
import strutils
import strformat
import json
import levelSystem
template withDataFile(f: File, dataFilePath: typed, mode:FileMode, body: untyped) =
if not dataFilePath.fileExists:
quit("Error: File does not exist: " & dataFilePath)
if not open(f, dataFilePath, mode):
quit("Error: Cannot open file: " & dataFilePath)
try:
body
except IOError as e:
quit("Fatal IO error: " & e.msg)
except OSError as e:
quit("Fatal OS error: " & e.msg)
finally:
close(f)
proc loadRecords*(dataFilePath: string): seq[XPOrb] {.raises: [].}=
var f: File
withDataFile(f, dataFilePath, fmRead):
for line in f.lines:
if line.isEmptyOrWhitespace:
continue
try:
let orb = parseXPOrb(line)
result.add(orb)
except ValueError, JsonParsingError:
quit(fmt"Error: Invalid XP record: {line}")
proc appendRecord*(orb:XPOrb, dataFilePath: string) {.raises: [].} =
var f: File
withDataFile(f, dataFilePath, fmAppend):
f.writeLine($(%orb))
when isMainModule:
proc quit*(msg: string) =
raise newException(CatchableError, msg)
block test_withDataFile_quits_when_file_does_not_exist:
let madeUpFile = "sdfsdffsadfsdfsadf"
var f: File
doAssertRaises(CatchableError):
withDataFile(f, madeUpFile, fmRead):
discard
block test_withDataFile_quits_on_when_cannot_open_file:
let filename = ".xpModel_test_tempfile"
try:
var f = open(filename, fmWrite)
f.close()
setFilePermissions(filename, {}) # nothing permitted
doAssertRaises(CatchableError):
withDataFile(f, filename, fmRead):
discard
finally:
removeFile(filename)
echo fmt"Cleaned testing tempfile {filename}"
echo "All tests passed in xpModel"