3 # Copyright (c) 2011-2012 David Bremner <david@tethera.net>
6 # - python 2.6 for json
7 # - argparse; either python 2.7, or install separately
9 # This program is free software: you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation, either version 3 of the License, or
12 # (at your option) any later version.
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
19 # You should have received a copy of the GNU General Public License
20 # along with this program. If not, see https://www.gnu.org/licenses/ .
22 """Generate text and/or HTML for one or more notmuch searches.
24 Messages matching each search are grouped by thread. Each message
25 that contains both a subject and message-id will have the displayed
26 subject link to an archive view of the message (defaulting to Gmane).
29 from __future__ import print_function
30 from __future__ import unicode_literals
37 from urllib.parse import quote
38 except ImportError: # Python 2
39 from urllib import quote
46 import xml.sax.saxutils
53 if not hasattr(collections, 'OrderedDict'): # Python 2.6 or earlier
54 class _OrderedDict (dict):
55 "Just enough of a stub to get through Page._get_threads"
56 def __init__(self, *args, **kwargs):
57 super(_OrderedDict, self).__init__(*args, **kwargs)
58 self._keys = [] # record key order
60 def __setitem__(self, key, value):
61 super(_OrderedDict, self).__setitem__(key, value)
62 self._keys.append(key)
65 for key in self._keys:
69 collections.OrderedDict = _OrderedDict
72 class ConfigError (Exception):
73 """Errors with config file usage
78 def read_config(path=None, encoding=None):
79 "Read config from json file"
84 with open(path, 'rb') as f:
85 config_bytes = f.read()
87 raise ConfigError('Could not read config from {}'.format(path))
89 nmbhome = os.getenv('NMBGIT', os.path.expanduser('~/.nmbug'))
91 filename = 'notmuch-report.json'
93 # read only the first line from the pipe
94 sha1_bytes = subprocess.Popen(
95 ['git', '--git-dir', nmbhome, 'show-ref', '-s', '--heads', branch],
96 stdout=subprocess.PIPE).stdout.readline()
97 sha1 = sha1_bytes.decode(encoding).rstrip()
100 ("No local branch '{branch}' in {nmbgit}. "
101 'Checkout a local {branch} branch or explicitly set --config.'
102 ).format(branch=branch, nmbgit=nmbhome))
104 p = subprocess.Popen(
105 ['git', '--git-dir', nmbhome, 'cat-file', 'blob',
106 '{}:{}'.format(sha1, filename)],
107 stdout=subprocess.PIPE)
108 config_bytes, err = p.communicate()
112 ("Missing {filename} in branch '{branch}' of {nmbgit}. "
113 'Add the file or explicitly set --config.'
114 ).format(filename=filename, branch=branch, nmbgit=nmbhome))
116 config_json = config_bytes.decode(encoding)
118 return json.loads(config_json)
119 except ValueError as e:
121 path = "{} in branch '{}' of {}".format(
122 filename, branch, nmbhome)
124 'Could not parse JSON from the config file {}:\n{}'.format(
130 self.running_data = {}
134 def __init__(self, header=None, footer=None):
138 def write(self, database, views, stream=None):
141 byte_stream = sys.stdout.buffer
142 except AttributeError: # Python 2
143 byte_stream = sys.stdout
144 stream = codecs.getwriter(encoding=_ENCODING)(stream=byte_stream)
145 self._write_header(views=views, stream=stream)
147 self._write_view(database=database, view=view, stream=stream)
148 self._write_footer(views=views, stream=stream)
150 def _write_header(self, views, stream):
152 stream.write(self.header)
154 def _write_footer(self, views, stream):
156 stream.write(self.footer)
158 def _write_view(self, database, view, stream):
159 # sort order, default to oldest-first
160 sort_key = view.get('sort', 'oldest-first')
161 # dynamically accept all values in Query.SORT
162 sort_attribute = sort_key.upper().replace('-', '_')
164 sort = getattr(notmuch.Query.SORT, sort_attribute)
165 except AttributeError:
166 raise ConfigError('Invalid sort setting for {}: {!r}'.format(
167 view['title'], sort_key))
168 if 'query-string' not in view:
169 query = view['query']
170 view['query-string'] = ' and '.join(
171 '( {} )'.format(q) for q in query)
172 q = notmuch.Query(database, view['query-string'])
174 threads = self._get_threads(messages=q.search_messages())
175 self._write_view_header(view=view, stream=stream)
176 self._write_threads(threads=threads, stream=stream)
178 def _get_threads(self, messages):
179 threads = collections.OrderedDict()
180 for message in messages:
181 thread_id = message.get_thread_id()
182 if thread_id in threads:
183 thread = threads[thread_id]
186 threads[thread_id] = thread
187 thread.running_data, display_data = self._message_display_data(
188 running_data=thread.running_data, message=message)
189 thread.append(display_data)
190 return list(threads.values())
192 def _write_view_header(self, view, stream):
195 def _write_threads(self, threads, stream):
196 for thread in threads:
197 for message_display_data in thread:
199 ('{date:10.10s} {from:20.20s} {subject:40.40s}\n'
200 '{message-id-term:>72}\n'
201 ).format(**message_display_data))
202 if thread != threads[-1]:
205 def _message_display_data(self, running_data, message):
206 headers = ('thread-id', 'message-id', 'date', 'from', 'subject')
208 for header in headers:
209 if header == 'thread-id':
210 value = message.get_thread_id()
211 elif header == 'message-id':
212 value = message.get_message_id()
213 data['message-id-term'] = 'id:"{0}"'.format(value)
214 elif header == 'date':
215 value = str(datetime.datetime.utcfromtimestamp(
216 message.get_date()).date())
218 value = message.get_header(header)
220 (value, addr) = email.utils.parseaddr(value)
222 value = addr.split('@')[0]
224 next_running_data = data.copy()
225 for header, value in data.items():
226 if header in ['message-id', 'subject']:
228 if value == running_data.get(header, None):
230 return (next_running_data, data)
233 class HtmlPage (Page):
234 _slug_regexp = re.compile('\W+')
236 def __init__(self, message_url_template, **kwargs):
237 self.message_url_template = message_url_template
238 super(HtmlPage, self).__init__(**kwargs)
240 def _write_header(self, views, stream):
241 super(HtmlPage, self)._write_header(views=views, stream=stream)
242 stream.write('<ul>\n')
245 view['id'] = self._slug(view['title'])
247 '<li><a href="#{id}">{title}</a></li>\n'.format(**view))
248 stream.write('</ul>\n')
250 def _write_view_header(self, view, stream):
251 stream.write('<h3 id="{id}">{title}</h3>\n'.format(**view))
252 stream.write('<p>\n')
253 if 'comment' in view:
254 stream.write(view['comment'])
257 'The view is generated from the following query:',
261 view['query-string'],
268 def _write_threads(self, threads, stream):
271 stream.write('<table>\n')
272 for thread in threads:
273 stream.write(' <tbody>\n')
274 for message_display_data in thread:
276 ' <tr class="message-first">\n'
278 ' <td><code>{message-id-term}</code></td>\n'
280 ' <tr class="message-last">\n'
282 ' <td>{subject}</td>\n'
284 ).format(**message_display_data))
285 stream.write(' </tbody>\n')
286 if thread != threads[-1]:
288 ' <tbody><tr><td colspan="2"><br /></td></tr></tbody>\n')
289 stream.write('</table>\n')
291 def _message_display_data(self, *args, **kwargs):
292 running_data, display_data = super(
293 HtmlPage, self)._message_display_data(
295 if 'subject' in display_data and 'message-id' in display_data:
297 'message-id': quote(display_data['message-id']),
298 'subject': xml.sax.saxutils.escape(display_data['subject']),
300 d['url'] = self.message_url_template.format(**d)
301 display_data['subject'] = (
302 '<a href="{url}">{subject}</a>'
304 for key in ['message-id', 'from']:
305 if key in display_data:
306 display_data[key] = xml.sax.saxutils.escape(display_data[key])
307 return (running_data, display_data)
309 def _slug(self, string):
310 return self._slug_regexp.sub('-', string)
312 parser = argparse.ArgumentParser(description=__doc__)
314 '--text', action='store_true', help='output plain text format')
316 '--config', metavar='PATH',
317 help='load config from given file. '
318 'The format is described in notmuch-report.json(5).')
320 '--list-views', action='store_true', help='list views')
322 '--get-query', metavar='VIEW', help='get query for view')
325 args = parser.parse_args()
328 config = read_config(path=args.config)
329 except ConfigError as e:
330 print(e, file=sys.stderr)
333 header_template = config['meta'].get('header', '''<!DOCTYPE html>
336 <meta http-equiv="Content-Type" content="text/html; charset={encoding}" />
337 <title>{title}</title>
338 <style media="screen" type="text/css">
351 tr.message-first td {{
352 padding-top: {inter_message_padding};
354 tr.message-last td {{
355 padding-bottom: {inter_message_padding};
358 padding-left: {border_radius};
359 padding-right: {border_radius};
361 tr:first-child td:first-child {{
362 border-top-left-radius: {border_radius};
364 tr:first-child td:last-child {{
365 border-top-right-radius: {border_radius};
367 tr:last-child td:first-child {{
368 border-bottom-left-radius: {border_radius};
370 tr:last-child td:last-child {{
371 border-bottom-right-radius: {border_radius};
373 tbody:nth-child(4n+1) tr td {{
374 background-color: #ffd96e;
376 tbody:nth-child(4n+3) tr td {{
377 background-color: #bce;
383 background-color: #ccc;
395 footer_template = config['meta'].get('footer', '''
397 <p>Generated: {datetime}</p>
402 now = datetime.datetime.utcnow()
405 'datetime': now.strftime('%Y-%m-%d %H:%M:%SZ'),
406 'title': config['meta']['title'],
407 'blurb': config['meta']['blurb'],
408 'encoding': _ENCODING,
409 'inter_message_padding': '0.25em',
410 'border_radius': '0.5em',
413 _PAGES['text'] = Page()
414 _PAGES['html'] = HtmlPage(
415 header=header_template.format(**context),
416 footer=footer_template.format(**context),
417 message_url_template=config['meta'].get(
418 'message-url', 'http://mid.gmane.org/{message-id}'),
422 for view in config['views']:
425 elif args.get_query != None:
426 for view in config['views']:
427 if args.get_query == view['title']:
428 print(' and '.join('( {} )'.format(q) for q in view['query']))
431 # only import notmuch if needed
435 page = _PAGES['text']
437 page = _PAGES['html']
439 db = notmuch.Database(mode=notmuch.Database.MODE.READ_ONLY)
440 page.write(database=db, views=config['views'])