-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
executable file
·68 lines (60 loc) · 1.56 KB
/
main.js
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
const {parse} = require('./parser')
module.exports.compute = compute
module.exports.StateError = StateError
function compute ({
init = () => ({}),
reducers = () => {},
end = () => {},
journal = '',
include = path => {
throw new Error(`cannot include ${path}. no include() function defined.`)
}
}) {
var state = init()
var prevLine = {date: new Date(0)}
for (let line of parse(journal, include)) {
if (line.kind) {
try {
if (line.date < prevLine.date) {
throw StateError(`Line on date ${line.date} appears after ${prevLine.date}.`)
}
if (typeof reducers[line.kind] !== 'function') {
throw new StateError(`Directive '${line.kind}' doesn't exists.`)
}
reducers[line.kind](state, line)
} catch (e) {
if (e.stateError) {
var errorMessage = `
ERROR: ${e.message}
on line ${line.n}: '${line.raw}'
`
if (process.exit) {
console.error(errorMessage)
console.error(
e.stack.split('\n')
.filter(s => s.indexOf(process.cwd()) !== -1)
.join('\n')
)
process.exitCode = 1
process.exit()
} else {
let err = new Error(errorMessage)
err.stack = e.stack
}
break
} else {
console.error(`line ${line.n}: '${line.raw}'`)
throw e
}
}
}
prevLine = line
}
end(state)
return state
}
function StateError (message) {
let e = new Error(message)
e.stateError = true
return e
}