-
Notifications
You must be signed in to change notification settings - Fork 106
/
journal.ts
70 lines (60 loc) · 1.73 KB
/
journal.ts
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
import _ from "lodash";
interface State {
inTransaction: boolean;
lines: string[];
}
export function format(text: string) {
const state: State = { inTransaction: false, lines: [] };
return text
.split("\n")
.reduce((state: State, line: string) => {
state.lines.push(formatLine(line, state));
return state;
}, state)
.lines.join("\n");
}
function space(length: number) {
return " ".repeat(length);
}
const DATE = /^\d{4}[/-]\d{2}[/-]\d{2}/;
// https://ledger-cli.org/doc/ledger3.html#Journal-Format
function formatLine(line: string, state: State) {
let amountAlignmentColumn = 52;
if (typeof USER_CONFIG !== "undefined") {
amountAlignmentColumn = USER_CONFIG.amount_alignment_column;
}
if (line.match(DATE) || line.match(/^[~=]/)) {
state.inTransaction = true;
return line;
}
if (_.isEmpty(_.trim(line)) || line.match(/^[^ \t]/)) {
state.inTransaction = false;
}
if (!state.inTransaction) {
return line;
}
const fullMatch = line.match(
/^[ \t]+(?<account>(?:[*!]\s+)?[^; \t\n](?:(?!\s{2})[^;\t\n])+)[ \t]+(?<prefix>[^;]*?)(?<amount>[+-]?[.,0-9]+)(?<suffix>.*)$/
);
if (fullMatch) {
const { account, prefix, amount, suffix } = fullMatch.groups;
if (account.length + prefix.length + amount.length <= amountAlignmentColumn - 6) {
return (
space(4) +
account +
space(amountAlignmentColumn - 4 - account.length - prefix.length - amount.length) +
prefix +
amount +
suffix
);
}
}
const partialMatch = line.match(
/^[ \t]+(?<account>(?:[*!]\s+)?[^; \t\n](?:(?!\s{2})[^;\t\n])+)$/
);
if (partialMatch) {
const { account } = partialMatch.groups;
return space(4) + account;
}
return line;
}