##// END OF EJS Templates
patch: fix patch hunk/metdata synchronization (issue3384)...
Patrick Mezard -
r16506:fc4e0fec stable
parent child Browse files
Show More
@@ -1,1867 +1,1879 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 or any later version.
7 # GNU General Public License version 2 or any later version.
8
8
9 import cStringIO, email.Parser, os, errno, re
9 import cStringIO, email.Parser, os, errno, re
10 import tempfile, zlib, shutil
10 import tempfile, zlib, shutil
11
11
12 from i18n import _
12 from i18n import _
13 from node import hex, nullid, short
13 from node import hex, nullid, short
14 import base85, mdiff, scmutil, util, diffhelpers, copies, encoding, error
14 import base85, mdiff, scmutil, util, diffhelpers, copies, encoding, error
15 import context
15 import context
16
16
17 gitre = re.compile('diff --git a/(.*) b/(.*)')
17 gitre = re.compile('diff --git a/(.*) b/(.*)')
18
18
19 class PatchError(Exception):
19 class PatchError(Exception):
20 pass
20 pass
21
21
22
22
23 # public functions
23 # public functions
24
24
25 def split(stream):
25 def split(stream):
26 '''return an iterator of individual patches from a stream'''
26 '''return an iterator of individual patches from a stream'''
27 def isheader(line, inheader):
27 def isheader(line, inheader):
28 if inheader and line[0] in (' ', '\t'):
28 if inheader and line[0] in (' ', '\t'):
29 # continuation
29 # continuation
30 return True
30 return True
31 if line[0] in (' ', '-', '+'):
31 if line[0] in (' ', '-', '+'):
32 # diff line - don't check for header pattern in there
32 # diff line - don't check for header pattern in there
33 return False
33 return False
34 l = line.split(': ', 1)
34 l = line.split(': ', 1)
35 return len(l) == 2 and ' ' not in l[0]
35 return len(l) == 2 and ' ' not in l[0]
36
36
37 def chunk(lines):
37 def chunk(lines):
38 return cStringIO.StringIO(''.join(lines))
38 return cStringIO.StringIO(''.join(lines))
39
39
40 def hgsplit(stream, cur):
40 def hgsplit(stream, cur):
41 inheader = True
41 inheader = True
42
42
43 for line in stream:
43 for line in stream:
44 if not line.strip():
44 if not line.strip():
45 inheader = False
45 inheader = False
46 if not inheader and line.startswith('# HG changeset patch'):
46 if not inheader and line.startswith('# HG changeset patch'):
47 yield chunk(cur)
47 yield chunk(cur)
48 cur = []
48 cur = []
49 inheader = True
49 inheader = True
50
50
51 cur.append(line)
51 cur.append(line)
52
52
53 if cur:
53 if cur:
54 yield chunk(cur)
54 yield chunk(cur)
55
55
56 def mboxsplit(stream, cur):
56 def mboxsplit(stream, cur):
57 for line in stream:
57 for line in stream:
58 if line.startswith('From '):
58 if line.startswith('From '):
59 for c in split(chunk(cur[1:])):
59 for c in split(chunk(cur[1:])):
60 yield c
60 yield c
61 cur = []
61 cur = []
62
62
63 cur.append(line)
63 cur.append(line)
64
64
65 if cur:
65 if cur:
66 for c in split(chunk(cur[1:])):
66 for c in split(chunk(cur[1:])):
67 yield c
67 yield c
68
68
69 def mimesplit(stream, cur):
69 def mimesplit(stream, cur):
70 def msgfp(m):
70 def msgfp(m):
71 fp = cStringIO.StringIO()
71 fp = cStringIO.StringIO()
72 g = email.Generator.Generator(fp, mangle_from_=False)
72 g = email.Generator.Generator(fp, mangle_from_=False)
73 g.flatten(m)
73 g.flatten(m)
74 fp.seek(0)
74 fp.seek(0)
75 return fp
75 return fp
76
76
77 for line in stream:
77 for line in stream:
78 cur.append(line)
78 cur.append(line)
79 c = chunk(cur)
79 c = chunk(cur)
80
80
81 m = email.Parser.Parser().parse(c)
81 m = email.Parser.Parser().parse(c)
82 if not m.is_multipart():
82 if not m.is_multipart():
83 yield msgfp(m)
83 yield msgfp(m)
84 else:
84 else:
85 ok_types = ('text/plain', 'text/x-diff', 'text/x-patch')
85 ok_types = ('text/plain', 'text/x-diff', 'text/x-patch')
86 for part in m.walk():
86 for part in m.walk():
87 ct = part.get_content_type()
87 ct = part.get_content_type()
88 if ct not in ok_types:
88 if ct not in ok_types:
89 continue
89 continue
90 yield msgfp(part)
90 yield msgfp(part)
91
91
92 def headersplit(stream, cur):
92 def headersplit(stream, cur):
93 inheader = False
93 inheader = False
94
94
95 for line in stream:
95 for line in stream:
96 if not inheader and isheader(line, inheader):
96 if not inheader and isheader(line, inheader):
97 yield chunk(cur)
97 yield chunk(cur)
98 cur = []
98 cur = []
99 inheader = True
99 inheader = True
100 if inheader and not isheader(line, inheader):
100 if inheader and not isheader(line, inheader):
101 inheader = False
101 inheader = False
102
102
103 cur.append(line)
103 cur.append(line)
104
104
105 if cur:
105 if cur:
106 yield chunk(cur)
106 yield chunk(cur)
107
107
108 def remainder(cur):
108 def remainder(cur):
109 yield chunk(cur)
109 yield chunk(cur)
110
110
111 class fiter(object):
111 class fiter(object):
112 def __init__(self, fp):
112 def __init__(self, fp):
113 self.fp = fp
113 self.fp = fp
114
114
115 def __iter__(self):
115 def __iter__(self):
116 return self
116 return self
117
117
118 def next(self):
118 def next(self):
119 l = self.fp.readline()
119 l = self.fp.readline()
120 if not l:
120 if not l:
121 raise StopIteration
121 raise StopIteration
122 return l
122 return l
123
123
124 inheader = False
124 inheader = False
125 cur = []
125 cur = []
126
126
127 mimeheaders = ['content-type']
127 mimeheaders = ['content-type']
128
128
129 if not util.safehasattr(stream, 'next'):
129 if not util.safehasattr(stream, 'next'):
130 # http responses, for example, have readline but not next
130 # http responses, for example, have readline but not next
131 stream = fiter(stream)
131 stream = fiter(stream)
132
132
133 for line in stream:
133 for line in stream:
134 cur.append(line)
134 cur.append(line)
135 if line.startswith('# HG changeset patch'):
135 if line.startswith('# HG changeset patch'):
136 return hgsplit(stream, cur)
136 return hgsplit(stream, cur)
137 elif line.startswith('From '):
137 elif line.startswith('From '):
138 return mboxsplit(stream, cur)
138 return mboxsplit(stream, cur)
139 elif isheader(line, inheader):
139 elif isheader(line, inheader):
140 inheader = True
140 inheader = True
141 if line.split(':', 1)[0].lower() in mimeheaders:
141 if line.split(':', 1)[0].lower() in mimeheaders:
142 # let email parser handle this
142 # let email parser handle this
143 return mimesplit(stream, cur)
143 return mimesplit(stream, cur)
144 elif line.startswith('--- ') and inheader:
144 elif line.startswith('--- ') and inheader:
145 # No evil headers seen by diff start, split by hand
145 # No evil headers seen by diff start, split by hand
146 return headersplit(stream, cur)
146 return headersplit(stream, cur)
147 # Not enough info, keep reading
147 # Not enough info, keep reading
148
148
149 # if we are here, we have a very plain patch
149 # if we are here, we have a very plain patch
150 return remainder(cur)
150 return remainder(cur)
151
151
152 def extract(ui, fileobj):
152 def extract(ui, fileobj):
153 '''extract patch from data read from fileobj.
153 '''extract patch from data read from fileobj.
154
154
155 patch can be a normal patch or contained in an email message.
155 patch can be a normal patch or contained in an email message.
156
156
157 return tuple (filename, message, user, date, branch, node, p1, p2).
157 return tuple (filename, message, user, date, branch, node, p1, p2).
158 Any item in the returned tuple can be None. If filename is None,
158 Any item in the returned tuple can be None. If filename is None,
159 fileobj did not contain a patch. Caller must unlink filename when done.'''
159 fileobj did not contain a patch. Caller must unlink filename when done.'''
160
160
161 # attempt to detect the start of a patch
161 # attempt to detect the start of a patch
162 # (this heuristic is borrowed from quilt)
162 # (this heuristic is borrowed from quilt)
163 diffre = re.compile(r'^(?:Index:[ \t]|diff[ \t]|RCS file: |'
163 diffre = re.compile(r'^(?:Index:[ \t]|diff[ \t]|RCS file: |'
164 r'retrieving revision [0-9]+(\.[0-9]+)*$|'
164 r'retrieving revision [0-9]+(\.[0-9]+)*$|'
165 r'---[ \t].*?^\+\+\+[ \t]|'
165 r'---[ \t].*?^\+\+\+[ \t]|'
166 r'\*\*\*[ \t].*?^---[ \t])', re.MULTILINE|re.DOTALL)
166 r'\*\*\*[ \t].*?^---[ \t])', re.MULTILINE|re.DOTALL)
167
167
168 fd, tmpname = tempfile.mkstemp(prefix='hg-patch-')
168 fd, tmpname = tempfile.mkstemp(prefix='hg-patch-')
169 tmpfp = os.fdopen(fd, 'w')
169 tmpfp = os.fdopen(fd, 'w')
170 try:
170 try:
171 msg = email.Parser.Parser().parse(fileobj)
171 msg = email.Parser.Parser().parse(fileobj)
172
172
173 subject = msg['Subject']
173 subject = msg['Subject']
174 user = msg['From']
174 user = msg['From']
175 if not subject and not user:
175 if not subject and not user:
176 # Not an email, restore parsed headers if any
176 # Not an email, restore parsed headers if any
177 subject = '\n'.join(': '.join(h) for h in msg.items()) + '\n'
177 subject = '\n'.join(': '.join(h) for h in msg.items()) + '\n'
178
178
179 gitsendmail = 'git-send-email' in msg.get('X-Mailer', '')
179 gitsendmail = 'git-send-email' in msg.get('X-Mailer', '')
180 # should try to parse msg['Date']
180 # should try to parse msg['Date']
181 date = None
181 date = None
182 nodeid = None
182 nodeid = None
183 branch = None
183 branch = None
184 parents = []
184 parents = []
185
185
186 if subject:
186 if subject:
187 if subject.startswith('[PATCH'):
187 if subject.startswith('[PATCH'):
188 pend = subject.find(']')
188 pend = subject.find(']')
189 if pend >= 0:
189 if pend >= 0:
190 subject = subject[pend + 1:].lstrip()
190 subject = subject[pend + 1:].lstrip()
191 subject = re.sub(r'\n[ \t]+', ' ', subject)
191 subject = re.sub(r'\n[ \t]+', ' ', subject)
192 ui.debug('Subject: %s\n' % subject)
192 ui.debug('Subject: %s\n' % subject)
193 if user:
193 if user:
194 ui.debug('From: %s\n' % user)
194 ui.debug('From: %s\n' % user)
195 diffs_seen = 0
195 diffs_seen = 0
196 ok_types = ('text/plain', 'text/x-diff', 'text/x-patch')
196 ok_types = ('text/plain', 'text/x-diff', 'text/x-patch')
197 message = ''
197 message = ''
198 for part in msg.walk():
198 for part in msg.walk():
199 content_type = part.get_content_type()
199 content_type = part.get_content_type()
200 ui.debug('Content-Type: %s\n' % content_type)
200 ui.debug('Content-Type: %s\n' % content_type)
201 if content_type not in ok_types:
201 if content_type not in ok_types:
202 continue
202 continue
203 payload = part.get_payload(decode=True)
203 payload = part.get_payload(decode=True)
204 m = diffre.search(payload)
204 m = diffre.search(payload)
205 if m:
205 if m:
206 hgpatch = False
206 hgpatch = False
207 hgpatchheader = False
207 hgpatchheader = False
208 ignoretext = False
208 ignoretext = False
209
209
210 ui.debug('found patch at byte %d\n' % m.start(0))
210 ui.debug('found patch at byte %d\n' % m.start(0))
211 diffs_seen += 1
211 diffs_seen += 1
212 cfp = cStringIO.StringIO()
212 cfp = cStringIO.StringIO()
213 for line in payload[:m.start(0)].splitlines():
213 for line in payload[:m.start(0)].splitlines():
214 if line.startswith('# HG changeset patch') and not hgpatch:
214 if line.startswith('# HG changeset patch') and not hgpatch:
215 ui.debug('patch generated by hg export\n')
215 ui.debug('patch generated by hg export\n')
216 hgpatch = True
216 hgpatch = True
217 hgpatchheader = True
217 hgpatchheader = True
218 # drop earlier commit message content
218 # drop earlier commit message content
219 cfp.seek(0)
219 cfp.seek(0)
220 cfp.truncate()
220 cfp.truncate()
221 subject = None
221 subject = None
222 elif hgpatchheader:
222 elif hgpatchheader:
223 if line.startswith('# User '):
223 if line.startswith('# User '):
224 user = line[7:]
224 user = line[7:]
225 ui.debug('From: %s\n' % user)
225 ui.debug('From: %s\n' % user)
226 elif line.startswith("# Date "):
226 elif line.startswith("# Date "):
227 date = line[7:]
227 date = line[7:]
228 elif line.startswith("# Branch "):
228 elif line.startswith("# Branch "):
229 branch = line[9:]
229 branch = line[9:]
230 elif line.startswith("# Node ID "):
230 elif line.startswith("# Node ID "):
231 nodeid = line[10:]
231 nodeid = line[10:]
232 elif line.startswith("# Parent "):
232 elif line.startswith("# Parent "):
233 parents.append(line[9:].lstrip())
233 parents.append(line[9:].lstrip())
234 elif not line.startswith("# "):
234 elif not line.startswith("# "):
235 hgpatchheader = False
235 hgpatchheader = False
236 elif line == '---' and gitsendmail:
236 elif line == '---' and gitsendmail:
237 ignoretext = True
237 ignoretext = True
238 if not hgpatchheader and not ignoretext:
238 if not hgpatchheader and not ignoretext:
239 cfp.write(line)
239 cfp.write(line)
240 cfp.write('\n')
240 cfp.write('\n')
241 message = cfp.getvalue()
241 message = cfp.getvalue()
242 if tmpfp:
242 if tmpfp:
243 tmpfp.write(payload)
243 tmpfp.write(payload)
244 if not payload.endswith('\n'):
244 if not payload.endswith('\n'):
245 tmpfp.write('\n')
245 tmpfp.write('\n')
246 elif not diffs_seen and message and content_type == 'text/plain':
246 elif not diffs_seen and message and content_type == 'text/plain':
247 message += '\n' + payload
247 message += '\n' + payload
248 except:
248 except:
249 tmpfp.close()
249 tmpfp.close()
250 os.unlink(tmpname)
250 os.unlink(tmpname)
251 raise
251 raise
252
252
253 if subject and not message.startswith(subject):
253 if subject and not message.startswith(subject):
254 message = '%s\n%s' % (subject, message)
254 message = '%s\n%s' % (subject, message)
255 tmpfp.close()
255 tmpfp.close()
256 if not diffs_seen:
256 if not diffs_seen:
257 os.unlink(tmpname)
257 os.unlink(tmpname)
258 return None, message, user, date, branch, None, None, None
258 return None, message, user, date, branch, None, None, None
259 p1 = parents and parents.pop(0) or None
259 p1 = parents and parents.pop(0) or None
260 p2 = parents and parents.pop(0) or None
260 p2 = parents and parents.pop(0) or None
261 return tmpname, message, user, date, branch, nodeid, p1, p2
261 return tmpname, message, user, date, branch, nodeid, p1, p2
262
262
263 class patchmeta(object):
263 class patchmeta(object):
264 """Patched file metadata
264 """Patched file metadata
265
265
266 'op' is the performed operation within ADD, DELETE, RENAME, MODIFY
266 'op' is the performed operation within ADD, DELETE, RENAME, MODIFY
267 or COPY. 'path' is patched file path. 'oldpath' is set to the
267 or COPY. 'path' is patched file path. 'oldpath' is set to the
268 origin file when 'op' is either COPY or RENAME, None otherwise. If
268 origin file when 'op' is either COPY or RENAME, None otherwise. If
269 file mode is changed, 'mode' is a tuple (islink, isexec) where
269 file mode is changed, 'mode' is a tuple (islink, isexec) where
270 'islink' is True if the file is a symlink and 'isexec' is True if
270 'islink' is True if the file is a symlink and 'isexec' is True if
271 the file is executable. Otherwise, 'mode' is None.
271 the file is executable. Otherwise, 'mode' is None.
272 """
272 """
273 def __init__(self, path):
273 def __init__(self, path):
274 self.path = path
274 self.path = path
275 self.oldpath = None
275 self.oldpath = None
276 self.mode = None
276 self.mode = None
277 self.op = 'MODIFY'
277 self.op = 'MODIFY'
278 self.binary = False
278 self.binary = False
279
279
280 def setmode(self, mode):
280 def setmode(self, mode):
281 islink = mode & 020000
281 islink = mode & 020000
282 isexec = mode & 0100
282 isexec = mode & 0100
283 self.mode = (islink, isexec)
283 self.mode = (islink, isexec)
284
284
285 def copy(self):
285 def copy(self):
286 other = patchmeta(self.path)
286 other = patchmeta(self.path)
287 other.oldpath = self.oldpath
287 other.oldpath = self.oldpath
288 other.mode = self.mode
288 other.mode = self.mode
289 other.op = self.op
289 other.op = self.op
290 other.binary = self.binary
290 other.binary = self.binary
291 return other
291 return other
292
292
293 def _ispatchinga(self, afile):
294 if afile == '/dev/null':
295 return self.op == 'ADD'
296 return afile == 'a/' + (self.oldpath or self.path)
297
298 def _ispatchingb(self, bfile):
299 if bfile == '/dev/null':
300 return self.op == 'DELETE'
301 return bfile == 'b/' + self.path
302
303 def ispatching(self, afile, bfile):
304 return self._ispatchinga(afile) and self._ispatchingb(bfile)
305
293 def __repr__(self):
306 def __repr__(self):
294 return "<patchmeta %s %r>" % (self.op, self.path)
307 return "<patchmeta %s %r>" % (self.op, self.path)
295
308
296 def readgitpatch(lr):
309 def readgitpatch(lr):
297 """extract git-style metadata about patches from <patchname>"""
310 """extract git-style metadata about patches from <patchname>"""
298
311
299 # Filter patch for git information
312 # Filter patch for git information
300 gp = None
313 gp = None
301 gitpatches = []
314 gitpatches = []
302 for line in lr:
315 for line in lr:
303 line = line.rstrip(' \r\n')
316 line = line.rstrip(' \r\n')
304 if line.startswith('diff --git'):
317 if line.startswith('diff --git'):
305 m = gitre.match(line)
318 m = gitre.match(line)
306 if m:
319 if m:
307 if gp:
320 if gp:
308 gitpatches.append(gp)
321 gitpatches.append(gp)
309 dst = m.group(2)
322 dst = m.group(2)
310 gp = patchmeta(dst)
323 gp = patchmeta(dst)
311 elif gp:
324 elif gp:
312 if line.startswith('--- '):
325 if line.startswith('--- '):
313 gitpatches.append(gp)
326 gitpatches.append(gp)
314 gp = None
327 gp = None
315 continue
328 continue
316 if line.startswith('rename from '):
329 if line.startswith('rename from '):
317 gp.op = 'RENAME'
330 gp.op = 'RENAME'
318 gp.oldpath = line[12:]
331 gp.oldpath = line[12:]
319 elif line.startswith('rename to '):
332 elif line.startswith('rename to '):
320 gp.path = line[10:]
333 gp.path = line[10:]
321 elif line.startswith('copy from '):
334 elif line.startswith('copy from '):
322 gp.op = 'COPY'
335 gp.op = 'COPY'
323 gp.oldpath = line[10:]
336 gp.oldpath = line[10:]
324 elif line.startswith('copy to '):
337 elif line.startswith('copy to '):
325 gp.path = line[8:]
338 gp.path = line[8:]
326 elif line.startswith('deleted file'):
339 elif line.startswith('deleted file'):
327 gp.op = 'DELETE'
340 gp.op = 'DELETE'
328 elif line.startswith('new file mode '):
341 elif line.startswith('new file mode '):
329 gp.op = 'ADD'
342 gp.op = 'ADD'
330 gp.setmode(int(line[-6:], 8))
343 gp.setmode(int(line[-6:], 8))
331 elif line.startswith('new mode '):
344 elif line.startswith('new mode '):
332 gp.setmode(int(line[-6:], 8))
345 gp.setmode(int(line[-6:], 8))
333 elif line.startswith('GIT binary patch'):
346 elif line.startswith('GIT binary patch'):
334 gp.binary = True
347 gp.binary = True
335 if gp:
348 if gp:
336 gitpatches.append(gp)
349 gitpatches.append(gp)
337
350
338 return gitpatches
351 return gitpatches
339
352
340 class linereader(object):
353 class linereader(object):
341 # simple class to allow pushing lines back into the input stream
354 # simple class to allow pushing lines back into the input stream
342 def __init__(self, fp):
355 def __init__(self, fp):
343 self.fp = fp
356 self.fp = fp
344 self.buf = []
357 self.buf = []
345
358
346 def push(self, line):
359 def push(self, line):
347 if line is not None:
360 if line is not None:
348 self.buf.append(line)
361 self.buf.append(line)
349
362
350 def readline(self):
363 def readline(self):
351 if self.buf:
364 if self.buf:
352 l = self.buf[0]
365 l = self.buf[0]
353 del self.buf[0]
366 del self.buf[0]
354 return l
367 return l
355 return self.fp.readline()
368 return self.fp.readline()
356
369
357 def __iter__(self):
370 def __iter__(self):
358 while True:
371 while True:
359 l = self.readline()
372 l = self.readline()
360 if not l:
373 if not l:
361 break
374 break
362 yield l
375 yield l
363
376
364 class abstractbackend(object):
377 class abstractbackend(object):
365 def __init__(self, ui):
378 def __init__(self, ui):
366 self.ui = ui
379 self.ui = ui
367
380
368 def getfile(self, fname):
381 def getfile(self, fname):
369 """Return target file data and flags as a (data, (islink,
382 """Return target file data and flags as a (data, (islink,
370 isexec)) tuple.
383 isexec)) tuple.
371 """
384 """
372 raise NotImplementedError
385 raise NotImplementedError
373
386
374 def setfile(self, fname, data, mode, copysource):
387 def setfile(self, fname, data, mode, copysource):
375 """Write data to target file fname and set its mode. mode is a
388 """Write data to target file fname and set its mode. mode is a
376 (islink, isexec) tuple. If data is None, the file content should
389 (islink, isexec) tuple. If data is None, the file content should
377 be left unchanged. If the file is modified after being copied,
390 be left unchanged. If the file is modified after being copied,
378 copysource is set to the original file name.
391 copysource is set to the original file name.
379 """
392 """
380 raise NotImplementedError
393 raise NotImplementedError
381
394
382 def unlink(self, fname):
395 def unlink(self, fname):
383 """Unlink target file."""
396 """Unlink target file."""
384 raise NotImplementedError
397 raise NotImplementedError
385
398
386 def writerej(self, fname, failed, total, lines):
399 def writerej(self, fname, failed, total, lines):
387 """Write rejected lines for fname. total is the number of hunks
400 """Write rejected lines for fname. total is the number of hunks
388 which failed to apply and total the total number of hunks for this
401 which failed to apply and total the total number of hunks for this
389 files.
402 files.
390 """
403 """
391 pass
404 pass
392
405
393 def exists(self, fname):
406 def exists(self, fname):
394 raise NotImplementedError
407 raise NotImplementedError
395
408
396 class fsbackend(abstractbackend):
409 class fsbackend(abstractbackend):
397 def __init__(self, ui, basedir):
410 def __init__(self, ui, basedir):
398 super(fsbackend, self).__init__(ui)
411 super(fsbackend, self).__init__(ui)
399 self.opener = scmutil.opener(basedir)
412 self.opener = scmutil.opener(basedir)
400
413
401 def _join(self, f):
414 def _join(self, f):
402 return os.path.join(self.opener.base, f)
415 return os.path.join(self.opener.base, f)
403
416
404 def getfile(self, fname):
417 def getfile(self, fname):
405 path = self._join(fname)
418 path = self._join(fname)
406 if os.path.islink(path):
419 if os.path.islink(path):
407 return (os.readlink(path), (True, False))
420 return (os.readlink(path), (True, False))
408 isexec = False
421 isexec = False
409 try:
422 try:
410 isexec = os.lstat(path).st_mode & 0100 != 0
423 isexec = os.lstat(path).st_mode & 0100 != 0
411 except OSError, e:
424 except OSError, e:
412 if e.errno != errno.ENOENT:
425 if e.errno != errno.ENOENT:
413 raise
426 raise
414 return (self.opener.read(fname), (False, isexec))
427 return (self.opener.read(fname), (False, isexec))
415
428
416 def setfile(self, fname, data, mode, copysource):
429 def setfile(self, fname, data, mode, copysource):
417 islink, isexec = mode
430 islink, isexec = mode
418 if data is None:
431 if data is None:
419 util.setflags(self._join(fname), islink, isexec)
432 util.setflags(self._join(fname), islink, isexec)
420 return
433 return
421 if islink:
434 if islink:
422 self.opener.symlink(data, fname)
435 self.opener.symlink(data, fname)
423 else:
436 else:
424 self.opener.write(fname, data)
437 self.opener.write(fname, data)
425 if isexec:
438 if isexec:
426 util.setflags(self._join(fname), False, True)
439 util.setflags(self._join(fname), False, True)
427
440
428 def unlink(self, fname):
441 def unlink(self, fname):
429 try:
442 try:
430 util.unlinkpath(self._join(fname))
443 util.unlinkpath(self._join(fname))
431 except OSError, inst:
444 except OSError, inst:
432 if inst.errno != errno.ENOENT:
445 if inst.errno != errno.ENOENT:
433 raise
446 raise
434
447
435 def writerej(self, fname, failed, total, lines):
448 def writerej(self, fname, failed, total, lines):
436 fname = fname + ".rej"
449 fname = fname + ".rej"
437 self.ui.warn(
450 self.ui.warn(
438 _("%d out of %d hunks FAILED -- saving rejects to file %s\n") %
451 _("%d out of %d hunks FAILED -- saving rejects to file %s\n") %
439 (failed, total, fname))
452 (failed, total, fname))
440 fp = self.opener(fname, 'w')
453 fp = self.opener(fname, 'w')
441 fp.writelines(lines)
454 fp.writelines(lines)
442 fp.close()
455 fp.close()
443
456
444 def exists(self, fname):
457 def exists(self, fname):
445 return os.path.lexists(self._join(fname))
458 return os.path.lexists(self._join(fname))
446
459
447 class workingbackend(fsbackend):
460 class workingbackend(fsbackend):
448 def __init__(self, ui, repo, similarity):
461 def __init__(self, ui, repo, similarity):
449 super(workingbackend, self).__init__(ui, repo.root)
462 super(workingbackend, self).__init__(ui, repo.root)
450 self.repo = repo
463 self.repo = repo
451 self.similarity = similarity
464 self.similarity = similarity
452 self.removed = set()
465 self.removed = set()
453 self.changed = set()
466 self.changed = set()
454 self.copied = []
467 self.copied = []
455
468
456 def _checkknown(self, fname):
469 def _checkknown(self, fname):
457 if self.repo.dirstate[fname] == '?' and self.exists(fname):
470 if self.repo.dirstate[fname] == '?' and self.exists(fname):
458 raise PatchError(_('cannot patch %s: file is not tracked') % fname)
471 raise PatchError(_('cannot patch %s: file is not tracked') % fname)
459
472
460 def setfile(self, fname, data, mode, copysource):
473 def setfile(self, fname, data, mode, copysource):
461 self._checkknown(fname)
474 self._checkknown(fname)
462 super(workingbackend, self).setfile(fname, data, mode, copysource)
475 super(workingbackend, self).setfile(fname, data, mode, copysource)
463 if copysource is not None:
476 if copysource is not None:
464 self.copied.append((copysource, fname))
477 self.copied.append((copysource, fname))
465 self.changed.add(fname)
478 self.changed.add(fname)
466
479
467 def unlink(self, fname):
480 def unlink(self, fname):
468 self._checkknown(fname)
481 self._checkknown(fname)
469 super(workingbackend, self).unlink(fname)
482 super(workingbackend, self).unlink(fname)
470 self.removed.add(fname)
483 self.removed.add(fname)
471 self.changed.add(fname)
484 self.changed.add(fname)
472
485
473 def close(self):
486 def close(self):
474 wctx = self.repo[None]
487 wctx = self.repo[None]
475 addremoved = set(self.changed)
488 addremoved = set(self.changed)
476 for src, dst in self.copied:
489 for src, dst in self.copied:
477 scmutil.dirstatecopy(self.ui, self.repo, wctx, src, dst)
490 scmutil.dirstatecopy(self.ui, self.repo, wctx, src, dst)
478 if self.removed:
491 if self.removed:
479 wctx.forget(sorted(self.removed))
492 wctx.forget(sorted(self.removed))
480 for f in self.removed:
493 for f in self.removed:
481 if f not in self.repo.dirstate:
494 if f not in self.repo.dirstate:
482 # File was deleted and no longer belongs to the
495 # File was deleted and no longer belongs to the
483 # dirstate, it was probably marked added then
496 # dirstate, it was probably marked added then
484 # deleted, and should not be considered by
497 # deleted, and should not be considered by
485 # addremove().
498 # addremove().
486 addremoved.discard(f)
499 addremoved.discard(f)
487 if addremoved:
500 if addremoved:
488 cwd = self.repo.getcwd()
501 cwd = self.repo.getcwd()
489 if cwd:
502 if cwd:
490 addremoved = [util.pathto(self.repo.root, cwd, f)
503 addremoved = [util.pathto(self.repo.root, cwd, f)
491 for f in addremoved]
504 for f in addremoved]
492 scmutil.addremove(self.repo, addremoved, similarity=self.similarity)
505 scmutil.addremove(self.repo, addremoved, similarity=self.similarity)
493 return sorted(self.changed)
506 return sorted(self.changed)
494
507
495 class filestore(object):
508 class filestore(object):
496 def __init__(self, maxsize=None):
509 def __init__(self, maxsize=None):
497 self.opener = None
510 self.opener = None
498 self.files = {}
511 self.files = {}
499 self.created = 0
512 self.created = 0
500 self.maxsize = maxsize
513 self.maxsize = maxsize
501 if self.maxsize is None:
514 if self.maxsize is None:
502 self.maxsize = 4*(2**20)
515 self.maxsize = 4*(2**20)
503 self.size = 0
516 self.size = 0
504 self.data = {}
517 self.data = {}
505
518
506 def setfile(self, fname, data, mode, copied=None):
519 def setfile(self, fname, data, mode, copied=None):
507 if self.maxsize < 0 or (len(data) + self.size) <= self.maxsize:
520 if self.maxsize < 0 or (len(data) + self.size) <= self.maxsize:
508 self.data[fname] = (data, mode, copied)
521 self.data[fname] = (data, mode, copied)
509 self.size += len(data)
522 self.size += len(data)
510 else:
523 else:
511 if self.opener is None:
524 if self.opener is None:
512 root = tempfile.mkdtemp(prefix='hg-patch-')
525 root = tempfile.mkdtemp(prefix='hg-patch-')
513 self.opener = scmutil.opener(root)
526 self.opener = scmutil.opener(root)
514 # Avoid filename issues with these simple names
527 # Avoid filename issues with these simple names
515 fn = str(self.created)
528 fn = str(self.created)
516 self.opener.write(fn, data)
529 self.opener.write(fn, data)
517 self.created += 1
530 self.created += 1
518 self.files[fname] = (fn, mode, copied)
531 self.files[fname] = (fn, mode, copied)
519
532
520 def getfile(self, fname):
533 def getfile(self, fname):
521 if fname in self.data:
534 if fname in self.data:
522 return self.data[fname]
535 return self.data[fname]
523 if not self.opener or fname not in self.files:
536 if not self.opener or fname not in self.files:
524 raise IOError()
537 raise IOError()
525 fn, mode, copied = self.files[fname]
538 fn, mode, copied = self.files[fname]
526 return self.opener.read(fn), mode, copied
539 return self.opener.read(fn), mode, copied
527
540
528 def close(self):
541 def close(self):
529 if self.opener:
542 if self.opener:
530 shutil.rmtree(self.opener.base)
543 shutil.rmtree(self.opener.base)
531
544
532 class repobackend(abstractbackend):
545 class repobackend(abstractbackend):
533 def __init__(self, ui, repo, ctx, store):
546 def __init__(self, ui, repo, ctx, store):
534 super(repobackend, self).__init__(ui)
547 super(repobackend, self).__init__(ui)
535 self.repo = repo
548 self.repo = repo
536 self.ctx = ctx
549 self.ctx = ctx
537 self.store = store
550 self.store = store
538 self.changed = set()
551 self.changed = set()
539 self.removed = set()
552 self.removed = set()
540 self.copied = {}
553 self.copied = {}
541
554
542 def _checkknown(self, fname):
555 def _checkknown(self, fname):
543 if fname not in self.ctx:
556 if fname not in self.ctx:
544 raise PatchError(_('cannot patch %s: file is not tracked') % fname)
557 raise PatchError(_('cannot patch %s: file is not tracked') % fname)
545
558
546 def getfile(self, fname):
559 def getfile(self, fname):
547 try:
560 try:
548 fctx = self.ctx[fname]
561 fctx = self.ctx[fname]
549 except error.LookupError:
562 except error.LookupError:
550 raise IOError()
563 raise IOError()
551 flags = fctx.flags()
564 flags = fctx.flags()
552 return fctx.data(), ('l' in flags, 'x' in flags)
565 return fctx.data(), ('l' in flags, 'x' in flags)
553
566
554 def setfile(self, fname, data, mode, copysource):
567 def setfile(self, fname, data, mode, copysource):
555 if copysource:
568 if copysource:
556 self._checkknown(copysource)
569 self._checkknown(copysource)
557 if data is None:
570 if data is None:
558 data = self.ctx[fname].data()
571 data = self.ctx[fname].data()
559 self.store.setfile(fname, data, mode, copysource)
572 self.store.setfile(fname, data, mode, copysource)
560 self.changed.add(fname)
573 self.changed.add(fname)
561 if copysource:
574 if copysource:
562 self.copied[fname] = copysource
575 self.copied[fname] = copysource
563
576
564 def unlink(self, fname):
577 def unlink(self, fname):
565 self._checkknown(fname)
578 self._checkknown(fname)
566 self.removed.add(fname)
579 self.removed.add(fname)
567
580
568 def exists(self, fname):
581 def exists(self, fname):
569 return fname in self.ctx
582 return fname in self.ctx
570
583
571 def close(self):
584 def close(self):
572 return self.changed | self.removed
585 return self.changed | self.removed
573
586
574 # @@ -start,len +start,len @@ or @@ -start +start @@ if len is 1
587 # @@ -start,len +start,len @@ or @@ -start +start @@ if len is 1
575 unidesc = re.compile('@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@')
588 unidesc = re.compile('@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@')
576 contextdesc = re.compile('(?:---|\*\*\*) (\d+)(?:,(\d+))? (?:---|\*\*\*)')
589 contextdesc = re.compile('(?:---|\*\*\*) (\d+)(?:,(\d+))? (?:---|\*\*\*)')
577 eolmodes = ['strict', 'crlf', 'lf', 'auto']
590 eolmodes = ['strict', 'crlf', 'lf', 'auto']
578
591
579 class patchfile(object):
592 class patchfile(object):
580 def __init__(self, ui, gp, backend, store, eolmode='strict'):
593 def __init__(self, ui, gp, backend, store, eolmode='strict'):
581 self.fname = gp.path
594 self.fname = gp.path
582 self.eolmode = eolmode
595 self.eolmode = eolmode
583 self.eol = None
596 self.eol = None
584 self.backend = backend
597 self.backend = backend
585 self.ui = ui
598 self.ui = ui
586 self.lines = []
599 self.lines = []
587 self.exists = False
600 self.exists = False
588 self.missing = True
601 self.missing = True
589 self.mode = gp.mode
602 self.mode = gp.mode
590 self.copysource = gp.oldpath
603 self.copysource = gp.oldpath
591 self.create = gp.op in ('ADD', 'COPY', 'RENAME')
604 self.create = gp.op in ('ADD', 'COPY', 'RENAME')
592 self.remove = gp.op == 'DELETE'
605 self.remove = gp.op == 'DELETE'
593 try:
606 try:
594 if self.copysource is None:
607 if self.copysource is None:
595 data, mode = backend.getfile(self.fname)
608 data, mode = backend.getfile(self.fname)
596 self.exists = True
609 self.exists = True
597 else:
610 else:
598 data, mode = store.getfile(self.copysource)[:2]
611 data, mode = store.getfile(self.copysource)[:2]
599 self.exists = backend.exists(self.fname)
612 self.exists = backend.exists(self.fname)
600 self.missing = False
613 self.missing = False
601 if data:
614 if data:
602 self.lines = mdiff.splitnewlines(data)
615 self.lines = mdiff.splitnewlines(data)
603 if self.mode is None:
616 if self.mode is None:
604 self.mode = mode
617 self.mode = mode
605 if self.lines:
618 if self.lines:
606 # Normalize line endings
619 # Normalize line endings
607 if self.lines[0].endswith('\r\n'):
620 if self.lines[0].endswith('\r\n'):
608 self.eol = '\r\n'
621 self.eol = '\r\n'
609 elif self.lines[0].endswith('\n'):
622 elif self.lines[0].endswith('\n'):
610 self.eol = '\n'
623 self.eol = '\n'
611 if eolmode != 'strict':
624 if eolmode != 'strict':
612 nlines = []
625 nlines = []
613 for l in self.lines:
626 for l in self.lines:
614 if l.endswith('\r\n'):
627 if l.endswith('\r\n'):
615 l = l[:-2] + '\n'
628 l = l[:-2] + '\n'
616 nlines.append(l)
629 nlines.append(l)
617 self.lines = nlines
630 self.lines = nlines
618 except IOError:
631 except IOError:
619 if self.create:
632 if self.create:
620 self.missing = False
633 self.missing = False
621 if self.mode is None:
634 if self.mode is None:
622 self.mode = (False, False)
635 self.mode = (False, False)
623 if self.missing:
636 if self.missing:
624 self.ui.warn(_("unable to find '%s' for patching\n") % self.fname)
637 self.ui.warn(_("unable to find '%s' for patching\n") % self.fname)
625
638
626 self.hash = {}
639 self.hash = {}
627 self.dirty = 0
640 self.dirty = 0
628 self.offset = 0
641 self.offset = 0
629 self.skew = 0
642 self.skew = 0
630 self.rej = []
643 self.rej = []
631 self.fileprinted = False
644 self.fileprinted = False
632 self.printfile(False)
645 self.printfile(False)
633 self.hunks = 0
646 self.hunks = 0
634
647
635 def writelines(self, fname, lines, mode):
648 def writelines(self, fname, lines, mode):
636 if self.eolmode == 'auto':
649 if self.eolmode == 'auto':
637 eol = self.eol
650 eol = self.eol
638 elif self.eolmode == 'crlf':
651 elif self.eolmode == 'crlf':
639 eol = '\r\n'
652 eol = '\r\n'
640 else:
653 else:
641 eol = '\n'
654 eol = '\n'
642
655
643 if self.eolmode != 'strict' and eol and eol != '\n':
656 if self.eolmode != 'strict' and eol and eol != '\n':
644 rawlines = []
657 rawlines = []
645 for l in lines:
658 for l in lines:
646 if l and l[-1] == '\n':
659 if l and l[-1] == '\n':
647 l = l[:-1] + eol
660 l = l[:-1] + eol
648 rawlines.append(l)
661 rawlines.append(l)
649 lines = rawlines
662 lines = rawlines
650
663
651 self.backend.setfile(fname, ''.join(lines), mode, self.copysource)
664 self.backend.setfile(fname, ''.join(lines), mode, self.copysource)
652
665
653 def printfile(self, warn):
666 def printfile(self, warn):
654 if self.fileprinted:
667 if self.fileprinted:
655 return
668 return
656 if warn or self.ui.verbose:
669 if warn or self.ui.verbose:
657 self.fileprinted = True
670 self.fileprinted = True
658 s = _("patching file %s\n") % self.fname
671 s = _("patching file %s\n") % self.fname
659 if warn:
672 if warn:
660 self.ui.warn(s)
673 self.ui.warn(s)
661 else:
674 else:
662 self.ui.note(s)
675 self.ui.note(s)
663
676
664
677
665 def findlines(self, l, linenum):
678 def findlines(self, l, linenum):
666 # looks through the hash and finds candidate lines. The
679 # looks through the hash and finds candidate lines. The
667 # result is a list of line numbers sorted based on distance
680 # result is a list of line numbers sorted based on distance
668 # from linenum
681 # from linenum
669
682
670 cand = self.hash.get(l, [])
683 cand = self.hash.get(l, [])
671 if len(cand) > 1:
684 if len(cand) > 1:
672 # resort our list of potentials forward then back.
685 # resort our list of potentials forward then back.
673 cand.sort(key=lambda x: abs(x - linenum))
686 cand.sort(key=lambda x: abs(x - linenum))
674 return cand
687 return cand
675
688
676 def write_rej(self):
689 def write_rej(self):
677 # our rejects are a little different from patch(1). This always
690 # our rejects are a little different from patch(1). This always
678 # creates rejects in the same form as the original patch. A file
691 # creates rejects in the same form as the original patch. A file
679 # header is inserted so that you can run the reject through patch again
692 # header is inserted so that you can run the reject through patch again
680 # without having to type the filename.
693 # without having to type the filename.
681 if not self.rej:
694 if not self.rej:
682 return
695 return
683 base = os.path.basename(self.fname)
696 base = os.path.basename(self.fname)
684 lines = ["--- %s\n+++ %s\n" % (base, base)]
697 lines = ["--- %s\n+++ %s\n" % (base, base)]
685 for x in self.rej:
698 for x in self.rej:
686 for l in x.hunk:
699 for l in x.hunk:
687 lines.append(l)
700 lines.append(l)
688 if l[-1] != '\n':
701 if l[-1] != '\n':
689 lines.append("\n\ No newline at end of file\n")
702 lines.append("\n\ No newline at end of file\n")
690 self.backend.writerej(self.fname, len(self.rej), self.hunks, lines)
703 self.backend.writerej(self.fname, len(self.rej), self.hunks, lines)
691
704
692 def apply(self, h):
705 def apply(self, h):
693 if not h.complete():
706 if not h.complete():
694 raise PatchError(_("bad hunk #%d %s (%d %d %d %d)") %
707 raise PatchError(_("bad hunk #%d %s (%d %d %d %d)") %
695 (h.number, h.desc, len(h.a), h.lena, len(h.b),
708 (h.number, h.desc, len(h.a), h.lena, len(h.b),
696 h.lenb))
709 h.lenb))
697
710
698 self.hunks += 1
711 self.hunks += 1
699
712
700 if self.missing:
713 if self.missing:
701 self.rej.append(h)
714 self.rej.append(h)
702 return -1
715 return -1
703
716
704 if self.exists and self.create:
717 if self.exists and self.create:
705 if self.copysource:
718 if self.copysource:
706 self.ui.warn(_("cannot create %s: destination already "
719 self.ui.warn(_("cannot create %s: destination already "
707 "exists\n" % self.fname))
720 "exists\n" % self.fname))
708 else:
721 else:
709 self.ui.warn(_("file %s already exists\n") % self.fname)
722 self.ui.warn(_("file %s already exists\n") % self.fname)
710 self.rej.append(h)
723 self.rej.append(h)
711 return -1
724 return -1
712
725
713 if isinstance(h, binhunk):
726 if isinstance(h, binhunk):
714 if self.remove:
727 if self.remove:
715 self.backend.unlink(self.fname)
728 self.backend.unlink(self.fname)
716 else:
729 else:
717 self.lines[:] = h.new()
730 self.lines[:] = h.new()
718 self.offset += len(h.new())
731 self.offset += len(h.new())
719 self.dirty = True
732 self.dirty = True
720 return 0
733 return 0
721
734
722 horig = h
735 horig = h
723 if (self.eolmode in ('crlf', 'lf')
736 if (self.eolmode in ('crlf', 'lf')
724 or self.eolmode == 'auto' and self.eol):
737 or self.eolmode == 'auto' and self.eol):
725 # If new eols are going to be normalized, then normalize
738 # If new eols are going to be normalized, then normalize
726 # hunk data before patching. Otherwise, preserve input
739 # hunk data before patching. Otherwise, preserve input
727 # line-endings.
740 # line-endings.
728 h = h.getnormalized()
741 h = h.getnormalized()
729
742
730 # fast case first, no offsets, no fuzz
743 # fast case first, no offsets, no fuzz
731 old, oldstart, new, newstart = h.fuzzit(0, False)
744 old, oldstart, new, newstart = h.fuzzit(0, False)
732 oldstart += self.offset
745 oldstart += self.offset
733 orig_start = oldstart
746 orig_start = oldstart
734 # if there's skew we want to emit the "(offset %d lines)" even
747 # if there's skew we want to emit the "(offset %d lines)" even
735 # when the hunk cleanly applies at start + skew, so skip the
748 # when the hunk cleanly applies at start + skew, so skip the
736 # fast case code
749 # fast case code
737 if (self.skew == 0 and
750 if (self.skew == 0 and
738 diffhelpers.testhunk(old, self.lines, oldstart) == 0):
751 diffhelpers.testhunk(old, self.lines, oldstart) == 0):
739 if self.remove:
752 if self.remove:
740 self.backend.unlink(self.fname)
753 self.backend.unlink(self.fname)
741 else:
754 else:
742 self.lines[oldstart:oldstart + len(old)] = new
755 self.lines[oldstart:oldstart + len(old)] = new
743 self.offset += len(new) - len(old)
756 self.offset += len(new) - len(old)
744 self.dirty = True
757 self.dirty = True
745 return 0
758 return 0
746
759
747 # ok, we couldn't match the hunk. Lets look for offsets and fuzz it
760 # ok, we couldn't match the hunk. Lets look for offsets and fuzz it
748 self.hash = {}
761 self.hash = {}
749 for x, s in enumerate(self.lines):
762 for x, s in enumerate(self.lines):
750 self.hash.setdefault(s, []).append(x)
763 self.hash.setdefault(s, []).append(x)
751
764
752 for fuzzlen in xrange(3):
765 for fuzzlen in xrange(3):
753 for toponly in [True, False]:
766 for toponly in [True, False]:
754 old, oldstart, new, newstart = h.fuzzit(fuzzlen, toponly)
767 old, oldstart, new, newstart = h.fuzzit(fuzzlen, toponly)
755 oldstart = oldstart + self.offset + self.skew
768 oldstart = oldstart + self.offset + self.skew
756 oldstart = min(oldstart, len(self.lines))
769 oldstart = min(oldstart, len(self.lines))
757 if old:
770 if old:
758 cand = self.findlines(old[0][1:], oldstart)
771 cand = self.findlines(old[0][1:], oldstart)
759 else:
772 else:
760 # Only adding lines with no or fuzzed context, just
773 # Only adding lines with no or fuzzed context, just
761 # take the skew in account
774 # take the skew in account
762 cand = [oldstart]
775 cand = [oldstart]
763
776
764 for l in cand:
777 for l in cand:
765 if not old or diffhelpers.testhunk(old, self.lines, l) == 0:
778 if not old or diffhelpers.testhunk(old, self.lines, l) == 0:
766 self.lines[l : l + len(old)] = new
779 self.lines[l : l + len(old)] = new
767 self.offset += len(new) - len(old)
780 self.offset += len(new) - len(old)
768 self.skew = l - orig_start
781 self.skew = l - orig_start
769 self.dirty = True
782 self.dirty = True
770 offset = l - orig_start - fuzzlen
783 offset = l - orig_start - fuzzlen
771 if fuzzlen:
784 if fuzzlen:
772 msg = _("Hunk #%d succeeded at %d "
785 msg = _("Hunk #%d succeeded at %d "
773 "with fuzz %d "
786 "with fuzz %d "
774 "(offset %d lines).\n")
787 "(offset %d lines).\n")
775 self.printfile(True)
788 self.printfile(True)
776 self.ui.warn(msg %
789 self.ui.warn(msg %
777 (h.number, l + 1, fuzzlen, offset))
790 (h.number, l + 1, fuzzlen, offset))
778 else:
791 else:
779 msg = _("Hunk #%d succeeded at %d "
792 msg = _("Hunk #%d succeeded at %d "
780 "(offset %d lines).\n")
793 "(offset %d lines).\n")
781 self.ui.note(msg % (h.number, l + 1, offset))
794 self.ui.note(msg % (h.number, l + 1, offset))
782 return fuzzlen
795 return fuzzlen
783 self.printfile(True)
796 self.printfile(True)
784 self.ui.warn(_("Hunk #%d FAILED at %d\n") % (h.number, orig_start))
797 self.ui.warn(_("Hunk #%d FAILED at %d\n") % (h.number, orig_start))
785 self.rej.append(horig)
798 self.rej.append(horig)
786 return -1
799 return -1
787
800
788 def close(self):
801 def close(self):
789 if self.dirty:
802 if self.dirty:
790 self.writelines(self.fname, self.lines, self.mode)
803 self.writelines(self.fname, self.lines, self.mode)
791 self.write_rej()
804 self.write_rej()
792 return len(self.rej)
805 return len(self.rej)
793
806
794 class hunk(object):
807 class hunk(object):
795 def __init__(self, desc, num, lr, context):
808 def __init__(self, desc, num, lr, context):
796 self.number = num
809 self.number = num
797 self.desc = desc
810 self.desc = desc
798 self.hunk = [desc]
811 self.hunk = [desc]
799 self.a = []
812 self.a = []
800 self.b = []
813 self.b = []
801 self.starta = self.lena = None
814 self.starta = self.lena = None
802 self.startb = self.lenb = None
815 self.startb = self.lenb = None
803 if lr is not None:
816 if lr is not None:
804 if context:
817 if context:
805 self.read_context_hunk(lr)
818 self.read_context_hunk(lr)
806 else:
819 else:
807 self.read_unified_hunk(lr)
820 self.read_unified_hunk(lr)
808
821
809 def getnormalized(self):
822 def getnormalized(self):
810 """Return a copy with line endings normalized to LF."""
823 """Return a copy with line endings normalized to LF."""
811
824
812 def normalize(lines):
825 def normalize(lines):
813 nlines = []
826 nlines = []
814 for line in lines:
827 for line in lines:
815 if line.endswith('\r\n'):
828 if line.endswith('\r\n'):
816 line = line[:-2] + '\n'
829 line = line[:-2] + '\n'
817 nlines.append(line)
830 nlines.append(line)
818 return nlines
831 return nlines
819
832
820 # Dummy object, it is rebuilt manually
833 # Dummy object, it is rebuilt manually
821 nh = hunk(self.desc, self.number, None, None)
834 nh = hunk(self.desc, self.number, None, None)
822 nh.number = self.number
835 nh.number = self.number
823 nh.desc = self.desc
836 nh.desc = self.desc
824 nh.hunk = self.hunk
837 nh.hunk = self.hunk
825 nh.a = normalize(self.a)
838 nh.a = normalize(self.a)
826 nh.b = normalize(self.b)
839 nh.b = normalize(self.b)
827 nh.starta = self.starta
840 nh.starta = self.starta
828 nh.startb = self.startb
841 nh.startb = self.startb
829 nh.lena = self.lena
842 nh.lena = self.lena
830 nh.lenb = self.lenb
843 nh.lenb = self.lenb
831 return nh
844 return nh
832
845
833 def read_unified_hunk(self, lr):
846 def read_unified_hunk(self, lr):
834 m = unidesc.match(self.desc)
847 m = unidesc.match(self.desc)
835 if not m:
848 if not m:
836 raise PatchError(_("bad hunk #%d") % self.number)
849 raise PatchError(_("bad hunk #%d") % self.number)
837 self.starta, self.lena, self.startb, self.lenb = m.groups()
850 self.starta, self.lena, self.startb, self.lenb = m.groups()
838 if self.lena is None:
851 if self.lena is None:
839 self.lena = 1
852 self.lena = 1
840 else:
853 else:
841 self.lena = int(self.lena)
854 self.lena = int(self.lena)
842 if self.lenb is None:
855 if self.lenb is None:
843 self.lenb = 1
856 self.lenb = 1
844 else:
857 else:
845 self.lenb = int(self.lenb)
858 self.lenb = int(self.lenb)
846 self.starta = int(self.starta)
859 self.starta = int(self.starta)
847 self.startb = int(self.startb)
860 self.startb = int(self.startb)
848 diffhelpers.addlines(lr, self.hunk, self.lena, self.lenb, self.a, self.b)
861 diffhelpers.addlines(lr, self.hunk, self.lena, self.lenb, self.a, self.b)
849 # if we hit eof before finishing out the hunk, the last line will
862 # if we hit eof before finishing out the hunk, the last line will
850 # be zero length. Lets try to fix it up.
863 # be zero length. Lets try to fix it up.
851 while len(self.hunk[-1]) == 0:
864 while len(self.hunk[-1]) == 0:
852 del self.hunk[-1]
865 del self.hunk[-1]
853 del self.a[-1]
866 del self.a[-1]
854 del self.b[-1]
867 del self.b[-1]
855 self.lena -= 1
868 self.lena -= 1
856 self.lenb -= 1
869 self.lenb -= 1
857 self._fixnewline(lr)
870 self._fixnewline(lr)
858
871
859 def read_context_hunk(self, lr):
872 def read_context_hunk(self, lr):
860 self.desc = lr.readline()
873 self.desc = lr.readline()
861 m = contextdesc.match(self.desc)
874 m = contextdesc.match(self.desc)
862 if not m:
875 if not m:
863 raise PatchError(_("bad hunk #%d") % self.number)
876 raise PatchError(_("bad hunk #%d") % self.number)
864 self.starta, aend = m.groups()
877 self.starta, aend = m.groups()
865 self.starta = int(self.starta)
878 self.starta = int(self.starta)
866 if aend is None:
879 if aend is None:
867 aend = self.starta
880 aend = self.starta
868 self.lena = int(aend) - self.starta
881 self.lena = int(aend) - self.starta
869 if self.starta:
882 if self.starta:
870 self.lena += 1
883 self.lena += 1
871 for x in xrange(self.lena):
884 for x in xrange(self.lena):
872 l = lr.readline()
885 l = lr.readline()
873 if l.startswith('---'):
886 if l.startswith('---'):
874 # lines addition, old block is empty
887 # lines addition, old block is empty
875 lr.push(l)
888 lr.push(l)
876 break
889 break
877 s = l[2:]
890 s = l[2:]
878 if l.startswith('- ') or l.startswith('! '):
891 if l.startswith('- ') or l.startswith('! '):
879 u = '-' + s
892 u = '-' + s
880 elif l.startswith(' '):
893 elif l.startswith(' '):
881 u = ' ' + s
894 u = ' ' + s
882 else:
895 else:
883 raise PatchError(_("bad hunk #%d old text line %d") %
896 raise PatchError(_("bad hunk #%d old text line %d") %
884 (self.number, x))
897 (self.number, x))
885 self.a.append(u)
898 self.a.append(u)
886 self.hunk.append(u)
899 self.hunk.append(u)
887
900
888 l = lr.readline()
901 l = lr.readline()
889 if l.startswith('\ '):
902 if l.startswith('\ '):
890 s = self.a[-1][:-1]
903 s = self.a[-1][:-1]
891 self.a[-1] = s
904 self.a[-1] = s
892 self.hunk[-1] = s
905 self.hunk[-1] = s
893 l = lr.readline()
906 l = lr.readline()
894 m = contextdesc.match(l)
907 m = contextdesc.match(l)
895 if not m:
908 if not m:
896 raise PatchError(_("bad hunk #%d") % self.number)
909 raise PatchError(_("bad hunk #%d") % self.number)
897 self.startb, bend = m.groups()
910 self.startb, bend = m.groups()
898 self.startb = int(self.startb)
911 self.startb = int(self.startb)
899 if bend is None:
912 if bend is None:
900 bend = self.startb
913 bend = self.startb
901 self.lenb = int(bend) - self.startb
914 self.lenb = int(bend) - self.startb
902 if self.startb:
915 if self.startb:
903 self.lenb += 1
916 self.lenb += 1
904 hunki = 1
917 hunki = 1
905 for x in xrange(self.lenb):
918 for x in xrange(self.lenb):
906 l = lr.readline()
919 l = lr.readline()
907 if l.startswith('\ '):
920 if l.startswith('\ '):
908 # XXX: the only way to hit this is with an invalid line range.
921 # XXX: the only way to hit this is with an invalid line range.
909 # The no-eol marker is not counted in the line range, but I
922 # The no-eol marker is not counted in the line range, but I
910 # guess there are diff(1) out there which behave differently.
923 # guess there are diff(1) out there which behave differently.
911 s = self.b[-1][:-1]
924 s = self.b[-1][:-1]
912 self.b[-1] = s
925 self.b[-1] = s
913 self.hunk[hunki - 1] = s
926 self.hunk[hunki - 1] = s
914 continue
927 continue
915 if not l:
928 if not l:
916 # line deletions, new block is empty and we hit EOF
929 # line deletions, new block is empty and we hit EOF
917 lr.push(l)
930 lr.push(l)
918 break
931 break
919 s = l[2:]
932 s = l[2:]
920 if l.startswith('+ ') or l.startswith('! '):
933 if l.startswith('+ ') or l.startswith('! '):
921 u = '+' + s
934 u = '+' + s
922 elif l.startswith(' '):
935 elif l.startswith(' '):
923 u = ' ' + s
936 u = ' ' + s
924 elif len(self.b) == 0:
937 elif len(self.b) == 0:
925 # line deletions, new block is empty
938 # line deletions, new block is empty
926 lr.push(l)
939 lr.push(l)
927 break
940 break
928 else:
941 else:
929 raise PatchError(_("bad hunk #%d old text line %d") %
942 raise PatchError(_("bad hunk #%d old text line %d") %
930 (self.number, x))
943 (self.number, x))
931 self.b.append(s)
944 self.b.append(s)
932 while True:
945 while True:
933 if hunki >= len(self.hunk):
946 if hunki >= len(self.hunk):
934 h = ""
947 h = ""
935 else:
948 else:
936 h = self.hunk[hunki]
949 h = self.hunk[hunki]
937 hunki += 1
950 hunki += 1
938 if h == u:
951 if h == u:
939 break
952 break
940 elif h.startswith('-'):
953 elif h.startswith('-'):
941 continue
954 continue
942 else:
955 else:
943 self.hunk.insert(hunki - 1, u)
956 self.hunk.insert(hunki - 1, u)
944 break
957 break
945
958
946 if not self.a:
959 if not self.a:
947 # this happens when lines were only added to the hunk
960 # this happens when lines were only added to the hunk
948 for x in self.hunk:
961 for x in self.hunk:
949 if x.startswith('-') or x.startswith(' '):
962 if x.startswith('-') or x.startswith(' '):
950 self.a.append(x)
963 self.a.append(x)
951 if not self.b:
964 if not self.b:
952 # this happens when lines were only deleted from the hunk
965 # this happens when lines were only deleted from the hunk
953 for x in self.hunk:
966 for x in self.hunk:
954 if x.startswith('+') or x.startswith(' '):
967 if x.startswith('+') or x.startswith(' '):
955 self.b.append(x[1:])
968 self.b.append(x[1:])
956 # @@ -start,len +start,len @@
969 # @@ -start,len +start,len @@
957 self.desc = "@@ -%d,%d +%d,%d @@\n" % (self.starta, self.lena,
970 self.desc = "@@ -%d,%d +%d,%d @@\n" % (self.starta, self.lena,
958 self.startb, self.lenb)
971 self.startb, self.lenb)
959 self.hunk[0] = self.desc
972 self.hunk[0] = self.desc
960 self._fixnewline(lr)
973 self._fixnewline(lr)
961
974
962 def _fixnewline(self, lr):
975 def _fixnewline(self, lr):
963 l = lr.readline()
976 l = lr.readline()
964 if l.startswith('\ '):
977 if l.startswith('\ '):
965 diffhelpers.fix_newline(self.hunk, self.a, self.b)
978 diffhelpers.fix_newline(self.hunk, self.a, self.b)
966 else:
979 else:
967 lr.push(l)
980 lr.push(l)
968
981
969 def complete(self):
982 def complete(self):
970 return len(self.a) == self.lena and len(self.b) == self.lenb
983 return len(self.a) == self.lena and len(self.b) == self.lenb
971
984
972 def _fuzzit(self, old, new, fuzz, toponly):
985 def _fuzzit(self, old, new, fuzz, toponly):
973 # this removes context lines from the top and bottom of list 'l'. It
986 # this removes context lines from the top and bottom of list 'l'. It
974 # checks the hunk to make sure only context lines are removed, and then
987 # checks the hunk to make sure only context lines are removed, and then
975 # returns a new shortened list of lines.
988 # returns a new shortened list of lines.
976 fuzz = min(fuzz, len(old))
989 fuzz = min(fuzz, len(old))
977 if fuzz:
990 if fuzz:
978 top = 0
991 top = 0
979 bot = 0
992 bot = 0
980 hlen = len(self.hunk)
993 hlen = len(self.hunk)
981 for x in xrange(hlen - 1):
994 for x in xrange(hlen - 1):
982 # the hunk starts with the @@ line, so use x+1
995 # the hunk starts with the @@ line, so use x+1
983 if self.hunk[x + 1][0] == ' ':
996 if self.hunk[x + 1][0] == ' ':
984 top += 1
997 top += 1
985 else:
998 else:
986 break
999 break
987 if not toponly:
1000 if not toponly:
988 for x in xrange(hlen - 1):
1001 for x in xrange(hlen - 1):
989 if self.hunk[hlen - bot - 1][0] == ' ':
1002 if self.hunk[hlen - bot - 1][0] == ' ':
990 bot += 1
1003 bot += 1
991 else:
1004 else:
992 break
1005 break
993
1006
994 bot = min(fuzz, bot)
1007 bot = min(fuzz, bot)
995 top = min(fuzz, top)
1008 top = min(fuzz, top)
996 return old[top:len(old)-bot], new[top:len(new)-bot], top
1009 return old[top:len(old)-bot], new[top:len(new)-bot], top
997 return old, new, 0
1010 return old, new, 0
998
1011
999 def fuzzit(self, fuzz, toponly):
1012 def fuzzit(self, fuzz, toponly):
1000 old, new, top = self._fuzzit(self.a, self.b, fuzz, toponly)
1013 old, new, top = self._fuzzit(self.a, self.b, fuzz, toponly)
1001 oldstart = self.starta + top
1014 oldstart = self.starta + top
1002 newstart = self.startb + top
1015 newstart = self.startb + top
1003 # zero length hunk ranges already have their start decremented
1016 # zero length hunk ranges already have their start decremented
1004 if self.lena:
1017 if self.lena:
1005 oldstart -= 1
1018 oldstart -= 1
1006 if self.lenb:
1019 if self.lenb:
1007 newstart -= 1
1020 newstart -= 1
1008 return old, oldstart, new, newstart
1021 return old, oldstart, new, newstart
1009
1022
1010 class binhunk(object):
1023 class binhunk(object):
1011 'A binary patch file. Only understands literals so far.'
1024 'A binary patch file. Only understands literals so far.'
1012 def __init__(self, lr):
1025 def __init__(self, lr):
1013 self.text = None
1026 self.text = None
1014 self.hunk = ['GIT binary patch\n']
1027 self.hunk = ['GIT binary patch\n']
1015 self._read(lr)
1028 self._read(lr)
1016
1029
1017 def complete(self):
1030 def complete(self):
1018 return self.text is not None
1031 return self.text is not None
1019
1032
1020 def new(self):
1033 def new(self):
1021 return [self.text]
1034 return [self.text]
1022
1035
1023 def _read(self, lr):
1036 def _read(self, lr):
1024 line = lr.readline()
1037 line = lr.readline()
1025 self.hunk.append(line)
1038 self.hunk.append(line)
1026 while line and not line.startswith('literal '):
1039 while line and not line.startswith('literal '):
1027 line = lr.readline()
1040 line = lr.readline()
1028 self.hunk.append(line)
1041 self.hunk.append(line)
1029 if not line:
1042 if not line:
1030 raise PatchError(_('could not extract binary patch'))
1043 raise PatchError(_('could not extract binary patch'))
1031 size = int(line[8:].rstrip())
1044 size = int(line[8:].rstrip())
1032 dec = []
1045 dec = []
1033 line = lr.readline()
1046 line = lr.readline()
1034 self.hunk.append(line)
1047 self.hunk.append(line)
1035 while len(line) > 1:
1048 while len(line) > 1:
1036 l = line[0]
1049 l = line[0]
1037 if l <= 'Z' and l >= 'A':
1050 if l <= 'Z' and l >= 'A':
1038 l = ord(l) - ord('A') + 1
1051 l = ord(l) - ord('A') + 1
1039 else:
1052 else:
1040 l = ord(l) - ord('a') + 27
1053 l = ord(l) - ord('a') + 27
1041 dec.append(base85.b85decode(line[1:-1])[:l])
1054 dec.append(base85.b85decode(line[1:-1])[:l])
1042 line = lr.readline()
1055 line = lr.readline()
1043 self.hunk.append(line)
1056 self.hunk.append(line)
1044 text = zlib.decompress(''.join(dec))
1057 text = zlib.decompress(''.join(dec))
1045 if len(text) != size:
1058 if len(text) != size:
1046 raise PatchError(_('binary patch is %d bytes, not %d') %
1059 raise PatchError(_('binary patch is %d bytes, not %d') %
1047 len(text), size)
1060 len(text), size)
1048 self.text = text
1061 self.text = text
1049
1062
1050 def parsefilename(str):
1063 def parsefilename(str):
1051 # --- filename \t|space stuff
1064 # --- filename \t|space stuff
1052 s = str[4:].rstrip('\r\n')
1065 s = str[4:].rstrip('\r\n')
1053 i = s.find('\t')
1066 i = s.find('\t')
1054 if i < 0:
1067 if i < 0:
1055 i = s.find(' ')
1068 i = s.find(' ')
1056 if i < 0:
1069 if i < 0:
1057 return s
1070 return s
1058 return s[:i]
1071 return s[:i]
1059
1072
1060 def pathstrip(path, strip):
1073 def pathstrip(path, strip):
1061 pathlen = len(path)
1074 pathlen = len(path)
1062 i = 0
1075 i = 0
1063 if strip == 0:
1076 if strip == 0:
1064 return '', path.rstrip()
1077 return '', path.rstrip()
1065 count = strip
1078 count = strip
1066 while count > 0:
1079 while count > 0:
1067 i = path.find('/', i)
1080 i = path.find('/', i)
1068 if i == -1:
1081 if i == -1:
1069 raise PatchError(_("unable to strip away %d of %d dirs from %s") %
1082 raise PatchError(_("unable to strip away %d of %d dirs from %s") %
1070 (count, strip, path))
1083 (count, strip, path))
1071 i += 1
1084 i += 1
1072 # consume '//' in the path
1085 # consume '//' in the path
1073 while i < pathlen - 1 and path[i] == '/':
1086 while i < pathlen - 1 and path[i] == '/':
1074 i += 1
1087 i += 1
1075 count -= 1
1088 count -= 1
1076 return path[:i].lstrip(), path[i:].rstrip()
1089 return path[:i].lstrip(), path[i:].rstrip()
1077
1090
1078 def makepatchmeta(backend, afile_orig, bfile_orig, hunk, strip):
1091 def makepatchmeta(backend, afile_orig, bfile_orig, hunk, strip):
1079 nulla = afile_orig == "/dev/null"
1092 nulla = afile_orig == "/dev/null"
1080 nullb = bfile_orig == "/dev/null"
1093 nullb = bfile_orig == "/dev/null"
1081 create = nulla and hunk.starta == 0 and hunk.lena == 0
1094 create = nulla and hunk.starta == 0 and hunk.lena == 0
1082 remove = nullb and hunk.startb == 0 and hunk.lenb == 0
1095 remove = nullb and hunk.startb == 0 and hunk.lenb == 0
1083 abase, afile = pathstrip(afile_orig, strip)
1096 abase, afile = pathstrip(afile_orig, strip)
1084 gooda = not nulla and backend.exists(afile)
1097 gooda = not nulla and backend.exists(afile)
1085 bbase, bfile = pathstrip(bfile_orig, strip)
1098 bbase, bfile = pathstrip(bfile_orig, strip)
1086 if afile == bfile:
1099 if afile == bfile:
1087 goodb = gooda
1100 goodb = gooda
1088 else:
1101 else:
1089 goodb = not nullb and backend.exists(bfile)
1102 goodb = not nullb and backend.exists(bfile)
1090 missing = not goodb and not gooda and not create
1103 missing = not goodb and not gooda and not create
1091
1104
1092 # some diff programs apparently produce patches where the afile is
1105 # some diff programs apparently produce patches where the afile is
1093 # not /dev/null, but afile starts with bfile
1106 # not /dev/null, but afile starts with bfile
1094 abasedir = afile[:afile.rfind('/') + 1]
1107 abasedir = afile[:afile.rfind('/') + 1]
1095 bbasedir = bfile[:bfile.rfind('/') + 1]
1108 bbasedir = bfile[:bfile.rfind('/') + 1]
1096 if (missing and abasedir == bbasedir and afile.startswith(bfile)
1109 if (missing and abasedir == bbasedir and afile.startswith(bfile)
1097 and hunk.starta == 0 and hunk.lena == 0):
1110 and hunk.starta == 0 and hunk.lena == 0):
1098 create = True
1111 create = True
1099 missing = False
1112 missing = False
1100
1113
1101 # If afile is "a/b/foo" and bfile is "a/b/foo.orig" we assume the
1114 # If afile is "a/b/foo" and bfile is "a/b/foo.orig" we assume the
1102 # diff is between a file and its backup. In this case, the original
1115 # diff is between a file and its backup. In this case, the original
1103 # file should be patched (see original mpatch code).
1116 # file should be patched (see original mpatch code).
1104 isbackup = (abase == bbase and bfile.startswith(afile))
1117 isbackup = (abase == bbase and bfile.startswith(afile))
1105 fname = None
1118 fname = None
1106 if not missing:
1119 if not missing:
1107 if gooda and goodb:
1120 if gooda and goodb:
1108 fname = isbackup and afile or bfile
1121 fname = isbackup and afile or bfile
1109 elif gooda:
1122 elif gooda:
1110 fname = afile
1123 fname = afile
1111
1124
1112 if not fname:
1125 if not fname:
1113 if not nullb:
1126 if not nullb:
1114 fname = isbackup and afile or bfile
1127 fname = isbackup and afile or bfile
1115 elif not nulla:
1128 elif not nulla:
1116 fname = afile
1129 fname = afile
1117 else:
1130 else:
1118 raise PatchError(_("undefined source and destination files"))
1131 raise PatchError(_("undefined source and destination files"))
1119
1132
1120 gp = patchmeta(fname)
1133 gp = patchmeta(fname)
1121 if create:
1134 if create:
1122 gp.op = 'ADD'
1135 gp.op = 'ADD'
1123 elif remove:
1136 elif remove:
1124 gp.op = 'DELETE'
1137 gp.op = 'DELETE'
1125 return gp
1138 return gp
1126
1139
1127 def scangitpatch(lr, firstline):
1140 def scangitpatch(lr, firstline):
1128 """
1141 """
1129 Git patches can emit:
1142 Git patches can emit:
1130 - rename a to b
1143 - rename a to b
1131 - change b
1144 - change b
1132 - copy a to c
1145 - copy a to c
1133 - change c
1146 - change c
1134
1147
1135 We cannot apply this sequence as-is, the renamed 'a' could not be
1148 We cannot apply this sequence as-is, the renamed 'a' could not be
1136 found for it would have been renamed already. And we cannot copy
1149 found for it would have been renamed already. And we cannot copy
1137 from 'b' instead because 'b' would have been changed already. So
1150 from 'b' instead because 'b' would have been changed already. So
1138 we scan the git patch for copy and rename commands so we can
1151 we scan the git patch for copy and rename commands so we can
1139 perform the copies ahead of time.
1152 perform the copies ahead of time.
1140 """
1153 """
1141 pos = 0
1154 pos = 0
1142 try:
1155 try:
1143 pos = lr.fp.tell()
1156 pos = lr.fp.tell()
1144 fp = lr.fp
1157 fp = lr.fp
1145 except IOError:
1158 except IOError:
1146 fp = cStringIO.StringIO(lr.fp.read())
1159 fp = cStringIO.StringIO(lr.fp.read())
1147 gitlr = linereader(fp)
1160 gitlr = linereader(fp)
1148 gitlr.push(firstline)
1161 gitlr.push(firstline)
1149 gitpatches = readgitpatch(gitlr)
1162 gitpatches = readgitpatch(gitlr)
1150 fp.seek(pos)
1163 fp.seek(pos)
1151 return gitpatches
1164 return gitpatches
1152
1165
1153 def iterhunks(fp):
1166 def iterhunks(fp):
1154 """Read a patch and yield the following events:
1167 """Read a patch and yield the following events:
1155 - ("file", afile, bfile, firsthunk): select a new target file.
1168 - ("file", afile, bfile, firsthunk): select a new target file.
1156 - ("hunk", hunk): a new hunk is ready to be applied, follows a
1169 - ("hunk", hunk): a new hunk is ready to be applied, follows a
1157 "file" event.
1170 "file" event.
1158 - ("git", gitchanges): current diff is in git format, gitchanges
1171 - ("git", gitchanges): current diff is in git format, gitchanges
1159 maps filenames to gitpatch records. Unique event.
1172 maps filenames to gitpatch records. Unique event.
1160 """
1173 """
1161 afile = ""
1174 afile = ""
1162 bfile = ""
1175 bfile = ""
1163 state = None
1176 state = None
1164 hunknum = 0
1177 hunknum = 0
1165 emitfile = newfile = False
1178 emitfile = newfile = False
1166 gitpatches = None
1179 gitpatches = None
1167
1180
1168 # our states
1181 # our states
1169 BFILE = 1
1182 BFILE = 1
1170 context = None
1183 context = None
1171 lr = linereader(fp)
1184 lr = linereader(fp)
1172
1185
1173 while True:
1186 while True:
1174 x = lr.readline()
1187 x = lr.readline()
1175 if not x:
1188 if not x:
1176 break
1189 break
1177 if state == BFILE and (
1190 if state == BFILE and (
1178 (not context and x[0] == '@')
1191 (not context and x[0] == '@')
1179 or (context is not False and x.startswith('***************'))
1192 or (context is not False and x.startswith('***************'))
1180 or x.startswith('GIT binary patch')):
1193 or x.startswith('GIT binary patch')):
1181 gp = None
1194 gp = None
1182 if (gitpatches and
1195 if (gitpatches and
1183 (gitpatches[-1][0] == afile or gitpatches[-1][1] == bfile)):
1196 gitpatches[-1].ispatching(afile, bfile)):
1184 gp = gitpatches.pop()[2]
1197 gp = gitpatches.pop()
1185 if x.startswith('GIT binary patch'):
1198 if x.startswith('GIT binary patch'):
1186 h = binhunk(lr)
1199 h = binhunk(lr)
1187 else:
1200 else:
1188 if context is None and x.startswith('***************'):
1201 if context is None and x.startswith('***************'):
1189 context = True
1202 context = True
1190 h = hunk(x, hunknum + 1, lr, context)
1203 h = hunk(x, hunknum + 1, lr, context)
1191 hunknum += 1
1204 hunknum += 1
1192 if emitfile:
1205 if emitfile:
1193 emitfile = False
1206 emitfile = False
1194 yield 'file', (afile, bfile, h, gp and gp.copy() or None)
1207 yield 'file', (afile, bfile, h, gp and gp.copy() or None)
1195 yield 'hunk', h
1208 yield 'hunk', h
1196 elif x.startswith('diff --git'):
1209 elif x.startswith('diff --git'):
1197 m = gitre.match(x)
1210 m = gitre.match(x)
1198 if not m:
1211 if not m:
1199 continue
1212 continue
1200 if not gitpatches:
1213 if gitpatches is None:
1201 # scan whole input for git metadata
1214 # scan whole input for git metadata
1202 gitpatches = [('a/' + gp.path, 'b/' + gp.path, gp) for gp
1215 gitpatches = scangitpatch(lr, x)
1203 in scangitpatch(lr, x)]
1216 yield 'git', [g.copy() for g in gitpatches
1204 yield 'git', [g[2].copy() for g in gitpatches
1217 if g.op in ('COPY', 'RENAME')]
1205 if g[2].op in ('COPY', 'RENAME')]
1206 gitpatches.reverse()
1218 gitpatches.reverse()
1207 afile = 'a/' + m.group(1)
1219 afile = 'a/' + m.group(1)
1208 bfile = 'b/' + m.group(2)
1220 bfile = 'b/' + m.group(2)
1209 while afile != gitpatches[-1][0] and bfile != gitpatches[-1][1]:
1221 while gitpatches and not gitpatches[-1].ispatching(afile, bfile):
1210 gp = gitpatches.pop()[2]
1222 gp = gitpatches.pop()
1211 yield 'file', ('a/' + gp.path, 'b/' + gp.path, None, gp.copy())
1223 yield 'file', ('a/' + gp.path, 'b/' + gp.path, None, gp.copy())
1212 gp = gitpatches[-1][2]
1224 if not gitpatches:
1213 # copy/rename + modify should modify target, not source
1225 raise PatchError(_('failed to synchronize metadata for "%s"')
1214 if gp.op in ('COPY', 'DELETE', 'RENAME', 'ADD') or gp.mode:
1226 % afile[2:])
1215 afile = bfile
1227 gp = gitpatches[-1]
1216 newfile = True
1228 newfile = True
1217 elif x.startswith('---'):
1229 elif x.startswith('---'):
1218 # check for a unified diff
1230 # check for a unified diff
1219 l2 = lr.readline()
1231 l2 = lr.readline()
1220 if not l2.startswith('+++'):
1232 if not l2.startswith('+++'):
1221 lr.push(l2)
1233 lr.push(l2)
1222 continue
1234 continue
1223 newfile = True
1235 newfile = True
1224 context = False
1236 context = False
1225 afile = parsefilename(x)
1237 afile = parsefilename(x)
1226 bfile = parsefilename(l2)
1238 bfile = parsefilename(l2)
1227 elif x.startswith('***'):
1239 elif x.startswith('***'):
1228 # check for a context diff
1240 # check for a context diff
1229 l2 = lr.readline()
1241 l2 = lr.readline()
1230 if not l2.startswith('---'):
1242 if not l2.startswith('---'):
1231 lr.push(l2)
1243 lr.push(l2)
1232 continue
1244 continue
1233 l3 = lr.readline()
1245 l3 = lr.readline()
1234 lr.push(l3)
1246 lr.push(l3)
1235 if not l3.startswith("***************"):
1247 if not l3.startswith("***************"):
1236 lr.push(l2)
1248 lr.push(l2)
1237 continue
1249 continue
1238 newfile = True
1250 newfile = True
1239 context = True
1251 context = True
1240 afile = parsefilename(x)
1252 afile = parsefilename(x)
1241 bfile = parsefilename(l2)
1253 bfile = parsefilename(l2)
1242
1254
1243 if newfile:
1255 if newfile:
1244 newfile = False
1256 newfile = False
1245 emitfile = True
1257 emitfile = True
1246 state = BFILE
1258 state = BFILE
1247 hunknum = 0
1259 hunknum = 0
1248
1260
1249 while gitpatches:
1261 while gitpatches:
1250 gp = gitpatches.pop()[2]
1262 gp = gitpatches.pop()
1251 yield 'file', ('a/' + gp.path, 'b/' + gp.path, None, gp.copy())
1263 yield 'file', ('a/' + gp.path, 'b/' + gp.path, None, gp.copy())
1252
1264
1253 def applydiff(ui, fp, backend, store, strip=1, eolmode='strict'):
1265 def applydiff(ui, fp, backend, store, strip=1, eolmode='strict'):
1254 """Reads a patch from fp and tries to apply it.
1266 """Reads a patch from fp and tries to apply it.
1255
1267
1256 Returns 0 for a clean patch, -1 if any rejects were found and 1 if
1268 Returns 0 for a clean patch, -1 if any rejects were found and 1 if
1257 there was any fuzz.
1269 there was any fuzz.
1258
1270
1259 If 'eolmode' is 'strict', the patch content and patched file are
1271 If 'eolmode' is 'strict', the patch content and patched file are
1260 read in binary mode. Otherwise, line endings are ignored when
1272 read in binary mode. Otherwise, line endings are ignored when
1261 patching then normalized according to 'eolmode'.
1273 patching then normalized according to 'eolmode'.
1262 """
1274 """
1263 return _applydiff(ui, fp, patchfile, backend, store, strip=strip,
1275 return _applydiff(ui, fp, patchfile, backend, store, strip=strip,
1264 eolmode=eolmode)
1276 eolmode=eolmode)
1265
1277
1266 def _applydiff(ui, fp, patcher, backend, store, strip=1,
1278 def _applydiff(ui, fp, patcher, backend, store, strip=1,
1267 eolmode='strict'):
1279 eolmode='strict'):
1268
1280
1269 def pstrip(p):
1281 def pstrip(p):
1270 return pathstrip(p, strip - 1)[1]
1282 return pathstrip(p, strip - 1)[1]
1271
1283
1272 rejects = 0
1284 rejects = 0
1273 err = 0
1285 err = 0
1274 current_file = None
1286 current_file = None
1275
1287
1276 for state, values in iterhunks(fp):
1288 for state, values in iterhunks(fp):
1277 if state == 'hunk':
1289 if state == 'hunk':
1278 if not current_file:
1290 if not current_file:
1279 continue
1291 continue
1280 ret = current_file.apply(values)
1292 ret = current_file.apply(values)
1281 if ret > 0:
1293 if ret > 0:
1282 err = 1
1294 err = 1
1283 elif state == 'file':
1295 elif state == 'file':
1284 if current_file:
1296 if current_file:
1285 rejects += current_file.close()
1297 rejects += current_file.close()
1286 current_file = None
1298 current_file = None
1287 afile, bfile, first_hunk, gp = values
1299 afile, bfile, first_hunk, gp = values
1288 if gp:
1300 if gp:
1289 gp.path = pstrip(gp.path)
1301 gp.path = pstrip(gp.path)
1290 if gp.oldpath:
1302 if gp.oldpath:
1291 gp.oldpath = pstrip(gp.oldpath)
1303 gp.oldpath = pstrip(gp.oldpath)
1292 else:
1304 else:
1293 gp = makepatchmeta(backend, afile, bfile, first_hunk, strip)
1305 gp = makepatchmeta(backend, afile, bfile, first_hunk, strip)
1294 if gp.op == 'RENAME':
1306 if gp.op == 'RENAME':
1295 backend.unlink(gp.oldpath)
1307 backend.unlink(gp.oldpath)
1296 if not first_hunk:
1308 if not first_hunk:
1297 if gp.op == 'DELETE':
1309 if gp.op == 'DELETE':
1298 backend.unlink(gp.path)
1310 backend.unlink(gp.path)
1299 continue
1311 continue
1300 data, mode = None, None
1312 data, mode = None, None
1301 if gp.op in ('RENAME', 'COPY'):
1313 if gp.op in ('RENAME', 'COPY'):
1302 data, mode = store.getfile(gp.oldpath)[:2]
1314 data, mode = store.getfile(gp.oldpath)[:2]
1303 if gp.mode:
1315 if gp.mode:
1304 mode = gp.mode
1316 mode = gp.mode
1305 if gp.op == 'ADD':
1317 if gp.op == 'ADD':
1306 # Added files without content have no hunk and
1318 # Added files without content have no hunk and
1307 # must be created
1319 # must be created
1308 data = ''
1320 data = ''
1309 if data or mode:
1321 if data or mode:
1310 if (gp.op in ('ADD', 'RENAME', 'COPY')
1322 if (gp.op in ('ADD', 'RENAME', 'COPY')
1311 and backend.exists(gp.path)):
1323 and backend.exists(gp.path)):
1312 raise PatchError(_("cannot create %s: destination "
1324 raise PatchError(_("cannot create %s: destination "
1313 "already exists") % gp.path)
1325 "already exists") % gp.path)
1314 backend.setfile(gp.path, data, mode, gp.oldpath)
1326 backend.setfile(gp.path, data, mode, gp.oldpath)
1315 continue
1327 continue
1316 try:
1328 try:
1317 current_file = patcher(ui, gp, backend, store,
1329 current_file = patcher(ui, gp, backend, store,
1318 eolmode=eolmode)
1330 eolmode=eolmode)
1319 except PatchError, inst:
1331 except PatchError, inst:
1320 ui.warn(str(inst) + '\n')
1332 ui.warn(str(inst) + '\n')
1321 current_file = None
1333 current_file = None
1322 rejects += 1
1334 rejects += 1
1323 continue
1335 continue
1324 elif state == 'git':
1336 elif state == 'git':
1325 for gp in values:
1337 for gp in values:
1326 path = pstrip(gp.oldpath)
1338 path = pstrip(gp.oldpath)
1327 data, mode = backend.getfile(path)
1339 data, mode = backend.getfile(path)
1328 store.setfile(path, data, mode)
1340 store.setfile(path, data, mode)
1329 else:
1341 else:
1330 raise util.Abort(_('unsupported parser state: %s') % state)
1342 raise util.Abort(_('unsupported parser state: %s') % state)
1331
1343
1332 if current_file:
1344 if current_file:
1333 rejects += current_file.close()
1345 rejects += current_file.close()
1334
1346
1335 if rejects:
1347 if rejects:
1336 return -1
1348 return -1
1337 return err
1349 return err
1338
1350
1339 def _externalpatch(ui, repo, patcher, patchname, strip, files,
1351 def _externalpatch(ui, repo, patcher, patchname, strip, files,
1340 similarity):
1352 similarity):
1341 """use <patcher> to apply <patchname> to the working directory.
1353 """use <patcher> to apply <patchname> to the working directory.
1342 returns whether patch was applied with fuzz factor."""
1354 returns whether patch was applied with fuzz factor."""
1343
1355
1344 fuzz = False
1356 fuzz = False
1345 args = []
1357 args = []
1346 cwd = repo.root
1358 cwd = repo.root
1347 if cwd:
1359 if cwd:
1348 args.append('-d %s' % util.shellquote(cwd))
1360 args.append('-d %s' % util.shellquote(cwd))
1349 fp = util.popen('%s %s -p%d < %s' % (patcher, ' '.join(args), strip,
1361 fp = util.popen('%s %s -p%d < %s' % (patcher, ' '.join(args), strip,
1350 util.shellquote(patchname)))
1362 util.shellquote(patchname)))
1351 try:
1363 try:
1352 for line in fp:
1364 for line in fp:
1353 line = line.rstrip()
1365 line = line.rstrip()
1354 ui.note(line + '\n')
1366 ui.note(line + '\n')
1355 if line.startswith('patching file '):
1367 if line.startswith('patching file '):
1356 pf = util.parsepatchoutput(line)
1368 pf = util.parsepatchoutput(line)
1357 printed_file = False
1369 printed_file = False
1358 files.add(pf)
1370 files.add(pf)
1359 elif line.find('with fuzz') >= 0:
1371 elif line.find('with fuzz') >= 0:
1360 fuzz = True
1372 fuzz = True
1361 if not printed_file:
1373 if not printed_file:
1362 ui.warn(pf + '\n')
1374 ui.warn(pf + '\n')
1363 printed_file = True
1375 printed_file = True
1364 ui.warn(line + '\n')
1376 ui.warn(line + '\n')
1365 elif line.find('saving rejects to file') >= 0:
1377 elif line.find('saving rejects to file') >= 0:
1366 ui.warn(line + '\n')
1378 ui.warn(line + '\n')
1367 elif line.find('FAILED') >= 0:
1379 elif line.find('FAILED') >= 0:
1368 if not printed_file:
1380 if not printed_file:
1369 ui.warn(pf + '\n')
1381 ui.warn(pf + '\n')
1370 printed_file = True
1382 printed_file = True
1371 ui.warn(line + '\n')
1383 ui.warn(line + '\n')
1372 finally:
1384 finally:
1373 if files:
1385 if files:
1374 cfiles = list(files)
1386 cfiles = list(files)
1375 cwd = repo.getcwd()
1387 cwd = repo.getcwd()
1376 if cwd:
1388 if cwd:
1377 cfiles = [util.pathto(repo.root, cwd, f)
1389 cfiles = [util.pathto(repo.root, cwd, f)
1378 for f in cfiles]
1390 for f in cfiles]
1379 scmutil.addremove(repo, cfiles, similarity=similarity)
1391 scmutil.addremove(repo, cfiles, similarity=similarity)
1380 code = fp.close()
1392 code = fp.close()
1381 if code:
1393 if code:
1382 raise PatchError(_("patch command failed: %s") %
1394 raise PatchError(_("patch command failed: %s") %
1383 util.explainexit(code)[0])
1395 util.explainexit(code)[0])
1384 return fuzz
1396 return fuzz
1385
1397
1386 def patchbackend(ui, backend, patchobj, strip, files=None, eolmode='strict'):
1398 def patchbackend(ui, backend, patchobj, strip, files=None, eolmode='strict'):
1387 if files is None:
1399 if files is None:
1388 files = set()
1400 files = set()
1389 if eolmode is None:
1401 if eolmode is None:
1390 eolmode = ui.config('patch', 'eol', 'strict')
1402 eolmode = ui.config('patch', 'eol', 'strict')
1391 if eolmode.lower() not in eolmodes:
1403 if eolmode.lower() not in eolmodes:
1392 raise util.Abort(_('unsupported line endings type: %s') % eolmode)
1404 raise util.Abort(_('unsupported line endings type: %s') % eolmode)
1393 eolmode = eolmode.lower()
1405 eolmode = eolmode.lower()
1394
1406
1395 store = filestore()
1407 store = filestore()
1396 try:
1408 try:
1397 fp = open(patchobj, 'rb')
1409 fp = open(patchobj, 'rb')
1398 except TypeError:
1410 except TypeError:
1399 fp = patchobj
1411 fp = patchobj
1400 try:
1412 try:
1401 ret = applydiff(ui, fp, backend, store, strip=strip,
1413 ret = applydiff(ui, fp, backend, store, strip=strip,
1402 eolmode=eolmode)
1414 eolmode=eolmode)
1403 finally:
1415 finally:
1404 if fp != patchobj:
1416 if fp != patchobj:
1405 fp.close()
1417 fp.close()
1406 files.update(backend.close())
1418 files.update(backend.close())
1407 store.close()
1419 store.close()
1408 if ret < 0:
1420 if ret < 0:
1409 raise PatchError(_('patch failed to apply'))
1421 raise PatchError(_('patch failed to apply'))
1410 return ret > 0
1422 return ret > 0
1411
1423
1412 def internalpatch(ui, repo, patchobj, strip, files=None, eolmode='strict',
1424 def internalpatch(ui, repo, patchobj, strip, files=None, eolmode='strict',
1413 similarity=0):
1425 similarity=0):
1414 """use builtin patch to apply <patchobj> to the working directory.
1426 """use builtin patch to apply <patchobj> to the working directory.
1415 returns whether patch was applied with fuzz factor."""
1427 returns whether patch was applied with fuzz factor."""
1416 backend = workingbackend(ui, repo, similarity)
1428 backend = workingbackend(ui, repo, similarity)
1417 return patchbackend(ui, backend, patchobj, strip, files, eolmode)
1429 return patchbackend(ui, backend, patchobj, strip, files, eolmode)
1418
1430
1419 def patchrepo(ui, repo, ctx, store, patchobj, strip, files=None,
1431 def patchrepo(ui, repo, ctx, store, patchobj, strip, files=None,
1420 eolmode='strict'):
1432 eolmode='strict'):
1421 backend = repobackend(ui, repo, ctx, store)
1433 backend = repobackend(ui, repo, ctx, store)
1422 return patchbackend(ui, backend, patchobj, strip, files, eolmode)
1434 return patchbackend(ui, backend, patchobj, strip, files, eolmode)
1423
1435
1424 def makememctx(repo, parents, text, user, date, branch, files, store,
1436 def makememctx(repo, parents, text, user, date, branch, files, store,
1425 editor=None):
1437 editor=None):
1426 def getfilectx(repo, memctx, path):
1438 def getfilectx(repo, memctx, path):
1427 data, (islink, isexec), copied = store.getfile(path)
1439 data, (islink, isexec), copied = store.getfile(path)
1428 return context.memfilectx(path, data, islink=islink, isexec=isexec,
1440 return context.memfilectx(path, data, islink=islink, isexec=isexec,
1429 copied=copied)
1441 copied=copied)
1430 extra = {}
1442 extra = {}
1431 if branch:
1443 if branch:
1432 extra['branch'] = encoding.fromlocal(branch)
1444 extra['branch'] = encoding.fromlocal(branch)
1433 ctx = context.memctx(repo, parents, text, files, getfilectx, user,
1445 ctx = context.memctx(repo, parents, text, files, getfilectx, user,
1434 date, extra)
1446 date, extra)
1435 if editor:
1447 if editor:
1436 ctx._text = editor(repo, ctx, [])
1448 ctx._text = editor(repo, ctx, [])
1437 return ctx
1449 return ctx
1438
1450
1439 def patch(ui, repo, patchname, strip=1, files=None, eolmode='strict',
1451 def patch(ui, repo, patchname, strip=1, files=None, eolmode='strict',
1440 similarity=0):
1452 similarity=0):
1441 """Apply <patchname> to the working directory.
1453 """Apply <patchname> to the working directory.
1442
1454
1443 'eolmode' specifies how end of lines should be handled. It can be:
1455 'eolmode' specifies how end of lines should be handled. It can be:
1444 - 'strict': inputs are read in binary mode, EOLs are preserved
1456 - 'strict': inputs are read in binary mode, EOLs are preserved
1445 - 'crlf': EOLs are ignored when patching and reset to CRLF
1457 - 'crlf': EOLs are ignored when patching and reset to CRLF
1446 - 'lf': EOLs are ignored when patching and reset to LF
1458 - 'lf': EOLs are ignored when patching and reset to LF
1447 - None: get it from user settings, default to 'strict'
1459 - None: get it from user settings, default to 'strict'
1448 'eolmode' is ignored when using an external patcher program.
1460 'eolmode' is ignored when using an external patcher program.
1449
1461
1450 Returns whether patch was applied with fuzz factor.
1462 Returns whether patch was applied with fuzz factor.
1451 """
1463 """
1452 patcher = ui.config('ui', 'patch')
1464 patcher = ui.config('ui', 'patch')
1453 if files is None:
1465 if files is None:
1454 files = set()
1466 files = set()
1455 try:
1467 try:
1456 if patcher:
1468 if patcher:
1457 return _externalpatch(ui, repo, patcher, patchname, strip,
1469 return _externalpatch(ui, repo, patcher, patchname, strip,
1458 files, similarity)
1470 files, similarity)
1459 return internalpatch(ui, repo, patchname, strip, files, eolmode,
1471 return internalpatch(ui, repo, patchname, strip, files, eolmode,
1460 similarity)
1472 similarity)
1461 except PatchError, err:
1473 except PatchError, err:
1462 raise util.Abort(str(err))
1474 raise util.Abort(str(err))
1463
1475
1464 def changedfiles(ui, repo, patchpath, strip=1):
1476 def changedfiles(ui, repo, patchpath, strip=1):
1465 backend = fsbackend(ui, repo.root)
1477 backend = fsbackend(ui, repo.root)
1466 fp = open(patchpath, 'rb')
1478 fp = open(patchpath, 'rb')
1467 try:
1479 try:
1468 changed = set()
1480 changed = set()
1469 for state, values in iterhunks(fp):
1481 for state, values in iterhunks(fp):
1470 if state == 'file':
1482 if state == 'file':
1471 afile, bfile, first_hunk, gp = values
1483 afile, bfile, first_hunk, gp = values
1472 if gp:
1484 if gp:
1473 gp.path = pathstrip(gp.path, strip - 1)[1]
1485 gp.path = pathstrip(gp.path, strip - 1)[1]
1474 if gp.oldpath:
1486 if gp.oldpath:
1475 gp.oldpath = pathstrip(gp.oldpath, strip - 1)[1]
1487 gp.oldpath = pathstrip(gp.oldpath, strip - 1)[1]
1476 else:
1488 else:
1477 gp = makepatchmeta(backend, afile, bfile, first_hunk, strip)
1489 gp = makepatchmeta(backend, afile, bfile, first_hunk, strip)
1478 changed.add(gp.path)
1490 changed.add(gp.path)
1479 if gp.op == 'RENAME':
1491 if gp.op == 'RENAME':
1480 changed.add(gp.oldpath)
1492 changed.add(gp.oldpath)
1481 elif state not in ('hunk', 'git'):
1493 elif state not in ('hunk', 'git'):
1482 raise util.Abort(_('unsupported parser state: %s') % state)
1494 raise util.Abort(_('unsupported parser state: %s') % state)
1483 return changed
1495 return changed
1484 finally:
1496 finally:
1485 fp.close()
1497 fp.close()
1486
1498
1487 def b85diff(to, tn):
1499 def b85diff(to, tn):
1488 '''print base85-encoded binary diff'''
1500 '''print base85-encoded binary diff'''
1489 def gitindex(text):
1501 def gitindex(text):
1490 if not text:
1502 if not text:
1491 return hex(nullid)
1503 return hex(nullid)
1492 l = len(text)
1504 l = len(text)
1493 s = util.sha1('blob %d\0' % l)
1505 s = util.sha1('blob %d\0' % l)
1494 s.update(text)
1506 s.update(text)
1495 return s.hexdigest()
1507 return s.hexdigest()
1496
1508
1497 def fmtline(line):
1509 def fmtline(line):
1498 l = len(line)
1510 l = len(line)
1499 if l <= 26:
1511 if l <= 26:
1500 l = chr(ord('A') + l - 1)
1512 l = chr(ord('A') + l - 1)
1501 else:
1513 else:
1502 l = chr(l - 26 + ord('a') - 1)
1514 l = chr(l - 26 + ord('a') - 1)
1503 return '%c%s\n' % (l, base85.b85encode(line, True))
1515 return '%c%s\n' % (l, base85.b85encode(line, True))
1504
1516
1505 def chunk(text, csize=52):
1517 def chunk(text, csize=52):
1506 l = len(text)
1518 l = len(text)
1507 i = 0
1519 i = 0
1508 while i < l:
1520 while i < l:
1509 yield text[i:i + csize]
1521 yield text[i:i + csize]
1510 i += csize
1522 i += csize
1511
1523
1512 tohash = gitindex(to)
1524 tohash = gitindex(to)
1513 tnhash = gitindex(tn)
1525 tnhash = gitindex(tn)
1514 if tohash == tnhash:
1526 if tohash == tnhash:
1515 return ""
1527 return ""
1516
1528
1517 # TODO: deltas
1529 # TODO: deltas
1518 ret = ['index %s..%s\nGIT binary patch\nliteral %s\n' %
1530 ret = ['index %s..%s\nGIT binary patch\nliteral %s\n' %
1519 (tohash, tnhash, len(tn))]
1531 (tohash, tnhash, len(tn))]
1520 for l in chunk(zlib.compress(tn)):
1532 for l in chunk(zlib.compress(tn)):
1521 ret.append(fmtline(l))
1533 ret.append(fmtline(l))
1522 ret.append('\n')
1534 ret.append('\n')
1523 return ''.join(ret)
1535 return ''.join(ret)
1524
1536
1525 class GitDiffRequired(Exception):
1537 class GitDiffRequired(Exception):
1526 pass
1538 pass
1527
1539
1528 def diffopts(ui, opts=None, untrusted=False, section='diff'):
1540 def diffopts(ui, opts=None, untrusted=False, section='diff'):
1529 def get(key, name=None, getter=ui.configbool):
1541 def get(key, name=None, getter=ui.configbool):
1530 return ((opts and opts.get(key)) or
1542 return ((opts and opts.get(key)) or
1531 getter(section, name or key, None, untrusted=untrusted))
1543 getter(section, name or key, None, untrusted=untrusted))
1532 return mdiff.diffopts(
1544 return mdiff.diffopts(
1533 text=opts and opts.get('text'),
1545 text=opts and opts.get('text'),
1534 git=get('git'),
1546 git=get('git'),
1535 nodates=get('nodates'),
1547 nodates=get('nodates'),
1536 showfunc=get('show_function', 'showfunc'),
1548 showfunc=get('show_function', 'showfunc'),
1537 ignorews=get('ignore_all_space', 'ignorews'),
1549 ignorews=get('ignore_all_space', 'ignorews'),
1538 ignorewsamount=get('ignore_space_change', 'ignorewsamount'),
1550 ignorewsamount=get('ignore_space_change', 'ignorewsamount'),
1539 ignoreblanklines=get('ignore_blank_lines', 'ignoreblanklines'),
1551 ignoreblanklines=get('ignore_blank_lines', 'ignoreblanklines'),
1540 context=get('unified', getter=ui.config))
1552 context=get('unified', getter=ui.config))
1541
1553
1542 def diff(repo, node1=None, node2=None, match=None, changes=None, opts=None,
1554 def diff(repo, node1=None, node2=None, match=None, changes=None, opts=None,
1543 losedatafn=None, prefix=''):
1555 losedatafn=None, prefix=''):
1544 '''yields diff of changes to files between two nodes, or node and
1556 '''yields diff of changes to files between two nodes, or node and
1545 working directory.
1557 working directory.
1546
1558
1547 if node1 is None, use first dirstate parent instead.
1559 if node1 is None, use first dirstate parent instead.
1548 if node2 is None, compare node1 with working directory.
1560 if node2 is None, compare node1 with working directory.
1549
1561
1550 losedatafn(**kwarg) is a callable run when opts.upgrade=True and
1562 losedatafn(**kwarg) is a callable run when opts.upgrade=True and
1551 every time some change cannot be represented with the current
1563 every time some change cannot be represented with the current
1552 patch format. Return False to upgrade to git patch format, True to
1564 patch format. Return False to upgrade to git patch format, True to
1553 accept the loss or raise an exception to abort the diff. It is
1565 accept the loss or raise an exception to abort the diff. It is
1554 called with the name of current file being diffed as 'fn'. If set
1566 called with the name of current file being diffed as 'fn'. If set
1555 to None, patches will always be upgraded to git format when
1567 to None, patches will always be upgraded to git format when
1556 necessary.
1568 necessary.
1557
1569
1558 prefix is a filename prefix that is prepended to all filenames on
1570 prefix is a filename prefix that is prepended to all filenames on
1559 display (used for subrepos).
1571 display (used for subrepos).
1560 '''
1572 '''
1561
1573
1562 if opts is None:
1574 if opts is None:
1563 opts = mdiff.defaultopts
1575 opts = mdiff.defaultopts
1564
1576
1565 if not node1 and not node2:
1577 if not node1 and not node2:
1566 node1 = repo.dirstate.p1()
1578 node1 = repo.dirstate.p1()
1567
1579
1568 def lrugetfilectx():
1580 def lrugetfilectx():
1569 cache = {}
1581 cache = {}
1570 order = []
1582 order = []
1571 def getfilectx(f, ctx):
1583 def getfilectx(f, ctx):
1572 fctx = ctx.filectx(f, filelog=cache.get(f))
1584 fctx = ctx.filectx(f, filelog=cache.get(f))
1573 if f not in cache:
1585 if f not in cache:
1574 if len(cache) > 20:
1586 if len(cache) > 20:
1575 del cache[order.pop(0)]
1587 del cache[order.pop(0)]
1576 cache[f] = fctx.filelog()
1588 cache[f] = fctx.filelog()
1577 else:
1589 else:
1578 order.remove(f)
1590 order.remove(f)
1579 order.append(f)
1591 order.append(f)
1580 return fctx
1592 return fctx
1581 return getfilectx
1593 return getfilectx
1582 getfilectx = lrugetfilectx()
1594 getfilectx = lrugetfilectx()
1583
1595
1584 ctx1 = repo[node1]
1596 ctx1 = repo[node1]
1585 ctx2 = repo[node2]
1597 ctx2 = repo[node2]
1586
1598
1587 if not changes:
1599 if not changes:
1588 changes = repo.status(ctx1, ctx2, match=match)
1600 changes = repo.status(ctx1, ctx2, match=match)
1589 modified, added, removed = changes[:3]
1601 modified, added, removed = changes[:3]
1590
1602
1591 if not modified and not added and not removed:
1603 if not modified and not added and not removed:
1592 return []
1604 return []
1593
1605
1594 revs = None
1606 revs = None
1595 if not repo.ui.quiet:
1607 if not repo.ui.quiet:
1596 hexfunc = repo.ui.debugflag and hex or short
1608 hexfunc = repo.ui.debugflag and hex or short
1597 revs = [hexfunc(node) for node in [node1, node2] if node]
1609 revs = [hexfunc(node) for node in [node1, node2] if node]
1598
1610
1599 copy = {}
1611 copy = {}
1600 if opts.git or opts.upgrade:
1612 if opts.git or opts.upgrade:
1601 copy = copies.pathcopies(ctx1, ctx2)
1613 copy = copies.pathcopies(ctx1, ctx2)
1602
1614
1603 difffn = lambda opts, losedata: trydiff(repo, revs, ctx1, ctx2,
1615 difffn = lambda opts, losedata: trydiff(repo, revs, ctx1, ctx2,
1604 modified, added, removed, copy, getfilectx, opts, losedata, prefix)
1616 modified, added, removed, copy, getfilectx, opts, losedata, prefix)
1605 if opts.upgrade and not opts.git:
1617 if opts.upgrade and not opts.git:
1606 try:
1618 try:
1607 def losedata(fn):
1619 def losedata(fn):
1608 if not losedatafn or not losedatafn(fn=fn):
1620 if not losedatafn or not losedatafn(fn=fn):
1609 raise GitDiffRequired()
1621 raise GitDiffRequired()
1610 # Buffer the whole output until we are sure it can be generated
1622 # Buffer the whole output until we are sure it can be generated
1611 return list(difffn(opts.copy(git=False), losedata))
1623 return list(difffn(opts.copy(git=False), losedata))
1612 except GitDiffRequired:
1624 except GitDiffRequired:
1613 return difffn(opts.copy(git=True), None)
1625 return difffn(opts.copy(git=True), None)
1614 else:
1626 else:
1615 return difffn(opts, None)
1627 return difffn(opts, None)
1616
1628
1617 def difflabel(func, *args, **kw):
1629 def difflabel(func, *args, **kw):
1618 '''yields 2-tuples of (output, label) based on the output of func()'''
1630 '''yields 2-tuples of (output, label) based on the output of func()'''
1619 headprefixes = [('diff', 'diff.diffline'),
1631 headprefixes = [('diff', 'diff.diffline'),
1620 ('copy', 'diff.extended'),
1632 ('copy', 'diff.extended'),
1621 ('rename', 'diff.extended'),
1633 ('rename', 'diff.extended'),
1622 ('old', 'diff.extended'),
1634 ('old', 'diff.extended'),
1623 ('new', 'diff.extended'),
1635 ('new', 'diff.extended'),
1624 ('deleted', 'diff.extended'),
1636 ('deleted', 'diff.extended'),
1625 ('---', 'diff.file_a'),
1637 ('---', 'diff.file_a'),
1626 ('+++', 'diff.file_b')]
1638 ('+++', 'diff.file_b')]
1627 textprefixes = [('@', 'diff.hunk'),
1639 textprefixes = [('@', 'diff.hunk'),
1628 ('-', 'diff.deleted'),
1640 ('-', 'diff.deleted'),
1629 ('+', 'diff.inserted')]
1641 ('+', 'diff.inserted')]
1630 head = False
1642 head = False
1631 for chunk in func(*args, **kw):
1643 for chunk in func(*args, **kw):
1632 lines = chunk.split('\n')
1644 lines = chunk.split('\n')
1633 for i, line in enumerate(lines):
1645 for i, line in enumerate(lines):
1634 if i != 0:
1646 if i != 0:
1635 yield ('\n', '')
1647 yield ('\n', '')
1636 if head:
1648 if head:
1637 if line.startswith('@'):
1649 if line.startswith('@'):
1638 head = False
1650 head = False
1639 else:
1651 else:
1640 if line and not line[0] in ' +-@\\':
1652 if line and not line[0] in ' +-@\\':
1641 head = True
1653 head = True
1642 stripline = line
1654 stripline = line
1643 if not head and line and line[0] in '+-':
1655 if not head and line and line[0] in '+-':
1644 # highlight trailing whitespace, but only in changed lines
1656 # highlight trailing whitespace, but only in changed lines
1645 stripline = line.rstrip()
1657 stripline = line.rstrip()
1646 prefixes = textprefixes
1658 prefixes = textprefixes
1647 if head:
1659 if head:
1648 prefixes = headprefixes
1660 prefixes = headprefixes
1649 for prefix, label in prefixes:
1661 for prefix, label in prefixes:
1650 if stripline.startswith(prefix):
1662 if stripline.startswith(prefix):
1651 yield (stripline, label)
1663 yield (stripline, label)
1652 break
1664 break
1653 else:
1665 else:
1654 yield (line, '')
1666 yield (line, '')
1655 if line != stripline:
1667 if line != stripline:
1656 yield (line[len(stripline):], 'diff.trailingwhitespace')
1668 yield (line[len(stripline):], 'diff.trailingwhitespace')
1657
1669
1658 def diffui(*args, **kw):
1670 def diffui(*args, **kw):
1659 '''like diff(), but yields 2-tuples of (output, label) for ui.write()'''
1671 '''like diff(), but yields 2-tuples of (output, label) for ui.write()'''
1660 return difflabel(diff, *args, **kw)
1672 return difflabel(diff, *args, **kw)
1661
1673
1662
1674
1663 def _addmodehdr(header, omode, nmode):
1675 def _addmodehdr(header, omode, nmode):
1664 if omode != nmode:
1676 if omode != nmode:
1665 header.append('old mode %s\n' % omode)
1677 header.append('old mode %s\n' % omode)
1666 header.append('new mode %s\n' % nmode)
1678 header.append('new mode %s\n' % nmode)
1667
1679
1668 def trydiff(repo, revs, ctx1, ctx2, modified, added, removed,
1680 def trydiff(repo, revs, ctx1, ctx2, modified, added, removed,
1669 copy, getfilectx, opts, losedatafn, prefix):
1681 copy, getfilectx, opts, losedatafn, prefix):
1670
1682
1671 def join(f):
1683 def join(f):
1672 return os.path.join(prefix, f)
1684 return os.path.join(prefix, f)
1673
1685
1674 date1 = util.datestr(ctx1.date())
1686 date1 = util.datestr(ctx1.date())
1675 man1 = ctx1.manifest()
1687 man1 = ctx1.manifest()
1676
1688
1677 gone = set()
1689 gone = set()
1678 gitmode = {'l': '120000', 'x': '100755', '': '100644'}
1690 gitmode = {'l': '120000', 'x': '100755', '': '100644'}
1679
1691
1680 copyto = dict([(v, k) for k, v in copy.items()])
1692 copyto = dict([(v, k) for k, v in copy.items()])
1681
1693
1682 if opts.git:
1694 if opts.git:
1683 revs = None
1695 revs = None
1684
1696
1685 for f in sorted(modified + added + removed):
1697 for f in sorted(modified + added + removed):
1686 to = None
1698 to = None
1687 tn = None
1699 tn = None
1688 dodiff = True
1700 dodiff = True
1689 header = []
1701 header = []
1690 if f in man1:
1702 if f in man1:
1691 to = getfilectx(f, ctx1).data()
1703 to = getfilectx(f, ctx1).data()
1692 if f not in removed:
1704 if f not in removed:
1693 tn = getfilectx(f, ctx2).data()
1705 tn = getfilectx(f, ctx2).data()
1694 a, b = f, f
1706 a, b = f, f
1695 if opts.git or losedatafn:
1707 if opts.git or losedatafn:
1696 if f in added:
1708 if f in added:
1697 mode = gitmode[ctx2.flags(f)]
1709 mode = gitmode[ctx2.flags(f)]
1698 if f in copy or f in copyto:
1710 if f in copy or f in copyto:
1699 if opts.git:
1711 if opts.git:
1700 if f in copy:
1712 if f in copy:
1701 a = copy[f]
1713 a = copy[f]
1702 else:
1714 else:
1703 a = copyto[f]
1715 a = copyto[f]
1704 omode = gitmode[man1.flags(a)]
1716 omode = gitmode[man1.flags(a)]
1705 _addmodehdr(header, omode, mode)
1717 _addmodehdr(header, omode, mode)
1706 if a in removed and a not in gone:
1718 if a in removed and a not in gone:
1707 op = 'rename'
1719 op = 'rename'
1708 gone.add(a)
1720 gone.add(a)
1709 else:
1721 else:
1710 op = 'copy'
1722 op = 'copy'
1711 header.append('%s from %s\n' % (op, join(a)))
1723 header.append('%s from %s\n' % (op, join(a)))
1712 header.append('%s to %s\n' % (op, join(f)))
1724 header.append('%s to %s\n' % (op, join(f)))
1713 to = getfilectx(a, ctx1).data()
1725 to = getfilectx(a, ctx1).data()
1714 else:
1726 else:
1715 losedatafn(f)
1727 losedatafn(f)
1716 else:
1728 else:
1717 if opts.git:
1729 if opts.git:
1718 header.append('new file mode %s\n' % mode)
1730 header.append('new file mode %s\n' % mode)
1719 elif ctx2.flags(f):
1731 elif ctx2.flags(f):
1720 losedatafn(f)
1732 losedatafn(f)
1721 # In theory, if tn was copied or renamed we should check
1733 # In theory, if tn was copied or renamed we should check
1722 # if the source is binary too but the copy record already
1734 # if the source is binary too but the copy record already
1723 # forces git mode.
1735 # forces git mode.
1724 if util.binary(tn):
1736 if util.binary(tn):
1725 if opts.git:
1737 if opts.git:
1726 dodiff = 'binary'
1738 dodiff = 'binary'
1727 else:
1739 else:
1728 losedatafn(f)
1740 losedatafn(f)
1729 if not opts.git and not tn:
1741 if not opts.git and not tn:
1730 # regular diffs cannot represent new empty file
1742 # regular diffs cannot represent new empty file
1731 losedatafn(f)
1743 losedatafn(f)
1732 elif f in removed:
1744 elif f in removed:
1733 if opts.git:
1745 if opts.git:
1734 # have we already reported a copy above?
1746 # have we already reported a copy above?
1735 if ((f in copy and copy[f] in added
1747 if ((f in copy and copy[f] in added
1736 and copyto[copy[f]] == f) or
1748 and copyto[copy[f]] == f) or
1737 (f in copyto and copyto[f] in added
1749 (f in copyto and copyto[f] in added
1738 and copy[copyto[f]] == f)):
1750 and copy[copyto[f]] == f)):
1739 dodiff = False
1751 dodiff = False
1740 else:
1752 else:
1741 header.append('deleted file mode %s\n' %
1753 header.append('deleted file mode %s\n' %
1742 gitmode[man1.flags(f)])
1754 gitmode[man1.flags(f)])
1743 elif not to or util.binary(to):
1755 elif not to or util.binary(to):
1744 # regular diffs cannot represent empty file deletion
1756 # regular diffs cannot represent empty file deletion
1745 losedatafn(f)
1757 losedatafn(f)
1746 else:
1758 else:
1747 oflag = man1.flags(f)
1759 oflag = man1.flags(f)
1748 nflag = ctx2.flags(f)
1760 nflag = ctx2.flags(f)
1749 binary = util.binary(to) or util.binary(tn)
1761 binary = util.binary(to) or util.binary(tn)
1750 if opts.git:
1762 if opts.git:
1751 _addmodehdr(header, gitmode[oflag], gitmode[nflag])
1763 _addmodehdr(header, gitmode[oflag], gitmode[nflag])
1752 if binary:
1764 if binary:
1753 dodiff = 'binary'
1765 dodiff = 'binary'
1754 elif binary or nflag != oflag:
1766 elif binary or nflag != oflag:
1755 losedatafn(f)
1767 losedatafn(f)
1756 if opts.git:
1768 if opts.git:
1757 header.insert(0, mdiff.diffline(revs, join(a), join(b), opts))
1769 header.insert(0, mdiff.diffline(revs, join(a), join(b), opts))
1758
1770
1759 if dodiff:
1771 if dodiff:
1760 if dodiff == 'binary':
1772 if dodiff == 'binary':
1761 text = b85diff(to, tn)
1773 text = b85diff(to, tn)
1762 else:
1774 else:
1763 text = mdiff.unidiff(to, date1,
1775 text = mdiff.unidiff(to, date1,
1764 # ctx2 date may be dynamic
1776 # ctx2 date may be dynamic
1765 tn, util.datestr(ctx2.date()),
1777 tn, util.datestr(ctx2.date()),
1766 join(a), join(b), revs, opts=opts)
1778 join(a), join(b), revs, opts=opts)
1767 if header and (text or len(header) > 1):
1779 if header and (text or len(header) > 1):
1768 yield ''.join(header)
1780 yield ''.join(header)
1769 if text:
1781 if text:
1770 yield text
1782 yield text
1771
1783
1772 def diffstatsum(stats):
1784 def diffstatsum(stats):
1773 maxfile, maxtotal, addtotal, removetotal, binary = 0, 0, 0, 0, False
1785 maxfile, maxtotal, addtotal, removetotal, binary = 0, 0, 0, 0, False
1774 for f, a, r, b in stats:
1786 for f, a, r, b in stats:
1775 maxfile = max(maxfile, encoding.colwidth(f))
1787 maxfile = max(maxfile, encoding.colwidth(f))
1776 maxtotal = max(maxtotal, a + r)
1788 maxtotal = max(maxtotal, a + r)
1777 addtotal += a
1789 addtotal += a
1778 removetotal += r
1790 removetotal += r
1779 binary = binary or b
1791 binary = binary or b
1780
1792
1781 return maxfile, maxtotal, addtotal, removetotal, binary
1793 return maxfile, maxtotal, addtotal, removetotal, binary
1782
1794
1783 def diffstatdata(lines):
1795 def diffstatdata(lines):
1784 diffre = re.compile('^diff .*-r [a-z0-9]+\s(.*)$')
1796 diffre = re.compile('^diff .*-r [a-z0-9]+\s(.*)$')
1785
1797
1786 results = []
1798 results = []
1787 filename, adds, removes, isbinary = None, 0, 0, False
1799 filename, adds, removes, isbinary = None, 0, 0, False
1788
1800
1789 def addresult():
1801 def addresult():
1790 if filename:
1802 if filename:
1791 results.append((filename, adds, removes, isbinary))
1803 results.append((filename, adds, removes, isbinary))
1792
1804
1793 for line in lines:
1805 for line in lines:
1794 if line.startswith('diff'):
1806 if line.startswith('diff'):
1795 addresult()
1807 addresult()
1796 # set numbers to 0 anyway when starting new file
1808 # set numbers to 0 anyway when starting new file
1797 adds, removes, isbinary = 0, 0, False
1809 adds, removes, isbinary = 0, 0, False
1798 if line.startswith('diff --git'):
1810 if line.startswith('diff --git'):
1799 filename = gitre.search(line).group(1)
1811 filename = gitre.search(line).group(1)
1800 elif line.startswith('diff -r'):
1812 elif line.startswith('diff -r'):
1801 # format: "diff -r ... -r ... filename"
1813 # format: "diff -r ... -r ... filename"
1802 filename = diffre.search(line).group(1)
1814 filename = diffre.search(line).group(1)
1803 elif line.startswith('+') and not line.startswith('+++ '):
1815 elif line.startswith('+') and not line.startswith('+++ '):
1804 adds += 1
1816 adds += 1
1805 elif line.startswith('-') and not line.startswith('--- '):
1817 elif line.startswith('-') and not line.startswith('--- '):
1806 removes += 1
1818 removes += 1
1807 elif (line.startswith('GIT binary patch') or
1819 elif (line.startswith('GIT binary patch') or
1808 line.startswith('Binary file')):
1820 line.startswith('Binary file')):
1809 isbinary = True
1821 isbinary = True
1810 addresult()
1822 addresult()
1811 return results
1823 return results
1812
1824
1813 def diffstat(lines, width=80, git=False):
1825 def diffstat(lines, width=80, git=False):
1814 output = []
1826 output = []
1815 stats = diffstatdata(lines)
1827 stats = diffstatdata(lines)
1816 maxname, maxtotal, totaladds, totalremoves, hasbinary = diffstatsum(stats)
1828 maxname, maxtotal, totaladds, totalremoves, hasbinary = diffstatsum(stats)
1817
1829
1818 countwidth = len(str(maxtotal))
1830 countwidth = len(str(maxtotal))
1819 if hasbinary and countwidth < 3:
1831 if hasbinary and countwidth < 3:
1820 countwidth = 3
1832 countwidth = 3
1821 graphwidth = width - countwidth - maxname - 6
1833 graphwidth = width - countwidth - maxname - 6
1822 if graphwidth < 10:
1834 if graphwidth < 10:
1823 graphwidth = 10
1835 graphwidth = 10
1824
1836
1825 def scale(i):
1837 def scale(i):
1826 if maxtotal <= graphwidth:
1838 if maxtotal <= graphwidth:
1827 return i
1839 return i
1828 # If diffstat runs out of room it doesn't print anything,
1840 # If diffstat runs out of room it doesn't print anything,
1829 # which isn't very useful, so always print at least one + or -
1841 # which isn't very useful, so always print at least one + or -
1830 # if there were at least some changes.
1842 # if there were at least some changes.
1831 return max(i * graphwidth // maxtotal, int(bool(i)))
1843 return max(i * graphwidth // maxtotal, int(bool(i)))
1832
1844
1833 for filename, adds, removes, isbinary in stats:
1845 for filename, adds, removes, isbinary in stats:
1834 if isbinary:
1846 if isbinary:
1835 count = 'Bin'
1847 count = 'Bin'
1836 else:
1848 else:
1837 count = adds + removes
1849 count = adds + removes
1838 pluses = '+' * scale(adds)
1850 pluses = '+' * scale(adds)
1839 minuses = '-' * scale(removes)
1851 minuses = '-' * scale(removes)
1840 output.append(' %s%s | %*s %s%s\n' %
1852 output.append(' %s%s | %*s %s%s\n' %
1841 (filename, ' ' * (maxname - encoding.colwidth(filename)),
1853 (filename, ' ' * (maxname - encoding.colwidth(filename)),
1842 countwidth, count, pluses, minuses))
1854 countwidth, count, pluses, minuses))
1843
1855
1844 if stats:
1856 if stats:
1845 output.append(_(' %d files changed, %d insertions(+), %d deletions(-)\n')
1857 output.append(_(' %d files changed, %d insertions(+), %d deletions(-)\n')
1846 % (len(stats), totaladds, totalremoves))
1858 % (len(stats), totaladds, totalremoves))
1847
1859
1848 return ''.join(output)
1860 return ''.join(output)
1849
1861
1850 def diffstatui(*args, **kw):
1862 def diffstatui(*args, **kw):
1851 '''like diffstat(), but yields 2-tuples of (output, label) for
1863 '''like diffstat(), but yields 2-tuples of (output, label) for
1852 ui.write()
1864 ui.write()
1853 '''
1865 '''
1854
1866
1855 for line in diffstat(*args, **kw).splitlines():
1867 for line in diffstat(*args, **kw).splitlines():
1856 if line and line[-1] in '+-':
1868 if line and line[-1] in '+-':
1857 name, graph = line.rsplit(' ', 1)
1869 name, graph = line.rsplit(' ', 1)
1858 yield (name + ' ', '')
1870 yield (name + ' ', '')
1859 m = re.search(r'\++', graph)
1871 m = re.search(r'\++', graph)
1860 if m:
1872 if m:
1861 yield (m.group(0), 'diffstat.inserted')
1873 yield (m.group(0), 'diffstat.inserted')
1862 m = re.search(r'-+', graph)
1874 m = re.search(r'-+', graph)
1863 if m:
1875 if m:
1864 yield (m.group(0), 'diffstat.deleted')
1876 yield (m.group(0), 'diffstat.deleted')
1865 else:
1877 else:
1866 yield (line, '')
1878 yield (line, '')
1867 yield ('\n', '')
1879 yield ('\n', '')
@@ -1,486 +1,510 b''
1 $ "$TESTDIR/hghave" symlink || exit 80
1 $ "$TESTDIR/hghave" symlink || exit 80
2
2
3 $ hg init
3 $ hg init
4
4
5 New file:
5 New file:
6
6
7 $ hg import -d "1000000 0" -mnew - <<EOF
7 $ hg import -d "1000000 0" -mnew - <<EOF
8 > diff --git a/new b/new
8 > diff --git a/new b/new
9 > new file mode 100644
9 > new file mode 100644
10 > index 0000000..7898192
10 > index 0000000..7898192
11 > --- /dev/null
11 > --- /dev/null
12 > +++ b/new
12 > +++ b/new
13 > @@ -0,0 +1 @@
13 > @@ -0,0 +1 @@
14 > +a
14 > +a
15 > EOF
15 > EOF
16 applying patch from stdin
16 applying patch from stdin
17
17
18 $ hg tip -q
18 $ hg tip -q
19 0:ae3ee40d2079
19 0:ae3ee40d2079
20
20
21 New empty file:
21 New empty file:
22
22
23 $ hg import -d "1000000 0" -mempty - <<EOF
23 $ hg import -d "1000000 0" -mempty - <<EOF
24 > diff --git a/empty b/empty
24 > diff --git a/empty b/empty
25 > new file mode 100644
25 > new file mode 100644
26 > EOF
26 > EOF
27 applying patch from stdin
27 applying patch from stdin
28
28
29 $ hg tip -q
29 $ hg tip -q
30 1:ab199dc869b5
30 1:ab199dc869b5
31
31
32 $ hg locate empty
32 $ hg locate empty
33 empty
33 empty
34
34
35 chmod +x:
35 chmod +x:
36
36
37 $ hg import -d "1000000 0" -msetx - <<EOF
37 $ hg import -d "1000000 0" -msetx - <<EOF
38 > diff --git a/new b/new
38 > diff --git a/new b/new
39 > old mode 100644
39 > old mode 100644
40 > new mode 100755
40 > new mode 100755
41 > EOF
41 > EOF
42 applying patch from stdin
42 applying patch from stdin
43
43
44 $ hg tip -q
44 $ hg tip -q
45 2:3a34410f282e
45 2:3a34410f282e
46
46
47 $ test -x new
47 $ test -x new
48
48
49 Copy:
49 Copy:
50
50
51 $ hg import -d "1000000 0" -mcopy - <<EOF
51 $ hg import -d "1000000 0" -mcopy - <<EOF
52 > diff --git a/new b/copy
52 > diff --git a/new b/copy
53 > old mode 100755
53 > old mode 100755
54 > new mode 100644
54 > new mode 100644
55 > similarity index 100%
55 > similarity index 100%
56 > copy from new
56 > copy from new
57 > copy to copy
57 > copy to copy
58 > diff --git a/new b/copyx
58 > diff --git a/new b/copyx
59 > similarity index 100%
59 > similarity index 100%
60 > copy from new
60 > copy from new
61 > copy to copyx
61 > copy to copyx
62 > EOF
62 > EOF
63 applying patch from stdin
63 applying patch from stdin
64
64
65 $ hg tip -q
65 $ hg tip -q
66 3:37bacb7ca14d
66 3:37bacb7ca14d
67
67
68 $ if "$TESTDIR/hghave" -q execbit; then
68 $ if "$TESTDIR/hghave" -q execbit; then
69 > test -f copy -a ! -x copy || echo bad
69 > test -f copy -a ! -x copy || echo bad
70 > test -x copyx || echo bad
70 > test -x copyx || echo bad
71 > else
71 > else
72 > test -f copy || echo bad
72 > test -f copy || echo bad
73 > fi
73 > fi
74
74
75 $ cat copy
75 $ cat copy
76 a
76 a
77
77
78 $ hg cat copy
78 $ hg cat copy
79 a
79 a
80
80
81 Rename:
81 Rename:
82
82
83 $ hg import -d "1000000 0" -mrename - <<EOF
83 $ hg import -d "1000000 0" -mrename - <<EOF
84 > diff --git a/copy b/rename
84 > diff --git a/copy b/rename
85 > similarity index 100%
85 > similarity index 100%
86 > rename from copy
86 > rename from copy
87 > rename to rename
87 > rename to rename
88 > EOF
88 > EOF
89 applying patch from stdin
89 applying patch from stdin
90
90
91 $ hg tip -q
91 $ hg tip -q
92 4:47b81a94361d
92 4:47b81a94361d
93
93
94 $ hg locate
94 $ hg locate
95 copyx
95 copyx
96 empty
96 empty
97 new
97 new
98 rename
98 rename
99
99
100 Delete:
100 Delete:
101
101
102 $ hg import -d "1000000 0" -mdelete - <<EOF
102 $ hg import -d "1000000 0" -mdelete - <<EOF
103 > diff --git a/copyx b/copyx
103 > diff --git a/copyx b/copyx
104 > deleted file mode 100755
104 > deleted file mode 100755
105 > index 7898192..0000000
105 > index 7898192..0000000
106 > --- a/copyx
106 > --- a/copyx
107 > +++ /dev/null
107 > +++ /dev/null
108 > @@ -1 +0,0 @@
108 > @@ -1 +0,0 @@
109 > -a
109 > -a
110 > EOF
110 > EOF
111 applying patch from stdin
111 applying patch from stdin
112
112
113 $ hg tip -q
113 $ hg tip -q
114 5:d9b001d98336
114 5:d9b001d98336
115
115
116 $ hg locate
116 $ hg locate
117 empty
117 empty
118 new
118 new
119 rename
119 rename
120
120
121 $ test -f copyx
121 $ test -f copyx
122 [1]
122 [1]
123
123
124 Regular diff:
124 Regular diff:
125
125
126 $ hg import -d "1000000 0" -mregular - <<EOF
126 $ hg import -d "1000000 0" -mregular - <<EOF
127 > diff --git a/rename b/rename
127 > diff --git a/rename b/rename
128 > index 7898192..72e1fe3 100644
128 > index 7898192..72e1fe3 100644
129 > --- a/rename
129 > --- a/rename
130 > +++ b/rename
130 > +++ b/rename
131 > @@ -1 +1,5 @@
131 > @@ -1 +1,5 @@
132 > a
132 > a
133 > +a
133 > +a
134 > +a
134 > +a
135 > +a
135 > +a
136 > +a
136 > +a
137 > EOF
137 > EOF
138 applying patch from stdin
138 applying patch from stdin
139
139
140 $ hg tip -q
140 $ hg tip -q
141 6:ebe901e7576b
141 6:ebe901e7576b
142
142
143 Copy and modify:
143 Copy and modify:
144
144
145 $ hg import -d "1000000 0" -mcopymod - <<EOF
145 $ hg import -d "1000000 0" -mcopymod - <<EOF
146 > diff --git a/rename b/copy2
146 > diff --git a/rename b/copy2
147 > similarity index 80%
147 > similarity index 80%
148 > copy from rename
148 > copy from rename
149 > copy to copy2
149 > copy to copy2
150 > index 72e1fe3..b53c148 100644
150 > index 72e1fe3..b53c148 100644
151 > --- a/rename
151 > --- a/rename
152 > +++ b/copy2
152 > +++ b/copy2
153 > @@ -1,5 +1,5 @@
153 > @@ -1,5 +1,5 @@
154 > a
154 > a
155 > a
155 > a
156 > -a
156 > -a
157 > +b
157 > +b
158 > a
158 > a
159 > a
159 > a
160 > EOF
160 > EOF
161 applying patch from stdin
161 applying patch from stdin
162
162
163 $ hg tip -q
163 $ hg tip -q
164 7:18f368958ecd
164 7:18f368958ecd
165
165
166 $ hg cat copy2
166 $ hg cat copy2
167 a
167 a
168 a
168 a
169 b
169 b
170 a
170 a
171 a
171 a
172
172
173 Rename and modify:
173 Rename and modify:
174
174
175 $ hg import -d "1000000 0" -mrenamemod - <<EOF
175 $ hg import -d "1000000 0" -mrenamemod - <<EOF
176 > diff --git a/copy2 b/rename2
176 > diff --git a/copy2 b/rename2
177 > similarity index 80%
177 > similarity index 80%
178 > rename from copy2
178 > rename from copy2
179 > rename to rename2
179 > rename to rename2
180 > index b53c148..8f81e29 100644
180 > index b53c148..8f81e29 100644
181 > --- a/copy2
181 > --- a/copy2
182 > +++ b/rename2
182 > +++ b/rename2
183 > @@ -1,5 +1,5 @@
183 > @@ -1,5 +1,5 @@
184 > a
184 > a
185 > a
185 > a
186 > b
186 > b
187 > -a
187 > -a
188 > +c
188 > +c
189 > a
189 > a
190 > EOF
190 > EOF
191 applying patch from stdin
191 applying patch from stdin
192
192
193 $ hg tip -q
193 $ hg tip -q
194 8:c32b0d7e6f44
194 8:c32b0d7e6f44
195
195
196 $ hg locate copy2
196 $ hg locate copy2
197 [1]
197 [1]
198 $ hg cat rename2
198 $ hg cat rename2
199 a
199 a
200 a
200 a
201 b
201 b
202 c
202 c
203 a
203 a
204
204
205 One file renamed multiple times:
205 One file renamed multiple times:
206
206
207 $ hg import -d "1000000 0" -mmultirenames - <<EOF
207 $ hg import -d "1000000 0" -mmultirenames - <<EOF
208 > diff --git a/rename2 b/rename3
208 > diff --git a/rename2 b/rename3
209 > rename from rename2
209 > rename from rename2
210 > rename to rename3
210 > rename to rename3
211 > diff --git a/rename2 b/rename3-2
211 > diff --git a/rename2 b/rename3-2
212 > rename from rename2
212 > rename from rename2
213 > rename to rename3-2
213 > rename to rename3-2
214 > EOF
214 > EOF
215 applying patch from stdin
215 applying patch from stdin
216
216
217 $ hg tip -q
217 $ hg tip -q
218 9:034a6bf95330
218 9:034a6bf95330
219
219
220 $ hg log -vr. --template '{rev} {files} / {file_copies}\n'
220 $ hg log -vr. --template '{rev} {files} / {file_copies}\n'
221 9 rename2 rename3 rename3-2 / rename3 (rename2)rename3-2 (rename2)
221 9 rename2 rename3 rename3-2 / rename3 (rename2)rename3-2 (rename2)
222
222
223 $ hg locate rename2 rename3 rename3-2
223 $ hg locate rename2 rename3 rename3-2
224 rename3
224 rename3
225 rename3-2
225 rename3-2
226
226
227 $ hg cat rename3
227 $ hg cat rename3
228 a
228 a
229 a
229 a
230 b
230 b
231 c
231 c
232 a
232 a
233
233
234 $ hg cat rename3-2
234 $ hg cat rename3-2
235 a
235 a
236 a
236 a
237 b
237 b
238 c
238 c
239 a
239 a
240
240
241 $ echo foo > foo
241 $ echo foo > foo
242 $ hg add foo
242 $ hg add foo
243 $ hg ci -m 'add foo'
243 $ hg ci -m 'add foo'
244
244
245 Binary files and regular patch hunks:
245 Binary files and regular patch hunks:
246
246
247 $ hg import -d "1000000 0" -m binaryregular - <<EOF
247 $ hg import -d "1000000 0" -m binaryregular - <<EOF
248 > diff --git a/binary b/binary
248 > diff --git a/binary b/binary
249 > new file mode 100644
249 > new file mode 100644
250 > index 0000000000000000000000000000000000000000..593f4708db84ac8fd0f5cc47c634f38c013fe9e4
250 > index 0000000000000000000000000000000000000000..593f4708db84ac8fd0f5cc47c634f38c013fe9e4
251 > GIT binary patch
251 > GIT binary patch
252 > literal 4
252 > literal 4
253 > Lc\${NkU|;|M00aO5
253 > Lc\${NkU|;|M00aO5
254 >
254 >
255 > diff --git a/foo b/foo2
255 > diff --git a/foo b/foo2
256 > rename from foo
256 > rename from foo
257 > rename to foo2
257 > rename to foo2
258 > EOF
258 > EOF
259 applying patch from stdin
259 applying patch from stdin
260
260
261 $ hg tip -q
261 $ hg tip -q
262 11:c39bce63e786
262 11:c39bce63e786
263
263
264 $ cat foo2
264 $ cat foo2
265 foo
265 foo
266
266
267 $ hg manifest --debug | grep binary
267 $ hg manifest --debug | grep binary
268 045c85ba38952325e126c70962cc0f9d9077bc67 644 binary
268 045c85ba38952325e126c70962cc0f9d9077bc67 644 binary
269
269
270 Multiple binary files:
270 Multiple binary files:
271
271
272 $ hg import -d "1000000 0" -m multibinary - <<EOF
272 $ hg import -d "1000000 0" -m multibinary - <<EOF
273 > diff --git a/mbinary1 b/mbinary1
273 > diff --git a/mbinary1 b/mbinary1
274 > new file mode 100644
274 > new file mode 100644
275 > index 0000000000000000000000000000000000000000..593f4708db84ac8fd0f5cc47c634f38c013fe9e4
275 > index 0000000000000000000000000000000000000000..593f4708db84ac8fd0f5cc47c634f38c013fe9e4
276 > GIT binary patch
276 > GIT binary patch
277 > literal 4
277 > literal 4
278 > Lc\${NkU|;|M00aO5
278 > Lc\${NkU|;|M00aO5
279 >
279 >
280 > diff --git a/mbinary2 b/mbinary2
280 > diff --git a/mbinary2 b/mbinary2
281 > new file mode 100644
281 > new file mode 100644
282 > index 0000000000000000000000000000000000000000..112363ac1917b417ffbd7f376ca786a1e5fa7490
282 > index 0000000000000000000000000000000000000000..112363ac1917b417ffbd7f376ca786a1e5fa7490
283 > GIT binary patch
283 > GIT binary patch
284 > literal 5
284 > literal 5
285 > Mc\${NkU|\`?^000jF3jhEB
285 > Mc\${NkU|\`?^000jF3jhEB
286 >
286 >
287 > EOF
287 > EOF
288 applying patch from stdin
288 applying patch from stdin
289
289
290 $ hg tip -q
290 $ hg tip -q
291 12:30b530085242
291 12:30b530085242
292
292
293 $ hg manifest --debug | grep mbinary
293 $ hg manifest --debug | grep mbinary
294 045c85ba38952325e126c70962cc0f9d9077bc67 644 mbinary1
294 045c85ba38952325e126c70962cc0f9d9077bc67 644 mbinary1
295 a874b471193996e7cb034bb301cac7bdaf3e3f46 644 mbinary2
295 a874b471193996e7cb034bb301cac7bdaf3e3f46 644 mbinary2
296
296
297 Filenames with spaces:
297 Filenames with spaces:
298
298
299 $ hg import -d "1000000 0" -m spaces - <<EOF
299 $ hg import -d "1000000 0" -m spaces - <<EOF
300 > diff --git a/foo bar b/foo bar
300 > diff --git a/foo bar b/foo bar
301 > new file mode 100644
301 > new file mode 100644
302 > index 0000000..257cc56
302 > index 0000000..257cc56
303 > --- /dev/null
303 > --- /dev/null
304 > +++ b/foo bar
304 > +++ b/foo bar
305 > @@ -0,0 +1 @@
305 > @@ -0,0 +1 @@
306 > +foo
306 > +foo
307 > EOF
307 > EOF
308 applying patch from stdin
308 applying patch from stdin
309
309
310 $ hg tip -q
310 $ hg tip -q
311 13:04750ef42fb3
311 13:04750ef42fb3
312
312
313 $ cat "foo bar"
313 $ cat "foo bar"
314 foo
314 foo
315
315
316 Copy then modify the original file:
316 Copy then modify the original file:
317
317
318 $ hg import -d "1000000 0" -m copy-mod-orig - <<EOF
318 $ hg import -d "1000000 0" -m copy-mod-orig - <<EOF
319 > diff --git a/foo2 b/foo2
319 > diff --git a/foo2 b/foo2
320 > index 257cc56..fe08ec6 100644
320 > index 257cc56..fe08ec6 100644
321 > --- a/foo2
321 > --- a/foo2
322 > +++ b/foo2
322 > +++ b/foo2
323 > @@ -1 +1,2 @@
323 > @@ -1 +1,2 @@
324 > foo
324 > foo
325 > +new line
325 > +new line
326 > diff --git a/foo2 b/foo3
326 > diff --git a/foo2 b/foo3
327 > similarity index 100%
327 > similarity index 100%
328 > copy from foo2
328 > copy from foo2
329 > copy to foo3
329 > copy to foo3
330 > EOF
330 > EOF
331 applying patch from stdin
331 applying patch from stdin
332
332
333 $ hg tip -q
333 $ hg tip -q
334 14:c4cd9cdeaa74
334 14:c4cd9cdeaa74
335
335
336 $ cat foo3
336 $ cat foo3
337 foo
337 foo
338
338
339 Move text file and patch as binary
339 Move text file and patch as binary
340
340
341 $ echo a > text2
341 $ echo a > text2
342 $ hg ci -Am0
342 $ hg ci -Am0
343 adding text2
343 adding text2
344 $ hg import -d "1000000 0" -m rename-as-binary - <<"EOF"
344 $ hg import -d "1000000 0" -m rename-as-binary - <<"EOF"
345 > diff --git a/text2 b/binary2
345 > diff --git a/text2 b/binary2
346 > rename from text2
346 > rename from text2
347 > rename to binary2
347 > rename to binary2
348 > index 78981922613b2afb6025042ff6bd878ac1994e85..10efcb362e9f3b3420fcfbfc0e37f3dc16e29757
348 > index 78981922613b2afb6025042ff6bd878ac1994e85..10efcb362e9f3b3420fcfbfc0e37f3dc16e29757
349 > GIT binary patch
349 > GIT binary patch
350 > literal 5
350 > literal 5
351 > Mc$`b*O5$Pw00T?_*Z=?k
351 > Mc$`b*O5$Pw00T?_*Z=?k
352 >
352 >
353 > EOF
353 > EOF
354 applying patch from stdin
354 applying patch from stdin
355
355
356 $ cat binary2
356 $ cat binary2
357 a
357 a
358 b
358 b
359 \x00 (no-eol) (esc)
359 \x00 (no-eol) (esc)
360
360
361 $ hg st --copies --change .
361 $ hg st --copies --change .
362 A binary2
362 A binary2
363 text2
363 text2
364 R text2
364 R text2
365 $ cd ..
365 $ cd ..
366
366
367 Consecutive import with renames (issue2459)
367 Consecutive import with renames (issue2459)
368
368
369 $ hg init issue2459
369 $ hg init issue2459
370 $ cd issue2459
370 $ cd issue2459
371 $ hg import --no-commit --force - <<EOF
371 $ hg import --no-commit --force - <<EOF
372 > diff --git a/a b/a
372 > diff --git a/a b/a
373 > new file mode 100644
373 > new file mode 100644
374 > EOF
374 > EOF
375 applying patch from stdin
375 applying patch from stdin
376 $ hg import --no-commit --force - <<EOF
376 $ hg import --no-commit --force - <<EOF
377 > diff --git a/a b/b
377 > diff --git a/a b/b
378 > rename from a
378 > rename from a
379 > rename to b
379 > rename to b
380 > EOF
380 > EOF
381 applying patch from stdin
381 applying patch from stdin
382 a has not been committed yet, so no copy data will be stored for b.
382 a has not been committed yet, so no copy data will be stored for b.
383 $ hg debugstate
383 $ hg debugstate
384 a 0 -1 unset b
384 a 0 -1 unset b
385 $ hg ci -m done
385 $ hg ci -m done
386 $ cd ..
386 $ cd ..
387
387
388 Renames and strip
388 Renames and strip
389
389
390 $ hg init renameandstrip
390 $ hg init renameandstrip
391 $ cd renameandstrip
391 $ cd renameandstrip
392 $ echo a > a
392 $ echo a > a
393 $ hg ci -Am adda
393 $ hg ci -Am adda
394 adding a
394 adding a
395 $ hg import --no-commit -p2 - <<EOF
395 $ hg import --no-commit -p2 - <<EOF
396 > diff --git a/foo/a b/foo/b
396 > diff --git a/foo/a b/foo/b
397 > rename from foo/a
397 > rename from foo/a
398 > rename to foo/b
398 > rename to foo/b
399 > EOF
399 > EOF
400 applying patch from stdin
400 applying patch from stdin
401 $ hg st --copies
401 $ hg st --copies
402 A b
402 A b
403 a
403 a
404 R a
404 R a
405
405
406 Renames, similarity and git diff
406 Renames, similarity and git diff
407
407
408 $ hg revert -aC
408 $ hg revert -aC
409 undeleting a
409 undeleting a
410 forgetting b
410 forgetting b
411 $ rm b
411 $ rm b
412 $ hg import --similarity 90 --no-commit - <<EOF
412 $ hg import --similarity 90 --no-commit - <<EOF
413 > diff --git a/a b/b
413 > diff --git a/a b/b
414 > rename from a
414 > rename from a
415 > rename to b
415 > rename to b
416 > EOF
416 > EOF
417 applying patch from stdin
417 applying patch from stdin
418 $ hg st --copies
418 $ hg st --copies
419 A b
419 A b
420 a
420 a
421 R a
421 R a
422 $ cd ..
422 $ cd ..
423
423
424 Pure copy with existing destination
424 Pure copy with existing destination
425
425
426 $ hg init copytoexisting
426 $ hg init copytoexisting
427 $ cd copytoexisting
427 $ cd copytoexisting
428 $ echo a > a
428 $ echo a > a
429 $ echo b > b
429 $ echo b > b
430 $ hg ci -Am add
430 $ hg ci -Am add
431 adding a
431 adding a
432 adding b
432 adding b
433 $ hg import --no-commit - <<EOF
433 $ hg import --no-commit - <<EOF
434 > diff --git a/a b/b
434 > diff --git a/a b/b
435 > copy from a
435 > copy from a
436 > copy to b
436 > copy to b
437 > EOF
437 > EOF
438 applying patch from stdin
438 applying patch from stdin
439 abort: cannot create b: destination already exists
439 abort: cannot create b: destination already exists
440 [255]
440 [255]
441 $ cat b
441 $ cat b
442 b
442 b
443
443
444 Copy and changes with existing destination
444 Copy and changes with existing destination
445
445
446 $ hg import --no-commit - <<EOF
446 $ hg import --no-commit - <<EOF
447 > diff --git a/a b/b
447 > diff --git a/a b/b
448 > copy from a
448 > copy from a
449 > copy to b
449 > copy to b
450 > --- a/a
450 > --- a/a
451 > +++ b/b
451 > +++ b/b
452 > @@ -1,1 +1,2 @@
452 > @@ -1,1 +1,2 @@
453 > a
453 > a
454 > +b
454 > +b
455 > EOF
455 > EOF
456 applying patch from stdin
456 applying patch from stdin
457 cannot create b: destination already exists
457 cannot create b: destination already exists
458 1 out of 1 hunks FAILED -- saving rejects to file b.rej
458 1 out of 1 hunks FAILED -- saving rejects to file b.rej
459 abort: patch failed to apply
459 abort: patch failed to apply
460 [255]
460 [255]
461 $ cat b
461 $ cat b
462 b
462 b
463
463
464 $ ln -s b linkb
464 $ ln -s b linkb
465 $ hg add linkb
465 $ hg add linkb
466 $ hg ci -m addlinkb
466 $ hg ci -m addlinkb
467 $ hg import --no-commit - <<EOF
467 $ hg import --no-commit - <<EOF
468 > diff --git a/linkb b/linkb
468 > diff --git a/linkb b/linkb
469 > deleted file mode 120000
469 > deleted file mode 120000
470 > --- a/linkb
470 > --- a/linkb
471 > +++ /dev/null
471 > +++ /dev/null
472 > @@ -1,1 +0,0 @@
472 > @@ -1,1 +0,0 @@
473 > -badhunk
473 > -badhunk
474 > \ No newline at end of file
474 > \ No newline at end of file
475 > EOF
475 > EOF
476 applying patch from stdin
476 applying patch from stdin
477 patching file linkb
477 patching file linkb
478 Hunk #1 FAILED at 0
478 Hunk #1 FAILED at 0
479 1 out of 1 hunks FAILED -- saving rejects to file linkb.rej
479 1 out of 1 hunks FAILED -- saving rejects to file linkb.rej
480 abort: patch failed to apply
480 abort: patch failed to apply
481 [255]
481 [255]
482 $ hg st
482 $ hg st
483 ? b.rej
483 ? b.rej
484 ? linkb.rej
484 ? linkb.rej
485
485
486 Test corner case involving copies and multiple hunks (issue3384)
487
488 $ hg revert -qa
489 $ hg import --no-commit - <<EOF
490 > diff --git a/a b/c
491 > copy from a
492 > copy to c
493 > --- a/a
494 > +++ b/c
495 > @@ -1,1 +1,2 @@
496 > a
497 > +a
498 > @@ -2,1 +2,2 @@
499 > a
500 > +a
501 > diff --git a/a b/a
502 > --- a/a
503 > +++ b/a
504 > @@ -1,1 +1,2 @@
505 > a
506 > +b
507 > EOF
508 applying patch from stdin
509
486 $ cd ..
510 $ cd ..
General Comments 0
You need to be logged in to leave comments. Login now