2 # |
2 # |
3 # Copyright 2012 Matt Mackall <mpm@selenic.com> |
3 # Copyright 2012 Matt Mackall <mpm@selenic.com> |
4 # |
4 # |
5 # This software may be used and distributed according to the terms of the |
5 # This software may be used and distributed according to the terms of the |
6 # GNU General Public License version 2 or any later version. |
6 # GNU General Public License version 2 or any later version. |
|
7 |
|
8 from i18n import _ |
|
9 import encoding, util |
7 |
10 |
8 class baseformatter(object): |
11 class baseformatter(object): |
9 def __init__(self, ui, topic, opts): |
12 def __init__(self, ui, topic, opts): |
10 self._ui = ui |
13 self._ui = ui |
11 self._topic = topic |
14 self._topic = topic |
72 self._ui.write(" " + repr(self._item) + ",\n") |
75 self._ui.write(" " + repr(self._item) + ",\n") |
73 def end(self): |
76 def end(self): |
74 baseformatter.end(self) |
77 baseformatter.end(self) |
75 self._ui.write("]\n") |
78 self._ui.write("]\n") |
76 |
79 |
|
80 class jsonformatter(baseformatter): |
|
81 def __init__(self, ui, topic, opts): |
|
82 baseformatter.__init__(self, ui, topic, opts) |
|
83 self._ui.write("[") |
|
84 self._ui._first = True |
|
85 def _showitem(self): |
|
86 if self._ui._first: |
|
87 self._ui._first = False |
|
88 else: |
|
89 self._ui.write(",") |
|
90 |
|
91 self._ui.write("\n {\n") |
|
92 first = True |
|
93 for k, v in sorted(self._item.items()): |
|
94 if first: |
|
95 first = False |
|
96 else: |
|
97 self._ui.write(",\n") |
|
98 if isinstance(v, int): |
|
99 self._ui.write(' "%s": %d' % (k, v)) |
|
100 else: |
|
101 self._ui.write(' "%s": "%s"' % (k, encoding.jsonescape(v))) |
|
102 self._ui.write("\n }") |
|
103 def end(self): |
|
104 baseformatter.end(self) |
|
105 self._ui.write("\n]\n") |
|
106 |
77 def formatter(ui, topic, opts): |
107 def formatter(ui, topic, opts): |
78 if ui.configbool('ui', 'formatdebug'): |
108 template = opts.get("template", "") |
|
109 if template == "json": |
|
110 return jsonformatter(ui, topic, opts) |
|
111 elif template == "debug": |
79 return debugformatter(ui, topic, opts) |
112 return debugformatter(ui, topic, opts) |
|
113 elif template != "": |
|
114 raise util.Abort(_("custom templates not yet supported")) |
|
115 elif ui.configbool('ui', 'formatdebug'): |
|
116 return debugformatter(ui, topic, opts) |
|
117 elif ui.configbool('ui', 'formatjson'): |
|
118 return jsonformatter(ui, topic, opts) |
80 return plainformatter(ui, topic, opts) |
119 return plainformatter(ui, topic, opts) |