summary refs log tree commit diff
path: root/dot_local/bin
diff options
context:
space:
mode:
authorAlen <alen@dotfiles.xyz>2023-12-18 19:53:27 +0400
committerAlen <alen@dotfiles.xyz>2023-12-18 19:54:23 +0400
commitdc86bb5b13d51d2da057021a2553058ccf4fe9c1 (patch)
tree60d317bcb535c3217e76ca154dd1ed92ba7a9e00 /dot_local/bin
parentcd42ca47ec8a839bbceb9395d530abd706d9b477 (diff)
Add simple utility for doing FX conversions. HEAD main
Diffstat (limited to 'dot_local/bin')
-rw-r--r--dot_local/bin/executable_fx45
1 files changed, 45 insertions, 0 deletions
diff --git a/dot_local/bin/executable_fx b/dot_local/bin/executable_fx
new file mode 100644
index 0000000..699151f
--- /dev/null
+++ b/dot_local/bin/executable_fx
@@ -0,0 +1,45 @@
+#!/usr/bin/env python3
+
+"""Utility for doing simple FX conversions."""
+
+from __future__ import annotations
+
+import plistlib
+import subprocess
+import sys
+
+
+def read_cache() -> dict[str, float]:
+    return plistlib.loads(
+        subprocess.check_output(
+            ("defaults", "export", "com.apple.calculateframework", "-"),
+        )
+    )["currencyCache"]
+
+
+def main() -> None:
+    if len(sys.argv) == 1 or "--help" in sys.argv[1:] or "-h" in sys.argv[1:]:
+        print(f"{sys.argv[0]} <value> <from_currency> [to_currency=USD]")
+        print(__doc__)
+        sys.exit(0)
+
+    value_raw, *args = sys.argv[1:]
+    value_raw = value_raw.replace(",", "").replace(" ", "")
+    if not value_raw.isnumeric():
+        value = float("".join(x for x in value_raw if x.isnumeric()) or "1")
+        from_currency = "".join(x for x in value_raw if not x.isnumeric())
+    else:
+        value = float(value_raw)
+        from_currency, *args = args
+    if args:
+        to_currency, *args = args
+    else:
+        to_currency = "USD"
+
+    cache = read_cache()
+    fx_rate = cache[to_currency] / cache[from_currency]
+    print(f"{value * fx_rate:{',.2f' if value != 1.0 else ''}}")
+
+
+if __name__ == "__main__":
+    main()