]> git.notmuchmail.org Git - notmuch/blob - devel/nmbug/nmbug-status
nmbug-status: print config errors to stderr
[notmuch] / devel / nmbug / nmbug-status
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2011-2012 David Bremner <david@tethera.net>
4 #
5 # dependencies
6 #       - python 2.6 for json
7 #       - argparse; either python 2.7, or install separately
8 #
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.
13 #
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.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with this program.  If not, see http://www.gnu.org/licenses/ .
21
22 """Generate HTML for one or more notmuch searches.
23
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 the Gmane view of the message.
27 """
28
29 from __future__ import print_function
30 from __future__ import unicode_literals
31
32 import codecs
33 import collections
34 import datetime
35 import email.utils
36 try:  # Python 3
37     from urllib.parse import quote
38 except ImportError:  # Python 2
39     from urllib import quote
40 import json
41 import argparse
42 import os
43 import re
44 import sys
45 import subprocess
46 import xml.sax.saxutils
47
48
49 _ENCODING = 'UTF-8'
50 _PAGES = {}
51
52
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
59
60         def __setitem__(self, key, value):
61             super(_OrderedDict, self).__setitem__(key, value)
62             self._keys.append(key)
63
64         def values(self):
65             for key in self._keys:
66                 yield self[key]
67
68
69     collections.OrderedDict = _OrderedDict
70
71
72 class ConfigError (Exception):
73     """Errors with config file usage
74     """
75     pass
76
77
78 def read_config(path=None, encoding=None):
79     "Read config from json file"
80     if not encoding:
81         encoding = _ENCODING
82     if path:
83         try:
84             with open(path, 'rb') as f:
85                 config_bytes = f.read()
86         except IOError as e:
87             raise ConfigError('Could not read config from {}'.format(path))
88     else:
89         nmbhome = os.getenv('NMBGIT', os.path.expanduser('~/.nmbug'))
90         branch = 'config'
91         filename = 'status-config.json'
92
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()
98         if not sha1:
99             raise ConfigError(
100                 ("No local branch '{branch}' in {nmbgit}.  "
101                  'Checkout a local {branch} branch or explicitly set --config.'
102                 ).format(branch=branch, nmbgit=nmbhome))
103
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()
109         status = p.wait()
110         if status != 0:
111             raise ConfigError(
112                 ("Missing status-config.json in branch '{branch}' of"
113                  '{nmbgit}.  Add the file or explicitly set --config.'
114                 ).format(branch=branch, nmbgit=nmbhome))
115
116     config_json = config_bytes.decode(encoding)
117     try:
118         return json.loads(config_json)
119     except ValueError as e:
120         if not path:
121             path = "{} in branch '{}' of {}".format(
122                 filename, branch, nmbhome)
123         raise ConfigError(
124             'Could not parse JSON from the config file {}:\n{}'.format(
125                 path, e))
126
127
128 class Thread (list):
129     def __init__(self):
130         self.running_data = {}
131
132
133 class Page (object):
134     def __init__(self, header=None, footer=None):
135         self.header = header
136         self.footer = footer
137
138     def write(self, database, views, stream=None):
139         if not stream:
140             try:  # Python 3
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)
146         for view in views:
147             self._write_view(database=database, view=view, stream=stream)
148         self._write_footer(views=views, stream=stream)
149
150     def _write_header(self, views, stream):
151         if self.header:
152             stream.write(self.header)
153
154     def _write_footer(self, views, stream):
155         if self.footer:
156             stream.write(self.footer)
157
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('-', '_')
163         try:
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(query)
171         q = notmuch.Query(database, view['query-string'])
172         q.set_sort(sort)
173         threads = self._get_threads(messages=q.search_messages())
174         self._write_view_header(view=view, stream=stream)
175         self._write_threads(threads=threads, stream=stream)
176
177     def _get_threads(self, messages):
178         threads = collections.OrderedDict()
179         for message in messages:
180             thread_id = message.get_thread_id()
181             if thread_id in threads:
182                 thread = threads[thread_id]
183             else:
184                 thread = Thread()
185                 threads[thread_id] = thread
186             thread.running_data, display_data = self._message_display_data(
187                 running_data=thread.running_data, message=message)
188             thread.append(display_data)
189         return list(threads.values())
190
191     def _write_view_header(self, view, stream):
192         pass
193
194     def _write_threads(self, threads, stream):
195         for thread in threads:
196             for message_display_data in thread:
197                 stream.write(
198                     ('{date:10.10s} {from:20.20s} {subject:40.40s}\n'
199                      '{message-id-term:>72}\n'
200                      ).format(**message_display_data))
201             if thread != threads[-1]:
202                 stream.write('\n')
203
204     def _message_display_data(self, running_data, message):
205         headers = ('thread-id', 'message-id', 'date', 'from', 'subject')
206         data = {}
207         for header in headers:
208             if header == 'thread-id':
209                 value = message.get_thread_id()
210             elif header == 'message-id':
211                 value = message.get_message_id()
212                 data['message-id-term'] = 'id:"{0}"'.format(value)
213             elif header == 'date':
214                 value = str(datetime.datetime.utcfromtimestamp(
215                     message.get_date()).date())
216             else:
217                 value = message.get_header(header)
218             if header == 'from':
219                 (value, addr) = email.utils.parseaddr(value)
220                 if not value:
221                     value = addr.split('@')[0]
222             data[header] = value
223         next_running_data = data.copy()
224         for header, value in data.items():
225             if header in ['message-id', 'subject']:
226                 continue
227             if value == running_data.get(header, None):
228                 data[header] = ''
229         return (next_running_data, data)
230
231
232 class HtmlPage (Page):
233     _slug_regexp = re.compile('\W+')
234
235     def _write_header(self, views, stream):
236         super(HtmlPage, self)._write_header(views=views, stream=stream)
237         stream.write('<ul>\n')
238         for view in views:
239             if 'id' not in view:
240                 view['id'] = self._slug(view['title'])
241             stream.write(
242                 '<li><a href="#{id}">{title}</a></li>\n'.format(**view))
243         stream.write('</ul>\n')
244
245     def _write_view_header(self, view, stream):
246         stream.write('<h3 id="{id}">{title}</h3>\n'.format(**view))
247         stream.write('<p>\n')
248         if 'comment' in view:
249             stream.write(view['comment'])
250             stream.write('\n')
251         for line in [
252                 'The view is generated from the following query:',
253                 '</p>',
254                 '<p>',
255                 '  <code>',
256                 view['query-string'],
257                 '  </code>',
258                 '</p>',
259                 ]:
260             stream.write(line)
261             stream.write('\n')
262
263     def _write_threads(self, threads, stream):
264         if not threads:
265             return
266         stream.write('<table>\n')
267         for thread in threads:
268             stream.write('  <tbody>\n')
269             for message_display_data in thread:
270                 stream.write((
271                     '    <tr class="message-first">\n'
272                     '      <td>{date}</td>\n'
273                     '      <td><code>{message-id-term}</code></td>\n'
274                     '    </tr>\n'
275                     '    <tr class="message-last">\n'
276                     '      <td>{from}</td>\n'
277                     '      <td>{subject}</td>\n'
278                     '    </tr>\n'
279                     ).format(**message_display_data))
280             stream.write('  </tbody>\n')
281             if thread != threads[-1]:
282                 stream.write(
283                     '  <tbody><tr><td colspan="2"><br /></td></tr></tbody>\n')
284         stream.write('</table>\n')
285
286     def _message_display_data(self, *args, **kwargs):
287         running_data, display_data = super(
288             HtmlPage, self)._message_display_data(
289                 *args, **kwargs)
290         if 'subject' in display_data and 'message-id' in display_data:
291             d = {
292                 'message-id': quote(display_data['message-id']),
293                 'subject': xml.sax.saxutils.escape(display_data['subject']),
294                 }
295             display_data['subject'] = (
296                 '<a href="http://mid.gmane.org/{message-id}">{subject}</a>'
297                 ).format(**d)
298         for key in ['message-id', 'from']:
299             if key in display_data:
300                 display_data[key] = xml.sax.saxutils.escape(display_data[key])
301         return (running_data, display_data)
302
303     def _slug(self, string):
304         return self._slug_regexp.sub('-', string)
305
306 parser = argparse.ArgumentParser(description=__doc__)
307 parser.add_argument('--text', help='output plain text format',
308                     action='store_true')
309 parser.add_argument('--config', help='load config from given file',
310                     metavar='PATH')
311 parser.add_argument('--list-views', help='list views',
312                     action='store_true')
313 parser.add_argument('--get-query', help='get query for view',
314                     metavar='VIEW')
315
316 args = parser.parse_args()
317
318 try:
319     config = read_config(path=args.config)
320 except ConfigError as e:
321     print(e, file=sys.stderr)
322     sys.exit(1)
323
324 header_template = config['meta'].get('header', '''<!DOCTYPE html>
325 <html lang="en">
326 <head>
327   <meta http-equiv="Content-Type" content="text/html; charset={encoding}" />
328   <title>{title}</title>
329   <style media="screen" type="text/css">
330     table {{
331       border-spacing: 0;
332     }}
333     tr.message-first td {{
334       padding-top: {inter_message_padding};
335     }}
336     tr.message-last td {{
337       padding-bottom: {inter_message_padding};
338     }}
339     td {{
340       padding-left: {border_radius};
341       padding-right: {border_radius};
342     }}
343     tr:first-child td:first-child {{
344       border-top-left-radius: {border_radius};
345     }}
346     tr:first-child td:last-child {{
347       border-top-right-radius: {border_radius};
348     }}
349     tr:last-child td:first-child {{
350       border-bottom-left-radius: {border_radius};
351     }}
352     tr:last-child td:last-child {{
353       border-bottom-right-radius: {border_radius};
354     }}
355     tbody:nth-child(4n+1) tr td {{
356       background-color: #ffd96e;
357     }}
358     tbody:nth-child(4n+3) tr td {{
359       background-color: #bce;
360     }}
361     hr {{
362       border: 0;
363       height: 1px;
364       color: #ccc;
365       background-color: #ccc;
366     }}
367   </style>
368 </head>
369 <body>
370 <h2>{title}</h2>
371 {blurb}
372 </p>
373 <h3>Views</h3>
374 ''')
375
376 footer_template = config['meta'].get('footer', '''
377 <hr>
378 <p>Generated: {datetime}
379 </body>
380 </html>
381 ''')
382
383 now = datetime.datetime.utcnow()
384 context = {
385     'date': now,
386     'datetime': now.strftime('%Y-%m-%d %H:%M:%SZ'),
387     'title': config['meta']['title'],
388     'blurb': config['meta']['blurb'],
389     'encoding': _ENCODING,
390     'inter_message_padding': '0.25em',
391     'border_radius': '0.5em',
392     }
393
394 _PAGES['text'] = Page()
395 _PAGES['html'] = HtmlPage(
396     header=header_template.format(**context),
397     footer=footer_template.format(**context),
398     )
399
400 if args.list_views:
401     for view in config['views']:
402         print(view['title'])
403     sys.exit(0)
404 elif args.get_query != None:
405     for view in config['views']:
406         if args.get_query == view['title']:
407             print(' and '.join(view['query']))
408     sys.exit(0)
409 else:
410     # only import notmuch if needed
411     import notmuch
412
413 if args.text:
414     page = _PAGES['text']
415 else:
416     page = _PAGES['html']
417
418 db = notmuch.Database(mode=notmuch.Database.MODE.READ_ONLY)
419 page.write(database=db, views=config['views'])