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