1
0
PiggyBank/piggybank/cli/take.py

58 lines
2.1 KiB
Python
Raw Normal View History

"""CLI: Take a set of coins from a coin box."""
from re import match, search
from sys import argv, exit, stderr
from piggybank import print_program_version
from piggybank.configuration import Configuration
from piggybank.cli import complement_array_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<reversed>-r|--reversed)?(?P<coins>[\d ,]+) from (?P<file>\S+)"
argd = match(r, args)
if not argd is None:
argd = argd.groupdict()
return {
"coins": list(map(str, argd["coins"].split(", "))),
"file": argd["file"],
"reversed": argd["reversed"] is None }
def main():
handle_default_arguments(' '.join(argv), lambda: print(USAGE_TAKE))
args = parse_take_arguments(' '.join(argv))
if args["coins"] is None or args["file"] is None:
print(USAGE_TAKE)
exit()
try:
piggybank = PiggyBank.from_file(args["file"])
coins = complement_array_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)