1
0
PiggyBank/piggybank/cli/put.py

62 lines
2.2 KiB
Python
Raw Normal View History

"""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.piggybank import PiggyBank
from piggybank.cli import EPILOGUE
from piggybank.currencies import CURRENCIES, DEFAULT_CURRENCY, \
BaseCurrencyError, print_supported_currencies
from piggybank.util import add_common_arguments_to_parser, \
complement_array_of_coins
__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 to a piggy bank. 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")
add_common_arguments_to_parser(parser)
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)