#!/usr/bin/python3
# or you could run xmllint --format ${filename:-"-"}
import sys
import argparse
import functools


# sudo apt install python3-lxml
from lxml import etree


def main():
    parser = argparse.ArgumentParser(description="Pretty-print XML")
    parser.add_argument('--minify', action='store_true',
                        help='minify instead of pretty-printing')
    parser.add_argument('filenames', metavar='file', nargs='*', default=['-'])
    args = parser.parse_args()
    doit = functools.partial(reformat, pretty_print=not args.minify)
    for fn in args.filenames:
        if fn == '-':
            doit(sys.stdin, fn)
        else:
            with open(fn) as f:
                doit(f, fn)


def reformat(fp, filename, pretty_print=True):
    parser = etree.XMLParser(remove_blank_text=True)
    tree = etree.parse(filename, parser)
    sys.stdout.buffer.write(
        etree.tostring(tree, pretty_print=pretty_print, encoding='UTF-8'))


if __name__ == '__main__':
    main()
