]> git.notmuchmail.org Git - notmuch/blob - devel/nmbug/nmbug-status
nmbug-status: only import notmuch when needed
[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
9 import datetime
10 import rfc822
11 import urllib
12 import json
13 import argparse
14 import os
15 import sys
16 import subprocess
17
18 # parse command line arguments
19
20 parser = argparse.ArgumentParser()
21 parser.add_argument('--text', help='output plain text format',
22                     action='store_true')
23 parser.add_argument('--config', help='load config from given file')
24 parser.add_argument('--list-views', help='list views',
25                     action='store_true')
26 parser.add_argument('--get-query', help='get query for view')
27
28 args = parser.parse_args()
29
30 # read config from json file
31
32 if args.config != None:
33     fp = open(args.config)
34 else:
35     nmbhome = os.getenv('NMBGIT', os.path.expanduser('~/.nmbug'))
36
37     # read only the first line from the pipe
38     sha1 = subprocess.Popen(['git', '--git-dir', nmbhome,
39                              'show-ref', '-s', 'config'],
40                             stdout=subprocess.PIPE).stdout.readline()
41
42     sha1 = sha1.rstrip()
43
44     fp = subprocess.Popen(['git', '--git-dir', nmbhome,
45                            'cat-file', 'blob', sha1+':status-config.json'],
46                           stdout=subprocess.PIPE).stdout
47
48 config = json.load(fp)
49
50 if args.list_views:
51     for view in config['views']:
52         print view['title']
53     sys.exit(0)
54 elif args.get_query != None:
55     for view in config['views']:
56         if args.get_query == view['title']:
57             print ' and '.join(view['query'])
58     sys.exit(0)
59 else:
60     # only import notmuch if needed
61     import notmuch
62
63 if args.text:
64     output_format = 'text'
65 else:
66     output_format = 'html'
67
68 class Thread:
69     def __init__(self, last, lines):
70         self.last = last
71         self.lines = lines
72
73     def join_utf8_with_newlines(self):
74         return '\n'.join( (line.encode('utf-8') for line in self.lines) )
75
76 def output_with_separator(threadlist, sep):
77     outputs = (thread.join_utf8_with_newlines() for thread in threadlist)
78     print sep.join(outputs)
79
80 headers = ['date', 'from', 'subject']
81
82 def print_view(title, query, comment):
83
84     query_string = ' and '.join(query)
85     q_new = notmuch.Query(db, query_string)
86     q_new.set_sort(notmuch.Query.SORT.OLDEST_FIRST)
87
88     last_thread_id = ''
89     threads = {}
90     threadlist = []
91     out = {}
92     last = None
93     lines = None
94
95     if output_format == 'html':
96         print '<h3><a name="%s" />%s</h3>' % (title, title)
97         print comment
98         print 'The view is generated from the following query:'
99         print '<blockquote>'
100         print query_string
101         print '</blockquote>'
102         print '<table>\n'
103
104     for m in q_new.search_messages():
105
106         thread_id = m.get_thread_id()
107
108         if thread_id != last_thread_id:
109             if threads.has_key(thread_id):
110                 last = threads[thread_id].last
111                 lines = threads[thread_id].lines
112             else:
113                 last = {}
114                 lines = []
115                 thread = Thread(last, lines)
116                 threads[thread_id] = thread
117                 for h in headers:
118                     last[h] = ''
119                 threadlist.append(thread)
120             last_thread_id = thread_id
121
122         for header in headers:
123             val = m.get_header(header)
124
125             if header == 'date':
126                 val = str.join(' ', val.split(None)[1:4])
127                 val = str(datetime.datetime.strptime(val, '%d %b %Y').date())
128             elif header == 'from':
129                 (val, addr) = rfc822.parseaddr(val)
130                 if val == '':
131                     val = addr.split('@')[0]
132
133             if header != 'subject' and last[header] == val:
134                 out[header] = ''
135             else:
136                 out[header] = val
137                 last[header] = val
138
139         mid = m.get_message_id()
140         out['id'] = 'id:"%s"' % mid
141
142         if output_format == 'html':
143
144             out['subject'] = '<a href="http://mid.gmane.org/%s">%s</a>' \
145                 % (urllib.quote(mid), out['subject'])
146
147             lines.append(' <tr><td>%s' % out['date'])
148             lines.append('</td><td>%s' % out['id'])
149             lines.append('</td></tr>')
150             lines.append(' <tr><td>%s' % out['from'])
151             lines.append('</td><td>%s' % out['subject'])
152             lines.append('</td></tr>')
153         else:
154             lines.append('%(date)-10.10s %(from)-20.20s %(subject)-40.40s\n%(id)72s' % out)
155
156     if output_format == 'html':
157         output_with_separator(threadlist,
158                               '\n<tr><td colspan="2"><br /></td></tr>\n')
159         print '</table>'
160     else:
161         output_with_separator(threadlist, '\n\n')
162
163 # main program
164
165 db = notmuch.Database(mode=notmuch.Database.MODE.READ_WRITE)
166
167 if output_format == 'html':
168     print '''<?xml version="1.0" encoding="utf-8" ?>
169 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
170 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
171 <head>
172 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
173 <title>Notmuch Patches</title>
174 </head>
175 <body>'''
176     print '<h2>Notmuch Patches</h2>'
177     print 'Generated: %s<br />' % datetime.datetime.utcnow().date()
178     print 'For more infomation see <a href="http://notmuchmail.org/nmbug">nmbug</a>'
179
180     print '<h3>Views</h3>'
181     print '<ul>'
182     for view in config['views']:
183         print '<li><a href="#%(title)s">%(title)s</a></li>' % view
184     print '</ul>'
185
186 for view in config['views']:
187     print_view(**view)
188
189 if output_format == 'html':
190     print '</body>\n</html>'