62 lines
2.3 KiB
Python
62 lines
2.3 KiB
Python
"""CLI: Put a set of coins into a piggy bank."""
|
|
|
|
from re import split, search
|
|
from sys import argv, stderr
|
|
|
|
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
|
|
|
|
__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 ,]+) in (?P<file>\S+)(?= of (?P<currency>\S+))?"
|
|
argd = search(r, args)
|
|
if not argd is None:
|
|
argd = argd.groupdict()
|
|
return {
|
|
"coins": list(map(int, split(r"\D",argd["coins"]))),
|
|
"file": argd["file"],
|
|
"currency": Configuration()["default-currency"] \
|
|
if argd["currency"] is None else argd["currency"],
|
|
"reversed": not argd["reversed"] is None }
|
|
return None
|
|
|
|
|
|
def main() -> None:
|
|
handle_default_arguments(' '.join(argv[1:]), lambda: print(USAGE_PUT))
|
|
args = parse_put_arguments(' '.join(argv[1:]))
|
|
|
|
if args is None:
|
|
print(USAGE_PUT)
|
|
exit()
|
|
|
|
try:
|
|
try:
|
|
piggybank = PiggyBank.from_file(args["file"])
|
|
except FileNotFoundError:
|
|
currency = Configuration()["default-currency"] \
|
|
if args["currency"] is None else args["currency"]
|
|
piggybank = PiggyBank(currency)
|
|
coins = complement_list_of_coins(args["coins"], piggybank.currency,
|
|
args["reversed"])
|
|
piggybank.transact(coins)
|
|
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 Exception as err:
|
|
print(f"Something went exceptionally wrong. Error:",
|
|
f"{type(err).__name__}:", err, file=stderr)
|