#!/usr/bin/env python
# -*-coding: utf8-*-
# Author: Gribouillis for the python forum at www.daniweb.com
# Date: December 29 2012
# License: Public Domain
# Compatibility: python 2.7 and  3
# Use this code freely!
from __future__ import unicode_literals, print_function, division

__doc__ = """ viewxml.py: visualize xml files with treeline.

Treeline is available at http://treeline.bellz.org/index.html
Treeline is under GNU GPL V2 license.
import argparse
from contextlib import contextmanager
import os
import subprocess as sp
import sys

class ViewXmlError(Exception):

def autodirname(suffix='', prefix='tmp', dir=None, delete=True, ignore_errors=False, onerror=None):
    """This context creates a visible temporary directory in the file system.
    This directory is removed by default when the context exits (delete = True).
    The parameters ignore_error and onerror have the same meaning as in shutil.rmtree()
    from tempfile import mkdtemp
    name = mkdtemp(suffix=suffix, prefix=prefix, dir=dir)
        yield name
        if delete:
            from shutil import rmtree
            rmtree(name, ignore_errors) if onerror is None else rmtree(name, ignore_errors, onerror)

def run_command(com):
    prog = sp.Popen(com, shell=True, stderr = sp.PIPE)
    out, err = prog.communicate()
    if prog.returncode:
        raise ViewXmlError(("Command", com, "failed"))

def main(xmlfilename):
    root, ext = os.path.splitext(xmlfilename)
    trl = os.path.basename(root) + ".trl"
    with autodirname() as folder:
        trl = os.path.join(folder, trl)
        run_command("treeline --import-xml -o {trl} {xml}".format(
                xml = xmlfilename, trl = trl))
        run_command("treeline {trl}".format(trl=trl))

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("src", action="store",
        metavar = "XMLFILE",
        help = "Path to an xml file.")
    args = parser.parse_args()