Show More
@@ -1,1435 +1,1437 b'' | |||||
1 | # patch.py - patch file parsing routines |
|
1 | # patch.py - patch file parsing routines | |
2 | # |
|
2 | # | |
3 | # Copyright 2006 Brendan Cully <brendan@kublai.com> |
|
3 | # Copyright 2006 Brendan Cully <brendan@kublai.com> | |
4 | # Copyright 2007 Chris Mason <chris.mason@oracle.com> |
|
4 | # Copyright 2007 Chris Mason <chris.mason@oracle.com> | |
5 | # |
|
5 | # | |
6 | # This software may be used and distributed according to the terms of the |
|
6 | # This software may be used and distributed according to the terms of the | |
7 | # GNU General Public License version 2, incorporated herein by reference. |
|
7 | # GNU General Public License version 2, incorporated herein by reference. | |
8 |
|
8 | |||
9 | from i18n import _ |
|
9 | from i18n import _ | |
10 | from node import hex, nullid, short |
|
10 | from node import hex, nullid, short | |
11 | import base85, cmdutil, mdiff, util, diffhelpers, copies |
|
11 | import base85, cmdutil, mdiff, util, diffhelpers, copies | |
12 | import cStringIO, email.Parser, os, re |
|
12 | import cStringIO, email.Parser, os, re | |
13 | import sys, tempfile, zlib |
|
13 | import sys, tempfile, zlib | |
14 |
|
14 | |||
15 | gitre = re.compile('diff --git a/(.*) b/(.*)') |
|
15 | gitre = re.compile('diff --git a/(.*) b/(.*)') | |
16 |
|
16 | |||
17 | class PatchError(Exception): |
|
17 | class PatchError(Exception): | |
18 | pass |
|
18 | pass | |
19 |
|
19 | |||
20 | class NoHunks(PatchError): |
|
20 | class NoHunks(PatchError): | |
21 | pass |
|
21 | pass | |
22 |
|
22 | |||
23 | # helper functions |
|
23 | # helper functions | |
24 |
|
24 | |||
25 | def copyfile(src, dst, basedir): |
|
25 | def copyfile(src, dst, basedir): | |
26 | abssrc, absdst = [util.canonpath(basedir, basedir, x) for x in [src, dst]] |
|
26 | abssrc, absdst = [util.canonpath(basedir, basedir, x) for x in [src, dst]] | |
27 | if os.path.exists(absdst): |
|
27 | if os.path.exists(absdst): | |
28 | raise util.Abort(_("cannot create %s: destination already exists") % |
|
28 | raise util.Abort(_("cannot create %s: destination already exists") % | |
29 | dst) |
|
29 | dst) | |
30 |
|
30 | |||
31 | dstdir = os.path.dirname(absdst) |
|
31 | dstdir = os.path.dirname(absdst) | |
32 | if dstdir and not os.path.isdir(dstdir): |
|
32 | if dstdir and not os.path.isdir(dstdir): | |
33 | try: |
|
33 | try: | |
34 | os.makedirs(dstdir) |
|
34 | os.makedirs(dstdir) | |
35 | except IOError: |
|
35 | except IOError: | |
36 | raise util.Abort( |
|
36 | raise util.Abort( | |
37 | _("cannot create %s: unable to create destination directory") |
|
37 | _("cannot create %s: unable to create destination directory") | |
38 | % dst) |
|
38 | % dst) | |
39 |
|
39 | |||
40 | util.copyfile(abssrc, absdst) |
|
40 | util.copyfile(abssrc, absdst) | |
41 |
|
41 | |||
42 | # public functions |
|
42 | # public functions | |
43 |
|
43 | |||
44 | def extract(ui, fileobj): |
|
44 | def extract(ui, fileobj): | |
45 | '''extract patch from data read from fileobj. |
|
45 | '''extract patch from data read from fileobj. | |
46 |
|
46 | |||
47 | patch can be a normal patch or contained in an email message. |
|
47 | patch can be a normal patch or contained in an email message. | |
48 |
|
48 | |||
49 | return tuple (filename, message, user, date, node, p1, p2). |
|
49 | return tuple (filename, message, user, date, node, p1, p2). | |
50 | Any item in the returned tuple can be None. If filename is None, |
|
50 | Any item in the returned tuple can be None. If filename is None, | |
51 | fileobj did not contain a patch. Caller must unlink filename when done.''' |
|
51 | fileobj did not contain a patch. Caller must unlink filename when done.''' | |
52 |
|
52 | |||
53 | # attempt to detect the start of a patch |
|
53 | # attempt to detect the start of a patch | |
54 | # (this heuristic is borrowed from quilt) |
|
54 | # (this heuristic is borrowed from quilt) | |
55 | diffre = re.compile(r'^(?:Index:[ \t]|diff[ \t]|RCS file: |' |
|
55 | diffre = re.compile(r'^(?:Index:[ \t]|diff[ \t]|RCS file: |' | |
56 | r'retrieving revision [0-9]+(\.[0-9]+)*$|' |
|
56 | r'retrieving revision [0-9]+(\.[0-9]+)*$|' | |
57 | r'(---|\*\*\*)[ \t])', re.MULTILINE) |
|
57 | r'(---|\*\*\*)[ \t])', re.MULTILINE) | |
58 |
|
58 | |||
59 | fd, tmpname = tempfile.mkstemp(prefix='hg-patch-') |
|
59 | fd, tmpname = tempfile.mkstemp(prefix='hg-patch-') | |
60 | tmpfp = os.fdopen(fd, 'w') |
|
60 | tmpfp = os.fdopen(fd, 'w') | |
61 | try: |
|
61 | try: | |
62 | msg = email.Parser.Parser().parse(fileobj) |
|
62 | msg = email.Parser.Parser().parse(fileobj) | |
63 |
|
63 | |||
64 | subject = msg['Subject'] |
|
64 | subject = msg['Subject'] | |
65 | user = msg['From'] |
|
65 | user = msg['From'] | |
66 | if not subject and not user: |
|
66 | if not subject and not user: | |
67 | # Not an email, restore parsed headers if any |
|
67 | # Not an email, restore parsed headers if any | |
68 | subject = '\n'.join(': '.join(h) for h in msg.items()) + '\n' |
|
68 | subject = '\n'.join(': '.join(h) for h in msg.items()) + '\n' | |
69 |
|
69 | |||
70 | gitsendmail = 'git-send-email' in msg.get('X-Mailer', '') |
|
70 | gitsendmail = 'git-send-email' in msg.get('X-Mailer', '') | |
71 | # should try to parse msg['Date'] |
|
71 | # should try to parse msg['Date'] | |
72 | date = None |
|
72 | date = None | |
73 | nodeid = None |
|
73 | nodeid = None | |
74 | branch = None |
|
74 | branch = None | |
75 | parents = [] |
|
75 | parents = [] | |
76 |
|
76 | |||
77 | if subject: |
|
77 | if subject: | |
78 | if subject.startswith('[PATCH'): |
|
78 | if subject.startswith('[PATCH'): | |
79 | pend = subject.find(']') |
|
79 | pend = subject.find(']') | |
80 | if pend >= 0: |
|
80 | if pend >= 0: | |
81 | subject = subject[pend+1:].lstrip() |
|
81 | subject = subject[pend+1:].lstrip() | |
82 | subject = subject.replace('\n\t', ' ') |
|
82 | subject = subject.replace('\n\t', ' ') | |
83 | ui.debug('Subject: %s\n' % subject) |
|
83 | ui.debug('Subject: %s\n' % subject) | |
84 | if user: |
|
84 | if user: | |
85 | ui.debug('From: %s\n' % user) |
|
85 | ui.debug('From: %s\n' % user) | |
86 | diffs_seen = 0 |
|
86 | diffs_seen = 0 | |
87 | ok_types = ('text/plain', 'text/x-diff', 'text/x-patch') |
|
87 | ok_types = ('text/plain', 'text/x-diff', 'text/x-patch') | |
88 | message = '' |
|
88 | message = '' | |
89 | for part in msg.walk(): |
|
89 | for part in msg.walk(): | |
90 | content_type = part.get_content_type() |
|
90 | content_type = part.get_content_type() | |
91 | ui.debug('Content-Type: %s\n' % content_type) |
|
91 | ui.debug('Content-Type: %s\n' % content_type) | |
92 | if content_type not in ok_types: |
|
92 | if content_type not in ok_types: | |
93 | continue |
|
93 | continue | |
94 | payload = part.get_payload(decode=True) |
|
94 | payload = part.get_payload(decode=True) | |
95 | m = diffre.search(payload) |
|
95 | m = diffre.search(payload) | |
96 | if m: |
|
96 | if m: | |
97 | hgpatch = False |
|
97 | hgpatch = False | |
98 | ignoretext = False |
|
98 | ignoretext = False | |
99 |
|
99 | |||
100 | ui.debug('found patch at byte %d\n' % m.start(0)) |
|
100 | ui.debug('found patch at byte %d\n' % m.start(0)) | |
101 | diffs_seen += 1 |
|
101 | diffs_seen += 1 | |
102 | cfp = cStringIO.StringIO() |
|
102 | cfp = cStringIO.StringIO() | |
103 | for line in payload[:m.start(0)].splitlines(): |
|
103 | for line in payload[:m.start(0)].splitlines(): | |
104 | if line.startswith('# HG changeset patch'): |
|
104 | if line.startswith('# HG changeset patch'): | |
105 | ui.debug('patch generated by hg export\n') |
|
105 | ui.debug('patch generated by hg export\n') | |
106 | hgpatch = True |
|
106 | hgpatch = True | |
107 | # drop earlier commit message content |
|
107 | # drop earlier commit message content | |
108 | cfp.seek(0) |
|
108 | cfp.seek(0) | |
109 | cfp.truncate() |
|
109 | cfp.truncate() | |
110 | subject = None |
|
110 | subject = None | |
111 | elif hgpatch: |
|
111 | elif hgpatch: | |
112 | if line.startswith('# User '): |
|
112 | if line.startswith('# User '): | |
113 | user = line[7:] |
|
113 | user = line[7:] | |
114 | ui.debug('From: %s\n' % user) |
|
114 | ui.debug('From: %s\n' % user) | |
115 | elif line.startswith("# Date "): |
|
115 | elif line.startswith("# Date "): | |
116 | date = line[7:] |
|
116 | date = line[7:] | |
117 | elif line.startswith("# Branch "): |
|
117 | elif line.startswith("# Branch "): | |
118 | branch = line[9:] |
|
118 | branch = line[9:] | |
119 | elif line.startswith("# Node ID "): |
|
119 | elif line.startswith("# Node ID "): | |
120 | nodeid = line[10:] |
|
120 | nodeid = line[10:] | |
121 | elif line.startswith("# Parent "): |
|
121 | elif line.startswith("# Parent "): | |
122 | parents.append(line[10:]) |
|
122 | parents.append(line[10:]) | |
123 | elif line == '---' and gitsendmail: |
|
123 | elif line == '---' and gitsendmail: | |
124 | ignoretext = True |
|
124 | ignoretext = True | |
125 | if not line.startswith('# ') and not ignoretext: |
|
125 | if not line.startswith('# ') and not ignoretext: | |
126 | cfp.write(line) |
|
126 | cfp.write(line) | |
127 | cfp.write('\n') |
|
127 | cfp.write('\n') | |
128 | message = cfp.getvalue() |
|
128 | message = cfp.getvalue() | |
129 | if tmpfp: |
|
129 | if tmpfp: | |
130 | tmpfp.write(payload) |
|
130 | tmpfp.write(payload) | |
131 | if not payload.endswith('\n'): |
|
131 | if not payload.endswith('\n'): | |
132 | tmpfp.write('\n') |
|
132 | tmpfp.write('\n') | |
133 | elif not diffs_seen and message and content_type == 'text/plain': |
|
133 | elif not diffs_seen and message and content_type == 'text/plain': | |
134 | message += '\n' + payload |
|
134 | message += '\n' + payload | |
135 | except: |
|
135 | except: | |
136 | tmpfp.close() |
|
136 | tmpfp.close() | |
137 | os.unlink(tmpname) |
|
137 | os.unlink(tmpname) | |
138 | raise |
|
138 | raise | |
139 |
|
139 | |||
140 | if subject and not message.startswith(subject): |
|
140 | if subject and not message.startswith(subject): | |
141 | message = '%s\n%s' % (subject, message) |
|
141 | message = '%s\n%s' % (subject, message) | |
142 | tmpfp.close() |
|
142 | tmpfp.close() | |
143 | if not diffs_seen: |
|
143 | if not diffs_seen: | |
144 | os.unlink(tmpname) |
|
144 | os.unlink(tmpname) | |
145 | return None, message, user, date, branch, None, None, None |
|
145 | return None, message, user, date, branch, None, None, None | |
146 | p1 = parents and parents.pop(0) or None |
|
146 | p1 = parents and parents.pop(0) or None | |
147 | p2 = parents and parents.pop(0) or None |
|
147 | p2 = parents and parents.pop(0) or None | |
148 | return tmpname, message, user, date, branch, nodeid, p1, p2 |
|
148 | return tmpname, message, user, date, branch, nodeid, p1, p2 | |
149 |
|
149 | |||
150 | GP_PATCH = 1 << 0 # we have to run patch |
|
150 | GP_PATCH = 1 << 0 # we have to run patch | |
151 | GP_FILTER = 1 << 1 # there's some copy/rename operation |
|
151 | GP_FILTER = 1 << 1 # there's some copy/rename operation | |
152 | GP_BINARY = 1 << 2 # there's a binary patch |
|
152 | GP_BINARY = 1 << 2 # there's a binary patch | |
153 |
|
153 | |||
154 | class patchmeta(object): |
|
154 | class patchmeta(object): | |
155 | """Patched file metadata |
|
155 | """Patched file metadata | |
156 |
|
156 | |||
157 | 'op' is the performed operation within ADD, DELETE, RENAME, MODIFY |
|
157 | 'op' is the performed operation within ADD, DELETE, RENAME, MODIFY | |
158 | or COPY. 'path' is patched file path. 'oldpath' is set to the |
|
158 | or COPY. 'path' is patched file path. 'oldpath' is set to the | |
159 | origin file when 'op' is either COPY or RENAME, None otherwise. If |
|
159 | origin file when 'op' is either COPY or RENAME, None otherwise. If | |
160 | file mode is changed, 'mode' is a tuple (islink, isexec) where |
|
160 | file mode is changed, 'mode' is a tuple (islink, isexec) where | |
161 | 'islink' is True if the file is a symlink and 'isexec' is True if |
|
161 | 'islink' is True if the file is a symlink and 'isexec' is True if | |
162 | the file is executable. Otherwise, 'mode' is None. |
|
162 | the file is executable. Otherwise, 'mode' is None. | |
163 | """ |
|
163 | """ | |
164 | def __init__(self, path): |
|
164 | def __init__(self, path): | |
165 | self.path = path |
|
165 | self.path = path | |
166 | self.oldpath = None |
|
166 | self.oldpath = None | |
167 | self.mode = None |
|
167 | self.mode = None | |
168 | self.op = 'MODIFY' |
|
168 | self.op = 'MODIFY' | |
169 | self.lineno = 0 |
|
169 | self.lineno = 0 | |
170 | self.binary = False |
|
170 | self.binary = False | |
171 |
|
171 | |||
172 | def setmode(self, mode): |
|
172 | def setmode(self, mode): | |
173 | islink = mode & 020000 |
|
173 | islink = mode & 020000 | |
174 | isexec = mode & 0100 |
|
174 | isexec = mode & 0100 | |
175 | self.mode = (islink, isexec) |
|
175 | self.mode = (islink, isexec) | |
176 |
|
176 | |||
177 | def readgitpatch(lr): |
|
177 | def readgitpatch(lr): | |
178 | """extract git-style metadata about patches from <patchname>""" |
|
178 | """extract git-style metadata about patches from <patchname>""" | |
179 |
|
179 | |||
180 | # Filter patch for git information |
|
180 | # Filter patch for git information | |
181 | gp = None |
|
181 | gp = None | |
182 | gitpatches = [] |
|
182 | gitpatches = [] | |
183 | # Can have a git patch with only metadata, causing patch to complain |
|
183 | # Can have a git patch with only metadata, causing patch to complain | |
184 | dopatch = 0 |
|
184 | dopatch = 0 | |
185 |
|
185 | |||
186 | lineno = 0 |
|
186 | lineno = 0 | |
187 | for line in lr: |
|
187 | for line in lr: | |
188 | lineno += 1 |
|
188 | lineno += 1 | |
189 | line = line.rstrip(' \r\n') |
|
189 | line = line.rstrip(' \r\n') | |
190 | if line.startswith('diff --git'): |
|
190 | if line.startswith('diff --git'): | |
191 | m = gitre.match(line) |
|
191 | m = gitre.match(line) | |
192 | if m: |
|
192 | if m: | |
193 | if gp: |
|
193 | if gp: | |
194 | gitpatches.append(gp) |
|
194 | gitpatches.append(gp) | |
195 | dst = m.group(2) |
|
195 | dst = m.group(2) | |
196 | gp = patchmeta(dst) |
|
196 | gp = patchmeta(dst) | |
197 | gp.lineno = lineno |
|
197 | gp.lineno = lineno | |
198 | elif gp: |
|
198 | elif gp: | |
199 | if line.startswith('--- '): |
|
199 | if line.startswith('--- '): | |
200 | if gp.op in ('COPY', 'RENAME'): |
|
200 | if gp.op in ('COPY', 'RENAME'): | |
201 | dopatch |= GP_FILTER |
|
201 | dopatch |= GP_FILTER | |
202 | gitpatches.append(gp) |
|
202 | gitpatches.append(gp) | |
203 | gp = None |
|
203 | gp = None | |
204 | dopatch |= GP_PATCH |
|
204 | dopatch |= GP_PATCH | |
205 | continue |
|
205 | continue | |
206 | if line.startswith('rename from '): |
|
206 | if line.startswith('rename from '): | |
207 | gp.op = 'RENAME' |
|
207 | gp.op = 'RENAME' | |
208 | gp.oldpath = line[12:] |
|
208 | gp.oldpath = line[12:] | |
209 | elif line.startswith('rename to '): |
|
209 | elif line.startswith('rename to '): | |
210 | gp.path = line[10:] |
|
210 | gp.path = line[10:] | |
211 | elif line.startswith('copy from '): |
|
211 | elif line.startswith('copy from '): | |
212 | gp.op = 'COPY' |
|
212 | gp.op = 'COPY' | |
213 | gp.oldpath = line[10:] |
|
213 | gp.oldpath = line[10:] | |
214 | elif line.startswith('copy to '): |
|
214 | elif line.startswith('copy to '): | |
215 | gp.path = line[8:] |
|
215 | gp.path = line[8:] | |
216 | elif line.startswith('deleted file'): |
|
216 | elif line.startswith('deleted file'): | |
217 | gp.op = 'DELETE' |
|
217 | gp.op = 'DELETE' | |
218 | # is the deleted file a symlink? |
|
218 | # is the deleted file a symlink? | |
219 | gp.setmode(int(line[-6:], 8)) |
|
219 | gp.setmode(int(line[-6:], 8)) | |
220 | elif line.startswith('new file mode '): |
|
220 | elif line.startswith('new file mode '): | |
221 | gp.op = 'ADD' |
|
221 | gp.op = 'ADD' | |
222 | gp.setmode(int(line[-6:], 8)) |
|
222 | gp.setmode(int(line[-6:], 8)) | |
223 | elif line.startswith('new mode '): |
|
223 | elif line.startswith('new mode '): | |
224 | gp.setmode(int(line[-6:], 8)) |
|
224 | gp.setmode(int(line[-6:], 8)) | |
225 | elif line.startswith('GIT binary patch'): |
|
225 | elif line.startswith('GIT binary patch'): | |
226 | dopatch |= GP_BINARY |
|
226 | dopatch |= GP_BINARY | |
227 | gp.binary = True |
|
227 | gp.binary = True | |
228 | if gp: |
|
228 | if gp: | |
229 | gitpatches.append(gp) |
|
229 | gitpatches.append(gp) | |
230 |
|
230 | |||
231 | if not gitpatches: |
|
231 | if not gitpatches: | |
232 | dopatch = GP_PATCH |
|
232 | dopatch = GP_PATCH | |
233 |
|
233 | |||
234 | return (dopatch, gitpatches) |
|
234 | return (dopatch, gitpatches) | |
235 |
|
235 | |||
236 | class linereader(object): |
|
236 | class linereader(object): | |
237 | # simple class to allow pushing lines back into the input stream |
|
237 | # simple class to allow pushing lines back into the input stream | |
238 | def __init__(self, fp, textmode=False): |
|
238 | def __init__(self, fp, textmode=False): | |
239 | self.fp = fp |
|
239 | self.fp = fp | |
240 | self.buf = [] |
|
240 | self.buf = [] | |
241 | self.textmode = textmode |
|
241 | self.textmode = textmode | |
242 |
|
242 | |||
243 | def push(self, line): |
|
243 | def push(self, line): | |
244 | if line is not None: |
|
244 | if line is not None: | |
245 | self.buf.append(line) |
|
245 | self.buf.append(line) | |
246 |
|
246 | |||
247 | def readline(self): |
|
247 | def readline(self): | |
248 | if self.buf: |
|
248 | if self.buf: | |
249 | l = self.buf[0] |
|
249 | l = self.buf[0] | |
250 | del self.buf[0] |
|
250 | del self.buf[0] | |
251 | return l |
|
251 | return l | |
252 | l = self.fp.readline() |
|
252 | l = self.fp.readline() | |
253 | if self.textmode and l.endswith('\r\n'): |
|
253 | if self.textmode and l.endswith('\r\n'): | |
254 | l = l[:-2] + '\n' |
|
254 | l = l[:-2] + '\n' | |
255 | return l |
|
255 | return l | |
256 |
|
256 | |||
257 | def __iter__(self): |
|
257 | def __iter__(self): | |
258 | while 1: |
|
258 | while 1: | |
259 | l = self.readline() |
|
259 | l = self.readline() | |
260 | if not l: |
|
260 | if not l: | |
261 | break |
|
261 | break | |
262 | yield l |
|
262 | yield l | |
263 |
|
263 | |||
264 | # @@ -start,len +start,len @@ or @@ -start +start @@ if len is 1 |
|
264 | # @@ -start,len +start,len @@ or @@ -start +start @@ if len is 1 | |
265 | unidesc = re.compile('@@ -(\d+)(,(\d+))? \+(\d+)(,(\d+))? @@') |
|
265 | unidesc = re.compile('@@ -(\d+)(,(\d+))? \+(\d+)(,(\d+))? @@') | |
266 | contextdesc = re.compile('(---|\*\*\*) (\d+)(,(\d+))? (---|\*\*\*)') |
|
266 | contextdesc = re.compile('(---|\*\*\*) (\d+)(,(\d+))? (---|\*\*\*)') | |
267 |
|
267 | |||
268 | class patchfile(object): |
|
268 | class patchfile(object): | |
269 | def __init__(self, ui, fname, opener, missing=False, eol=None): |
|
269 | def __init__(self, ui, fname, opener, missing=False, eol=None): | |
270 | self.fname = fname |
|
270 | self.fname = fname | |
271 | self.eol = eol |
|
271 | self.eol = eol | |
272 | self.opener = opener |
|
272 | self.opener = opener | |
273 | self.ui = ui |
|
273 | self.ui = ui | |
274 | self.lines = [] |
|
274 | self.lines = [] | |
275 | self.exists = False |
|
275 | self.exists = False | |
276 | self.missing = missing |
|
276 | self.missing = missing | |
277 | if not missing: |
|
277 | if not missing: | |
278 | try: |
|
278 | try: | |
279 | self.lines = self.readlines(fname) |
|
279 | self.lines = self.readlines(fname) | |
280 | self.exists = True |
|
280 | self.exists = True | |
281 | except IOError: |
|
281 | except IOError: | |
282 | pass |
|
282 | pass | |
283 | else: |
|
283 | else: | |
284 | self.ui.warn(_("unable to find '%s' for patching\n") % self.fname) |
|
284 | self.ui.warn(_("unable to find '%s' for patching\n") % self.fname) | |
285 |
|
285 | |||
286 | self.hash = {} |
|
286 | self.hash = {} | |
287 | self.dirty = 0 |
|
287 | self.dirty = 0 | |
288 | self.offset = 0 |
|
288 | self.offset = 0 | |
289 | self.skew = 0 |
|
289 | self.skew = 0 | |
290 | self.rej = [] |
|
290 | self.rej = [] | |
291 | self.fileprinted = False |
|
291 | self.fileprinted = False | |
292 | self.printfile(False) |
|
292 | self.printfile(False) | |
293 | self.hunks = 0 |
|
293 | self.hunks = 0 | |
294 |
|
294 | |||
295 | def readlines(self, fname): |
|
295 | def readlines(self, fname): | |
296 | if os.path.islink(fname): |
|
296 | if os.path.islink(fname): | |
297 | return [os.readlink(fname)] |
|
297 | return [os.readlink(fname)] | |
298 | fp = self.opener(fname, 'r') |
|
298 | fp = self.opener(fname, 'r') | |
299 | try: |
|
299 | try: | |
300 | return list(linereader(fp, self.eol is not None)) |
|
300 | return list(linereader(fp, self.eol is not None)) | |
301 | finally: |
|
301 | finally: | |
302 | fp.close() |
|
302 | fp.close() | |
303 |
|
303 | |||
304 | def writelines(self, fname, lines): |
|
304 | def writelines(self, fname, lines): | |
305 | # Ensure supplied data ends in fname, being a regular file or |
|
305 | # Ensure supplied data ends in fname, being a regular file or | |
306 | # a symlink. updatedir() will -too magically- take care of |
|
306 | # a symlink. updatedir() will -too magically- take care of | |
307 | # setting it to the proper type afterwards. |
|
307 | # setting it to the proper type afterwards. | |
308 | islink = os.path.islink(fname) |
|
308 | islink = os.path.islink(fname) | |
309 | if islink: |
|
309 | if islink: | |
310 | fp = cStringIO.StringIO() |
|
310 | fp = cStringIO.StringIO() | |
311 | else: |
|
311 | else: | |
312 | fp = self.opener(fname, 'w') |
|
312 | fp = self.opener(fname, 'w') | |
313 | try: |
|
313 | try: | |
314 | if self.eol and self.eol != '\n': |
|
314 | if self.eol and self.eol != '\n': | |
315 | for l in lines: |
|
315 | for l in lines: | |
316 | if l and l[-1] == '\n': |
|
316 | if l and l[-1] == '\n': | |
317 | l = l[:-1] + self.eol |
|
317 | l = l[:-1] + self.eol | |
318 | fp.write(l) |
|
318 | fp.write(l) | |
319 | else: |
|
319 | else: | |
320 | fp.writelines(lines) |
|
320 | fp.writelines(lines) | |
321 | if islink: |
|
321 | if islink: | |
322 | self.opener.symlink(fp.getvalue(), fname) |
|
322 | self.opener.symlink(fp.getvalue(), fname) | |
323 | finally: |
|
323 | finally: | |
324 | fp.close() |
|
324 | fp.close() | |
325 |
|
325 | |||
326 | def unlink(self, fname): |
|
326 | def unlink(self, fname): | |
327 | os.unlink(fname) |
|
327 | os.unlink(fname) | |
328 |
|
328 | |||
329 | def printfile(self, warn): |
|
329 | def printfile(self, warn): | |
330 | if self.fileprinted: |
|
330 | if self.fileprinted: | |
331 | return |
|
331 | return | |
332 | if warn or self.ui.verbose: |
|
332 | if warn or self.ui.verbose: | |
333 | self.fileprinted = True |
|
333 | self.fileprinted = True | |
334 | s = _("patching file %s\n") % self.fname |
|
334 | s = _("patching file %s\n") % self.fname | |
335 | if warn: |
|
335 | if warn: | |
336 | self.ui.warn(s) |
|
336 | self.ui.warn(s) | |
337 | else: |
|
337 | else: | |
338 | self.ui.note(s) |
|
338 | self.ui.note(s) | |
339 |
|
339 | |||
340 |
|
340 | |||
341 | def findlines(self, l, linenum): |
|
341 | def findlines(self, l, linenum): | |
342 | # looks through the hash and finds candidate lines. The |
|
342 | # looks through the hash and finds candidate lines. The | |
343 | # result is a list of line numbers sorted based on distance |
|
343 | # result is a list of line numbers sorted based on distance | |
344 | # from linenum |
|
344 | # from linenum | |
345 |
|
345 | |||
346 | cand = self.hash.get(l, []) |
|
346 | cand = self.hash.get(l, []) | |
347 | if len(cand) > 1: |
|
347 | if len(cand) > 1: | |
348 | # resort our list of potentials forward then back. |
|
348 | # resort our list of potentials forward then back. | |
349 | cand.sort(key=lambda x: abs(x - linenum)) |
|
349 | cand.sort(key=lambda x: abs(x - linenum)) | |
350 | return cand |
|
350 | return cand | |
351 |
|
351 | |||
352 | def hashlines(self): |
|
352 | def hashlines(self): | |
353 | self.hash = {} |
|
353 | self.hash = {} | |
354 | for x, s in enumerate(self.lines): |
|
354 | for x, s in enumerate(self.lines): | |
355 | self.hash.setdefault(s, []).append(x) |
|
355 | self.hash.setdefault(s, []).append(x) | |
356 |
|
356 | |||
357 | def write_rej(self): |
|
357 | def write_rej(self): | |
358 | # our rejects are a little different from patch(1). This always |
|
358 | # our rejects are a little different from patch(1). This always | |
359 | # creates rejects in the same form as the original patch. A file |
|
359 | # creates rejects in the same form as the original patch. A file | |
360 | # header is inserted so that you can run the reject through patch again |
|
360 | # header is inserted so that you can run the reject through patch again | |
361 | # without having to type the filename. |
|
361 | # without having to type the filename. | |
362 |
|
362 | |||
363 | if not self.rej: |
|
363 | if not self.rej: | |
364 | return |
|
364 | return | |
365 |
|
365 | |||
366 | fname = self.fname + ".rej" |
|
366 | fname = self.fname + ".rej" | |
367 | self.ui.warn( |
|
367 | self.ui.warn( | |
368 | _("%d out of %d hunks FAILED -- saving rejects to file %s\n") % |
|
368 | _("%d out of %d hunks FAILED -- saving rejects to file %s\n") % | |
369 | (len(self.rej), self.hunks, fname)) |
|
369 | (len(self.rej), self.hunks, fname)) | |
370 |
|
370 | |||
371 | def rejlines(): |
|
371 | def rejlines(): | |
372 | base = os.path.basename(self.fname) |
|
372 | base = os.path.basename(self.fname) | |
373 | yield "--- %s\n+++ %s\n" % (base, base) |
|
373 | yield "--- %s\n+++ %s\n" % (base, base) | |
374 | for x in self.rej: |
|
374 | for x in self.rej: | |
375 | for l in x.hunk: |
|
375 | for l in x.hunk: | |
376 | yield l |
|
376 | yield l | |
377 | if l[-1] != '\n': |
|
377 | if l[-1] != '\n': | |
378 | yield "\n\ No newline at end of file\n" |
|
378 | yield "\n\ No newline at end of file\n" | |
379 |
|
379 | |||
380 | self.writelines(fname, rejlines()) |
|
380 | self.writelines(fname, rejlines()) | |
381 |
|
381 | |||
382 | def write(self, dest=None): |
|
382 | def write(self, dest=None): | |
383 | if not self.dirty: |
|
383 | if not self.dirty: | |
384 | return |
|
384 | return | |
385 | if not dest: |
|
385 | if not dest: | |
386 | dest = self.fname |
|
386 | dest = self.fname | |
387 | self.writelines(dest, self.lines) |
|
387 | self.writelines(dest, self.lines) | |
388 |
|
388 | |||
389 | def close(self): |
|
389 | def close(self): | |
390 | self.write() |
|
390 | self.write() | |
391 | self.write_rej() |
|
391 | self.write_rej() | |
392 |
|
392 | |||
393 | def apply(self, h): |
|
393 | def apply(self, h): | |
394 | if not h.complete(): |
|
394 | if not h.complete(): | |
395 | raise PatchError(_("bad hunk #%d %s (%d %d %d %d)") % |
|
395 | raise PatchError(_("bad hunk #%d %s (%d %d %d %d)") % | |
396 | (h.number, h.desc, len(h.a), h.lena, len(h.b), |
|
396 | (h.number, h.desc, len(h.a), h.lena, len(h.b), | |
397 | h.lenb)) |
|
397 | h.lenb)) | |
398 |
|
398 | |||
399 | self.hunks += 1 |
|
399 | self.hunks += 1 | |
400 |
|
400 | |||
401 | if self.missing: |
|
401 | if self.missing: | |
402 | self.rej.append(h) |
|
402 | self.rej.append(h) | |
403 | return -1 |
|
403 | return -1 | |
404 |
|
404 | |||
405 | if self.exists and h.createfile(): |
|
405 | if self.exists and h.createfile(): | |
406 | self.ui.warn(_("file %s already exists\n") % self.fname) |
|
406 | self.ui.warn(_("file %s already exists\n") % self.fname) | |
407 | self.rej.append(h) |
|
407 | self.rej.append(h) | |
408 | return -1 |
|
408 | return -1 | |
409 |
|
409 | |||
410 | if isinstance(h, binhunk): |
|
410 | if isinstance(h, binhunk): | |
411 | if h.rmfile(): |
|
411 | if h.rmfile(): | |
412 | self.unlink(self.fname) |
|
412 | self.unlink(self.fname) | |
413 | else: |
|
413 | else: | |
414 | self.lines[:] = h.new() |
|
414 | self.lines[:] = h.new() | |
415 | self.offset += len(h.new()) |
|
415 | self.offset += len(h.new()) | |
416 | self.dirty = 1 |
|
416 | self.dirty = 1 | |
417 | return 0 |
|
417 | return 0 | |
418 |
|
418 | |||
419 | # fast case first, no offsets, no fuzz |
|
419 | # fast case first, no offsets, no fuzz | |
420 | old = h.old() |
|
420 | old = h.old() | |
421 | # patch starts counting at 1 unless we are adding the file |
|
421 | # patch starts counting at 1 unless we are adding the file | |
422 | if h.starta == 0: |
|
422 | if h.starta == 0: | |
423 | start = 0 |
|
423 | start = 0 | |
424 | else: |
|
424 | else: | |
425 | start = h.starta + self.offset - 1 |
|
425 | start = h.starta + self.offset - 1 | |
426 | orig_start = start |
|
426 | orig_start = start | |
427 | # if there's skew we want to emit the "(offset %d lines)" even |
|
427 | # if there's skew we want to emit the "(offset %d lines)" even | |
428 | # when the hunk cleanly applies at start + skew, so skip the |
|
428 | # when the hunk cleanly applies at start + skew, so skip the | |
429 | # fast case code |
|
429 | # fast case code | |
430 | if self.skew == 0 and diffhelpers.testhunk(old, self.lines, start) == 0: |
|
430 | if self.skew == 0 and diffhelpers.testhunk(old, self.lines, start) == 0: | |
431 | if h.rmfile(): |
|
431 | if h.rmfile(): | |
432 | self.unlink(self.fname) |
|
432 | self.unlink(self.fname) | |
433 | else: |
|
433 | else: | |
434 | self.lines[start : start + h.lena] = h.new() |
|
434 | self.lines[start : start + h.lena] = h.new() | |
435 | self.offset += h.lenb - h.lena |
|
435 | self.offset += h.lenb - h.lena | |
436 | self.dirty = 1 |
|
436 | self.dirty = 1 | |
437 | return 0 |
|
437 | return 0 | |
438 |
|
438 | |||
439 | # ok, we couldn't match the hunk. Lets look for offsets and fuzz it |
|
439 | # ok, we couldn't match the hunk. Lets look for offsets and fuzz it | |
440 | self.hashlines() |
|
440 | self.hashlines() | |
441 | if h.hunk[-1][0] != ' ': |
|
441 | if h.hunk[-1][0] != ' ': | |
442 | # if the hunk tried to put something at the bottom of the file |
|
442 | # if the hunk tried to put something at the bottom of the file | |
443 | # override the start line and use eof here |
|
443 | # override the start line and use eof here | |
444 | search_start = len(self.lines) |
|
444 | search_start = len(self.lines) | |
445 | else: |
|
445 | else: | |
446 | search_start = orig_start + self.skew |
|
446 | search_start = orig_start + self.skew | |
447 |
|
447 | |||
448 | for fuzzlen in xrange(3): |
|
448 | for fuzzlen in xrange(3): | |
449 | for toponly in [ True, False ]: |
|
449 | for toponly in [ True, False ]: | |
450 | old = h.old(fuzzlen, toponly) |
|
450 | old = h.old(fuzzlen, toponly) | |
451 |
|
451 | |||
452 | cand = self.findlines(old[0][1:], search_start) |
|
452 | cand = self.findlines(old[0][1:], search_start) | |
453 | for l in cand: |
|
453 | for l in cand: | |
454 | if diffhelpers.testhunk(old, self.lines, l) == 0: |
|
454 | if diffhelpers.testhunk(old, self.lines, l) == 0: | |
455 | newlines = h.new(fuzzlen, toponly) |
|
455 | newlines = h.new(fuzzlen, toponly) | |
456 | self.lines[l : l + len(old)] = newlines |
|
456 | self.lines[l : l + len(old)] = newlines | |
457 | self.offset += len(newlines) - len(old) |
|
457 | self.offset += len(newlines) - len(old) | |
458 | self.skew = l - orig_start |
|
458 | self.skew = l - orig_start | |
459 | self.dirty = 1 |
|
459 | self.dirty = 1 | |
460 | if fuzzlen: |
|
460 | if fuzzlen: | |
461 | fuzzstr = "with fuzz %d " % fuzzlen |
|
461 | fuzzstr = "with fuzz %d " % fuzzlen | |
462 | f = self.ui.warn |
|
462 | f = self.ui.warn | |
463 | self.printfile(True) |
|
463 | self.printfile(True) | |
464 | else: |
|
464 | else: | |
465 | fuzzstr = "" |
|
465 | fuzzstr = "" | |
466 | f = self.ui.note |
|
466 | f = self.ui.note | |
467 | offset = l - orig_start - fuzzlen |
|
467 | offset = l - orig_start - fuzzlen | |
468 | if offset == 1: |
|
468 | if offset == 1: | |
469 | msg = _("Hunk #%d succeeded at %d %s" |
|
469 | msg = _("Hunk #%d succeeded at %d %s" | |
470 | "(offset %d line).\n") |
|
470 | "(offset %d line).\n") | |
471 | else: |
|
471 | else: | |
472 | msg = _("Hunk #%d succeeded at %d %s" |
|
472 | msg = _("Hunk #%d succeeded at %d %s" | |
473 | "(offset %d lines).\n") |
|
473 | "(offset %d lines).\n") | |
474 | f(msg % (h.number, l+1, fuzzstr, offset)) |
|
474 | f(msg % (h.number, l+1, fuzzstr, offset)) | |
475 | return fuzzlen |
|
475 | return fuzzlen | |
476 | self.printfile(True) |
|
476 | self.printfile(True) | |
477 | self.ui.warn(_("Hunk #%d FAILED at %d\n") % (h.number, orig_start)) |
|
477 | self.ui.warn(_("Hunk #%d FAILED at %d\n") % (h.number, orig_start)) | |
478 | self.rej.append(h) |
|
478 | self.rej.append(h) | |
479 | return -1 |
|
479 | return -1 | |
480 |
|
480 | |||
481 | class hunk(object): |
|
481 | class hunk(object): | |
482 | def __init__(self, desc, num, lr, context, create=False, remove=False): |
|
482 | def __init__(self, desc, num, lr, context, create=False, remove=False): | |
483 | self.number = num |
|
483 | self.number = num | |
484 | self.desc = desc |
|
484 | self.desc = desc | |
485 | self.hunk = [ desc ] |
|
485 | self.hunk = [ desc ] | |
486 | self.a = [] |
|
486 | self.a = [] | |
487 | self.b = [] |
|
487 | self.b = [] | |
488 | self.starta = self.lena = None |
|
488 | self.starta = self.lena = None | |
489 | self.startb = self.lenb = None |
|
489 | self.startb = self.lenb = None | |
490 | if context: |
|
490 | if context: | |
491 | self.read_context_hunk(lr) |
|
491 | self.read_context_hunk(lr) | |
492 | else: |
|
492 | else: | |
493 | self.read_unified_hunk(lr) |
|
493 | self.read_unified_hunk(lr) | |
494 | self.create = create |
|
494 | self.create = create | |
495 | self.remove = remove and not create |
|
495 | self.remove = remove and not create | |
496 |
|
496 | |||
497 | def read_unified_hunk(self, lr): |
|
497 | def read_unified_hunk(self, lr): | |
498 | m = unidesc.match(self.desc) |
|
498 | m = unidesc.match(self.desc) | |
499 | if not m: |
|
499 | if not m: | |
500 | raise PatchError(_("bad hunk #%d") % self.number) |
|
500 | raise PatchError(_("bad hunk #%d") % self.number) | |
501 | self.starta, foo, self.lena, self.startb, foo2, self.lenb = m.groups() |
|
501 | self.starta, foo, self.lena, self.startb, foo2, self.lenb = m.groups() | |
502 | if self.lena is None: |
|
502 | if self.lena is None: | |
503 | self.lena = 1 |
|
503 | self.lena = 1 | |
504 | else: |
|
504 | else: | |
505 | self.lena = int(self.lena) |
|
505 | self.lena = int(self.lena) | |
506 | if self.lenb is None: |
|
506 | if self.lenb is None: | |
507 | self.lenb = 1 |
|
507 | self.lenb = 1 | |
508 | else: |
|
508 | else: | |
509 | self.lenb = int(self.lenb) |
|
509 | self.lenb = int(self.lenb) | |
510 | self.starta = int(self.starta) |
|
510 | self.starta = int(self.starta) | |
511 | self.startb = int(self.startb) |
|
511 | self.startb = int(self.startb) | |
512 | diffhelpers.addlines(lr, self.hunk, self.lena, self.lenb, self.a, self.b) |
|
512 | diffhelpers.addlines(lr, self.hunk, self.lena, self.lenb, self.a, self.b) | |
513 | # if we hit eof before finishing out the hunk, the last line will |
|
513 | # if we hit eof before finishing out the hunk, the last line will | |
514 | # be zero length. Lets try to fix it up. |
|
514 | # be zero length. Lets try to fix it up. | |
515 | while len(self.hunk[-1]) == 0: |
|
515 | while len(self.hunk[-1]) == 0: | |
516 | del self.hunk[-1] |
|
516 | del self.hunk[-1] | |
517 | del self.a[-1] |
|
517 | del self.a[-1] | |
518 | del self.b[-1] |
|
518 | del self.b[-1] | |
519 | self.lena -= 1 |
|
519 | self.lena -= 1 | |
520 | self.lenb -= 1 |
|
520 | self.lenb -= 1 | |
521 |
|
521 | |||
522 | def read_context_hunk(self, lr): |
|
522 | def read_context_hunk(self, lr): | |
523 | self.desc = lr.readline() |
|
523 | self.desc = lr.readline() | |
524 | m = contextdesc.match(self.desc) |
|
524 | m = contextdesc.match(self.desc) | |
525 | if not m: |
|
525 | if not m: | |
526 | raise PatchError(_("bad hunk #%d") % self.number) |
|
526 | raise PatchError(_("bad hunk #%d") % self.number) | |
527 | foo, self.starta, foo2, aend, foo3 = m.groups() |
|
527 | foo, self.starta, foo2, aend, foo3 = m.groups() | |
528 | self.starta = int(self.starta) |
|
528 | self.starta = int(self.starta) | |
529 | if aend is None: |
|
529 | if aend is None: | |
530 | aend = self.starta |
|
530 | aend = self.starta | |
531 | self.lena = int(aend) - self.starta |
|
531 | self.lena = int(aend) - self.starta | |
532 | if self.starta: |
|
532 | if self.starta: | |
533 | self.lena += 1 |
|
533 | self.lena += 1 | |
534 | for x in xrange(self.lena): |
|
534 | for x in xrange(self.lena): | |
535 | l = lr.readline() |
|
535 | l = lr.readline() | |
536 | if l.startswith('---'): |
|
536 | if l.startswith('---'): | |
537 | lr.push(l) |
|
537 | lr.push(l) | |
538 | break |
|
538 | break | |
539 | s = l[2:] |
|
539 | s = l[2:] | |
540 | if l.startswith('- ') or l.startswith('! '): |
|
540 | if l.startswith('- ') or l.startswith('! '): | |
541 | u = '-' + s |
|
541 | u = '-' + s | |
542 | elif l.startswith(' '): |
|
542 | elif l.startswith(' '): | |
543 | u = ' ' + s |
|
543 | u = ' ' + s | |
544 | else: |
|
544 | else: | |
545 | raise PatchError(_("bad hunk #%d old text line %d") % |
|
545 | raise PatchError(_("bad hunk #%d old text line %d") % | |
546 | (self.number, x)) |
|
546 | (self.number, x)) | |
547 | self.a.append(u) |
|
547 | self.a.append(u) | |
548 | self.hunk.append(u) |
|
548 | self.hunk.append(u) | |
549 |
|
549 | |||
550 | l = lr.readline() |
|
550 | l = lr.readline() | |
551 | if l.startswith('\ '): |
|
551 | if l.startswith('\ '): | |
552 | s = self.a[-1][:-1] |
|
552 | s = self.a[-1][:-1] | |
553 | self.a[-1] = s |
|
553 | self.a[-1] = s | |
554 | self.hunk[-1] = s |
|
554 | self.hunk[-1] = s | |
555 | l = lr.readline() |
|
555 | l = lr.readline() | |
556 | m = contextdesc.match(l) |
|
556 | m = contextdesc.match(l) | |
557 | if not m: |
|
557 | if not m: | |
558 | raise PatchError(_("bad hunk #%d") % self.number) |
|
558 | raise PatchError(_("bad hunk #%d") % self.number) | |
559 | foo, self.startb, foo2, bend, foo3 = m.groups() |
|
559 | foo, self.startb, foo2, bend, foo3 = m.groups() | |
560 | self.startb = int(self.startb) |
|
560 | self.startb = int(self.startb) | |
561 | if bend is None: |
|
561 | if bend is None: | |
562 | bend = self.startb |
|
562 | bend = self.startb | |
563 | self.lenb = int(bend) - self.startb |
|
563 | self.lenb = int(bend) - self.startb | |
564 | if self.startb: |
|
564 | if self.startb: | |
565 | self.lenb += 1 |
|
565 | self.lenb += 1 | |
566 | hunki = 1 |
|
566 | hunki = 1 | |
567 | for x in xrange(self.lenb): |
|
567 | for x in xrange(self.lenb): | |
568 | l = lr.readline() |
|
568 | l = lr.readline() | |
569 | if l.startswith('\ '): |
|
569 | if l.startswith('\ '): | |
570 | s = self.b[-1][:-1] |
|
570 | s = self.b[-1][:-1] | |
571 | self.b[-1] = s |
|
571 | self.b[-1] = s | |
572 | self.hunk[hunki-1] = s |
|
572 | self.hunk[hunki-1] = s | |
573 | continue |
|
573 | continue | |
574 | if not l: |
|
574 | if not l: | |
575 | lr.push(l) |
|
575 | lr.push(l) | |
576 | break |
|
576 | break | |
577 | s = l[2:] |
|
577 | s = l[2:] | |
578 | if l.startswith('+ ') or l.startswith('! '): |
|
578 | if l.startswith('+ ') or l.startswith('! '): | |
579 | u = '+' + s |
|
579 | u = '+' + s | |
580 | elif l.startswith(' '): |
|
580 | elif l.startswith(' '): | |
581 | u = ' ' + s |
|
581 | u = ' ' + s | |
582 | elif len(self.b) == 0: |
|
582 | elif len(self.b) == 0: | |
583 | # this can happen when the hunk does not add any lines |
|
583 | # this can happen when the hunk does not add any lines | |
584 | lr.push(l) |
|
584 | lr.push(l) | |
585 | break |
|
585 | break | |
586 | else: |
|
586 | else: | |
587 | raise PatchError(_("bad hunk #%d old text line %d") % |
|
587 | raise PatchError(_("bad hunk #%d old text line %d") % | |
588 | (self.number, x)) |
|
588 | (self.number, x)) | |
589 | self.b.append(s) |
|
589 | self.b.append(s) | |
590 | while True: |
|
590 | while True: | |
591 | if hunki >= len(self.hunk): |
|
591 | if hunki >= len(self.hunk): | |
592 | h = "" |
|
592 | h = "" | |
593 | else: |
|
593 | else: | |
594 | h = self.hunk[hunki] |
|
594 | h = self.hunk[hunki] | |
595 | hunki += 1 |
|
595 | hunki += 1 | |
596 | if h == u: |
|
596 | if h == u: | |
597 | break |
|
597 | break | |
598 | elif h.startswith('-'): |
|
598 | elif h.startswith('-'): | |
599 | continue |
|
599 | continue | |
600 | else: |
|
600 | else: | |
601 | self.hunk.insert(hunki-1, u) |
|
601 | self.hunk.insert(hunki-1, u) | |
602 | break |
|
602 | break | |
603 |
|
603 | |||
604 | if not self.a: |
|
604 | if not self.a: | |
605 | # this happens when lines were only added to the hunk |
|
605 | # this happens when lines were only added to the hunk | |
606 | for x in self.hunk: |
|
606 | for x in self.hunk: | |
607 | if x.startswith('-') or x.startswith(' '): |
|
607 | if x.startswith('-') or x.startswith(' '): | |
608 | self.a.append(x) |
|
608 | self.a.append(x) | |
609 | if not self.b: |
|
609 | if not self.b: | |
610 | # this happens when lines were only deleted from the hunk |
|
610 | # this happens when lines were only deleted from the hunk | |
611 | for x in self.hunk: |
|
611 | for x in self.hunk: | |
612 | if x.startswith('+') or x.startswith(' '): |
|
612 | if x.startswith('+') or x.startswith(' '): | |
613 | self.b.append(x[1:]) |
|
613 | self.b.append(x[1:]) | |
614 | # @@ -start,len +start,len @@ |
|
614 | # @@ -start,len +start,len @@ | |
615 | self.desc = "@@ -%d,%d +%d,%d @@\n" % (self.starta, self.lena, |
|
615 | self.desc = "@@ -%d,%d +%d,%d @@\n" % (self.starta, self.lena, | |
616 | self.startb, self.lenb) |
|
616 | self.startb, self.lenb) | |
617 | self.hunk[0] = self.desc |
|
617 | self.hunk[0] = self.desc | |
618 |
|
618 | |||
619 | def fix_newline(self): |
|
619 | def fix_newline(self): | |
620 | diffhelpers.fix_newline(self.hunk, self.a, self.b) |
|
620 | diffhelpers.fix_newline(self.hunk, self.a, self.b) | |
621 |
|
621 | |||
622 | def complete(self): |
|
622 | def complete(self): | |
623 | return len(self.a) == self.lena and len(self.b) == self.lenb |
|
623 | return len(self.a) == self.lena and len(self.b) == self.lenb | |
624 |
|
624 | |||
625 | def createfile(self): |
|
625 | def createfile(self): | |
626 | return self.starta == 0 and self.lena == 0 and self.create |
|
626 | return self.starta == 0 and self.lena == 0 and self.create | |
627 |
|
627 | |||
628 | def rmfile(self): |
|
628 | def rmfile(self): | |
629 | return self.startb == 0 and self.lenb == 0 and self.remove |
|
629 | return self.startb == 0 and self.lenb == 0 and self.remove | |
630 |
|
630 | |||
631 | def fuzzit(self, l, fuzz, toponly): |
|
631 | def fuzzit(self, l, fuzz, toponly): | |
632 | # this removes context lines from the top and bottom of list 'l'. It |
|
632 | # this removes context lines from the top and bottom of list 'l'. It | |
633 | # checks the hunk to make sure only context lines are removed, and then |
|
633 | # checks the hunk to make sure only context lines are removed, and then | |
634 | # returns a new shortened list of lines. |
|
634 | # returns a new shortened list of lines. | |
635 | fuzz = min(fuzz, len(l)-1) |
|
635 | fuzz = min(fuzz, len(l)-1) | |
636 | if fuzz: |
|
636 | if fuzz: | |
637 | top = 0 |
|
637 | top = 0 | |
638 | bot = 0 |
|
638 | bot = 0 | |
639 | hlen = len(self.hunk) |
|
639 | hlen = len(self.hunk) | |
640 | for x in xrange(hlen-1): |
|
640 | for x in xrange(hlen-1): | |
641 | # the hunk starts with the @@ line, so use x+1 |
|
641 | # the hunk starts with the @@ line, so use x+1 | |
642 | if self.hunk[x+1][0] == ' ': |
|
642 | if self.hunk[x+1][0] == ' ': | |
643 | top += 1 |
|
643 | top += 1 | |
644 | else: |
|
644 | else: | |
645 | break |
|
645 | break | |
646 | if not toponly: |
|
646 | if not toponly: | |
647 | for x in xrange(hlen-1): |
|
647 | for x in xrange(hlen-1): | |
648 | if self.hunk[hlen-bot-1][0] == ' ': |
|
648 | if self.hunk[hlen-bot-1][0] == ' ': | |
649 | bot += 1 |
|
649 | bot += 1 | |
650 | else: |
|
650 | else: | |
651 | break |
|
651 | break | |
652 |
|
652 | |||
653 | # top and bot now count context in the hunk |
|
653 | # top and bot now count context in the hunk | |
654 | # adjust them if either one is short |
|
654 | # adjust them if either one is short | |
655 | context = max(top, bot, 3) |
|
655 | context = max(top, bot, 3) | |
656 | if bot < context: |
|
656 | if bot < context: | |
657 | bot = max(0, fuzz - (context - bot)) |
|
657 | bot = max(0, fuzz - (context - bot)) | |
658 | else: |
|
658 | else: | |
659 | bot = min(fuzz, bot) |
|
659 | bot = min(fuzz, bot) | |
660 | if top < context: |
|
660 | if top < context: | |
661 | top = max(0, fuzz - (context - top)) |
|
661 | top = max(0, fuzz - (context - top)) | |
662 | else: |
|
662 | else: | |
663 | top = min(fuzz, top) |
|
663 | top = min(fuzz, top) | |
664 |
|
664 | |||
665 | return l[top:len(l)-bot] |
|
665 | return l[top:len(l)-bot] | |
666 | return l |
|
666 | return l | |
667 |
|
667 | |||
668 | def old(self, fuzz=0, toponly=False): |
|
668 | def old(self, fuzz=0, toponly=False): | |
669 | return self.fuzzit(self.a, fuzz, toponly) |
|
669 | return self.fuzzit(self.a, fuzz, toponly) | |
670 |
|
670 | |||
671 | def newctrl(self): |
|
671 | def newctrl(self): | |
672 | res = [] |
|
672 | res = [] | |
673 | for x in self.hunk: |
|
673 | for x in self.hunk: | |
674 | c = x[0] |
|
674 | c = x[0] | |
675 | if c == ' ' or c == '+': |
|
675 | if c == ' ' or c == '+': | |
676 | res.append(x) |
|
676 | res.append(x) | |
677 | return res |
|
677 | return res | |
678 |
|
678 | |||
679 | def new(self, fuzz=0, toponly=False): |
|
679 | def new(self, fuzz=0, toponly=False): | |
680 | return self.fuzzit(self.b, fuzz, toponly) |
|
680 | return self.fuzzit(self.b, fuzz, toponly) | |
681 |
|
681 | |||
682 | class binhunk: |
|
682 | class binhunk: | |
683 | 'A binary patch file. Only understands literals so far.' |
|
683 | 'A binary patch file. Only understands literals so far.' | |
684 | def __init__(self, gitpatch): |
|
684 | def __init__(self, gitpatch): | |
685 | self.gitpatch = gitpatch |
|
685 | self.gitpatch = gitpatch | |
686 | self.text = None |
|
686 | self.text = None | |
687 | self.hunk = ['GIT binary patch\n'] |
|
687 | self.hunk = ['GIT binary patch\n'] | |
688 |
|
688 | |||
689 | def createfile(self): |
|
689 | def createfile(self): | |
690 | return self.gitpatch.op in ('ADD', 'RENAME', 'COPY') |
|
690 | return self.gitpatch.op in ('ADD', 'RENAME', 'COPY') | |
691 |
|
691 | |||
692 | def rmfile(self): |
|
692 | def rmfile(self): | |
693 | return self.gitpatch.op == 'DELETE' |
|
693 | return self.gitpatch.op == 'DELETE' | |
694 |
|
694 | |||
695 | def complete(self): |
|
695 | def complete(self): | |
696 | return self.text is not None |
|
696 | return self.text is not None | |
697 |
|
697 | |||
698 | def new(self): |
|
698 | def new(self): | |
699 | return [self.text] |
|
699 | return [self.text] | |
700 |
|
700 | |||
701 | def extract(self, lr): |
|
701 | def extract(self, lr): | |
702 | line = lr.readline() |
|
702 | line = lr.readline() | |
703 | self.hunk.append(line) |
|
703 | self.hunk.append(line) | |
704 | while line and not line.startswith('literal '): |
|
704 | while line and not line.startswith('literal '): | |
705 | line = lr.readline() |
|
705 | line = lr.readline() | |
706 | self.hunk.append(line) |
|
706 | self.hunk.append(line) | |
707 | if not line: |
|
707 | if not line: | |
708 | raise PatchError(_('could not extract binary patch')) |
|
708 | raise PatchError(_('could not extract binary patch')) | |
709 | size = int(line[8:].rstrip()) |
|
709 | size = int(line[8:].rstrip()) | |
710 | dec = [] |
|
710 | dec = [] | |
711 | line = lr.readline() |
|
711 | line = lr.readline() | |
712 | self.hunk.append(line) |
|
712 | self.hunk.append(line) | |
713 | while len(line) > 1: |
|
713 | while len(line) > 1: | |
714 | l = line[0] |
|
714 | l = line[0] | |
715 | if l <= 'Z' and l >= 'A': |
|
715 | if l <= 'Z' and l >= 'A': | |
716 | l = ord(l) - ord('A') + 1 |
|
716 | l = ord(l) - ord('A') + 1 | |
717 | else: |
|
717 | else: | |
718 | l = ord(l) - ord('a') + 27 |
|
718 | l = ord(l) - ord('a') + 27 | |
719 | dec.append(base85.b85decode(line[1:-1])[:l]) |
|
719 | dec.append(base85.b85decode(line[1:-1])[:l]) | |
720 | line = lr.readline() |
|
720 | line = lr.readline() | |
721 | self.hunk.append(line) |
|
721 | self.hunk.append(line) | |
722 | text = zlib.decompress(''.join(dec)) |
|
722 | text = zlib.decompress(''.join(dec)) | |
723 | if len(text) != size: |
|
723 | if len(text) != size: | |
724 | raise PatchError(_('binary patch is %d bytes, not %d') % |
|
724 | raise PatchError(_('binary patch is %d bytes, not %d') % | |
725 | len(text), size) |
|
725 | len(text), size) | |
726 | self.text = text |
|
726 | self.text = text | |
727 |
|
727 | |||
728 | def parsefilename(str): |
|
728 | def parsefilename(str): | |
729 | # --- filename \t|space stuff |
|
729 | # --- filename \t|space stuff | |
730 | s = str[4:].rstrip('\r\n') |
|
730 | s = str[4:].rstrip('\r\n') | |
731 | i = s.find('\t') |
|
731 | i = s.find('\t') | |
732 | if i < 0: |
|
732 | if i < 0: | |
733 | i = s.find(' ') |
|
733 | i = s.find(' ') | |
734 | if i < 0: |
|
734 | if i < 0: | |
735 | return s |
|
735 | return s | |
736 | return s[:i] |
|
736 | return s[:i] | |
737 |
|
737 | |||
738 | def selectfile(afile_orig, bfile_orig, hunk, strip): |
|
738 | def selectfile(afile_orig, bfile_orig, hunk, strip): | |
739 | def pathstrip(path, count=1): |
|
739 | def pathstrip(path, count=1): | |
740 | pathlen = len(path) |
|
740 | pathlen = len(path) | |
741 | i = 0 |
|
741 | i = 0 | |
742 | if count == 0: |
|
742 | if count == 0: | |
743 | return '', path.rstrip() |
|
743 | return '', path.rstrip() | |
744 | while count > 0: |
|
744 | while count > 0: | |
745 | i = path.find('/', i) |
|
745 | i = path.find('/', i) | |
746 | if i == -1: |
|
746 | if i == -1: | |
747 | raise PatchError(_("unable to strip away %d dirs from %s") % |
|
747 | raise PatchError(_("unable to strip away %d dirs from %s") % | |
748 | (count, path)) |
|
748 | (count, path)) | |
749 | i += 1 |
|
749 | i += 1 | |
750 | # consume '//' in the path |
|
750 | # consume '//' in the path | |
751 | while i < pathlen - 1 and path[i] == '/': |
|
751 | while i < pathlen - 1 and path[i] == '/': | |
752 | i += 1 |
|
752 | i += 1 | |
753 | count -= 1 |
|
753 | count -= 1 | |
754 | return path[:i].lstrip(), path[i:].rstrip() |
|
754 | return path[:i].lstrip(), path[i:].rstrip() | |
755 |
|
755 | |||
756 | nulla = afile_orig == "/dev/null" |
|
756 | nulla = afile_orig == "/dev/null" | |
757 | nullb = bfile_orig == "/dev/null" |
|
757 | nullb = bfile_orig == "/dev/null" | |
758 | abase, afile = pathstrip(afile_orig, strip) |
|
758 | abase, afile = pathstrip(afile_orig, strip) | |
759 | gooda = not nulla and util.lexists(afile) |
|
759 | gooda = not nulla and util.lexists(afile) | |
760 | bbase, bfile = pathstrip(bfile_orig, strip) |
|
760 | bbase, bfile = pathstrip(bfile_orig, strip) | |
761 | if afile == bfile: |
|
761 | if afile == bfile: | |
762 | goodb = gooda |
|
762 | goodb = gooda | |
763 | else: |
|
763 | else: | |
764 | goodb = not nullb and os.path.exists(bfile) |
|
764 | goodb = not nullb and os.path.exists(bfile) | |
765 | createfunc = hunk.createfile |
|
765 | createfunc = hunk.createfile | |
766 | missing = not goodb and not gooda and not createfunc() |
|
766 | missing = not goodb and not gooda and not createfunc() | |
767 |
|
767 | |||
768 | # some diff programs apparently produce create patches where the |
|
768 | # some diff programs apparently produce create patches where the | |
769 | # afile is not /dev/null, but rather the same name as the bfile |
|
769 | # afile is not /dev/null, but rather the same name as the bfile | |
770 | if missing and afile == bfile: |
|
770 | if missing and afile == bfile: | |
771 | # this isn't very pretty |
|
771 | # this isn't very pretty | |
772 | hunk.create = True |
|
772 | hunk.create = True | |
773 | if createfunc(): |
|
773 | if createfunc(): | |
774 | missing = False |
|
774 | missing = False | |
775 | else: |
|
775 | else: | |
776 | hunk.create = False |
|
776 | hunk.create = False | |
777 |
|
777 | |||
778 | # If afile is "a/b/foo" and bfile is "a/b/foo.orig" we assume the |
|
778 | # If afile is "a/b/foo" and bfile is "a/b/foo.orig" we assume the | |
779 | # diff is between a file and its backup. In this case, the original |
|
779 | # diff is between a file and its backup. In this case, the original | |
780 | # file should be patched (see original mpatch code). |
|
780 | # file should be patched (see original mpatch code). | |
781 | isbackup = (abase == bbase and bfile.startswith(afile)) |
|
781 | isbackup = (abase == bbase and bfile.startswith(afile)) | |
782 | fname = None |
|
782 | fname = None | |
783 | if not missing: |
|
783 | if not missing: | |
784 | if gooda and goodb: |
|
784 | if gooda and goodb: | |
785 | fname = isbackup and afile or bfile |
|
785 | fname = isbackup and afile or bfile | |
786 | elif gooda: |
|
786 | elif gooda: | |
787 | fname = afile |
|
787 | fname = afile | |
788 |
|
788 | |||
789 | if not fname: |
|
789 | if not fname: | |
790 | if not nullb: |
|
790 | if not nullb: | |
791 | fname = isbackup and afile or bfile |
|
791 | fname = isbackup and afile or bfile | |
792 | elif not nulla: |
|
792 | elif not nulla: | |
793 | fname = afile |
|
793 | fname = afile | |
794 | else: |
|
794 | else: | |
795 | raise PatchError(_("undefined source and destination files")) |
|
795 | raise PatchError(_("undefined source and destination files")) | |
796 |
|
796 | |||
797 | return fname, missing |
|
797 | return fname, missing | |
798 |
|
798 | |||
799 | def scangitpatch(lr, firstline): |
|
799 | def scangitpatch(lr, firstline): | |
800 | """ |
|
800 | """ | |
801 | Git patches can emit: |
|
801 | Git patches can emit: | |
802 | - rename a to b |
|
802 | - rename a to b | |
803 | - change b |
|
803 | - change b | |
804 | - copy a to c |
|
804 | - copy a to c | |
805 | - change c |
|
805 | - change c | |
806 |
|
806 | |||
807 | We cannot apply this sequence as-is, the renamed 'a' could not be |
|
807 | We cannot apply this sequence as-is, the renamed 'a' could not be | |
808 | found for it would have been renamed already. And we cannot copy |
|
808 | found for it would have been renamed already. And we cannot copy | |
809 | from 'b' instead because 'b' would have been changed already. So |
|
809 | from 'b' instead because 'b' would have been changed already. So | |
810 | we scan the git patch for copy and rename commands so we can |
|
810 | we scan the git patch for copy and rename commands so we can | |
811 | perform the copies ahead of time. |
|
811 | perform the copies ahead of time. | |
812 | """ |
|
812 | """ | |
813 | pos = 0 |
|
813 | pos = 0 | |
814 | try: |
|
814 | try: | |
815 | pos = lr.fp.tell() |
|
815 | pos = lr.fp.tell() | |
816 | fp = lr.fp |
|
816 | fp = lr.fp | |
817 | except IOError: |
|
817 | except IOError: | |
818 | fp = cStringIO.StringIO(lr.fp.read()) |
|
818 | fp = cStringIO.StringIO(lr.fp.read()) | |
819 | gitlr = linereader(fp, lr.textmode) |
|
819 | gitlr = linereader(fp, lr.textmode) | |
820 | gitlr.push(firstline) |
|
820 | gitlr.push(firstline) | |
821 | (dopatch, gitpatches) = readgitpatch(gitlr) |
|
821 | (dopatch, gitpatches) = readgitpatch(gitlr) | |
822 | fp.seek(pos) |
|
822 | fp.seek(pos) | |
823 | return dopatch, gitpatches |
|
823 | return dopatch, gitpatches | |
824 |
|
824 | |||
825 | def iterhunks(ui, fp, sourcefile=None, textmode=False): |
|
825 | def iterhunks(ui, fp, sourcefile=None, textmode=False): | |
826 | """Read a patch and yield the following events: |
|
826 | """Read a patch and yield the following events: | |
827 | - ("file", afile, bfile, firsthunk): select a new target file. |
|
827 | - ("file", afile, bfile, firsthunk): select a new target file. | |
828 | - ("hunk", hunk): a new hunk is ready to be applied, follows a |
|
828 | - ("hunk", hunk): a new hunk is ready to be applied, follows a | |
829 | "file" event. |
|
829 | "file" event. | |
830 | - ("git", gitchanges): current diff is in git format, gitchanges |
|
830 | - ("git", gitchanges): current diff is in git format, gitchanges | |
831 | maps filenames to gitpatch records. Unique event. |
|
831 | maps filenames to gitpatch records. Unique event. | |
832 |
|
832 | |||
833 | If textmode is True, input line-endings are normalized to LF. |
|
833 | If textmode is True, input line-endings are normalized to LF. | |
834 | """ |
|
834 | """ | |
835 | changed = {} |
|
835 | changed = {} | |
836 | current_hunk = None |
|
836 | current_hunk = None | |
837 | afile = "" |
|
837 | afile = "" | |
838 | bfile = "" |
|
838 | bfile = "" | |
839 | state = None |
|
839 | state = None | |
840 | hunknum = 0 |
|
840 | hunknum = 0 | |
841 | emitfile = False |
|
841 | emitfile = False | |
842 | git = False |
|
842 | git = False | |
843 |
|
843 | |||
844 | # our states |
|
844 | # our states | |
845 | BFILE = 1 |
|
845 | BFILE = 1 | |
846 | context = None |
|
846 | context = None | |
847 | lr = linereader(fp, textmode) |
|
847 | lr = linereader(fp, textmode) | |
848 | dopatch = True |
|
848 | dopatch = True | |
849 | # gitworkdone is True if a git operation (copy, rename, ...) was |
|
849 | # gitworkdone is True if a git operation (copy, rename, ...) was | |
850 | # performed already for the current file. Useful when the file |
|
850 | # performed already for the current file. Useful when the file | |
851 | # section may have no hunk. |
|
851 | # section may have no hunk. | |
852 | gitworkdone = False |
|
852 | gitworkdone = False | |
853 |
|
853 | |||
854 | while True: |
|
854 | while True: | |
855 | newfile = False |
|
855 | newfile = False | |
856 | x = lr.readline() |
|
856 | x = lr.readline() | |
857 | if not x: |
|
857 | if not x: | |
858 | break |
|
858 | break | |
859 | if current_hunk: |
|
859 | if current_hunk: | |
860 | if x.startswith('\ '): |
|
860 | if x.startswith('\ '): | |
861 | current_hunk.fix_newline() |
|
861 | current_hunk.fix_newline() | |
862 | yield 'hunk', current_hunk |
|
862 | yield 'hunk', current_hunk | |
863 | current_hunk = None |
|
863 | current_hunk = None | |
864 | gitworkdone = False |
|
864 | gitworkdone = False | |
865 | if ((sourcefile or state == BFILE) and ((not context and x[0] == '@') or |
|
865 | if ((sourcefile or state == BFILE) and ((not context and x[0] == '@') or | |
866 | ((context is not False) and x.startswith('***************')))): |
|
866 | ((context is not False) and x.startswith('***************')))): | |
867 | try: |
|
867 | try: | |
868 | if context is None and x.startswith('***************'): |
|
868 | if context is None and x.startswith('***************'): | |
869 | context = True |
|
869 | context = True | |
870 | gpatch = changed.get(bfile) |
|
870 | gpatch = changed.get(bfile) | |
871 | create = afile == '/dev/null' or gpatch and gpatch.op == 'ADD' |
|
871 | create = afile == '/dev/null' or gpatch and gpatch.op == 'ADD' | |
872 | remove = bfile == '/dev/null' or gpatch and gpatch.op == 'DELETE' |
|
872 | remove = bfile == '/dev/null' or gpatch and gpatch.op == 'DELETE' | |
873 | current_hunk = hunk(x, hunknum + 1, lr, context, create, remove) |
|
873 | current_hunk = hunk(x, hunknum + 1, lr, context, create, remove) | |
874 | except PatchError, err: |
|
874 | except PatchError, err: | |
875 | ui.debug(err) |
|
875 | ui.debug(err) | |
876 | current_hunk = None |
|
876 | current_hunk = None | |
877 | continue |
|
877 | continue | |
878 | hunknum += 1 |
|
878 | hunknum += 1 | |
879 | if emitfile: |
|
879 | if emitfile: | |
880 | emitfile = False |
|
880 | emitfile = False | |
881 | yield 'file', (afile, bfile, current_hunk) |
|
881 | yield 'file', (afile, bfile, current_hunk) | |
882 | elif state == BFILE and x.startswith('GIT binary patch'): |
|
882 | elif state == BFILE and x.startswith('GIT binary patch'): | |
883 | current_hunk = binhunk(changed[bfile]) |
|
883 | current_hunk = binhunk(changed[bfile]) | |
884 | hunknum += 1 |
|
884 | hunknum += 1 | |
885 | if emitfile: |
|
885 | if emitfile: | |
886 | emitfile = False |
|
886 | emitfile = False | |
887 | yield 'file', ('a/' + afile, 'b/' + bfile, current_hunk) |
|
887 | yield 'file', ('a/' + afile, 'b/' + bfile, current_hunk) | |
888 | current_hunk.extract(lr) |
|
888 | current_hunk.extract(lr) | |
889 | elif x.startswith('diff --git'): |
|
889 | elif x.startswith('diff --git'): | |
890 | # check for git diff, scanning the whole patch file if needed |
|
890 | # check for git diff, scanning the whole patch file if needed | |
891 | m = gitre.match(x) |
|
891 | m = gitre.match(x) | |
892 | if m: |
|
892 | if m: | |
893 | afile, bfile = m.group(1, 2) |
|
893 | afile, bfile = m.group(1, 2) | |
894 | if not git: |
|
894 | if not git: | |
895 | git = True |
|
895 | git = True | |
896 | dopatch, gitpatches = scangitpatch(lr, x) |
|
896 | dopatch, gitpatches = scangitpatch(lr, x) | |
897 | yield 'git', gitpatches |
|
897 | yield 'git', gitpatches | |
898 | for gp in gitpatches: |
|
898 | for gp in gitpatches: | |
899 | changed[gp.path] = gp |
|
899 | changed[gp.path] = gp | |
900 | # else error? |
|
900 | # else error? | |
901 | # copy/rename + modify should modify target, not source |
|
901 | # copy/rename + modify should modify target, not source | |
902 | gp = changed.get(bfile) |
|
902 | gp = changed.get(bfile) | |
903 | if gp and gp.op in ('COPY', 'DELETE', 'RENAME', 'ADD'): |
|
903 | if gp and gp.op in ('COPY', 'DELETE', 'RENAME', 'ADD'): | |
904 | afile = bfile |
|
904 | afile = bfile | |
905 | gitworkdone = True |
|
905 | gitworkdone = True | |
906 | newfile = True |
|
906 | newfile = True | |
907 | elif x.startswith('---'): |
|
907 | elif x.startswith('---'): | |
908 | # check for a unified diff |
|
908 | # check for a unified diff | |
909 | l2 = lr.readline() |
|
909 | l2 = lr.readline() | |
910 | if not l2.startswith('+++'): |
|
910 | if not l2.startswith('+++'): | |
911 | lr.push(l2) |
|
911 | lr.push(l2) | |
912 | continue |
|
912 | continue | |
913 | newfile = True |
|
913 | newfile = True | |
914 | context = False |
|
914 | context = False | |
915 | afile = parsefilename(x) |
|
915 | afile = parsefilename(x) | |
916 | bfile = parsefilename(l2) |
|
916 | bfile = parsefilename(l2) | |
917 | elif x.startswith('***'): |
|
917 | elif x.startswith('***'): | |
918 | # check for a context diff |
|
918 | # check for a context diff | |
919 | l2 = lr.readline() |
|
919 | l2 = lr.readline() | |
920 | if not l2.startswith('---'): |
|
920 | if not l2.startswith('---'): | |
921 | lr.push(l2) |
|
921 | lr.push(l2) | |
922 | continue |
|
922 | continue | |
923 | l3 = lr.readline() |
|
923 | l3 = lr.readline() | |
924 | lr.push(l3) |
|
924 | lr.push(l3) | |
925 | if not l3.startswith("***************"): |
|
925 | if not l3.startswith("***************"): | |
926 | lr.push(l2) |
|
926 | lr.push(l2) | |
927 | continue |
|
927 | continue | |
928 | newfile = True |
|
928 | newfile = True | |
929 | context = True |
|
929 | context = True | |
930 | afile = parsefilename(x) |
|
930 | afile = parsefilename(x) | |
931 | bfile = parsefilename(l2) |
|
931 | bfile = parsefilename(l2) | |
932 |
|
932 | |||
933 | if newfile: |
|
933 | if newfile: | |
934 | emitfile = True |
|
934 | emitfile = True | |
935 | state = BFILE |
|
935 | state = BFILE | |
936 | hunknum = 0 |
|
936 | hunknum = 0 | |
937 | if current_hunk: |
|
937 | if current_hunk: | |
938 | if current_hunk.complete(): |
|
938 | if current_hunk.complete(): | |
939 | yield 'hunk', current_hunk |
|
939 | yield 'hunk', current_hunk | |
940 | else: |
|
940 | else: | |
941 | raise PatchError(_("malformed patch %s %s") % (afile, |
|
941 | raise PatchError(_("malformed patch %s %s") % (afile, | |
942 | current_hunk.desc)) |
|
942 | current_hunk.desc)) | |
943 |
|
943 | |||
944 | if hunknum == 0 and dopatch and not gitworkdone: |
|
944 | if hunknum == 0 and dopatch and not gitworkdone: | |
945 | raise NoHunks |
|
945 | raise NoHunks | |
946 |
|
946 | |||
947 | def applydiff(ui, fp, changed, strip=1, sourcefile=None, eol=None): |
|
947 | def applydiff(ui, fp, changed, strip=1, sourcefile=None, eol=None): | |
948 | """ |
|
948 | """ | |
949 | Reads a patch from fp and tries to apply it. |
|
949 | Reads a patch from fp and tries to apply it. | |
950 |
|
950 | |||
951 | The dict 'changed' is filled in with all of the filenames changed |
|
951 | The dict 'changed' is filled in with all of the filenames changed | |
952 | by the patch. Returns 0 for a clean patch, -1 if any rejects were |
|
952 | by the patch. Returns 0 for a clean patch, -1 if any rejects were | |
953 | found and 1 if there was any fuzz. |
|
953 | found and 1 if there was any fuzz. | |
954 |
|
954 | |||
955 | If 'eol' is None, the patch content and patched file are read in |
|
955 | If 'eol' is None, the patch content and patched file are read in | |
956 | binary mode. Otherwise, line endings are ignored when patching then |
|
956 | binary mode. Otherwise, line endings are ignored when patching then | |
957 | normalized to 'eol' (usually '\n' or \r\n'). |
|
957 | normalized to 'eol' (usually '\n' or \r\n'). | |
958 | """ |
|
958 | """ | |
959 | rejects = 0 |
|
959 | rejects = 0 | |
960 | err = 0 |
|
960 | err = 0 | |
961 | current_file = None |
|
961 | current_file = None | |
962 | gitpatches = None |
|
962 | gitpatches = None | |
963 | opener = util.opener(os.getcwd()) |
|
963 | opener = util.opener(os.getcwd()) | |
964 | textmode = eol is not None |
|
964 | textmode = eol is not None | |
965 |
|
965 | |||
966 | def closefile(): |
|
966 | def closefile(): | |
967 | if not current_file: |
|
967 | if not current_file: | |
968 | return 0 |
|
968 | return 0 | |
969 | current_file.close() |
|
969 | current_file.close() | |
970 | return len(current_file.rej) |
|
970 | return len(current_file.rej) | |
971 |
|
971 | |||
972 | for state, values in iterhunks(ui, fp, sourcefile, textmode): |
|
972 | for state, values in iterhunks(ui, fp, sourcefile, textmode): | |
973 | if state == 'hunk': |
|
973 | if state == 'hunk': | |
974 | if not current_file: |
|
974 | if not current_file: | |
975 | continue |
|
975 | continue | |
976 | current_hunk = values |
|
976 | current_hunk = values | |
977 | ret = current_file.apply(current_hunk) |
|
977 | ret = current_file.apply(current_hunk) | |
978 | if ret >= 0: |
|
978 | if ret >= 0: | |
979 | changed.setdefault(current_file.fname, None) |
|
979 | changed.setdefault(current_file.fname, None) | |
980 | if ret > 0: |
|
980 | if ret > 0: | |
981 | err = 1 |
|
981 | err = 1 | |
982 | elif state == 'file': |
|
982 | elif state == 'file': | |
983 | rejects += closefile() |
|
983 | rejects += closefile() | |
984 | afile, bfile, first_hunk = values |
|
984 | afile, bfile, first_hunk = values | |
985 | try: |
|
985 | try: | |
986 | if sourcefile: |
|
986 | if sourcefile: | |
987 | current_file = patchfile(ui, sourcefile, opener, eol=eol) |
|
987 | current_file = patchfile(ui, sourcefile, opener, eol=eol) | |
988 | else: |
|
988 | else: | |
989 | current_file, missing = selectfile(afile, bfile, first_hunk, |
|
989 | current_file, missing = selectfile(afile, bfile, first_hunk, | |
990 | strip) |
|
990 | strip) | |
991 | current_file = patchfile(ui, current_file, opener, missing, eol) |
|
991 | current_file = patchfile(ui, current_file, opener, missing, eol) | |
992 | except PatchError, err: |
|
992 | except PatchError, err: | |
993 | ui.warn(str(err) + '\n') |
|
993 | ui.warn(str(err) + '\n') | |
994 | current_file, current_hunk = None, None |
|
994 | current_file, current_hunk = None, None | |
995 | rejects += 1 |
|
995 | rejects += 1 | |
996 | continue |
|
996 | continue | |
997 | elif state == 'git': |
|
997 | elif state == 'git': | |
998 | gitpatches = values |
|
998 | gitpatches = values | |
999 | cwd = os.getcwd() |
|
999 | cwd = os.getcwd() | |
1000 | for gp in gitpatches: |
|
1000 | for gp in gitpatches: | |
1001 | if gp.op in ('COPY', 'RENAME'): |
|
1001 | if gp.op in ('COPY', 'RENAME'): | |
1002 | copyfile(gp.oldpath, gp.path, cwd) |
|
1002 | copyfile(gp.oldpath, gp.path, cwd) | |
1003 | changed[gp.path] = gp |
|
1003 | changed[gp.path] = gp | |
1004 | else: |
|
1004 | else: | |
1005 | raise util.Abort(_('unsupported parser state: %s') % state) |
|
1005 | raise util.Abort(_('unsupported parser state: %s') % state) | |
1006 |
|
1006 | |||
1007 | rejects += closefile() |
|
1007 | rejects += closefile() | |
1008 |
|
1008 | |||
1009 | if rejects: |
|
1009 | if rejects: | |
1010 | return -1 |
|
1010 | return -1 | |
1011 | return err |
|
1011 | return err | |
1012 |
|
1012 | |||
1013 | def diffopts(ui, opts=None, untrusted=False): |
|
1013 | def diffopts(ui, opts=None, untrusted=False): | |
1014 | def get(key, name=None, getter=ui.configbool): |
|
1014 | def get(key, name=None, getter=ui.configbool): | |
1015 | return ((opts and opts.get(key)) or |
|
1015 | return ((opts and opts.get(key)) or | |
1016 | getter('diff', name or key, None, untrusted=untrusted)) |
|
1016 | getter('diff', name or key, None, untrusted=untrusted)) | |
1017 | return mdiff.diffopts( |
|
1017 | return mdiff.diffopts( | |
1018 | text=opts and opts.get('text'), |
|
1018 | text=opts and opts.get('text'), | |
1019 | git=get('git'), |
|
1019 | git=get('git'), | |
1020 | nodates=get('nodates'), |
|
1020 | nodates=get('nodates'), | |
1021 | showfunc=get('show_function', 'showfunc'), |
|
1021 | showfunc=get('show_function', 'showfunc'), | |
1022 | ignorews=get('ignore_all_space', 'ignorews'), |
|
1022 | ignorews=get('ignore_all_space', 'ignorews'), | |
1023 | ignorewsamount=get('ignore_space_change', 'ignorewsamount'), |
|
1023 | ignorewsamount=get('ignore_space_change', 'ignorewsamount'), | |
1024 | ignoreblanklines=get('ignore_blank_lines', 'ignoreblanklines'), |
|
1024 | ignoreblanklines=get('ignore_blank_lines', 'ignoreblanklines'), | |
1025 | context=get('unified', getter=ui.config)) |
|
1025 | context=get('unified', getter=ui.config)) | |
1026 |
|
1026 | |||
1027 | def updatedir(ui, repo, patches, similarity=0): |
|
1027 | def updatedir(ui, repo, patches, similarity=0): | |
1028 | '''Update dirstate after patch application according to metadata''' |
|
1028 | '''Update dirstate after patch application according to metadata''' | |
1029 | if not patches: |
|
1029 | if not patches: | |
1030 | return |
|
1030 | return | |
1031 | copies = [] |
|
1031 | copies = [] | |
1032 | removes = set() |
|
1032 | removes = set() | |
1033 | cfiles = patches.keys() |
|
1033 | cfiles = patches.keys() | |
1034 | cwd = repo.getcwd() |
|
1034 | cwd = repo.getcwd() | |
1035 | if cwd: |
|
1035 | if cwd: | |
1036 | cfiles = [util.pathto(repo.root, cwd, f) for f in patches.keys()] |
|
1036 | cfiles = [util.pathto(repo.root, cwd, f) for f in patches.keys()] | |
1037 | for f in patches: |
|
1037 | for f in patches: | |
1038 | gp = patches[f] |
|
1038 | gp = patches[f] | |
1039 | if not gp: |
|
1039 | if not gp: | |
1040 | continue |
|
1040 | continue | |
1041 | if gp.op == 'RENAME': |
|
1041 | if gp.op == 'RENAME': | |
1042 | copies.append((gp.oldpath, gp.path)) |
|
1042 | copies.append((gp.oldpath, gp.path)) | |
1043 | removes.add(gp.oldpath) |
|
1043 | removes.add(gp.oldpath) | |
1044 | elif gp.op == 'COPY': |
|
1044 | elif gp.op == 'COPY': | |
1045 | copies.append((gp.oldpath, gp.path)) |
|
1045 | copies.append((gp.oldpath, gp.path)) | |
1046 | elif gp.op == 'DELETE': |
|
1046 | elif gp.op == 'DELETE': | |
1047 | removes.add(gp.path) |
|
1047 | removes.add(gp.path) | |
1048 | for src, dst in copies: |
|
1048 | for src, dst in copies: | |
1049 | repo.copy(src, dst) |
|
1049 | repo.copy(src, dst) | |
1050 | if (not similarity) and removes: |
|
1050 | if (not similarity) and removes: | |
1051 | repo.remove(sorted(removes), True) |
|
1051 | repo.remove(sorted(removes), True) | |
1052 | for f in patches: |
|
1052 | for f in patches: | |
1053 | gp = patches[f] |
|
1053 | gp = patches[f] | |
1054 | if gp and gp.mode: |
|
1054 | if gp and gp.mode: | |
1055 | islink, isexec = gp.mode |
|
1055 | islink, isexec = gp.mode | |
1056 | dst = repo.wjoin(gp.path) |
|
1056 | dst = repo.wjoin(gp.path) | |
1057 | # patch won't create empty files |
|
1057 | # patch won't create empty files | |
1058 | if gp.op == 'ADD' and not os.path.exists(dst): |
|
1058 | if gp.op == 'ADD' and not os.path.exists(dst): | |
1059 | flags = (isexec and 'x' or '') + (islink and 'l' or '') |
|
1059 | flags = (isexec and 'x' or '') + (islink and 'l' or '') | |
1060 | repo.wwrite(gp.path, '', flags) |
|
1060 | repo.wwrite(gp.path, '', flags) | |
1061 | elif gp.op != 'DELETE': |
|
1061 | elif gp.op != 'DELETE': | |
1062 | util.set_flags(dst, islink, isexec) |
|
1062 | util.set_flags(dst, islink, isexec) | |
1063 | cmdutil.addremove(repo, cfiles, similarity=similarity) |
|
1063 | cmdutil.addremove(repo, cfiles, similarity=similarity) | |
1064 | files = patches.keys() |
|
1064 | files = patches.keys() | |
1065 | files.extend([r for r in removes if r not in files]) |
|
1065 | files.extend([r for r in removes if r not in files]) | |
1066 | return sorted(files) |
|
1066 | return sorted(files) | |
1067 |
|
1067 | |||
1068 | def externalpatch(patcher, args, patchname, ui, strip, cwd, files): |
|
1068 | def externalpatch(patcher, args, patchname, ui, strip, cwd, files): | |
1069 | """use <patcher> to apply <patchname> to the working directory. |
|
1069 | """use <patcher> to apply <patchname> to the working directory. | |
1070 | returns whether patch was applied with fuzz factor.""" |
|
1070 | returns whether patch was applied with fuzz factor.""" | |
1071 |
|
1071 | |||
1072 | fuzz = False |
|
1072 | fuzz = False | |
1073 | if cwd: |
|
1073 | if cwd: | |
1074 | args.append('-d %s' % util.shellquote(cwd)) |
|
1074 | args.append('-d %s' % util.shellquote(cwd)) | |
1075 | fp = util.popen('%s %s -p%d < %s' % (patcher, ' '.join(args), strip, |
|
1075 | fp = util.popen('%s %s -p%d < %s' % (patcher, ' '.join(args), strip, | |
1076 | util.shellquote(patchname))) |
|
1076 | util.shellquote(patchname))) | |
1077 |
|
1077 | |||
1078 | for line in fp: |
|
1078 | for line in fp: | |
1079 | line = line.rstrip() |
|
1079 | line = line.rstrip() | |
1080 | ui.note(line + '\n') |
|
1080 | ui.note(line + '\n') | |
1081 | if line.startswith('patching file '): |
|
1081 | if line.startswith('patching file '): | |
1082 | pf = util.parse_patch_output(line) |
|
1082 | pf = util.parse_patch_output(line) | |
1083 | printed_file = False |
|
1083 | printed_file = False | |
1084 | files.setdefault(pf, None) |
|
1084 | files.setdefault(pf, None) | |
1085 | elif line.find('with fuzz') >= 0: |
|
1085 | elif line.find('with fuzz') >= 0: | |
1086 | fuzz = True |
|
1086 | fuzz = True | |
1087 | if not printed_file: |
|
1087 | if not printed_file: | |
1088 | ui.warn(pf + '\n') |
|
1088 | ui.warn(pf + '\n') | |
1089 | printed_file = True |
|
1089 | printed_file = True | |
1090 | ui.warn(line + '\n') |
|
1090 | ui.warn(line + '\n') | |
1091 | elif line.find('saving rejects to file') >= 0: |
|
1091 | elif line.find('saving rejects to file') >= 0: | |
1092 | ui.warn(line + '\n') |
|
1092 | ui.warn(line + '\n') | |
1093 | elif line.find('FAILED') >= 0: |
|
1093 | elif line.find('FAILED') >= 0: | |
1094 | if not printed_file: |
|
1094 | if not printed_file: | |
1095 | ui.warn(pf + '\n') |
|
1095 | ui.warn(pf + '\n') | |
1096 | printed_file = True |
|
1096 | printed_file = True | |
1097 | ui.warn(line + '\n') |
|
1097 | ui.warn(line + '\n') | |
1098 | code = fp.close() |
|
1098 | code = fp.close() | |
1099 | if code: |
|
1099 | if code: | |
1100 | raise PatchError(_("patch command failed: %s") % |
|
1100 | raise PatchError(_("patch command failed: %s") % | |
1101 | util.explain_exit(code)[0]) |
|
1101 | util.explain_exit(code)[0]) | |
1102 | return fuzz |
|
1102 | return fuzz | |
1103 |
|
1103 | |||
1104 | def internalpatch(patchobj, ui, strip, cwd, files=None, eolmode='strict'): |
|
1104 | def internalpatch(patchobj, ui, strip, cwd, files=None, eolmode='strict'): | |
1105 | """use builtin patch to apply <patchobj> to the working directory. |
|
1105 | """use builtin patch to apply <patchobj> to the working directory. | |
1106 | returns whether patch was applied with fuzz factor.""" |
|
1106 | returns whether patch was applied with fuzz factor.""" | |
1107 |
|
1107 | |||
1108 | if files is None: |
|
1108 | if files is None: | |
1109 | files = {} |
|
1109 | files = {} | |
1110 | if eolmode is None: |
|
1110 | if eolmode is None: | |
1111 | eolmode = ui.config('patch', 'eol', 'strict') |
|
1111 | eolmode = ui.config('patch', 'eol', 'strict') | |
1112 | try: |
|
1112 | try: | |
1113 | eol = {'strict': None, 'crlf': '\r\n', 'lf': '\n'}[eolmode.lower()] |
|
1113 | eol = {'strict': None, 'crlf': '\r\n', 'lf': '\n'}[eolmode.lower()] | |
1114 | except KeyError: |
|
1114 | except KeyError: | |
1115 | raise util.Abort(_('Unsupported line endings type: %s') % eolmode) |
|
1115 | raise util.Abort(_('Unsupported line endings type: %s') % eolmode) | |
1116 |
|
1116 | |||
1117 | try: |
|
1117 | try: | |
1118 | fp = open(patchobj, 'rb') |
|
1118 | fp = open(patchobj, 'rb') | |
1119 | except TypeError: |
|
1119 | except TypeError: | |
1120 | fp = patchobj |
|
1120 | fp = patchobj | |
1121 | if cwd: |
|
1121 | if cwd: | |
1122 | curdir = os.getcwd() |
|
1122 | curdir = os.getcwd() | |
1123 | os.chdir(cwd) |
|
1123 | os.chdir(cwd) | |
1124 | try: |
|
1124 | try: | |
1125 | ret = applydiff(ui, fp, files, strip=strip, eol=eol) |
|
1125 | ret = applydiff(ui, fp, files, strip=strip, eol=eol) | |
1126 | finally: |
|
1126 | finally: | |
1127 | if cwd: |
|
1127 | if cwd: | |
1128 | os.chdir(curdir) |
|
1128 | os.chdir(curdir) | |
|
1129 | if fp != patchobj: | |||
|
1130 | fp.close() | |||
1129 | if ret < 0: |
|
1131 | if ret < 0: | |
1130 | raise PatchError |
|
1132 | raise PatchError | |
1131 | return ret > 0 |
|
1133 | return ret > 0 | |
1132 |
|
1134 | |||
1133 | def patch(patchname, ui, strip=1, cwd=None, files=None, eolmode='strict'): |
|
1135 | def patch(patchname, ui, strip=1, cwd=None, files=None, eolmode='strict'): | |
1134 | """Apply <patchname> to the working directory. |
|
1136 | """Apply <patchname> to the working directory. | |
1135 |
|
1137 | |||
1136 | 'eolmode' specifies how end of lines should be handled. It can be: |
|
1138 | 'eolmode' specifies how end of lines should be handled. It can be: | |
1137 | - 'strict': inputs are read in binary mode, EOLs are preserved |
|
1139 | - 'strict': inputs are read in binary mode, EOLs are preserved | |
1138 | - 'crlf': EOLs are ignored when patching and reset to CRLF |
|
1140 | - 'crlf': EOLs are ignored when patching and reset to CRLF | |
1139 | - 'lf': EOLs are ignored when patching and reset to LF |
|
1141 | - 'lf': EOLs are ignored when patching and reset to LF | |
1140 | - None: get it from user settings, default to 'strict' |
|
1142 | - None: get it from user settings, default to 'strict' | |
1141 | 'eolmode' is ignored when using an external patcher program. |
|
1143 | 'eolmode' is ignored when using an external patcher program. | |
1142 |
|
1144 | |||
1143 | Returns whether patch was applied with fuzz factor. |
|
1145 | Returns whether patch was applied with fuzz factor. | |
1144 | """ |
|
1146 | """ | |
1145 | patcher = ui.config('ui', 'patch') |
|
1147 | patcher = ui.config('ui', 'patch') | |
1146 | args = [] |
|
1148 | args = [] | |
1147 | if files is None: |
|
1149 | if files is None: | |
1148 | files = {} |
|
1150 | files = {} | |
1149 | try: |
|
1151 | try: | |
1150 | if patcher: |
|
1152 | if patcher: | |
1151 | return externalpatch(patcher, args, patchname, ui, strip, cwd, |
|
1153 | return externalpatch(patcher, args, patchname, ui, strip, cwd, | |
1152 | files) |
|
1154 | files) | |
1153 | else: |
|
1155 | else: | |
1154 | try: |
|
1156 | try: | |
1155 | return internalpatch(patchname, ui, strip, cwd, files, eolmode) |
|
1157 | return internalpatch(patchname, ui, strip, cwd, files, eolmode) | |
1156 | except NoHunks: |
|
1158 | except NoHunks: | |
1157 | patcher = util.find_exe('gpatch') or util.find_exe('patch') or 'patch' |
|
1159 | patcher = util.find_exe('gpatch') or util.find_exe('patch') or 'patch' | |
1158 | ui.debug('no valid hunks found; trying with %r instead\n' % |
|
1160 | ui.debug('no valid hunks found; trying with %r instead\n' % | |
1159 | patcher) |
|
1161 | patcher) | |
1160 | if util.needbinarypatch(): |
|
1162 | if util.needbinarypatch(): | |
1161 | args.append('--binary') |
|
1163 | args.append('--binary') | |
1162 | return externalpatch(patcher, args, patchname, ui, strip, cwd, |
|
1164 | return externalpatch(patcher, args, patchname, ui, strip, cwd, | |
1163 | files) |
|
1165 | files) | |
1164 | except PatchError, err: |
|
1166 | except PatchError, err: | |
1165 | s = str(err) |
|
1167 | s = str(err) | |
1166 | if s: |
|
1168 | if s: | |
1167 | raise util.Abort(s) |
|
1169 | raise util.Abort(s) | |
1168 | else: |
|
1170 | else: | |
1169 | raise util.Abort(_('patch failed to apply')) |
|
1171 | raise util.Abort(_('patch failed to apply')) | |
1170 |
|
1172 | |||
1171 | def b85diff(to, tn): |
|
1173 | def b85diff(to, tn): | |
1172 | '''print base85-encoded binary diff''' |
|
1174 | '''print base85-encoded binary diff''' | |
1173 | def gitindex(text): |
|
1175 | def gitindex(text): | |
1174 | if not text: |
|
1176 | if not text: | |
1175 | return '0' * 40 |
|
1177 | return '0' * 40 | |
1176 | l = len(text) |
|
1178 | l = len(text) | |
1177 | s = util.sha1('blob %d\0' % l) |
|
1179 | s = util.sha1('blob %d\0' % l) | |
1178 | s.update(text) |
|
1180 | s.update(text) | |
1179 | return s.hexdigest() |
|
1181 | return s.hexdigest() | |
1180 |
|
1182 | |||
1181 | def fmtline(line): |
|
1183 | def fmtline(line): | |
1182 | l = len(line) |
|
1184 | l = len(line) | |
1183 | if l <= 26: |
|
1185 | if l <= 26: | |
1184 | l = chr(ord('A') + l - 1) |
|
1186 | l = chr(ord('A') + l - 1) | |
1185 | else: |
|
1187 | else: | |
1186 | l = chr(l - 26 + ord('a') - 1) |
|
1188 | l = chr(l - 26 + ord('a') - 1) | |
1187 | return '%c%s\n' % (l, base85.b85encode(line, True)) |
|
1189 | return '%c%s\n' % (l, base85.b85encode(line, True)) | |
1188 |
|
1190 | |||
1189 | def chunk(text, csize=52): |
|
1191 | def chunk(text, csize=52): | |
1190 | l = len(text) |
|
1192 | l = len(text) | |
1191 | i = 0 |
|
1193 | i = 0 | |
1192 | while i < l: |
|
1194 | while i < l: | |
1193 | yield text[i:i+csize] |
|
1195 | yield text[i:i+csize] | |
1194 | i += csize |
|
1196 | i += csize | |
1195 |
|
1197 | |||
1196 | tohash = gitindex(to) |
|
1198 | tohash = gitindex(to) | |
1197 | tnhash = gitindex(tn) |
|
1199 | tnhash = gitindex(tn) | |
1198 | if tohash == tnhash: |
|
1200 | if tohash == tnhash: | |
1199 | return "" |
|
1201 | return "" | |
1200 |
|
1202 | |||
1201 | # TODO: deltas |
|
1203 | # TODO: deltas | |
1202 | ret = ['index %s..%s\nGIT binary patch\nliteral %s\n' % |
|
1204 | ret = ['index %s..%s\nGIT binary patch\nliteral %s\n' % | |
1203 | (tohash, tnhash, len(tn))] |
|
1205 | (tohash, tnhash, len(tn))] | |
1204 | for l in chunk(zlib.compress(tn)): |
|
1206 | for l in chunk(zlib.compress(tn)): | |
1205 | ret.append(fmtline(l)) |
|
1207 | ret.append(fmtline(l)) | |
1206 | ret.append('\n') |
|
1208 | ret.append('\n') | |
1207 | return ''.join(ret) |
|
1209 | return ''.join(ret) | |
1208 |
|
1210 | |||
1209 | def _addmodehdr(header, omode, nmode): |
|
1211 | def _addmodehdr(header, omode, nmode): | |
1210 | if omode != nmode: |
|
1212 | if omode != nmode: | |
1211 | header.append('old mode %s\n' % omode) |
|
1213 | header.append('old mode %s\n' % omode) | |
1212 | header.append('new mode %s\n' % nmode) |
|
1214 | header.append('new mode %s\n' % nmode) | |
1213 |
|
1215 | |||
1214 | def diff(repo, node1=None, node2=None, match=None, changes=None, opts=None): |
|
1216 | def diff(repo, node1=None, node2=None, match=None, changes=None, opts=None): | |
1215 | '''yields diff of changes to files between two nodes, or node and |
|
1217 | '''yields diff of changes to files between two nodes, or node and | |
1216 | working directory. |
|
1218 | working directory. | |
1217 |
|
1219 | |||
1218 | if node1 is None, use first dirstate parent instead. |
|
1220 | if node1 is None, use first dirstate parent instead. | |
1219 | if node2 is None, compare node1 with working directory.''' |
|
1221 | if node2 is None, compare node1 with working directory.''' | |
1220 |
|
1222 | |||
1221 | if opts is None: |
|
1223 | if opts is None: | |
1222 | opts = mdiff.defaultopts |
|
1224 | opts = mdiff.defaultopts | |
1223 |
|
1225 | |||
1224 | if not node1 and not node2: |
|
1226 | if not node1 and not node2: | |
1225 | node1 = repo.dirstate.parents()[0] |
|
1227 | node1 = repo.dirstate.parents()[0] | |
1226 |
|
1228 | |||
1227 | def lrugetfilectx(): |
|
1229 | def lrugetfilectx(): | |
1228 | cache = {} |
|
1230 | cache = {} | |
1229 | order = [] |
|
1231 | order = [] | |
1230 | def getfilectx(f, ctx): |
|
1232 | def getfilectx(f, ctx): | |
1231 | fctx = ctx.filectx(f, filelog=cache.get(f)) |
|
1233 | fctx = ctx.filectx(f, filelog=cache.get(f)) | |
1232 | if f not in cache: |
|
1234 | if f not in cache: | |
1233 | if len(cache) > 20: |
|
1235 | if len(cache) > 20: | |
1234 | del cache[order.pop(0)] |
|
1236 | del cache[order.pop(0)] | |
1235 | cache[f] = fctx.filelog() |
|
1237 | cache[f] = fctx.filelog() | |
1236 | else: |
|
1238 | else: | |
1237 | order.remove(f) |
|
1239 | order.remove(f) | |
1238 | order.append(f) |
|
1240 | order.append(f) | |
1239 | return fctx |
|
1241 | return fctx | |
1240 | return getfilectx |
|
1242 | return getfilectx | |
1241 | getfilectx = lrugetfilectx() |
|
1243 | getfilectx = lrugetfilectx() | |
1242 |
|
1244 | |||
1243 | ctx1 = repo[node1] |
|
1245 | ctx1 = repo[node1] | |
1244 | ctx2 = repo[node2] |
|
1246 | ctx2 = repo[node2] | |
1245 |
|
1247 | |||
1246 | if not changes: |
|
1248 | if not changes: | |
1247 | changes = repo.status(ctx1, ctx2, match=match) |
|
1249 | changes = repo.status(ctx1, ctx2, match=match) | |
1248 | modified, added, removed = changes[:3] |
|
1250 | modified, added, removed = changes[:3] | |
1249 |
|
1251 | |||
1250 | if not modified and not added and not removed: |
|
1252 | if not modified and not added and not removed: | |
1251 | return |
|
1253 | return | |
1252 |
|
1254 | |||
1253 | date1 = util.datestr(ctx1.date()) |
|
1255 | date1 = util.datestr(ctx1.date()) | |
1254 | man1 = ctx1.manifest() |
|
1256 | man1 = ctx1.manifest() | |
1255 |
|
1257 | |||
1256 | if repo.ui.quiet: |
|
1258 | if repo.ui.quiet: | |
1257 | r = None |
|
1259 | r = None | |
1258 | else: |
|
1260 | else: | |
1259 | hexfunc = repo.ui.debugflag and hex or short |
|
1261 | hexfunc = repo.ui.debugflag and hex or short | |
1260 | r = [hexfunc(node) for node in [node1, node2] if node] |
|
1262 | r = [hexfunc(node) for node in [node1, node2] if node] | |
1261 |
|
1263 | |||
1262 | if opts.git: |
|
1264 | if opts.git: | |
1263 | copy, diverge = copies.copies(repo, ctx1, ctx2, repo[nullid]) |
|
1265 | copy, diverge = copies.copies(repo, ctx1, ctx2, repo[nullid]) | |
1264 | copy = copy.copy() |
|
1266 | copy = copy.copy() | |
1265 | for k, v in copy.items(): |
|
1267 | for k, v in copy.items(): | |
1266 | copy[v] = k |
|
1268 | copy[v] = k | |
1267 |
|
1269 | |||
1268 | gone = set() |
|
1270 | gone = set() | |
1269 | gitmode = {'l': '120000', 'x': '100755', '': '100644'} |
|
1271 | gitmode = {'l': '120000', 'x': '100755', '': '100644'} | |
1270 |
|
1272 | |||
1271 | for f in sorted(modified + added + removed): |
|
1273 | for f in sorted(modified + added + removed): | |
1272 | to = None |
|
1274 | to = None | |
1273 | tn = None |
|
1275 | tn = None | |
1274 | dodiff = True |
|
1276 | dodiff = True | |
1275 | header = [] |
|
1277 | header = [] | |
1276 | if f in man1: |
|
1278 | if f in man1: | |
1277 | to = getfilectx(f, ctx1).data() |
|
1279 | to = getfilectx(f, ctx1).data() | |
1278 | if f not in removed: |
|
1280 | if f not in removed: | |
1279 | tn = getfilectx(f, ctx2).data() |
|
1281 | tn = getfilectx(f, ctx2).data() | |
1280 | a, b = f, f |
|
1282 | a, b = f, f | |
1281 | if opts.git: |
|
1283 | if opts.git: | |
1282 | if f in added: |
|
1284 | if f in added: | |
1283 | mode = gitmode[ctx2.flags(f)] |
|
1285 | mode = gitmode[ctx2.flags(f)] | |
1284 | if f in copy: |
|
1286 | if f in copy: | |
1285 | a = copy[f] |
|
1287 | a = copy[f] | |
1286 | omode = gitmode[man1.flags(a)] |
|
1288 | omode = gitmode[man1.flags(a)] | |
1287 | _addmodehdr(header, omode, mode) |
|
1289 | _addmodehdr(header, omode, mode) | |
1288 | if a in removed and a not in gone: |
|
1290 | if a in removed and a not in gone: | |
1289 | op = 'rename' |
|
1291 | op = 'rename' | |
1290 | gone.add(a) |
|
1292 | gone.add(a) | |
1291 | else: |
|
1293 | else: | |
1292 | op = 'copy' |
|
1294 | op = 'copy' | |
1293 | header.append('%s from %s\n' % (op, a)) |
|
1295 | header.append('%s from %s\n' % (op, a)) | |
1294 | header.append('%s to %s\n' % (op, f)) |
|
1296 | header.append('%s to %s\n' % (op, f)) | |
1295 | to = getfilectx(a, ctx1).data() |
|
1297 | to = getfilectx(a, ctx1).data() | |
1296 | else: |
|
1298 | else: | |
1297 | header.append('new file mode %s\n' % mode) |
|
1299 | header.append('new file mode %s\n' % mode) | |
1298 | if util.binary(tn): |
|
1300 | if util.binary(tn): | |
1299 | dodiff = 'binary' |
|
1301 | dodiff = 'binary' | |
1300 | elif f in removed: |
|
1302 | elif f in removed: | |
1301 | # have we already reported a copy above? |
|
1303 | # have we already reported a copy above? | |
1302 | if f in copy and copy[f] in added and copy[copy[f]] == f: |
|
1304 | if f in copy and copy[f] in added and copy[copy[f]] == f: | |
1303 | dodiff = False |
|
1305 | dodiff = False | |
1304 | else: |
|
1306 | else: | |
1305 | header.append('deleted file mode %s\n' % |
|
1307 | header.append('deleted file mode %s\n' % | |
1306 | gitmode[man1.flags(f)]) |
|
1308 | gitmode[man1.flags(f)]) | |
1307 | else: |
|
1309 | else: | |
1308 | omode = gitmode[man1.flags(f)] |
|
1310 | omode = gitmode[man1.flags(f)] | |
1309 | nmode = gitmode[ctx2.flags(f)] |
|
1311 | nmode = gitmode[ctx2.flags(f)] | |
1310 | _addmodehdr(header, omode, nmode) |
|
1312 | _addmodehdr(header, omode, nmode) | |
1311 | if util.binary(to) or util.binary(tn): |
|
1313 | if util.binary(to) or util.binary(tn): | |
1312 | dodiff = 'binary' |
|
1314 | dodiff = 'binary' | |
1313 | r = None |
|
1315 | r = None | |
1314 | header.insert(0, mdiff.diffline(r, a, b, opts)) |
|
1316 | header.insert(0, mdiff.diffline(r, a, b, opts)) | |
1315 | if dodiff: |
|
1317 | if dodiff: | |
1316 | if dodiff == 'binary': |
|
1318 | if dodiff == 'binary': | |
1317 | text = b85diff(to, tn) |
|
1319 | text = b85diff(to, tn) | |
1318 | else: |
|
1320 | else: | |
1319 | text = mdiff.unidiff(to, date1, |
|
1321 | text = mdiff.unidiff(to, date1, | |
1320 | # ctx2 date may be dynamic |
|
1322 | # ctx2 date may be dynamic | |
1321 | tn, util.datestr(ctx2.date()), |
|
1323 | tn, util.datestr(ctx2.date()), | |
1322 | a, b, r, opts=opts) |
|
1324 | a, b, r, opts=opts) | |
1323 | if header and (text or len(header) > 1): |
|
1325 | if header and (text or len(header) > 1): | |
1324 | yield ''.join(header) |
|
1326 | yield ''.join(header) | |
1325 | if text: |
|
1327 | if text: | |
1326 | yield text |
|
1328 | yield text | |
1327 |
|
1329 | |||
1328 | def export(repo, revs, template='hg-%h.patch', fp=None, switch_parent=False, |
|
1330 | def export(repo, revs, template='hg-%h.patch', fp=None, switch_parent=False, | |
1329 | opts=None): |
|
1331 | opts=None): | |
1330 | '''export changesets as hg patches.''' |
|
1332 | '''export changesets as hg patches.''' | |
1331 |
|
1333 | |||
1332 | total = len(revs) |
|
1334 | total = len(revs) | |
1333 | revwidth = max([len(str(rev)) for rev in revs]) |
|
1335 | revwidth = max([len(str(rev)) for rev in revs]) | |
1334 |
|
1336 | |||
1335 | def single(rev, seqno, fp): |
|
1337 | def single(rev, seqno, fp): | |
1336 | ctx = repo[rev] |
|
1338 | ctx = repo[rev] | |
1337 | node = ctx.node() |
|
1339 | node = ctx.node() | |
1338 | parents = [p.node() for p in ctx.parents() if p] |
|
1340 | parents = [p.node() for p in ctx.parents() if p] | |
1339 | branch = ctx.branch() |
|
1341 | branch = ctx.branch() | |
1340 | if switch_parent: |
|
1342 | if switch_parent: | |
1341 | parents.reverse() |
|
1343 | parents.reverse() | |
1342 | prev = (parents and parents[0]) or nullid |
|
1344 | prev = (parents and parents[0]) or nullid | |
1343 |
|
1345 | |||
1344 | if not fp: |
|
1346 | if not fp: | |
1345 | fp = cmdutil.make_file(repo, template, node, total=total, |
|
1347 | fp = cmdutil.make_file(repo, template, node, total=total, | |
1346 | seqno=seqno, revwidth=revwidth, |
|
1348 | seqno=seqno, revwidth=revwidth, | |
1347 | mode='ab') |
|
1349 | mode='ab') | |
1348 | if fp != sys.stdout and hasattr(fp, 'name'): |
|
1350 | if fp != sys.stdout and hasattr(fp, 'name'): | |
1349 | repo.ui.note("%s\n" % fp.name) |
|
1351 | repo.ui.note("%s\n" % fp.name) | |
1350 |
|
1352 | |||
1351 | fp.write("# HG changeset patch\n") |
|
1353 | fp.write("# HG changeset patch\n") | |
1352 | fp.write("# User %s\n" % ctx.user()) |
|
1354 | fp.write("# User %s\n" % ctx.user()) | |
1353 | fp.write("# Date %d %d\n" % ctx.date()) |
|
1355 | fp.write("# Date %d %d\n" % ctx.date()) | |
1354 | if branch and (branch != 'default'): |
|
1356 | if branch and (branch != 'default'): | |
1355 | fp.write("# Branch %s\n" % branch) |
|
1357 | fp.write("# Branch %s\n" % branch) | |
1356 | fp.write("# Node ID %s\n" % hex(node)) |
|
1358 | fp.write("# Node ID %s\n" % hex(node)) | |
1357 | fp.write("# Parent %s\n" % hex(prev)) |
|
1359 | fp.write("# Parent %s\n" % hex(prev)) | |
1358 | if len(parents) > 1: |
|
1360 | if len(parents) > 1: | |
1359 | fp.write("# Parent %s\n" % hex(parents[1])) |
|
1361 | fp.write("# Parent %s\n" % hex(parents[1])) | |
1360 | fp.write(ctx.description().rstrip()) |
|
1362 | fp.write(ctx.description().rstrip()) | |
1361 | fp.write("\n\n") |
|
1363 | fp.write("\n\n") | |
1362 |
|
1364 | |||
1363 | for chunk in diff(repo, prev, node, opts=opts): |
|
1365 | for chunk in diff(repo, prev, node, opts=opts): | |
1364 | fp.write(chunk) |
|
1366 | fp.write(chunk) | |
1365 |
|
1367 | |||
1366 | for seqno, rev in enumerate(revs): |
|
1368 | for seqno, rev in enumerate(revs): | |
1367 | single(rev, seqno+1, fp) |
|
1369 | single(rev, seqno+1, fp) | |
1368 |
|
1370 | |||
1369 | def diffstatdata(lines): |
|
1371 | def diffstatdata(lines): | |
1370 | filename, adds, removes = None, 0, 0 |
|
1372 | filename, adds, removes = None, 0, 0 | |
1371 | for line in lines: |
|
1373 | for line in lines: | |
1372 | if line.startswith('diff'): |
|
1374 | if line.startswith('diff'): | |
1373 | if filename: |
|
1375 | if filename: | |
1374 | isbinary = adds == 0 and removes == 0 |
|
1376 | isbinary = adds == 0 and removes == 0 | |
1375 | yield (filename, adds, removes, isbinary) |
|
1377 | yield (filename, adds, removes, isbinary) | |
1376 | # set numbers to 0 anyway when starting new file |
|
1378 | # set numbers to 0 anyway when starting new file | |
1377 | adds, removes = 0, 0 |
|
1379 | adds, removes = 0, 0 | |
1378 | if line.startswith('diff --git'): |
|
1380 | if line.startswith('diff --git'): | |
1379 | filename = gitre.search(line).group(1) |
|
1381 | filename = gitre.search(line).group(1) | |
1380 | else: |
|
1382 | else: | |
1381 | # format: "diff -r ... -r ... filename" |
|
1383 | # format: "diff -r ... -r ... filename" | |
1382 | filename = line.split(None, 5)[-1] |
|
1384 | filename = line.split(None, 5)[-1] | |
1383 | elif line.startswith('+') and not line.startswith('+++'): |
|
1385 | elif line.startswith('+') and not line.startswith('+++'): | |
1384 | adds += 1 |
|
1386 | adds += 1 | |
1385 | elif line.startswith('-') and not line.startswith('---'): |
|
1387 | elif line.startswith('-') and not line.startswith('---'): | |
1386 | removes += 1 |
|
1388 | removes += 1 | |
1387 | if filename: |
|
1389 | if filename: | |
1388 | isbinary = adds == 0 and removes == 0 |
|
1390 | isbinary = adds == 0 and removes == 0 | |
1389 | yield (filename, adds, removes, isbinary) |
|
1391 | yield (filename, adds, removes, isbinary) | |
1390 |
|
1392 | |||
1391 | def diffstat(lines, width=80, git=False): |
|
1393 | def diffstat(lines, width=80, git=False): | |
1392 | output = [] |
|
1394 | output = [] | |
1393 | stats = list(diffstatdata(lines)) |
|
1395 | stats = list(diffstatdata(lines)) | |
1394 |
|
1396 | |||
1395 | maxtotal, maxname = 0, 0 |
|
1397 | maxtotal, maxname = 0, 0 | |
1396 | totaladds, totalremoves = 0, 0 |
|
1398 | totaladds, totalremoves = 0, 0 | |
1397 | hasbinary = False |
|
1399 | hasbinary = False | |
1398 | for filename, adds, removes, isbinary in stats: |
|
1400 | for filename, adds, removes, isbinary in stats: | |
1399 | totaladds += adds |
|
1401 | totaladds += adds | |
1400 | totalremoves += removes |
|
1402 | totalremoves += removes | |
1401 | maxname = max(maxname, len(filename)) |
|
1403 | maxname = max(maxname, len(filename)) | |
1402 | maxtotal = max(maxtotal, adds+removes) |
|
1404 | maxtotal = max(maxtotal, adds+removes) | |
1403 | if isbinary: |
|
1405 | if isbinary: | |
1404 | hasbinary = True |
|
1406 | hasbinary = True | |
1405 |
|
1407 | |||
1406 | countwidth = len(str(maxtotal)) |
|
1408 | countwidth = len(str(maxtotal)) | |
1407 | if hasbinary and countwidth < 3: |
|
1409 | if hasbinary and countwidth < 3: | |
1408 | countwidth = 3 |
|
1410 | countwidth = 3 | |
1409 | graphwidth = width - countwidth - maxname - 6 |
|
1411 | graphwidth = width - countwidth - maxname - 6 | |
1410 | if graphwidth < 10: |
|
1412 | if graphwidth < 10: | |
1411 | graphwidth = 10 |
|
1413 | graphwidth = 10 | |
1412 |
|
1414 | |||
1413 | def scale(i): |
|
1415 | def scale(i): | |
1414 | if maxtotal <= graphwidth: |
|
1416 | if maxtotal <= graphwidth: | |
1415 | return i |
|
1417 | return i | |
1416 | # If diffstat runs out of room it doesn't print anything, |
|
1418 | # If diffstat runs out of room it doesn't print anything, | |
1417 | # which isn't very useful, so always print at least one + or - |
|
1419 | # which isn't very useful, so always print at least one + or - | |
1418 | # if there were at least some changes. |
|
1420 | # if there were at least some changes. | |
1419 | return max(i * graphwidth // maxtotal, int(bool(i))) |
|
1421 | return max(i * graphwidth // maxtotal, int(bool(i))) | |
1420 |
|
1422 | |||
1421 | for filename, adds, removes, isbinary in stats: |
|
1423 | for filename, adds, removes, isbinary in stats: | |
1422 | if git and isbinary: |
|
1424 | if git and isbinary: | |
1423 | count = 'Bin' |
|
1425 | count = 'Bin' | |
1424 | else: |
|
1426 | else: | |
1425 | count = adds + removes |
|
1427 | count = adds + removes | |
1426 | pluses = '+' * scale(adds) |
|
1428 | pluses = '+' * scale(adds) | |
1427 | minuses = '-' * scale(removes) |
|
1429 | minuses = '-' * scale(removes) | |
1428 | output.append(' %-*s | %*s %s%s\n' % (maxname, filename, countwidth, |
|
1430 | output.append(' %-*s | %*s %s%s\n' % (maxname, filename, countwidth, | |
1429 | count, pluses, minuses)) |
|
1431 | count, pluses, minuses)) | |
1430 |
|
1432 | |||
1431 | if stats: |
|
1433 | if stats: | |
1432 | output.append(_(' %d files changed, %d insertions(+), %d deletions(-)\n') |
|
1434 | output.append(_(' %d files changed, %d insertions(+), %d deletions(-)\n') | |
1433 | % (len(stats), totaladds, totalremoves)) |
|
1435 | % (len(stats), totaladds, totalremoves)) | |
1434 |
|
1436 | |||
1435 | return ''.join(output) |
|
1437 | return ''.join(output) |
General Comments 0
You need to be logged in to leave comments.
Login now