2019-12-25 23:08:20 +04:00
|
|
|
"""CLI: Take a set of coins from a coin box."""
|
|
|
|
|
2020-06-04 05:11:29 +04:00
|
|
|
from re import match, search
|
|
|
|
from sys import argv, exit, stderr
|
2019-12-25 23:08:20 +04:00
|
|
|
|
|
|
|
from piggybank import print_program_version
|
2020-06-04 05:11:29 +04:00
|
|
|
from piggybank.configuration import Configuration
|
|
|
|
from piggybank.cli import complement_array_of_coins, handle_default_arguments
|
|
|
|
from piggybank.currencies import CURRENCIES, BaseCurrencyError
|
2019-12-29 18:26:37 +04:00
|
|
|
from piggybank.piggybank import PiggyBank
|
2019-12-25 23:08:20 +04:00
|
|
|
from piggybank.transaction import TYPE_OUTCOME
|
|
|
|
|
|
|
|
__all__ = ["main"]
|
|
|
|
|
|
|
|
|
2020-06-04 05:11:29 +04:00
|
|
|
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 }
|
|
|
|
|
|
|
|
|
2019-12-25 23:08:20 +04:00
|
|
|
def main():
|
2020-06-04 05:11:29 +04:00
|
|
|
handle_default_arguments(' '.join(argv), lambda: print(USAGE_TAKE))
|
|
|
|
|
|
|
|
args = parse_take_arguments(' '.join(argv))
|
2019-12-25 23:08:20 +04:00
|
|
|
|
2020-06-04 05:11:29 +04:00
|
|
|
if args["coins"] is None or args["file"] is None:
|
|
|
|
print(USAGE_TAKE)
|
2019-12-25 23:08:20 +04:00
|
|
|
exit()
|
|
|
|
|
|
|
|
try:
|
2020-06-04 05:11:29 +04:00
|
|
|
piggybank = PiggyBank.from_file(args["file"])
|
|
|
|
coins = complement_array_of_coins(args["coins"], piggybank.currency,
|
|
|
|
args["reversed"])
|
2019-12-25 23:08:20 +04:00
|
|
|
piggybank.transact(coins, TYPE_OUTCOME)
|
2020-06-04 05:11:29 +04:00
|
|
|
piggybank.save(args["file"])
|
2019-12-25 23:08:20 +04:00
|
|
|
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)
|