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