1
0
Fork 0
PiggyBank/piggybank/cli/put.py

69 lines
2.6 KiB
Python

"""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
from piggybank.cli import EPILOGUE, complement_array_of_coins
from piggybank.currencies import CURRENCIES, DEFAULT_CURRENCY, \
BaseCurrencyError, print_supported_currencies
from piggybank.piggybank import PiggyBank
__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",
help="a set of coins to add. A new file will be"
"created if it doesn't exist")
parser.add_argument("-c", "--currency", type=str, default=DEFAULT_CURRENCY,
help="set currency of a piggy bank. Not applicable to"
"an existing one")
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'")
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)