Drop foreign key from 'References:' relation
[trackgit.git] / patch.py
blobfef69d3b09e7d856107515541fd983c17ac73f75
1 import re
2 import sys
4 from git import git
6 _boundary_line_regex = re.compile(r'^---')
7 _diff_head_regex = re.compile(r'^diff --git ')
8 _index_line_regex = re.compile(r'^index ([a-f0-9]{7,})\.\.([a-f0-9]{7,}) ')
10 class PatchError(Exception):
11 pass
13 class Patch(object):
15 def __init__(self, data):
16 self.blobs_pre = set()
17 self.blobs_post = set()
18 self.data = data
19 self.notes = None
20 self._parse(data)
22 def _parse(self, data):
23 boundary_seen = False
24 diff_seen = False
25 notes = []
26 for line in data.splitlines(True):
27 if diff_seen:
28 m = _index_line_regex.match(line)
29 if m:
30 self.blobs_pre.add(m.group(1))
31 self.blobs_post.add(m.group(2))
32 continue
33 if _diff_head_regex.match(line):
34 diff_seen = True
35 continue
36 if boundary_seen:
37 notes.append(line)
38 if _boundary_line_regex.match(line):
39 boundary_seen = True
40 continue
41 if diff_seen:
42 self.notes = ''.join(notes)
44 def apply(self):
45 print 'trying to apply patch-%x' % id(self)
46 output, ret = git('am', input=self.data)
47 if ret != 0:
48 # clean up
49 git('am', '--abort')
50 git('reset', '--hard')
51 raise PatchError()
52 return output