AnkiNoteTemplate/antp/__main__.py

72 lines
1.9 KiB
Python
Raw Normal View History

2021-11-27 11:54:42 +00:00
# Copyright: Ren Tatsumoto <tatsu at autistici.org>
# License: GNU GPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import sys
2022-04-03 14:57:00 +00:00
from typing import Callable
2021-04-20 11:14:09 +00:00
from urllib.error import URLError
2021-11-27 11:54:42 +00:00
from .common import ANTPError
from .exporter import export_note_type
from .importer import import_note_type
2021-12-25 20:17:48 +00:00
from .updater import update_note_type
2022-04-03 14:57:00 +00:00
def wrap_errors(fn: Callable):
try:
2022-04-03 14:57:00 +00:00
fn()
except URLError:
print("Couldn't connect. Make sure Anki is open and AnkiConnect is installed.")
2021-11-27 11:54:42 +00:00
except ANTPError as ex:
print(ex)
2021-12-25 20:38:41 +00:00
except KeyboardInterrupt:
print("\nAborted.")
2021-04-20 09:27:48 +00:00
2022-04-03 14:57:00 +00:00
def print_help():
options = (
("import", "Add one of the available note types to Anki."),
2022-10-23 21:17:37 +00:00
("update", "Overwrite a previously imported note type with new data. Fields will not be updated."),
2022-04-03 14:57:00 +00:00
("export", "Save your note type as a template."),
("-v, --verbose", "Show detailed info when errors occur."),
)
print(
"Usage: antp.sh [OPTIONS]\n\n"
"Options:"
)
col_width = [max(len(word) for word in col) + 2 for col in zip(*options)]
for row in options:
print(" " * 4, "".join(col.ljust(col_width[i]) for i, col in enumerate(row)), sep='')
def main():
if len(sys.argv) < 2:
print("No action provided.")
print_help()
return
action = None
wrap = True
for arg in sys.argv[1:]:
match arg:
case 'export':
action = export_note_type
case 'import':
action = import_note_type
case 'update':
action = update_note_type
case '-v' | '--verbose':
wrap = False
if action and wrap:
wrap_errors(action)
elif action:
action()
else:
print("Unknown action.")
print_help()
if __name__ == '__main__':
main()