]> git.ozlabs.org Git - patchwork/blob - apps/patchwork/parser.py
Decode patch from UTF-8 while parsing from stdin
[patchwork] / apps / patchwork / parser.py
1 #!/usr/bin/python
2 #
3 # Patchwork - automated patch tracking system
4 # Copyright (C) 2008 Jeremy Kerr <jk@ozlabs.org>
5 #
6 # This file is part of the Patchwork package.
7 #
8 # Patchwork is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 2 of the License, or
11 # (at your option) any later version.
12 #
13 # Patchwork is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with Patchwork; if not, write to the Free Software
20 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21
22
23 import re
24
25 try:
26     import hashlib
27     sha1_hash = hashlib.sha1
28 except ImportError:
29     import sha
30     sha1_hash = sha.sha
31
32 _hunk_re = re.compile('^\@\@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? \@\@')
33 _filename_re = re.compile('^(---|\+\+\+) (\S+)')
34
35 def parse_patch(text):
36     patchbuf = ''
37     commentbuf = ''
38     buf = ''
39
40     # state specified the line we just saw, and what to expect next
41     state = 0
42     # 0: text
43     # 1: suspected patch header (diff, ====, Index:)
44     # 2: patch header line 1 (---)
45     # 3: patch header line 2 (+++)
46     # 4: patch hunk header line (@@ line)
47     # 5: patch hunk content
48     #
49     # valid transitions:
50     #  0 -> 1 (diff, ===, Index:)
51     #  0 -> 2 (---)
52     #  1 -> 2 (---)
53     #  2 -> 3 (+++)
54     #  3 -> 4 (@@ line)
55     #  4 -> 5 (patch content)
56     #  5 -> 1 (run out of lines from @@-specifed count)
57     #
58     # Suspected patch header is stored into buf, and appended to
59     # patchbuf if we find a following hunk. Otherwise, append to
60     # comment after parsing.
61
62     # line counts while parsing a patch hunk
63     lc = (0, 0)
64     hunk = 0
65
66     for line in text.decode('utf-8').split('\n'):
67         line += '\n'
68
69         if state == 0:
70             if line.startswith('diff') or line.startswith('===') \
71                     or line.startswith('Index: '):
72                 state = 1
73                 buf += line
74
75             elif line.startswith('--- '):
76                 state = 2
77                 buf += line
78
79             else:
80                 commentbuf += line
81
82         elif state == 1:
83             buf += line
84             if line.startswith('--- '):
85                 state = 2
86
87         elif state == 2:
88             if line.startswith('+++ '):
89                 state = 3
90                 buf += line
91
92             elif hunk:
93                 state = 1
94                 buf += line
95
96             else:
97                 state = 0
98                 commentbuf += buf + line
99                 buf = ''
100
101         elif state == 3:
102             match = _hunk_re.match(line)
103             if match:
104
105                 def fn(x):
106                     if not x:
107                         return 1
108                     return int(x)
109
110                 lc = map(fn, match.groups())
111
112                 state = 4
113                 patchbuf += buf + line
114                 buf = ''
115
116             elif line.startswith('--- '):
117                 patchbuf += buf + line
118                 buf = ''
119                 state = 2
120
121             elif hunk:
122                 state = 1
123                 buf += line
124
125             else:
126                 state = 0
127                 commentbuf += buf + line
128                 buf = ''
129
130         elif state == 4 or state == 5:
131             if line.startswith('-'):
132                 lc[0] -= 1
133             elif line.startswith('+'):
134                 lc[1] -= 1
135             elif line.startswith('\ No newline at end of file'):
136                 # Special case: Not included as part of the hunk's line count
137                 pass
138             else:
139                 lc[0] -= 1
140                 lc[1] -= 1
141
142             patchbuf += line
143
144             if lc[0] <= 0 and lc[1] <= 0:
145                 state = 3
146                 hunk += 1
147             else:
148                 state = 5
149
150         else:
151             raise Exception("Unknown state %d! (line '%s')" % (state, line))
152
153     commentbuf += buf
154
155     if patchbuf == '':
156         patchbuf = None
157
158     if commentbuf == '':
159         commentbuf = None
160
161     return (patchbuf, commentbuf)
162
163 def hash_patch(str):
164     # normalise spaces
165     str = str.replace('\r', '')
166     str = str.strip() + '\n'
167
168     prefixes = ['-', '+', ' ']
169     hash = sha1_hash()
170
171     for line in str.split('\n'):
172
173         if len(line) <= 0:
174             continue
175
176         hunk_match = _hunk_re.match(line)
177         filename_match = _filename_re.match(line)
178
179         if filename_match:
180             # normalise -p1 top-directories
181             if filename_match.group(1) == '---':
182                 filename = 'a/'
183             else:
184                 filename = 'b/'
185             filename += '/'.join(filename_match.group(2).split('/')[1:])
186
187             line = filename_match.group(1) + ' ' + filename
188
189         elif hunk_match:
190             # remove line numbers, but leave line counts
191             def fn(x):
192                 if not x:
193                     return 1
194                 return int(x)
195             line_nos = map(fn, hunk_match.groups())
196             line = '@@ -%d +%d @@' % tuple(line_nos)
197
198         elif line[0] in prefixes:
199             # if we have a +, - or context line, leave as-is
200             pass
201
202         else:
203             # other lines are ignored
204             continue
205
206         hash.update(line.encode('utf-8') + '\n')
207
208     return hash
209
210
211 def main(args):
212     from optparse import OptionParser
213
214     parser = OptionParser()
215     parser.add_option('-p', '--patch', action = 'store_true',
216             dest = 'print_patch', help = 'print parsed patch')
217     parser.add_option('-c', '--comment', action = 'store_true',
218             dest = 'print_comment', help = 'print parsed comment')
219     parser.add_option('-#', '--hash', action = 'store_true',
220             dest = 'print_hash', help = 'print patch hash')
221
222     (options, args) = parser.parse_args()
223
224     # decode from (assumed) UTF-8
225     content = sys.stdin.read().decode('utf-8')
226
227     (patch, comment) = parse_patch(content)
228
229     if options.print_hash and patch:
230         print hash_patch(patch).hexdigest()
231
232     if options.print_patch and patch:
233         print "Patch: ------\n" + patch
234
235     if options.print_comment and comment:
236         print "Comment: ----\n" + comment
237
238 if __name__ == '__main__':
239     import sys
240     sys.exit(main(sys.argv))