#!/usr/bin/env python3
# Read snippets from snippets.yaml.
# Original source: https://github.com/shachaf/kak/blob/master/scripts/snippet

import sys,yaml

# The cursor will replace the first hole in the snippet.
# Snippets should have at least one hole, as specified in %opt{snippet_hole_pattern}.


def usage():
    print(
        'Usage: {} <snippet-file> [snippet-file ... ] [-- <snippet-name>]'.
        format(sys.argv[0]),
        file=sys.stderr)
    print(
        '  With no snippet name argument, prints a list of valid snippet names.'
    )
    sys.exit(2)


if not 2 <= len(sys.argv):
    usage()

snippets = {}
snippet_name = None
for arg in sys.argv[1:]:
    if arg != '--':
        with open(arg, 'r') as f:
            snippets.update(yaml.safe_load(f))
    else:
        snippet_name = sys.argv[-1]
        break

if snippet_name is None:
    for k in sorted(snippets.keys()):
        print(k)
    sys.exit(0)

try:
    print(snippets[snippet_name], end='')
    sys.exit(0)
except KeyError:
    sys.exit(1)
