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