]> git.notmuchmail.org Git - notmuch/blob - devel/nmbug/nmbug-status
nmbug-status: Add Page and HtmlPage for modular rendering
[notmuch] / devel / nmbug / nmbug-status
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2011-2012 David Bremner <david@tethera.net>
4 # License: Same as notmuch
5 # dependencies
6 #       - python 2.6 for json
7 #       - argparse; either python 2.7, or install separately
8 #       - collections.OrderedDict; python 2.7
9
10 from __future__ import print_function
11 from __future__ import unicode_literals
12
13 import codecs
14 import collections
15 import datetime
16 import email.utils
17 import locale
18 try:  # Python 3
19     from urllib.parse import quote
20 except ImportError:  # Python 2
21     from urllib import quote
22 import json
23 import argparse
24 import os
25 import sys
26 import subprocess
27
28
29 _ENCODING = locale.getpreferredencoding() or sys.getdefaultencoding()
30 _PAGES = {}
31
32
33 def read_config(path=None, encoding=None):
34     "Read config from json file"
35     if not encoding:
36         encoding = _ENCODING
37     if path:
38         fp = open(path)
39     else:
40         nmbhome = os.getenv('NMBGIT', os.path.expanduser('~/.nmbug'))
41
42         # read only the first line from the pipe
43         sha1_bytes = subprocess.Popen(
44             ['git', '--git-dir', nmbhome, 'show-ref', '-s', 'config'],
45             stdout=subprocess.PIPE).stdout.readline()
46         sha1 = sha1_bytes.decode(encoding).rstrip()
47
48         fp_byte_stream = subprocess.Popen(
49             ['git', '--git-dir', nmbhome, 'cat-file', 'blob',
50              sha1+':status-config.json'],
51             stdout=subprocess.PIPE).stdout
52         fp = codecs.getreader(encoding=encoding)(stream=fp_byte_stream)
53
54     return json.load(fp)
55
56
57 class Thread (list):
58     def __init__(self):
59         self.running_data = {}
60
61
62 class Page (object):
63     def __init__(self, header=None, footer=None):
64         self.header = header
65         self.footer = footer
66
67     def write(self, database, views, stream=None):
68         if not stream:
69             try:  # Python 3
70                 byte_stream = sys.stdout.buffer
71             except AttributeError:  # Python 2
72                 byte_stream = sys.stdout
73             stream = codecs.getwriter(encoding='UTF-8')(stream=byte_stream)
74         self._write_header(views=views, stream=stream)
75         for view in views:
76             self._write_view(database=database, view=view, stream=stream)
77         self._write_footer(views=views, stream=stream)
78
79     def _write_header(self, views, stream):
80         if self.header:
81             stream.write(self.header)
82
83     def _write_footer(self, views, stream):
84         if self.footer:
85             stream.write(self.footer)
86
87     def _write_view(self, database, view, stream):
88         if 'query-string' not in view:
89             query = view['query']
90             view['query-string'] = ' and '.join(query)
91         q = notmuch.Query(database, view['query-string'])
92         q.set_sort(notmuch.Query.SORT.OLDEST_FIRST)
93         threads = self._get_threads(messages=q.search_messages())
94         self._write_view_header(view=view, stream=stream)
95         self._write_threads(threads=threads, stream=stream)
96
97     def _get_threads(self, messages):
98         threads = collections.OrderedDict()
99         for message in messages:
100             thread_id = message.get_thread_id()
101             if thread_id in threads:
102                 thread = threads[thread_id]
103             else:
104                 thread = Thread()
105                 threads[thread_id] = thread
106             thread.running_data, display_data = self._message_display_data(
107                 running_data=thread.running_data, message=message)
108             thread.append(display_data)
109         return list(threads.values())
110
111     def _write_view_header(self, view, stream):
112         pass
113
114     def _write_threads(self, threads, stream):
115         for thread in threads:
116             for message_display_data in thread:
117                 stream.write(
118                     ('{date:10.10s} {from:20.20s} {subject:40.40s}\n'
119                      '{message-id-term:>72}\n'
120                      ).format(**message_display_data))
121             if thread != threads[-1]:
122                 stream.write('\n')
123
124     def _message_display_data(self, running_data, message):
125         headers = ('thread-id', 'message-id', 'date', 'from', 'subject')
126         data = {}
127         for header in headers:
128             if header == 'thread-id':
129                 value = message.get_thread_id()
130             elif header == 'message-id':
131                 value = message.get_message_id()
132                 data['message-id-term'] = 'id:"{0}"'.format(value)
133             elif header == 'date':
134                 value = str(datetime.datetime.utcfromtimestamp(
135                     message.get_date()).date())
136             else:
137                 value = message.get_header(header)
138             if header == 'from':
139                 (value, addr) = email.utils.parseaddr(value)
140                 if not value:
141                     value = addr.split('@')[0]
142             data[header] = value
143         next_running_data = data.copy()
144         for header, value in data.items():
145             if header in ['message-id', 'subject']:
146                 continue
147             if value == running_data.get(header, None):
148                 data[header] = ''
149         return (next_running_data, data)
150
151
152 class HtmlPage (Page):
153     def _write_header(self, views, stream):
154         super(HtmlPage, self)._write_header(views=views, stream=stream)
155         stream.write('<ul>\n')
156         for view in views:
157             stream.write(
158                 '<li><a href="#{title}">{title}</a></li>\n'.format(**view))
159         stream.write('</ul>\n')
160
161     def _write_view_header(self, view, stream):
162         stream.write('<h3><a name="{title}" />{title}</h3>\n'.format(**view))
163         if 'comment' in view:
164             stream.write(view['comment'])
165             stream.write('\n')
166         for line in [
167                 'The view is generated from the following query:',
168                 '<blockquote>',
169                 view['query-string'],
170                 '</blockquote>',
171                 ]:
172             stream.write(line)
173             stream.write('\n')
174
175     def _write_threads(self, threads, stream):
176         if not threads:
177             return
178         stream.write('<table>\n')
179         for thread in threads:
180             for message_display_data in thread:
181                 stream.write((
182                     '<tr><td>{date}\n'
183                     '</td><td>{message-id-term}\n'
184                     '</td></tr>\n'
185                     '<tr><td>{from}\n'
186                     '</td><td>{subject}\n'
187                     '</td></tr>\n'
188                     ).format(**message_display_data))
189             if thread != threads[-1]:
190                 stream.write('<tr><td colspan="2"><br /></td></tr>\n')
191         stream.write('</table>\n')
192
193     def _message_display_data(self, *args, **kwargs):
194         running_data, display_data = super(
195             HtmlPage, self)._message_display_data(
196                 *args, **kwargs)
197         if 'subject' in display_data and 'message-id' in display_data:
198             d = {
199                 'message-id': quote(display_data['message-id']),
200                 'subject': display_data['subject'],
201                 }
202             display_data['subject'] = (
203                 '<a href="http://mid.gmane.org/{message-id}">{subject}</a>'
204                 ).format(**d)
205         return (running_data, display_data)
206
207
208 _PAGES['text'] = Page()
209 _PAGES['html'] = HtmlPage(
210     header='''<?xml version="1.0" encoding="utf-8" ?>
211 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
212 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
213 <head>
214 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
215 <title>Notmuch Patches</title>
216 </head>
217 <body>
218 <h2>Notmuch Patches</h2>
219 Generated: {date}<br />
220 For more infomation see <a href="http://notmuchmail.org/nmbug">nmbug</a>
221 <h3>Views</h3>
222 '''.format(date=datetime.datetime.utcnow().date()),
223     footer='</body>\n</html>\n',
224     )
225
226
227 parser = argparse.ArgumentParser()
228 parser.add_argument('--text', help='output plain text format',
229                     action='store_true')
230 parser.add_argument('--config', help='load config from given file',
231                     metavar='PATH')
232 parser.add_argument('--list-views', help='list views',
233                     action='store_true')
234 parser.add_argument('--get-query', help='get query for view',
235                     metavar='VIEW')
236
237 args = parser.parse_args()
238
239 config = read_config(path=args.config)
240
241 if args.list_views:
242     for view in config['views']:
243         print(view['title'])
244     sys.exit(0)
245 elif args.get_query != None:
246     for view in config['views']:
247         if args.get_query == view['title']:
248             print(' and '.join(view['query']))
249     sys.exit(0)
250 else:
251     # only import notmuch if needed
252     import notmuch
253
254 if args.text:
255     page = _PAGES['text']
256 else:
257     page = _PAGES['html']
258
259 db = notmuch.Database(mode=notmuch.Database.MODE.READ_ONLY)
260 page.write(database=db, views=config['views'])