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