"""CLI: Take a set of coins from a coin box.""" from argparse import ArgumentParser from sys import exit, stderr from piggybank import print_program_version from piggybank.cli import EPILOGUE, complement_array_of_coins from piggybank.currencies import CURRENCIES, DEFAULT_CURRENCY, \ BaseCurrencyError, print_supported_currencies from piggybank.piggybank import PiggyBank from piggybank.transaction import TYPE_OUTCOME __all__ = ["main"] def main(): """An entry point for a take command.""" parser = ArgumentParser(prog="piggybank-take", description="Take a set of coins from a piggy bank.", epilog=EPILOGUE) parser.add_argument("file", type=str, help="a piggy bank file name. Missing .pb extension" "will be added") parser.add_argument("coins", type=int, nargs="+", metavar="COIN", help="add a set of coins. A new file will be created" "if it doesn't exist") parser.add_argument("-v", "--version", action="store_true", help="show program's version and license and exit") parser.add_argument("--list-currencies", action="store_true", help="list all supported currencies and exit") parser.add_argument("-r", "--reverse", action="store_true", help="reverse a set of coins so incomplete set" "fills with zeros from right. E.g. '8 9' will be" "interpreted as '8 9 0 0 0 0' instead of" "'0 0 0 0 8 9'") args = parser.parse_args() if args.version: print_program_version() exit() if args.list_currencies: print_supported_currencies() exit() try: piggybank = PiggyBank.from_file(args.file) coins = complement_array_of_coins(args.coins, piggybank.currency, args.reverse) 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)