From 669aed9ec7261c49c49ed26c31f218e42faa491a Mon Sep 17 00:00:00 2001 From: zlg Date: Wed, 10 Oct 2018 19:44:18 -0700 Subject: cli: Add "import" command Currently the import command will only accept YAML files, but is ready for expansion to other formats as needed. --- src/vgstash_cli.py | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) (limited to 'src/vgstash_cli.py') diff --git a/src/vgstash_cli.py b/src/vgstash_cli.py index 6289dba..5f69c47 100644 --- a/src/vgstash_cli.py +++ b/src/vgstash_cli.py @@ -5,6 +5,7 @@ import os import subprocess import sys import tempfile +import yaml # Click also has this, but it doesn't support a fallback value. from shutil import get_terminal_size @@ -196,3 +197,42 @@ def notes(title, system, edit): click.echo("Notes for {} on {}:".format(target_game.title, target_game.system)) click.echo() click.echo(target_game.notes) + + +@cli.command("import") +@click.option("--format", "-f", type=click.Choice(["yaml"]), required=False, default="yaml") +@click.option("--update", "-u", is_flag=True, default=False, help="Overwrite existing games with the file's data") +@click.argument("filepath", + type=click.Path( + readable=True, + resolve_path=True, + dir_okay=False, + file_okay=True), + default=sys.stdin, + ) +def import_file(format, filepath, update): + """ + Import game data from an external file matching the chosen format. + + The default format is YAML. + """ + if format == "yaml": + with open(filepath) as fp: + data = yaml.safe_load(fp) + db = get_db() + count = len(data) + for game in data: + try: + db.add_game( + vgstash.Game( + game["title"], + game["system"], + game["ownership"], + game["progress"], + game["notes"] + ), + update=update + ) + except sqlite3.IntegrityError as e: + count -= 1 + click.echo("Successfully imported {} games from {}.".format(count, filepath)) -- cgit v1.2.3-54-g00ecf