summaryrefslogtreecommitdiffstats
path: root/ledger/lib/balance
diff options
context:
space:
mode:
authormakefu <github@syntax-fehler.de>2013-09-25 23:21:00 +0200
committermakefu <github@syntax-fehler.de>2013-09-25 23:21:00 +0200
commit5ff7f557b8e9f5a0966ec029c6f7a5dd15a2dcc8 (patch)
tree1a0922ec1677efe9c2c926d0316bdc69c1e886d5 /ledger/lib/balance
parent67ddf2c41e1285b2a1f11ff3eca8c3d9a7a377c5 (diff)
parent9f3a8aff6cfb84cf7ad43d917050126cf54c7d8b (diff)
Merge branch 'master' of github.com:krebscode/painload
Diffstat (limited to 'ledger/lib/balance')
-rwxr-xr-xledger/lib/balance85
1 files changed, 85 insertions, 0 deletions
diff --git a/ledger/lib/balance b/ledger/lib/balance
new file mode 100755
index 00000000..77cb7f6d
--- /dev/null
+++ b/ledger/lib/balance
@@ -0,0 +1,85 @@
+#! /bin/awk -f
+#
+# ledger balance calculator
+#
+# usage:
+# [colorize=false] [scale=N] //ledger/lib/balance LEDGER_FILE...
+# [colorize=false] [scale=N] //ledger/lib/balance < LEDGER_FILE
+#
+# description:
+# The ledger balance calculator computes the balance of each account it
+# encounters in the provided ledger files.
+#
+# example:
+# //ledger/lib/balance < //cholerab/ledger-spec.markdown
+#
+# see also:
+# //cholerab/ledger-spec.markdown (ledger file format)
+#
+
+BEGIN {
+ colorize = ENVIRON["colorize"] == "" || ENVIRON["colorize"] == "true"
+ # TODO use bc for arbitrary precision arithmetic
+ scale = ENVIRON["scale"]
+}
+
+/^[[:space:]]*[0-9]+-[0-9][0-9]-[0-9][0-9]/{
+ tx($2, $3, $4, $5)
+}
+
+END {
+ display_accounts()
+}
+
+function tx (dst, src, amt, u) {
+ withdraw(src, amt, u)
+ deposit(dst, amt, u)
+}
+
+function deposit (name, amt, u) {
+ accounts[name][u] += amt
+}
+
+function withdraw (name, amt, u) {
+ accounts[name][u] -= amt
+}
+
+function display_accounts() {
+ max_name_len = 0
+ for (name in accounts) {
+ if (length(name) > max_name_len) {
+ max_name_len = length(name)
+ }
+ }
+
+ max_balance_len = 0
+ for (name in accounts) {
+ for (u in accounts[name]) {
+ n = length(int(accounts[name][u]))
+ if (n > max_balance_len) {
+ max_balance_len = n
+ }
+ }
+ }
+ if (scale > 0) {
+ max_balance_len += length(".") + scale
+ }
+
+ for (name in accounts) {
+ for (u in accounts[name]) {
+
+ fmt = "NAME BALANCE UNIT\n"
+ balance = accounts[name][u]
+
+ if (colorize) {
+ sub("BALANCE", "[" (balance < 0 ? 31 : 32) "m&", fmt)
+ }
+
+ sub("NAME", "%-" max_name_len "s", fmt)
+ sub("BALANCE", "%" max_balance_len "." scale "f", fmt)
+ sub("UNIT", "%s", fmt)
+
+ printf fmt, name, balance, u
+ }
+ }
+}