1# coding: utf-8
2
3"""
4This module provides command-line access to pystache.
5
6Run this script using the -h option for command-line help.
7
8"""
9
10
11try:
12    import json
13except:
14    # The json module is new in Python 2.6, whereas simplejson is
15    # compatible with earlier versions.
16    try:
17        import simplejson as json
18    except ImportError:
19        # Raise an error with a type different from ImportError as a hack around
20        # this issue:
21        #   http://bugs.python.org/issue7559
22        from sys import exc_info
23        ex_type, ex_value, tb = exc_info()
24        new_ex = Exception("%s: %s" % (ex_type.__name__, ex_value))
25        raise new_ex.__class__, new_ex, tb
26
27# The optparse module is deprecated in Python 2.7 in favor of argparse.
28# However, argparse is not available in Python 2.6 and earlier.
29from optparse import OptionParser
30import sys
31
32# We use absolute imports here to allow use of this script from its
33# location in source control (e.g. for development purposes).
34# Otherwise, the following error occurs:
35#
36#   ValueError: Attempted relative import in non-package
37#
38from pystache.common import TemplateNotFoundError
39from pystache.renderer import Renderer
40
41
42USAGE = """\
43%prog [-h] template context
44
45Render a mustache template with the given context.
46
47positional arguments:
48  template    A filename or template string.
49  context     A filename or JSON string."""
50
51
52def parse_args(sys_argv, usage):
53    """
54    Return an OptionParser for the script.
55
56    """
57    args = sys_argv[1:]
58
59    parser = OptionParser(usage=usage)
60    options, args = parser.parse_args(args)
61
62    template, context = args
63
64    return template, context
65
66
67# TODO: verify whether the setup() method's entry_points argument
68# supports passing arguments to main:
69#
70#     http://packages.python.org/distribute/setuptools.html#automatic-script-creation
71#
72def main(sys_argv=sys.argv):
73    template, context = parse_args(sys_argv, USAGE)
74
75    if template.endswith('.mustache'):
76        template = template[:-9]
77
78    renderer = Renderer()
79
80    try:
81        template = renderer.load_template(template)
82    except TemplateNotFoundError:
83        pass
84
85    try:
86        context = json.load(open(context))
87    except IOError:
88        context = json.loads(context)
89
90    rendered = renderer.render(template, context)
91    print rendered
92
93
94if __name__=='__main__':
95    main()
96