1
0
PiggyBank/piggybank/cli/put.py

58 lines
2.2 KiB
Python
Raw Normal View History

"""CLI: Put a set of coins into a piggy bank."""
from re import match
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
__all__ = ["main"]
USAGE_PUT = "Usage: piggybank-put [-r|--reversed] COINS in FILE of CURRENCY\n" \
"Put a set of coins in a piggybank. Set a currency of a new one.\n\n" \
"-r, --reversed -- use reversed order of COINS (from greater to least);\n" \
"COINS -- array of comma or whitespace separated coins;\n" \
"in FILE -- .pb file name of your piggybank;\n" \
"of CURRENCY -- set a currency for a new piggybank.\n"
def parse_put_arguments(args):
r = r"^(?P<reversed>-r|--reversed)? (?P<coins>[\d ,]+)" \
r" in (?P<file>\S+)(?= of (?P<currency>\w+))?"
argd = match(r, args)
if not argd is None:
argd = argd.groupdict()
return {
"coins": list(map(str, argd["coins"].split(", "))),
"file": argd["file"],
"currency": Configuration()["default-currency"] \
if argd["currency"] is None else argd["currency"],
"reversed": argd["reversed"] is None }
def main() -> None:
handle_default_arguments(' '.join(argv), lambda: print(USAGE_PUT))
args = parse_put_arguments(' '.join(argv))
try:
try:
piggybank = PiggyBank.from_file(args["file"])
except FileNotFoundError:
piggybank = PiggyBank(args["currency"])
coins = complement_array_of_coins(args["coins"], piggybank.currency,
args["reversed"])
piggybank.transact(coins)
piggybank.save(args["file"])
except BaseCurrencyError:
print(f"{type(err).__name__}:", err, file=stderr)
except ValueError as err:
print(f"{type(err).__name__}:", err, file=stderr)
except Exception as err:
print(f"Something went exceptionally wrong. Error:",
f"{type(err).__name__}:", err, file=stderr)