]> git.notmuchmail.org Git - notmuch/blob - devel/nmbug/notmuch-report
emacs: Add new option notmuch-search-hide-excluded
[notmuch] / devel / nmbug / notmuch-report
1 #!/usr/bin/env python3
2 #
3 # Copyright (c) 2011-2012 David Bremner <david@tethera.net>
4 #
5 # dependencies
6 #       - python3 or python2.7
7 #
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with this program.  If not, see https://www.gnu.org/licenses/ .
20
21 """Generate text and/or HTML for one or more notmuch searches.
22
23 Messages matching each search are grouped by thread.  Each message
24 that contains both a subject and message-id will have the displayed
25 subject link to an archive view of the message (defaulting to Gmane).
26 """
27
28 from __future__ import print_function
29 from __future__ import unicode_literals
30
31 import codecs
32 import collections
33 import datetime
34 import email.utils
35 try:  # Python 3
36     from urllib.parse import quote
37 except ImportError:  # Python 2
38     from urllib import quote
39 import json
40 import argparse
41 import os
42 import re
43 import sys
44 import subprocess
45 import xml.sax.saxutils
46
47
48 _ENCODING = 'UTF-8'
49 _PAGES = {}
50
51
52 if not hasattr(collections, 'OrderedDict'):  # Python 2.6 or earlier
53     class _OrderedDict (dict):
54         "Just enough of a stub to get through Page._get_threads"
55         def __init__(self, *args, **kwargs):
56             super(_OrderedDict, self).__init__(*args, **kwargs)
57             self._keys = []  # record key order
58
59         def __setitem__(self, key, value):
60             super(_OrderedDict, self).__setitem__(key, value)
61             self._keys.append(key)
62
63         def values(self):
64             for key in self._keys:
65                 yield self[key]
66
67
68     collections.OrderedDict = _OrderedDict
69
70
71 class ConfigError (Exception):
72     """Errors with config file usage
73     """
74     pass
75
76
77 def read_config(path=None, encoding=None):
78     "Read config from json file"
79     if not encoding:
80         encoding = _ENCODING
81     if path:
82         try:
83             with open(path, 'rb') as f:
84                 config_bytes = f.read()
85         except IOError as e:
86             raise ConfigError('Could not read config from {}'.format(path))
87     else:
88         nmbhome = os.getenv('NMBGIT', os.path.expanduser('~/.nmbug'))
89         branch = 'config'
90         filename = 'notmuch-report.json'
91
92         # read only the first line from the pipe
93         sha1_bytes = subprocess.Popen(
94             ['git', '--git-dir', nmbhome, 'show-ref', '-s', '--heads', branch],
95             stdout=subprocess.PIPE).stdout.readline()
96         sha1 = sha1_bytes.decode(encoding).rstrip()
97         if not sha1:
98             raise ConfigError(
99                 ("No local branch '{branch}' in {nmbgit}.  "
100                  'Checkout a local {branch} branch or explicitly set --config.'
101                 ).format(branch=branch, nmbgit=nmbhome))
102
103         p = subprocess.Popen(
104             ['git', '--git-dir', nmbhome, 'cat-file', 'blob',
105              '{}:{}'.format(sha1, filename)],
106             stdout=subprocess.PIPE)
107         config_bytes, err = p.communicate()
108         status = p.wait()
109         if status != 0:
110             raise ConfigError(
111                 ("Missing {filename} in branch '{branch}' of {nmbgit}.  "
112                  'Add the file or explicitly set --config.'
113                 ).format(filename=filename, branch=branch, nmbgit=nmbhome))
114
115     config_json = config_bytes.decode(encoding)
116     try:
117         return json.loads(config_json)
118     except ValueError as e:
119         if not path:
120             path = "{} in branch '{}' of {}".format(
121                 filename, branch, nmbhome)
122         raise ConfigError(
123             'Could not parse JSON from the config file {}:\n{}'.format(
124                 path, e))
125
126
127 class Thread (list):
128     def __init__(self):
129         self.running_data = {}
130
131
132 class Page (object):
133     def __init__(self, header=None, footer=None):
134         self.header = header
135         self.footer = footer
136
137     def write(self, database, views, stream=None):
138         if not stream:
139             try:  # Python 3
140                 byte_stream = sys.stdout.buffer
141             except AttributeError:  # Python 2
142                 byte_stream = sys.stdout
143             stream = codecs.getwriter(encoding=_ENCODING)(stream=byte_stream)
144         self._write_header(views=views, stream=stream)
145         for view in views:
146             self._write_view(database=database, view=view, stream=stream)
147         self._write_footer(views=views, stream=stream)
148
149     def _write_header(self, views, stream):
150         if self.header:
151             stream.write(self.header)
152
153     def _write_footer(self, views, stream):
154         if self.footer:
155             stream.write(self.footer)
156
157     def _write_view(self, database, view, stream):
158         # sort order, default to oldest-first
159         sort_key = view.get('sort', 'oldest-first')
160         # dynamically accept all values in Query.SORT
161         sort_attribute = sort_key.upper().replace('-', '_')
162         try:
163             sort = getattr(notmuch.Query.SORT, sort_attribute)
164         except AttributeError:
165             raise ConfigError('Invalid sort setting for {}: {!r}'.format(
166                 view['title'], sort_key))
167         if 'query-string' not in view:
168             query = view['query']
169             view['query-string'] = ' and '.join(
170                 '( {} )'.format(q) for q in 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 __init__(self, message_url_template, **kwargs):
236         self.message_url_template = message_url_template
237         super(HtmlPage, self).__init__(**kwargs)
238
239     def _write_header(self, views, stream):
240         super(HtmlPage, self)._write_header(views=views, stream=stream)
241         stream.write('<ul>\n')
242         for view in views:
243             if 'id' not in view:
244                 view['id'] = self._slug(view['title'])
245             stream.write(
246                 '<li><a href="#{id}">{title}</a></li>\n'.format(**view))
247         stream.write('</ul>\n')
248
249     def _write_view_header(self, view, stream):
250         stream.write('<h3 id="{id}">{title}</h3>\n'.format(**view))
251         stream.write('<p>\n')
252         if 'comment' in view:
253             stream.write(view['comment'])
254             stream.write('\n')
255         for line in [
256                 'The view is generated from the following query:',
257                 '</p>',
258                 '<p>',
259                 '  <code>',
260                 view['query-string'],
261                 '  </code>',
262                 '</p>',
263                 ]:
264             stream.write(line)
265             stream.write('\n')
266
267     def _write_threads(self, threads, stream):
268         if not threads:
269             return
270         stream.write('<table>\n')
271         for thread in threads:
272             stream.write('  <tbody>\n')
273             for message_display_data in thread:
274                 stream.write((
275                     '    <tr class="message-first">\n'
276                     '      <td>{date}</td>\n'
277                     '      <td><code>{message-id-term}</code></td>\n'
278                     '    </tr>\n'
279                     '    <tr class="message-last">\n'
280                     '      <td>{from}</td>\n'
281                     '      <td>{subject}</td>\n'
282                     '    </tr>\n'
283                     ).format(**message_display_data))
284             stream.write('  </tbody>\n')
285             if thread != threads[-1]:
286                 stream.write(
287                     '  <tbody><tr><td colspan="2"><br /></td></tr></tbody>\n')
288         stream.write('</table>\n')
289
290     def _message_display_data(self, *args, **kwargs):
291         running_data, display_data = super(
292             HtmlPage, self)._message_display_data(
293                 *args, **kwargs)
294         if 'subject' in display_data and 'message-id' in display_data:
295             d = {
296                 'message-id': quote(display_data['message-id']),
297                 'subject': xml.sax.saxutils.escape(display_data['subject']),
298                 }
299             d['url'] = self.message_url_template.format(**d)
300             display_data['subject'] = (
301                 '<a href="{url}">{subject}</a>'
302                 ).format(**d)
303         for key in ['message-id', 'from']:
304             if key in display_data:
305                 display_data[key] = xml.sax.saxutils.escape(display_data[key])
306         return (running_data, display_data)
307
308     def _slug(self, string):
309         return self._slug_regexp.sub('-', string)
310
311 parser = argparse.ArgumentParser(description=__doc__)
312 parser.add_argument(
313     '--text', action='store_true', help='output plain text format')
314 parser.add_argument(
315     '--config', metavar='PATH',
316     help='load config from given file.  '
317         'The format is described in notmuch-report.json(5).')
318 parser.add_argument(
319     '--list-views', action='store_true', help='list views')
320 parser.add_argument(
321     '--get-query', metavar='VIEW', help='get query for view')
322
323
324 args = parser.parse_args()
325
326 try:
327     config = read_config(path=args.config)
328 except ConfigError as e:
329     print(e, file=sys.stderr)
330     sys.exit(1)
331
332 header_template = config['meta'].get('header', '''<!DOCTYPE html>
333 <html lang="en">
334 <head>
335   <meta http-equiv="Content-Type" content="text/html; charset={encoding}" />
336   <title>{title}</title>
337   <style media="screen" type="text/css">
338     h1 {{
339       font-size: 1.5em;
340     }}
341     h2 {{
342       font-size: 1.17em;
343     }}
344     h3 {{
345       font-size: 100%;
346     }}
347     table {{
348       border-spacing: 0;
349     }}
350     tr.message-first td {{
351       padding-top: {inter_message_padding};
352     }}
353     tr.message-last td {{
354       padding-bottom: {inter_message_padding};
355     }}
356     td {{
357       padding-left: {border_radius};
358       padding-right: {border_radius};
359     }}
360     tr:first-child td:first-child {{
361       border-top-left-radius: {border_radius};
362     }}
363     tr:first-child td:last-child {{
364       border-top-right-radius: {border_radius};
365     }}
366     tr:last-child td:first-child {{
367       border-bottom-left-radius: {border_radius};
368     }}
369     tr:last-child td:last-child {{
370       border-bottom-right-radius: {border_radius};
371     }}
372     tbody:nth-child(4n+1) tr td {{
373       color: #000;
374       background-color: #ffd96e;
375     }}
376     tbody:nth-child(4n+3) tr td {{
377       color: #000;
378       background-color: #bce;
379     }}
380     hr {{
381       border: 0;
382       height: 1px;
383       color: #ccc;
384       background-color: #ccc;
385     }}
386   </style>
387 </head>
388 <body>
389 <h1>{title}</h1>
390 <p>
391 {blurb}
392 </p>
393 <h2>Views</h2>
394 ''')
395
396 footer_template = config['meta'].get('footer', '''
397 <hr>
398 <p>Generated: {datetime}</p>
399 </body>
400 </html>
401 ''')
402
403 now = datetime.datetime.utcnow()
404 context = {
405     'date': now,
406     'datetime': now.strftime('%Y-%m-%d %H:%M:%SZ'),
407     'title': config['meta']['title'],
408     'blurb': config['meta']['blurb'],
409     'encoding': _ENCODING,
410     'inter_message_padding': '0.25em',
411     'border_radius': '0.5em',
412     }
413
414 _PAGES['text'] = Page()
415 _PAGES['html'] = HtmlPage(
416     header=header_template.format(**context),
417     footer=footer_template.format(**context),
418     message_url_template=config['meta'].get(
419         'message-url', 'https://mid.gmane.org/{message-id}'),
420     )
421
422 if args.list_views:
423     for view in config['views']:
424         print(view['title'])
425     sys.exit(0)
426 elif args.get_query != None:
427     for view in config['views']:
428         if args.get_query == view['title']:
429             print(' and '.join('( {} )'.format(q) for q in view['query']))
430     sys.exit(0)
431 else:
432     # only import notmuch if needed
433     import notmuch
434
435 if args.text:
436     page = _PAGES['text']
437 else:
438     page = _PAGES['html']
439
440 db = notmuch.Database(mode=notmuch.Database.MODE.READ_ONLY)
441 page.write(database=db, views=config['views'])