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