From dc86bb5b13d51d2da057021a2553058ccf4fe9c1 Mon Sep 17 00:00:00 2001 From: Alen Date: Mon, 18 Dec 2023 19:53:27 +0400 Subject: Add simple utility for doing FX conversions. --- dot_local/bin/executable_fx | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 dot_local/bin/executable_fx (limited to 'dot_local') 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]} [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() -- cgit 1.4.1-2-gfad0