"""CLI: Take a set of coins from a coin box.""" from re import match, split from sys import argv, exit, stderr from piggybank import print_program_version from piggybank.configuration import Configuration from piggybank.cli import complement_list_of_coins, handle_default_arguments from piggybank.currencies import CURRENCIES, BaseCurrencyError from piggybank.piggybank import PiggyBank from piggybank.transaction import TYPE_OUTCOME __all__ = ["main"] USAGE_TAKE: str = "Usage: piggybank-take [-r|--reversed] COINS from FILE\n\n" \ "Take a set of coins from a piggybank.\n" \ "-r, --reversed -- use reversed order of COINS (from greater to least);\n" \ "COINS -- array of comma or whitespace separated coins;\n" \ "from FILE -- .pb filename.\n" def parse_take_arguments(args): r = r"^(?P-r|--reversed)? ?(?P[\d ,]+) from (?P\S+)" argd = match(r, args) if not argd is None: argd = argd.groupdict() return { "coins": list(map(int, split(r"\D", argd["coins"]))), "file": argd["file"], "reversed": not argd["reversed"] is None } return None def main(): handle_default_arguments(' '.join(argv[1:]), lambda: print(USAGE_TAKE)) args = parse_take_arguments(' '.join(argv[1:])) if args is None: print(USAGE_TAKE) exit() try: piggybank = PiggyBank.from_file(args["file"]) coins = complement_list_of_coins(args["coins"], piggybank.currency, args["reversed"]) piggybank.transact(coins, TYPE_OUTCOME) piggybank.save(args["file"]) except BaseCurrencyError as err: print(f"{type(err).__name__}:", err, file=stderr) except ValueError as err: print(f"{type(err).__name__}:", err, file=stderr) except FileNotFoundError as err: print(f"{type(err).__name__}:", f"{err} doesn't exist.", file=stderr) except Exception as err: print(f"Something went exceptionally wrong. Error:", f"{type(err).__name__}:", err, file=stderr)