2019-12-25 23:08:20 +04:00
|
|
|
"""CLI: Put a set of coins into a piggy bank."""
|
|
|
|
|
|
|
|
from argparse import ArgumentParser
|
|
|
|
from os.path import exists
|
|
|
|
from sys import exit, stderr
|
|
|
|
|
|
|
|
from piggybank import print_program_version
|
2020-03-27 20:14:22 +04:00
|
|
|
from piggybank.cli import EPILOGUE, complement_array_of_coins
|
2019-12-25 23:08:20 +04:00
|
|
|
from piggybank.currencies import CURRENCIES, DEFAULT_CURRENCY, \
|
|
|
|
BaseCurrencyError, print_supported_currencies
|
2019-12-29 18:26:37 +04:00
|
|
|
from piggybank.piggybank import PiggyBank
|
2019-12-25 23:08:20 +04:00
|
|
|
|
|
|
|
__all__ = ["main"]
|
|
|
|
|
|
|
|
|
|
|
|
def main() -> None:
|
|
|
|
"""An entry point for a put command."""
|
|
|
|
parser = ArgumentParser(prog="piggybank-put",
|
|
|
|
description="Add a set of coins to 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",
|
2019-12-29 18:26:37 +04:00
|
|
|
help="a set of coins to add. A new file will be"
|
|
|
|
"created if it doesn't exist")
|
2019-12-25 23:08:20 +04:00
|
|
|
|
|
|
|
parser.add_argument("-c", "--currency", type=str, default=DEFAULT_CURRENCY,
|
|
|
|
help="set currency of a piggy bank. Not applicable to"
|
|
|
|
"an existing one")
|
|
|
|
|
2020-03-27 20:14:22 +04:00
|
|
|
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'")
|
2019-12-25 23:08:20 +04:00
|
|
|
|
|
|
|
args = parser.parse_args()
|
|
|
|
|
|
|
|
if args.version:
|
|
|
|
print_program_version()
|
|
|
|
exit()
|
|
|
|
|
|
|
|
if args.list_currencies:
|
|
|
|
print_supported_currencies()
|
|
|
|
exit()
|
|
|
|
|
|
|
|
try:
|
|
|
|
try:
|
|
|
|
piggybank = PiggyBank.from_file(args.file)
|
|
|
|
except FileNotFoundError:
|
|
|
|
piggybank = PiggyBank(args.currency)
|
|
|
|
coins = complement_array_of_coins(args.coins, piggybank.currency,
|
|
|
|
args.reverse)
|
|
|
|
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)
|