##// END OF EJS Templates
context: make forget work like commands.forget...
Matt Mackall -
r14435:5f6090e5 default
parent child Browse files
Show More
@@ -1,3296 +1,3295 b''
1 1 # mq.py - patch queues for mercurial
2 2 #
3 3 # Copyright 2005, 2006 Chris Mason <mason@suse.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 '''manage a stack of patches
9 9
10 10 This extension lets you work with a stack of patches in a Mercurial
11 11 repository. It manages two stacks of patches - all known patches, and
12 12 applied patches (subset of known patches).
13 13
14 14 Known patches are represented as patch files in the .hg/patches
15 15 directory. Applied patches are both patch files and changesets.
16 16
17 17 Common tasks (use :hg:`help command` for more details)::
18 18
19 19 create new patch qnew
20 20 import existing patch qimport
21 21
22 22 print patch series qseries
23 23 print applied patches qapplied
24 24
25 25 add known patch to applied stack qpush
26 26 remove patch from applied stack qpop
27 27 refresh contents of top applied patch qrefresh
28 28
29 29 By default, mq will automatically use git patches when required to
30 30 avoid losing file mode changes, copy records, binary files or empty
31 31 files creations or deletions. This behaviour can be configured with::
32 32
33 33 [mq]
34 34 git = auto/keep/yes/no
35 35
36 36 If set to 'keep', mq will obey the [diff] section configuration while
37 37 preserving existing git patches upon qrefresh. If set to 'yes' or
38 38 'no', mq will override the [diff] section and always generate git or
39 39 regular patches, possibly losing data in the second case.
40 40
41 41 You will by default be managing a patch queue named "patches". You can
42 42 create other, independent patch queues with the :hg:`qqueue` command.
43 43 '''
44 44
45 45 from mercurial.i18n import _
46 46 from mercurial.node import bin, hex, short, nullid, nullrev
47 47 from mercurial.lock import release
48 48 from mercurial import commands, cmdutil, hg, scmutil, util, revset
49 49 from mercurial import repair, extensions, url, error
50 50 from mercurial import patch as patchmod
51 51 import os, sys, re, errno, shutil
52 52
53 53 commands.norepo += " qclone"
54 54
55 55 seriesopts = [('s', 'summary', None, _('print first line of patch header'))]
56 56
57 57 cmdtable = {}
58 58 command = cmdutil.command(cmdtable)
59 59
60 60 # Patch names looks like unix-file names.
61 61 # They must be joinable with queue directory and result in the patch path.
62 62 normname = util.normpath
63 63
64 64 class statusentry(object):
65 65 def __init__(self, node, name):
66 66 self.node, self.name = node, name
67 67 def __repr__(self):
68 68 return hex(self.node) + ':' + self.name
69 69
70 70 class patchheader(object):
71 71 def __init__(self, pf, plainmode=False):
72 72 def eatdiff(lines):
73 73 while lines:
74 74 l = lines[-1]
75 75 if (l.startswith("diff -") or
76 76 l.startswith("Index:") or
77 77 l.startswith("===========")):
78 78 del lines[-1]
79 79 else:
80 80 break
81 81 def eatempty(lines):
82 82 while lines:
83 83 if not lines[-1].strip():
84 84 del lines[-1]
85 85 else:
86 86 break
87 87
88 88 message = []
89 89 comments = []
90 90 user = None
91 91 date = None
92 92 parent = None
93 93 format = None
94 94 subject = None
95 95 branch = None
96 96 nodeid = None
97 97 diffstart = 0
98 98
99 99 for line in file(pf):
100 100 line = line.rstrip()
101 101 if (line.startswith('diff --git')
102 102 or (diffstart and line.startswith('+++ '))):
103 103 diffstart = 2
104 104 break
105 105 diffstart = 0 # reset
106 106 if line.startswith("--- "):
107 107 diffstart = 1
108 108 continue
109 109 elif format == "hgpatch":
110 110 # parse values when importing the result of an hg export
111 111 if line.startswith("# User "):
112 112 user = line[7:]
113 113 elif line.startswith("# Date "):
114 114 date = line[7:]
115 115 elif line.startswith("# Parent "):
116 116 parent = line[9:].lstrip()
117 117 elif line.startswith("# Branch "):
118 118 branch = line[9:]
119 119 elif line.startswith("# Node ID "):
120 120 nodeid = line[10:]
121 121 elif not line.startswith("# ") and line:
122 122 message.append(line)
123 123 format = None
124 124 elif line == '# HG changeset patch':
125 125 message = []
126 126 format = "hgpatch"
127 127 elif (format != "tagdone" and (line.startswith("Subject: ") or
128 128 line.startswith("subject: "))):
129 129 subject = line[9:]
130 130 format = "tag"
131 131 elif (format != "tagdone" and (line.startswith("From: ") or
132 132 line.startswith("from: "))):
133 133 user = line[6:]
134 134 format = "tag"
135 135 elif (format != "tagdone" and (line.startswith("Date: ") or
136 136 line.startswith("date: "))):
137 137 date = line[6:]
138 138 format = "tag"
139 139 elif format == "tag" and line == "":
140 140 # when looking for tags (subject: from: etc) they
141 141 # end once you find a blank line in the source
142 142 format = "tagdone"
143 143 elif message or line:
144 144 message.append(line)
145 145 comments.append(line)
146 146
147 147 eatdiff(message)
148 148 eatdiff(comments)
149 149 # Remember the exact starting line of the patch diffs before consuming
150 150 # empty lines, for external use by TortoiseHg and others
151 151 self.diffstartline = len(comments)
152 152 eatempty(message)
153 153 eatempty(comments)
154 154
155 155 # make sure message isn't empty
156 156 if format and format.startswith("tag") and subject:
157 157 message.insert(0, "")
158 158 message.insert(0, subject)
159 159
160 160 self.message = message
161 161 self.comments = comments
162 162 self.user = user
163 163 self.date = date
164 164 self.parent = parent
165 165 # nodeid and branch are for external use by TortoiseHg and others
166 166 self.nodeid = nodeid
167 167 self.branch = branch
168 168 self.haspatch = diffstart > 1
169 169 self.plainmode = plainmode
170 170
171 171 def setuser(self, user):
172 172 if not self.updateheader(['From: ', '# User '], user):
173 173 try:
174 174 patchheaderat = self.comments.index('# HG changeset patch')
175 175 self.comments.insert(patchheaderat + 1, '# User ' + user)
176 176 except ValueError:
177 177 if self.plainmode or self._hasheader(['Date: ']):
178 178 self.comments = ['From: ' + user] + self.comments
179 179 else:
180 180 tmp = ['# HG changeset patch', '# User ' + user, '']
181 181 self.comments = tmp + self.comments
182 182 self.user = user
183 183
184 184 def setdate(self, date):
185 185 if not self.updateheader(['Date: ', '# Date '], date):
186 186 try:
187 187 patchheaderat = self.comments.index('# HG changeset patch')
188 188 self.comments.insert(patchheaderat + 1, '# Date ' + date)
189 189 except ValueError:
190 190 if self.plainmode or self._hasheader(['From: ']):
191 191 self.comments = ['Date: ' + date] + self.comments
192 192 else:
193 193 tmp = ['# HG changeset patch', '# Date ' + date, '']
194 194 self.comments = tmp + self.comments
195 195 self.date = date
196 196
197 197 def setparent(self, parent):
198 198 if not self.updateheader(['# Parent '], parent):
199 199 try:
200 200 patchheaderat = self.comments.index('# HG changeset patch')
201 201 self.comments.insert(patchheaderat + 1, '# Parent ' + parent)
202 202 except ValueError:
203 203 pass
204 204 self.parent = parent
205 205
206 206 def setmessage(self, message):
207 207 if self.comments:
208 208 self._delmsg()
209 209 self.message = [message]
210 210 self.comments += self.message
211 211
212 212 def updateheader(self, prefixes, new):
213 213 '''Update all references to a field in the patch header.
214 214 Return whether the field is present.'''
215 215 res = False
216 216 for prefix in prefixes:
217 217 for i in xrange(len(self.comments)):
218 218 if self.comments[i].startswith(prefix):
219 219 self.comments[i] = prefix + new
220 220 res = True
221 221 break
222 222 return res
223 223
224 224 def _hasheader(self, prefixes):
225 225 '''Check if a header starts with any of the given prefixes.'''
226 226 for prefix in prefixes:
227 227 for comment in self.comments:
228 228 if comment.startswith(prefix):
229 229 return True
230 230 return False
231 231
232 232 def __str__(self):
233 233 if not self.comments:
234 234 return ''
235 235 return '\n'.join(self.comments) + '\n\n'
236 236
237 237 def _delmsg(self):
238 238 '''Remove existing message, keeping the rest of the comments fields.
239 239 If comments contains 'subject: ', message will prepend
240 240 the field and a blank line.'''
241 241 if self.message:
242 242 subj = 'subject: ' + self.message[0].lower()
243 243 for i in xrange(len(self.comments)):
244 244 if subj == self.comments[i].lower():
245 245 del self.comments[i]
246 246 self.message = self.message[2:]
247 247 break
248 248 ci = 0
249 249 for mi in self.message:
250 250 while mi != self.comments[ci]:
251 251 ci += 1
252 252 del self.comments[ci]
253 253
254 254 class queue(object):
255 255 def __init__(self, ui, path, patchdir=None):
256 256 self.basepath = path
257 257 try:
258 258 fh = open(os.path.join(path, 'patches.queue'))
259 259 cur = fh.read().rstrip()
260 260 fh.close()
261 261 if not cur:
262 262 curpath = os.path.join(path, 'patches')
263 263 else:
264 264 curpath = os.path.join(path, 'patches-' + cur)
265 265 except IOError:
266 266 curpath = os.path.join(path, 'patches')
267 267 self.path = patchdir or curpath
268 268 self.opener = scmutil.opener(self.path)
269 269 self.ui = ui
270 270 self.applied_dirty = 0
271 271 self.series_dirty = 0
272 272 self.added = []
273 273 self.series_path = "series"
274 274 self.status_path = "status"
275 275 self.guards_path = "guards"
276 276 self.active_guards = None
277 277 self.guards_dirty = False
278 278 # Handle mq.git as a bool with extended values
279 279 try:
280 280 gitmode = ui.configbool('mq', 'git', None)
281 281 if gitmode is None:
282 282 raise error.ConfigError()
283 283 self.gitmode = gitmode and 'yes' or 'no'
284 284 except error.ConfigError:
285 285 self.gitmode = ui.config('mq', 'git', 'auto').lower()
286 286 self.plainmode = ui.configbool('mq', 'plain', False)
287 287
288 288 @util.propertycache
289 289 def applied(self):
290 290 if os.path.exists(self.join(self.status_path)):
291 291 def parselines(lines):
292 292 for l in lines:
293 293 entry = l.split(':', 1)
294 294 if len(entry) > 1:
295 295 n, name = entry
296 296 yield statusentry(bin(n), name)
297 297 elif l.strip():
298 298 self.ui.warn(_('malformated mq status line: %s\n') % entry)
299 299 # else we ignore empty lines
300 300 lines = self.opener.read(self.status_path).splitlines()
301 301 return list(parselines(lines))
302 302 return []
303 303
304 304 @util.propertycache
305 305 def full_series(self):
306 306 if os.path.exists(self.join(self.series_path)):
307 307 return self.opener.read(self.series_path).splitlines()
308 308 return []
309 309
310 310 @util.propertycache
311 311 def series(self):
312 312 self.parse_series()
313 313 return self.series
314 314
315 315 @util.propertycache
316 316 def series_guards(self):
317 317 self.parse_series()
318 318 return self.series_guards
319 319
320 320 def invalidate(self):
321 321 for a in 'applied full_series series series_guards'.split():
322 322 if a in self.__dict__:
323 323 delattr(self, a)
324 324 self.applied_dirty = 0
325 325 self.series_dirty = 0
326 326 self.guards_dirty = False
327 327 self.active_guards = None
328 328
329 329 def diffopts(self, opts={}, patchfn=None):
330 330 diffopts = patchmod.diffopts(self.ui, opts)
331 331 if self.gitmode == 'auto':
332 332 diffopts.upgrade = True
333 333 elif self.gitmode == 'keep':
334 334 pass
335 335 elif self.gitmode in ('yes', 'no'):
336 336 diffopts.git = self.gitmode == 'yes'
337 337 else:
338 338 raise util.Abort(_('mq.git option can be auto/keep/yes/no'
339 339 ' got %s') % self.gitmode)
340 340 if patchfn:
341 341 diffopts = self.patchopts(diffopts, patchfn)
342 342 return diffopts
343 343
344 344 def patchopts(self, diffopts, *patches):
345 345 """Return a copy of input diff options with git set to true if
346 346 referenced patch is a git patch and should be preserved as such.
347 347 """
348 348 diffopts = diffopts.copy()
349 349 if not diffopts.git and self.gitmode == 'keep':
350 350 for patchfn in patches:
351 351 patchf = self.opener(patchfn, 'r')
352 352 # if the patch was a git patch, refresh it as a git patch
353 353 for line in patchf:
354 354 if line.startswith('diff --git'):
355 355 diffopts.git = True
356 356 break
357 357 patchf.close()
358 358 return diffopts
359 359
360 360 def join(self, *p):
361 361 return os.path.join(self.path, *p)
362 362
363 363 def find_series(self, patch):
364 364 def matchpatch(l):
365 365 l = l.split('#', 1)[0]
366 366 return l.strip() == patch
367 367 for index, l in enumerate(self.full_series):
368 368 if matchpatch(l):
369 369 return index
370 370 return None
371 371
372 372 guard_re = re.compile(r'\s?#([-+][^-+# \t\r\n\f][^# \t\r\n\f]*)')
373 373
374 374 def parse_series(self):
375 375 self.series = []
376 376 self.series_guards = []
377 377 for l in self.full_series:
378 378 h = l.find('#')
379 379 if h == -1:
380 380 patch = l
381 381 comment = ''
382 382 elif h == 0:
383 383 continue
384 384 else:
385 385 patch = l[:h]
386 386 comment = l[h:]
387 387 patch = patch.strip()
388 388 if patch:
389 389 if patch in self.series:
390 390 raise util.Abort(_('%s appears more than once in %s') %
391 391 (patch, self.join(self.series_path)))
392 392 self.series.append(patch)
393 393 self.series_guards.append(self.guard_re.findall(comment))
394 394
395 395 def check_guard(self, guard):
396 396 if not guard:
397 397 return _('guard cannot be an empty string')
398 398 bad_chars = '# \t\r\n\f'
399 399 first = guard[0]
400 400 if first in '-+':
401 401 return (_('guard %r starts with invalid character: %r') %
402 402 (guard, first))
403 403 for c in bad_chars:
404 404 if c in guard:
405 405 return _('invalid character in guard %r: %r') % (guard, c)
406 406
407 407 def set_active(self, guards):
408 408 for guard in guards:
409 409 bad = self.check_guard(guard)
410 410 if bad:
411 411 raise util.Abort(bad)
412 412 guards = sorted(set(guards))
413 413 self.ui.debug('active guards: %s\n' % ' '.join(guards))
414 414 self.active_guards = guards
415 415 self.guards_dirty = True
416 416
417 417 def active(self):
418 418 if self.active_guards is None:
419 419 self.active_guards = []
420 420 try:
421 421 guards = self.opener.read(self.guards_path).split()
422 422 except IOError, err:
423 423 if err.errno != errno.ENOENT:
424 424 raise
425 425 guards = []
426 426 for i, guard in enumerate(guards):
427 427 bad = self.check_guard(guard)
428 428 if bad:
429 429 self.ui.warn('%s:%d: %s\n' %
430 430 (self.join(self.guards_path), i + 1, bad))
431 431 else:
432 432 self.active_guards.append(guard)
433 433 return self.active_guards
434 434
435 435 def set_guards(self, idx, guards):
436 436 for g in guards:
437 437 if len(g) < 2:
438 438 raise util.Abort(_('guard %r too short') % g)
439 439 if g[0] not in '-+':
440 440 raise util.Abort(_('guard %r starts with invalid char') % g)
441 441 bad = self.check_guard(g[1:])
442 442 if bad:
443 443 raise util.Abort(bad)
444 444 drop = self.guard_re.sub('', self.full_series[idx])
445 445 self.full_series[idx] = drop + ''.join([' #' + g for g in guards])
446 446 self.parse_series()
447 447 self.series_dirty = True
448 448
449 449 def pushable(self, idx):
450 450 if isinstance(idx, str):
451 451 idx = self.series.index(idx)
452 452 patchguards = self.series_guards[idx]
453 453 if not patchguards:
454 454 return True, None
455 455 guards = self.active()
456 456 exactneg = [g for g in patchguards if g[0] == '-' and g[1:] in guards]
457 457 if exactneg:
458 458 return False, exactneg[0]
459 459 pos = [g for g in patchguards if g[0] == '+']
460 460 exactpos = [g for g in pos if g[1:] in guards]
461 461 if pos:
462 462 if exactpos:
463 463 return True, exactpos[0]
464 464 return False, pos
465 465 return True, ''
466 466
467 467 def explain_pushable(self, idx, all_patches=False):
468 468 write = all_patches and self.ui.write or self.ui.warn
469 469 if all_patches or self.ui.verbose:
470 470 if isinstance(idx, str):
471 471 idx = self.series.index(idx)
472 472 pushable, why = self.pushable(idx)
473 473 if all_patches and pushable:
474 474 if why is None:
475 475 write(_('allowing %s - no guards in effect\n') %
476 476 self.series[idx])
477 477 else:
478 478 if not why:
479 479 write(_('allowing %s - no matching negative guards\n') %
480 480 self.series[idx])
481 481 else:
482 482 write(_('allowing %s - guarded by %r\n') %
483 483 (self.series[idx], why))
484 484 if not pushable:
485 485 if why:
486 486 write(_('skipping %s - guarded by %r\n') %
487 487 (self.series[idx], why))
488 488 else:
489 489 write(_('skipping %s - no matching guards\n') %
490 490 self.series[idx])
491 491
492 492 def save_dirty(self):
493 493 def write_list(items, path):
494 494 fp = self.opener(path, 'w')
495 495 for i in items:
496 496 fp.write("%s\n" % i)
497 497 fp.close()
498 498 if self.applied_dirty:
499 499 write_list(map(str, self.applied), self.status_path)
500 500 if self.series_dirty:
501 501 write_list(self.full_series, self.series_path)
502 502 if self.guards_dirty:
503 503 write_list(self.active_guards, self.guards_path)
504 504 if self.added:
505 505 qrepo = self.qrepo()
506 506 if qrepo:
507 507 qrepo[None].add(f for f in self.added if f not in qrepo[None])
508 508 self.added = []
509 509
510 510 def removeundo(self, repo):
511 511 undo = repo.sjoin('undo')
512 512 if not os.path.exists(undo):
513 513 return
514 514 try:
515 515 os.unlink(undo)
516 516 except OSError, inst:
517 517 self.ui.warn(_('error removing undo: %s\n') % str(inst))
518 518
519 519 def printdiff(self, repo, diffopts, node1, node2=None, files=None,
520 520 fp=None, changes=None, opts={}):
521 521 stat = opts.get('stat')
522 522 m = scmutil.match(repo, files, opts)
523 523 cmdutil.diffordiffstat(self.ui, repo, diffopts, node1, node2, m,
524 524 changes, stat, fp)
525 525
526 526 def mergeone(self, repo, mergeq, head, patch, rev, diffopts):
527 527 # first try just applying the patch
528 528 (err, n) = self.apply(repo, [patch], update_status=False,
529 529 strict=True, merge=rev)
530 530
531 531 if err == 0:
532 532 return (err, n)
533 533
534 534 if n is None:
535 535 raise util.Abort(_("apply failed for patch %s") % patch)
536 536
537 537 self.ui.warn(_("patch didn't work out, merging %s\n") % patch)
538 538
539 539 # apply failed, strip away that rev and merge.
540 540 hg.clean(repo, head)
541 541 self.strip(repo, [n], update=False, backup='strip')
542 542
543 543 ctx = repo[rev]
544 544 ret = hg.merge(repo, rev)
545 545 if ret:
546 546 raise util.Abort(_("update returned %d") % ret)
547 547 n = repo.commit(ctx.description(), ctx.user(), force=True)
548 548 if n is None:
549 549 raise util.Abort(_("repo commit failed"))
550 550 try:
551 551 ph = patchheader(mergeq.join(patch), self.plainmode)
552 552 except:
553 553 raise util.Abort(_("unable to read %s") % patch)
554 554
555 555 diffopts = self.patchopts(diffopts, patch)
556 556 patchf = self.opener(patch, "w")
557 557 comments = str(ph)
558 558 if comments:
559 559 patchf.write(comments)
560 560 self.printdiff(repo, diffopts, head, n, fp=patchf)
561 561 patchf.close()
562 562 self.removeundo(repo)
563 563 return (0, n)
564 564
565 565 def qparents(self, repo, rev=None):
566 566 if rev is None:
567 567 (p1, p2) = repo.dirstate.parents()
568 568 if p2 == nullid:
569 569 return p1
570 570 if not self.applied:
571 571 return None
572 572 return self.applied[-1].node
573 573 p1, p2 = repo.changelog.parents(rev)
574 574 if p2 != nullid and p2 in [x.node for x in self.applied]:
575 575 return p2
576 576 return p1
577 577
578 578 def mergepatch(self, repo, mergeq, series, diffopts):
579 579 if not self.applied:
580 580 # each of the patches merged in will have two parents. This
581 581 # can confuse the qrefresh, qdiff, and strip code because it
582 582 # needs to know which parent is actually in the patch queue.
583 583 # so, we insert a merge marker with only one parent. This way
584 584 # the first patch in the queue is never a merge patch
585 585 #
586 586 pname = ".hg.patches.merge.marker"
587 587 n = repo.commit('[mq]: merge marker', force=True)
588 588 self.removeundo(repo)
589 589 self.applied.append(statusentry(n, pname))
590 590 self.applied_dirty = 1
591 591
592 592 head = self.qparents(repo)
593 593
594 594 for patch in series:
595 595 patch = mergeq.lookup(patch, strict=True)
596 596 if not patch:
597 597 self.ui.warn(_("patch %s does not exist\n") % patch)
598 598 return (1, None)
599 599 pushable, reason = self.pushable(patch)
600 600 if not pushable:
601 601 self.explain_pushable(patch, all_patches=True)
602 602 continue
603 603 info = mergeq.isapplied(patch)
604 604 if not info:
605 605 self.ui.warn(_("patch %s is not applied\n") % patch)
606 606 return (1, None)
607 607 rev = info[1]
608 608 err, head = self.mergeone(repo, mergeq, head, patch, rev, diffopts)
609 609 if head:
610 610 self.applied.append(statusentry(head, patch))
611 611 self.applied_dirty = 1
612 612 if err:
613 613 return (err, head)
614 614 self.save_dirty()
615 615 return (0, head)
616 616
617 617 def patch(self, repo, patchfile):
618 618 '''Apply patchfile to the working directory.
619 619 patchfile: name of patch file'''
620 620 files = {}
621 621 try:
622 622 fuzz = patchmod.patch(self.ui, repo, patchfile, strip=1,
623 623 files=files, eolmode=None)
624 624 return (True, list(files), fuzz)
625 625 except Exception, inst:
626 626 self.ui.note(str(inst) + '\n')
627 627 if not self.ui.verbose:
628 628 self.ui.warn(_("patch failed, unable to continue (try -v)\n"))
629 629 return (False, list(files), False)
630 630
631 631 def apply(self, repo, series, list=False, update_status=True,
632 632 strict=False, patchdir=None, merge=None, all_files=None):
633 633 wlock = lock = tr = None
634 634 try:
635 635 wlock = repo.wlock()
636 636 lock = repo.lock()
637 637 tr = repo.transaction("qpush")
638 638 try:
639 639 ret = self._apply(repo, series, list, update_status,
640 640 strict, patchdir, merge, all_files=all_files)
641 641 tr.close()
642 642 self.save_dirty()
643 643 return ret
644 644 except:
645 645 try:
646 646 tr.abort()
647 647 finally:
648 648 repo.invalidate()
649 649 repo.dirstate.invalidate()
650 650 raise
651 651 finally:
652 652 release(tr, lock, wlock)
653 653 self.removeundo(repo)
654 654
655 655 def _apply(self, repo, series, list=False, update_status=True,
656 656 strict=False, patchdir=None, merge=None, all_files=None):
657 657 '''returns (error, hash)
658 658 error = 1 for unable to read, 2 for patch failed, 3 for patch fuzz'''
659 659 # TODO unify with commands.py
660 660 if not patchdir:
661 661 patchdir = self.path
662 662 err = 0
663 663 n = None
664 664 for patchname in series:
665 665 pushable, reason = self.pushable(patchname)
666 666 if not pushable:
667 667 self.explain_pushable(patchname, all_patches=True)
668 668 continue
669 669 self.ui.status(_("applying %s\n") % patchname)
670 670 pf = os.path.join(patchdir, patchname)
671 671
672 672 try:
673 673 ph = patchheader(self.join(patchname), self.plainmode)
674 674 except IOError:
675 675 self.ui.warn(_("unable to read %s\n") % patchname)
676 676 err = 1
677 677 break
678 678
679 679 message = ph.message
680 680 if not message:
681 681 # The commit message should not be translated
682 682 message = "imported patch %s\n" % patchname
683 683 else:
684 684 if list:
685 685 # The commit message should not be translated
686 686 message.append("\nimported patch %s" % patchname)
687 687 message = '\n'.join(message)
688 688
689 689 if ph.haspatch:
690 690 (patcherr, files, fuzz) = self.patch(repo, pf)
691 691 if all_files is not None:
692 692 all_files.update(files)
693 693 patcherr = not patcherr
694 694 else:
695 695 self.ui.warn(_("patch %s is empty\n") % patchname)
696 696 patcherr, files, fuzz = 0, [], 0
697 697
698 698 if merge and files:
699 699 # Mark as removed/merged and update dirstate parent info
700 700 removed = []
701 701 merged = []
702 702 for f in files:
703 703 if os.path.lexists(repo.wjoin(f)):
704 704 merged.append(f)
705 705 else:
706 706 removed.append(f)
707 707 for f in removed:
708 708 repo.dirstate.remove(f)
709 709 for f in merged:
710 710 repo.dirstate.merge(f)
711 711 p1, p2 = repo.dirstate.parents()
712 712 repo.dirstate.setparents(p1, merge)
713 713
714 714 match = scmutil.matchfiles(repo, files or [])
715 715 n = repo.commit(message, ph.user, ph.date, match=match, force=True)
716 716
717 717 if n is None:
718 718 raise util.Abort(_("repository commit failed"))
719 719
720 720 if update_status:
721 721 self.applied.append(statusentry(n, patchname))
722 722
723 723 if patcherr:
724 724 self.ui.warn(_("patch failed, rejects left in working dir\n"))
725 725 err = 2
726 726 break
727 727
728 728 if fuzz and strict:
729 729 self.ui.warn(_("fuzz found when applying patch, stopping\n"))
730 730 err = 3
731 731 break
732 732 return (err, n)
733 733
734 734 def _cleanup(self, patches, numrevs, keep=False):
735 735 if not keep:
736 736 r = self.qrepo()
737 737 if r:
738 r[None].remove(patches, True)
739 else:
740 for p in patches:
741 os.unlink(self.join(p))
738 r[None].forget(patches)
739 for p in patches:
740 os.unlink(self.join(p))
742 741
743 742 if numrevs:
744 743 qfinished = self.applied[:numrevs]
745 744 del self.applied[:numrevs]
746 745 self.applied_dirty = 1
747 746
748 747 unknown = []
749 748
750 749 for (i, p) in sorted([(self.find_series(p), p) for p in patches],
751 750 reverse=True):
752 751 if i is not None:
753 752 del self.full_series[i]
754 753 else:
755 754 unknown.append(p)
756 755
757 756 if unknown:
758 757 if numrevs:
759 758 rev = dict((entry.name, entry.node) for entry in qfinished)
760 759 for p in unknown:
761 760 msg = _('revision %s refers to unknown patches: %s\n')
762 761 self.ui.warn(msg % (short(rev[p]), p))
763 762 else:
764 763 msg = _('unknown patches: %s\n')
765 764 raise util.Abort(''.join(msg % p for p in unknown))
766 765
767 766 self.parse_series()
768 767 self.series_dirty = 1
769 768
770 769 def _revpatches(self, repo, revs):
771 770 firstrev = repo[self.applied[0].node].rev()
772 771 patches = []
773 772 for i, rev in enumerate(revs):
774 773
775 774 if rev < firstrev:
776 775 raise util.Abort(_('revision %d is not managed') % rev)
777 776
778 777 ctx = repo[rev]
779 778 base = self.applied[i].node
780 779 if ctx.node() != base:
781 780 msg = _('cannot delete revision %d above applied patches')
782 781 raise util.Abort(msg % rev)
783 782
784 783 patch = self.applied[i].name
785 784 for fmt in ('[mq]: %s', 'imported patch %s'):
786 785 if ctx.description() == fmt % patch:
787 786 msg = _('patch %s finalized without changeset message\n')
788 787 repo.ui.status(msg % patch)
789 788 break
790 789
791 790 patches.append(patch)
792 791 return patches
793 792
794 793 def finish(self, repo, revs):
795 794 patches = self._revpatches(repo, sorted(revs))
796 795 self._cleanup(patches, len(patches))
797 796
798 797 def delete(self, repo, patches, opts):
799 798 if not patches and not opts.get('rev'):
800 799 raise util.Abort(_('qdelete requires at least one revision or '
801 800 'patch name'))
802 801
803 802 realpatches = []
804 803 for patch in patches:
805 804 patch = self.lookup(patch, strict=True)
806 805 info = self.isapplied(patch)
807 806 if info:
808 807 raise util.Abort(_("cannot delete applied patch %s") % patch)
809 808 if patch not in self.series:
810 809 raise util.Abort(_("patch %s not in series file") % patch)
811 810 if patch not in realpatches:
812 811 realpatches.append(patch)
813 812
814 813 numrevs = 0
815 814 if opts.get('rev'):
816 815 if not self.applied:
817 816 raise util.Abort(_('no patches applied'))
818 817 revs = scmutil.revrange(repo, opts.get('rev'))
819 818 if len(revs) > 1 and revs[0] > revs[1]:
820 819 revs.reverse()
821 820 revpatches = self._revpatches(repo, revs)
822 821 realpatches += revpatches
823 822 numrevs = len(revpatches)
824 823
825 824 self._cleanup(realpatches, numrevs, opts.get('keep'))
826 825
827 826 def check_toppatch(self, repo):
828 827 if self.applied:
829 828 top = self.applied[-1].node
830 829 patch = self.applied[-1].name
831 830 pp = repo.dirstate.parents()
832 831 if top not in pp:
833 832 raise util.Abort(_("working directory revision is not qtip"))
834 833 return top, patch
835 834 return None, None
836 835
837 836 def check_substate(self, repo):
838 837 '''return list of subrepos at a different revision than substate.
839 838 Abort if any subrepos have uncommitted changes.'''
840 839 inclsubs = []
841 840 wctx = repo[None]
842 841 for s in wctx.substate:
843 842 if wctx.sub(s).dirty(True):
844 843 raise util.Abort(
845 844 _("uncommitted changes in subrepository %s") % s)
846 845 elif wctx.sub(s).dirty():
847 846 inclsubs.append(s)
848 847 return inclsubs
849 848
850 849 def localchangesfound(self, refresh=True):
851 850 if refresh:
852 851 raise util.Abort(_("local changes found, refresh first"))
853 852 else:
854 853 raise util.Abort(_("local changes found"))
855 854
856 855 def check_localchanges(self, repo, force=False, refresh=True):
857 856 m, a, r, d = repo.status()[:4]
858 857 if (m or a or r or d) and not force:
859 858 self.localchangesfound(refresh)
860 859 return m, a, r, d
861 860
862 861 _reserved = ('series', 'status', 'guards', '.', '..')
863 862 def check_reserved_name(self, name):
864 863 if name in self._reserved:
865 864 raise util.Abort(_('"%s" cannot be used as the name of a patch')
866 865 % name)
867 866 for prefix in ('.hg', '.mq'):
868 867 if name.startswith(prefix):
869 868 raise util.Abort(_('patch name cannot begin with "%s"')
870 869 % prefix)
871 870 for c in ('#', ':'):
872 871 if c in name:
873 872 raise util.Abort(_('"%s" cannot be used in the name of a patch')
874 873 % c)
875 874
876 875 def checkpatchname(self, name, force=False):
877 876 self.check_reserved_name(name)
878 877 if not force and os.path.exists(self.join(name)):
879 878 if os.path.isdir(self.join(name)):
880 879 raise util.Abort(_('"%s" already exists as a directory')
881 880 % name)
882 881 else:
883 882 raise util.Abort(_('patch "%s" already exists') % name)
884 883
885 884 def new(self, repo, patchfn, *pats, **opts):
886 885 """options:
887 886 msg: a string or a no-argument function returning a string
888 887 """
889 888 msg = opts.get('msg')
890 889 user = opts.get('user')
891 890 date = opts.get('date')
892 891 if date:
893 892 date = util.parsedate(date)
894 893 diffopts = self.diffopts({'git': opts.get('git')})
895 894 if opts.get('checkname', True):
896 895 self.checkpatchname(patchfn)
897 896 inclsubs = self.check_substate(repo)
898 897 if inclsubs:
899 898 inclsubs.append('.hgsubstate')
900 899 if opts.get('include') or opts.get('exclude') or pats:
901 900 if inclsubs:
902 901 pats = list(pats or []) + inclsubs
903 902 match = scmutil.match(repo, pats, opts)
904 903 # detect missing files in pats
905 904 def badfn(f, msg):
906 905 if f != '.hgsubstate': # .hgsubstate is auto-created
907 906 raise util.Abort('%s: %s' % (f, msg))
908 907 match.bad = badfn
909 908 m, a, r, d = repo.status(match=match)[:4]
910 909 else:
911 910 m, a, r, d = self.check_localchanges(repo, force=True)
912 911 match = scmutil.matchfiles(repo, m + a + r + inclsubs)
913 912 if len(repo[None].parents()) > 1:
914 913 raise util.Abort(_('cannot manage merge changesets'))
915 914 commitfiles = m + a + r
916 915 self.check_toppatch(repo)
917 916 insert = self.full_series_end()
918 917 wlock = repo.wlock()
919 918 try:
920 919 try:
921 920 # if patch file write fails, abort early
922 921 p = self.opener(patchfn, "w")
923 922 except IOError, e:
924 923 raise util.Abort(_('cannot write patch "%s": %s')
925 924 % (patchfn, e.strerror))
926 925 try:
927 926 if self.plainmode:
928 927 if user:
929 928 p.write("From: " + user + "\n")
930 929 if not date:
931 930 p.write("\n")
932 931 if date:
933 932 p.write("Date: %d %d\n\n" % date)
934 933 else:
935 934 p.write("# HG changeset patch\n")
936 935 p.write("# Parent "
937 936 + hex(repo[None].p1().node()) + "\n")
938 937 if user:
939 938 p.write("# User " + user + "\n")
940 939 if date:
941 940 p.write("# Date %s %s\n\n" % date)
942 941 if hasattr(msg, '__call__'):
943 942 msg = msg()
944 943 commitmsg = msg and msg or ("[mq]: %s" % patchfn)
945 944 n = repo.commit(commitmsg, user, date, match=match, force=True)
946 945 if n is None:
947 946 raise util.Abort(_("repo commit failed"))
948 947 try:
949 948 self.full_series[insert:insert] = [patchfn]
950 949 self.applied.append(statusentry(n, patchfn))
951 950 self.parse_series()
952 951 self.series_dirty = 1
953 952 self.applied_dirty = 1
954 953 if msg:
955 954 msg = msg + "\n\n"
956 955 p.write(msg)
957 956 if commitfiles:
958 957 parent = self.qparents(repo, n)
959 958 chunks = patchmod.diff(repo, node1=parent, node2=n,
960 959 match=match, opts=diffopts)
961 960 for chunk in chunks:
962 961 p.write(chunk)
963 962 p.close()
964 963 wlock.release()
965 964 wlock = None
966 965 r = self.qrepo()
967 966 if r:
968 967 r[None].add([patchfn])
969 968 except:
970 969 repo.rollback()
971 970 raise
972 971 except Exception:
973 972 patchpath = self.join(patchfn)
974 973 try:
975 974 os.unlink(patchpath)
976 975 except:
977 976 self.ui.warn(_('error unlinking %s\n') % patchpath)
978 977 raise
979 978 self.removeundo(repo)
980 979 finally:
981 980 release(wlock)
982 981
983 982 def strip(self, repo, revs, update=True, backup="all", force=None):
984 983 wlock = lock = None
985 984 try:
986 985 wlock = repo.wlock()
987 986 lock = repo.lock()
988 987
989 988 if update:
990 989 self.check_localchanges(repo, force=force, refresh=False)
991 990 urev = self.qparents(repo, revs[0])
992 991 hg.clean(repo, urev)
993 992 repo.dirstate.write()
994 993
995 994 self.removeundo(repo)
996 995 for rev in revs:
997 996 repair.strip(self.ui, repo, rev, backup)
998 997 # strip may have unbundled a set of backed up revisions after
999 998 # the actual strip
1000 999 self.removeundo(repo)
1001 1000 finally:
1002 1001 release(lock, wlock)
1003 1002
1004 1003 def isapplied(self, patch):
1005 1004 """returns (index, rev, patch)"""
1006 1005 for i, a in enumerate(self.applied):
1007 1006 if a.name == patch:
1008 1007 return (i, a.node, a.name)
1009 1008 return None
1010 1009
1011 1010 # if the exact patch name does not exist, we try a few
1012 1011 # variations. If strict is passed, we try only #1
1013 1012 #
1014 1013 # 1) a number to indicate an offset in the series file
1015 1014 # 2) a unique substring of the patch name was given
1016 1015 # 3) patchname[-+]num to indicate an offset in the series file
1017 1016 def lookup(self, patch, strict=False):
1018 1017 patch = patch and str(patch)
1019 1018
1020 1019 def partial_name(s):
1021 1020 if s in self.series:
1022 1021 return s
1023 1022 matches = [x for x in self.series if s in x]
1024 1023 if len(matches) > 1:
1025 1024 self.ui.warn(_('patch name "%s" is ambiguous:\n') % s)
1026 1025 for m in matches:
1027 1026 self.ui.warn(' %s\n' % m)
1028 1027 return None
1029 1028 if matches:
1030 1029 return matches[0]
1031 1030 if self.series and self.applied:
1032 1031 if s == 'qtip':
1033 1032 return self.series[self.series_end(True)-1]
1034 1033 if s == 'qbase':
1035 1034 return self.series[0]
1036 1035 return None
1037 1036
1038 1037 if patch is None:
1039 1038 return None
1040 1039 if patch in self.series:
1041 1040 return patch
1042 1041
1043 1042 if not os.path.isfile(self.join(patch)):
1044 1043 try:
1045 1044 sno = int(patch)
1046 1045 except (ValueError, OverflowError):
1047 1046 pass
1048 1047 else:
1049 1048 if -len(self.series) <= sno < len(self.series):
1050 1049 return self.series[sno]
1051 1050
1052 1051 if not strict:
1053 1052 res = partial_name(patch)
1054 1053 if res:
1055 1054 return res
1056 1055 minus = patch.rfind('-')
1057 1056 if minus >= 0:
1058 1057 res = partial_name(patch[:minus])
1059 1058 if res:
1060 1059 i = self.series.index(res)
1061 1060 try:
1062 1061 off = int(patch[minus + 1:] or 1)
1063 1062 except (ValueError, OverflowError):
1064 1063 pass
1065 1064 else:
1066 1065 if i - off >= 0:
1067 1066 return self.series[i - off]
1068 1067 plus = patch.rfind('+')
1069 1068 if plus >= 0:
1070 1069 res = partial_name(patch[:plus])
1071 1070 if res:
1072 1071 i = self.series.index(res)
1073 1072 try:
1074 1073 off = int(patch[plus + 1:] or 1)
1075 1074 except (ValueError, OverflowError):
1076 1075 pass
1077 1076 else:
1078 1077 if i + off < len(self.series):
1079 1078 return self.series[i + off]
1080 1079 raise util.Abort(_("patch %s not in series") % patch)
1081 1080
1082 1081 def push(self, repo, patch=None, force=False, list=False,
1083 1082 mergeq=None, all=False, move=False, exact=False):
1084 1083 diffopts = self.diffopts()
1085 1084 wlock = repo.wlock()
1086 1085 try:
1087 1086 heads = []
1088 1087 for b, ls in repo.branchmap().iteritems():
1089 1088 heads += ls
1090 1089 if not heads:
1091 1090 heads = [nullid]
1092 1091 if repo.dirstate.p1() not in heads and not exact:
1093 1092 self.ui.status(_("(working directory not at a head)\n"))
1094 1093
1095 1094 if not self.series:
1096 1095 self.ui.warn(_('no patches in series\n'))
1097 1096 return 0
1098 1097
1099 1098 patch = self.lookup(patch)
1100 1099 # Suppose our series file is: A B C and the current 'top'
1101 1100 # patch is B. qpush C should be performed (moving forward)
1102 1101 # qpush B is a NOP (no change) qpush A is an error (can't
1103 1102 # go backwards with qpush)
1104 1103 if patch:
1105 1104 info = self.isapplied(patch)
1106 1105 if info and info[0] >= len(self.applied) - 1:
1107 1106 self.ui.warn(
1108 1107 _('qpush: %s is already at the top\n') % patch)
1109 1108 return 0
1110 1109
1111 1110 pushable, reason = self.pushable(patch)
1112 1111 if pushable:
1113 1112 if self.series.index(patch) < self.series_end():
1114 1113 raise util.Abort(
1115 1114 _("cannot push to a previous patch: %s") % patch)
1116 1115 else:
1117 1116 if reason:
1118 1117 reason = _('guarded by %r') % reason
1119 1118 else:
1120 1119 reason = _('no matching guards')
1121 1120 self.ui.warn(_("cannot push '%s' - %s\n") % (patch, reason))
1122 1121 return 1
1123 1122 elif all:
1124 1123 patch = self.series[-1]
1125 1124 if self.isapplied(patch):
1126 1125 self.ui.warn(_('all patches are currently applied\n'))
1127 1126 return 0
1128 1127
1129 1128 # Following the above example, starting at 'top' of B:
1130 1129 # qpush should be performed (pushes C), but a subsequent
1131 1130 # qpush without an argument is an error (nothing to
1132 1131 # apply). This allows a loop of "...while hg qpush..." to
1133 1132 # work as it detects an error when done
1134 1133 start = self.series_end()
1135 1134 if start == len(self.series):
1136 1135 self.ui.warn(_('patch series already fully applied\n'))
1137 1136 return 1
1138 1137
1139 1138 if exact:
1140 1139 if move:
1141 1140 raise util.Abort(_("cannot use --exact and --move together"))
1142 1141 if self.applied:
1143 1142 raise util.Abort(_("cannot push --exact with applied patches"))
1144 1143 root = self.series[start]
1145 1144 target = patchheader(self.join(root), self.plainmode).parent
1146 1145 if not target:
1147 1146 raise util.Abort(_("%s does not have a parent recorded" % root))
1148 1147 if not repo[target] == repo['.']:
1149 1148 hg.update(repo, target)
1150 1149
1151 1150 if move:
1152 1151 if not patch:
1153 1152 raise util.Abort(_("please specify the patch to move"))
1154 1153 for i, rpn in enumerate(self.full_series[start:]):
1155 1154 # strip markers for patch guards
1156 1155 if self.guard_re.split(rpn, 1)[0] == patch:
1157 1156 break
1158 1157 index = start + i
1159 1158 assert index < len(self.full_series)
1160 1159 fullpatch = self.full_series[index]
1161 1160 del self.full_series[index]
1162 1161 self.full_series.insert(start, fullpatch)
1163 1162 self.parse_series()
1164 1163 self.series_dirty = 1
1165 1164
1166 1165 self.applied_dirty = 1
1167 1166 if start > 0:
1168 1167 self.check_toppatch(repo)
1169 1168 if not patch:
1170 1169 patch = self.series[start]
1171 1170 end = start + 1
1172 1171 else:
1173 1172 end = self.series.index(patch, start) + 1
1174 1173
1175 1174 s = self.series[start:end]
1176 1175
1177 1176 if not force:
1178 1177 mm, aa, rr, dd = repo.status()[:4]
1179 1178 wcfiles = set(mm + aa + rr + dd)
1180 1179 if wcfiles:
1181 1180 for patchname in s:
1182 1181 pf = os.path.join(self.path, patchname)
1183 1182 patchfiles = patchmod.changedfiles(self.ui, repo, pf)
1184 1183 if wcfiles.intersection(patchfiles):
1185 1184 self.localchangesfound(self.applied)
1186 1185 elif mergeq:
1187 1186 self.check_localchanges(refresh=self.applied)
1188 1187
1189 1188 all_files = set()
1190 1189 try:
1191 1190 if mergeq:
1192 1191 ret = self.mergepatch(repo, mergeq, s, diffopts)
1193 1192 else:
1194 1193 ret = self.apply(repo, s, list, all_files=all_files)
1195 1194 except:
1196 1195 self.ui.warn(_('cleaning up working directory...'))
1197 1196 node = repo.dirstate.p1()
1198 1197 hg.revert(repo, node, None)
1199 1198 # only remove unknown files that we know we touched or
1200 1199 # created while patching
1201 1200 for f in all_files:
1202 1201 if f not in repo.dirstate:
1203 1202 try:
1204 1203 util.unlinkpath(repo.wjoin(f))
1205 1204 except OSError, inst:
1206 1205 if inst.errno != errno.ENOENT:
1207 1206 raise
1208 1207 self.ui.warn(_('done\n'))
1209 1208 raise
1210 1209
1211 1210 if not self.applied:
1212 1211 return ret[0]
1213 1212 top = self.applied[-1].name
1214 1213 if ret[0] and ret[0] > 1:
1215 1214 msg = _("errors during apply, please fix and refresh %s\n")
1216 1215 self.ui.write(msg % top)
1217 1216 else:
1218 1217 self.ui.write(_("now at: %s\n") % top)
1219 1218 return ret[0]
1220 1219
1221 1220 finally:
1222 1221 wlock.release()
1223 1222
1224 1223 def pop(self, repo, patch=None, force=False, update=True, all=False):
1225 1224 wlock = repo.wlock()
1226 1225 try:
1227 1226 if patch:
1228 1227 # index, rev, patch
1229 1228 info = self.isapplied(patch)
1230 1229 if not info:
1231 1230 patch = self.lookup(patch)
1232 1231 info = self.isapplied(patch)
1233 1232 if not info:
1234 1233 raise util.Abort(_("patch %s is not applied") % patch)
1235 1234
1236 1235 if not self.applied:
1237 1236 # Allow qpop -a to work repeatedly,
1238 1237 # but not qpop without an argument
1239 1238 self.ui.warn(_("no patches applied\n"))
1240 1239 return not all
1241 1240
1242 1241 if all:
1243 1242 start = 0
1244 1243 elif patch:
1245 1244 start = info[0] + 1
1246 1245 else:
1247 1246 start = len(self.applied) - 1
1248 1247
1249 1248 if start >= len(self.applied):
1250 1249 self.ui.warn(_("qpop: %s is already at the top\n") % patch)
1251 1250 return
1252 1251
1253 1252 if not update:
1254 1253 parents = repo.dirstate.parents()
1255 1254 rr = [x.node for x in self.applied]
1256 1255 for p in parents:
1257 1256 if p in rr:
1258 1257 self.ui.warn(_("qpop: forcing dirstate update\n"))
1259 1258 update = True
1260 1259 else:
1261 1260 parents = [p.node() for p in repo[None].parents()]
1262 1261 needupdate = False
1263 1262 for entry in self.applied[start:]:
1264 1263 if entry.node in parents:
1265 1264 needupdate = True
1266 1265 break
1267 1266 update = needupdate
1268 1267
1269 1268 self.applied_dirty = 1
1270 1269 end = len(self.applied)
1271 1270 rev = self.applied[start].node
1272 1271 if update:
1273 1272 top = self.check_toppatch(repo)[0]
1274 1273
1275 1274 try:
1276 1275 heads = repo.changelog.heads(rev)
1277 1276 except error.LookupError:
1278 1277 node = short(rev)
1279 1278 raise util.Abort(_('trying to pop unknown node %s') % node)
1280 1279
1281 1280 if heads != [self.applied[-1].node]:
1282 1281 raise util.Abort(_("popping would remove a revision not "
1283 1282 "managed by this patch queue"))
1284 1283
1285 1284 # we know there are no local changes, so we can make a simplified
1286 1285 # form of hg.update.
1287 1286 if update:
1288 1287 qp = self.qparents(repo, rev)
1289 1288 ctx = repo[qp]
1290 1289 m, a, r, d = repo.status(qp, top)[:4]
1291 1290 parentfiles = set(m + a + r + d)
1292 1291 if not force and parentfiles:
1293 1292 mm, aa, rr, dd = repo.status()[:4]
1294 1293 wcfiles = set(mm + aa + rr + dd)
1295 1294 if wcfiles.intersection(parentfiles):
1296 1295 self.localchangesfound()
1297 1296 if d:
1298 1297 raise util.Abort(_("deletions found between repo revs"))
1299 1298 for f in a:
1300 1299 try:
1301 1300 util.unlinkpath(repo.wjoin(f))
1302 1301 except OSError, e:
1303 1302 if e.errno != errno.ENOENT:
1304 1303 raise
1305 1304 repo.dirstate.drop(f)
1306 1305 for f in m + r:
1307 1306 fctx = ctx[f]
1308 1307 repo.wwrite(f, fctx.data(), fctx.flags())
1309 1308 repo.dirstate.normal(f)
1310 1309 repo.dirstate.setparents(qp, nullid)
1311 1310 for patch in reversed(self.applied[start:end]):
1312 1311 self.ui.status(_("popping %s\n") % patch.name)
1313 1312 del self.applied[start:end]
1314 1313 self.strip(repo, [rev], update=False, backup='strip')
1315 1314 if self.applied:
1316 1315 self.ui.write(_("now at: %s\n") % self.applied[-1].name)
1317 1316 else:
1318 1317 self.ui.write(_("patch queue now empty\n"))
1319 1318 finally:
1320 1319 wlock.release()
1321 1320
1322 1321 def diff(self, repo, pats, opts):
1323 1322 top, patch = self.check_toppatch(repo)
1324 1323 if not top:
1325 1324 self.ui.write(_("no patches applied\n"))
1326 1325 return
1327 1326 qp = self.qparents(repo, top)
1328 1327 if opts.get('reverse'):
1329 1328 node1, node2 = None, qp
1330 1329 else:
1331 1330 node1, node2 = qp, None
1332 1331 diffopts = self.diffopts(opts, patch)
1333 1332 self.printdiff(repo, diffopts, node1, node2, files=pats, opts=opts)
1334 1333
1335 1334 def refresh(self, repo, pats=None, **opts):
1336 1335 if not self.applied:
1337 1336 self.ui.write(_("no patches applied\n"))
1338 1337 return 1
1339 1338 msg = opts.get('msg', '').rstrip()
1340 1339 newuser = opts.get('user')
1341 1340 newdate = opts.get('date')
1342 1341 if newdate:
1343 1342 newdate = '%d %d' % util.parsedate(newdate)
1344 1343 wlock = repo.wlock()
1345 1344
1346 1345 try:
1347 1346 self.check_toppatch(repo)
1348 1347 (top, patchfn) = (self.applied[-1].node, self.applied[-1].name)
1349 1348 if repo.changelog.heads(top) != [top]:
1350 1349 raise util.Abort(_("cannot refresh a revision with children"))
1351 1350
1352 1351 inclsubs = self.check_substate(repo)
1353 1352
1354 1353 cparents = repo.changelog.parents(top)
1355 1354 patchparent = self.qparents(repo, top)
1356 1355 ph = patchheader(self.join(patchfn), self.plainmode)
1357 1356 diffopts = self.diffopts({'git': opts.get('git')}, patchfn)
1358 1357 if msg:
1359 1358 ph.setmessage(msg)
1360 1359 if newuser:
1361 1360 ph.setuser(newuser)
1362 1361 if newdate:
1363 1362 ph.setdate(newdate)
1364 1363 ph.setparent(hex(patchparent))
1365 1364
1366 1365 # only commit new patch when write is complete
1367 1366 patchf = self.opener(patchfn, 'w', atomictemp=True)
1368 1367
1369 1368 comments = str(ph)
1370 1369 if comments:
1371 1370 patchf.write(comments)
1372 1371
1373 1372 # update the dirstate in place, strip off the qtip commit
1374 1373 # and then commit.
1375 1374 #
1376 1375 # this should really read:
1377 1376 # mm, dd, aa = repo.status(top, patchparent)[:3]
1378 1377 # but we do it backwards to take advantage of manifest/chlog
1379 1378 # caching against the next repo.status call
1380 1379 mm, aa, dd = repo.status(patchparent, top)[:3]
1381 1380 changes = repo.changelog.read(top)
1382 1381 man = repo.manifest.read(changes[0])
1383 1382 aaa = aa[:]
1384 1383 matchfn = scmutil.match(repo, pats, opts)
1385 1384 # in short mode, we only diff the files included in the
1386 1385 # patch already plus specified files
1387 1386 if opts.get('short'):
1388 1387 # if amending a patch, we start with existing
1389 1388 # files plus specified files - unfiltered
1390 1389 match = scmutil.matchfiles(repo, mm + aa + dd + matchfn.files())
1391 1390 # filter with inc/exl options
1392 1391 matchfn = scmutil.match(repo, opts=opts)
1393 1392 else:
1394 1393 match = scmutil.matchall(repo)
1395 1394 m, a, r, d = repo.status(match=match)[:4]
1396 1395 mm = set(mm)
1397 1396 aa = set(aa)
1398 1397 dd = set(dd)
1399 1398
1400 1399 # we might end up with files that were added between
1401 1400 # qtip and the dirstate parent, but then changed in the
1402 1401 # local dirstate. in this case, we want them to only
1403 1402 # show up in the added section
1404 1403 for x in m:
1405 1404 if x not in aa:
1406 1405 mm.add(x)
1407 1406 # we might end up with files added by the local dirstate that
1408 1407 # were deleted by the patch. In this case, they should only
1409 1408 # show up in the changed section.
1410 1409 for x in a:
1411 1410 if x in dd:
1412 1411 dd.remove(x)
1413 1412 mm.add(x)
1414 1413 else:
1415 1414 aa.add(x)
1416 1415 # make sure any files deleted in the local dirstate
1417 1416 # are not in the add or change column of the patch
1418 1417 forget = []
1419 1418 for x in d + r:
1420 1419 if x in aa:
1421 1420 aa.remove(x)
1422 1421 forget.append(x)
1423 1422 continue
1424 1423 else:
1425 1424 mm.discard(x)
1426 1425 dd.add(x)
1427 1426
1428 1427 m = list(mm)
1429 1428 r = list(dd)
1430 1429 a = list(aa)
1431 1430 c = [filter(matchfn, l) for l in (m, a, r)]
1432 1431 match = scmutil.matchfiles(repo, set(c[0] + c[1] + c[2] + inclsubs))
1433 1432 chunks = patchmod.diff(repo, patchparent, match=match,
1434 1433 changes=c, opts=diffopts)
1435 1434 for chunk in chunks:
1436 1435 patchf.write(chunk)
1437 1436
1438 1437 try:
1439 1438 if diffopts.git or diffopts.upgrade:
1440 1439 copies = {}
1441 1440 for dst in a:
1442 1441 src = repo.dirstate.copied(dst)
1443 1442 # during qfold, the source file for copies may
1444 1443 # be removed. Treat this as a simple add.
1445 1444 if src is not None and src in repo.dirstate:
1446 1445 copies.setdefault(src, []).append(dst)
1447 1446 repo.dirstate.add(dst)
1448 1447 # remember the copies between patchparent and qtip
1449 1448 for dst in aaa:
1450 1449 f = repo.file(dst)
1451 1450 src = f.renamed(man[dst])
1452 1451 if src:
1453 1452 copies.setdefault(src[0], []).extend(
1454 1453 copies.get(dst, []))
1455 1454 if dst in a:
1456 1455 copies[src[0]].append(dst)
1457 1456 # we can't copy a file created by the patch itself
1458 1457 if dst in copies:
1459 1458 del copies[dst]
1460 1459 for src, dsts in copies.iteritems():
1461 1460 for dst in dsts:
1462 1461 repo.dirstate.copy(src, dst)
1463 1462 else:
1464 1463 for dst in a:
1465 1464 repo.dirstate.add(dst)
1466 1465 # Drop useless copy information
1467 1466 for f in list(repo.dirstate.copies()):
1468 1467 repo.dirstate.copy(None, f)
1469 1468 for f in r:
1470 1469 repo.dirstate.remove(f)
1471 1470 # if the patch excludes a modified file, mark that
1472 1471 # file with mtime=0 so status can see it.
1473 1472 mm = []
1474 1473 for i in xrange(len(m)-1, -1, -1):
1475 1474 if not matchfn(m[i]):
1476 1475 mm.append(m[i])
1477 1476 del m[i]
1478 1477 for f in m:
1479 1478 repo.dirstate.normal(f)
1480 1479 for f in mm:
1481 1480 repo.dirstate.normallookup(f)
1482 1481 for f in forget:
1483 1482 repo.dirstate.drop(f)
1484 1483
1485 1484 if not msg:
1486 1485 if not ph.message:
1487 1486 message = "[mq]: %s\n" % patchfn
1488 1487 else:
1489 1488 message = "\n".join(ph.message)
1490 1489 else:
1491 1490 message = msg
1492 1491
1493 1492 user = ph.user or changes[1]
1494 1493
1495 1494 # assumes strip can roll itself back if interrupted
1496 1495 repo.dirstate.setparents(*cparents)
1497 1496 self.applied.pop()
1498 1497 self.applied_dirty = 1
1499 1498 self.strip(repo, [top], update=False,
1500 1499 backup='strip')
1501 1500 except:
1502 1501 repo.dirstate.invalidate()
1503 1502 raise
1504 1503
1505 1504 try:
1506 1505 # might be nice to attempt to roll back strip after this
1507 1506 n = repo.commit(message, user, ph.date, match=match,
1508 1507 force=True)
1509 1508 # only write patch after a successful commit
1510 1509 patchf.rename()
1511 1510 self.applied.append(statusentry(n, patchfn))
1512 1511 except:
1513 1512 ctx = repo[cparents[0]]
1514 1513 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1515 1514 self.save_dirty()
1516 1515 self.ui.warn(_('refresh interrupted while patch was popped! '
1517 1516 '(revert --all, qpush to recover)\n'))
1518 1517 raise
1519 1518 finally:
1520 1519 wlock.release()
1521 1520 self.removeundo(repo)
1522 1521
1523 1522 def init(self, repo, create=False):
1524 1523 if not create and os.path.isdir(self.path):
1525 1524 raise util.Abort(_("patch queue directory already exists"))
1526 1525 try:
1527 1526 os.mkdir(self.path)
1528 1527 except OSError, inst:
1529 1528 if inst.errno != errno.EEXIST or not create:
1530 1529 raise
1531 1530 if create:
1532 1531 return self.qrepo(create=True)
1533 1532
1534 1533 def unapplied(self, repo, patch=None):
1535 1534 if patch and patch not in self.series:
1536 1535 raise util.Abort(_("patch %s is not in series file") % patch)
1537 1536 if not patch:
1538 1537 start = self.series_end()
1539 1538 else:
1540 1539 start = self.series.index(patch) + 1
1541 1540 unapplied = []
1542 1541 for i in xrange(start, len(self.series)):
1543 1542 pushable, reason = self.pushable(i)
1544 1543 if pushable:
1545 1544 unapplied.append((i, self.series[i]))
1546 1545 self.explain_pushable(i)
1547 1546 return unapplied
1548 1547
1549 1548 def qseries(self, repo, missing=None, start=0, length=None, status=None,
1550 1549 summary=False):
1551 1550 def displayname(pfx, patchname, state):
1552 1551 if pfx:
1553 1552 self.ui.write(pfx)
1554 1553 if summary:
1555 1554 ph = patchheader(self.join(patchname), self.plainmode)
1556 1555 msg = ph.message and ph.message[0] or ''
1557 1556 if self.ui.formatted():
1558 1557 width = self.ui.termwidth() - len(pfx) - len(patchname) - 2
1559 1558 if width > 0:
1560 1559 msg = util.ellipsis(msg, width)
1561 1560 else:
1562 1561 msg = ''
1563 1562 self.ui.write(patchname, label='qseries.' + state)
1564 1563 self.ui.write(': ')
1565 1564 self.ui.write(msg, label='qseries.message.' + state)
1566 1565 else:
1567 1566 self.ui.write(patchname, label='qseries.' + state)
1568 1567 self.ui.write('\n')
1569 1568
1570 1569 applied = set([p.name for p in self.applied])
1571 1570 if length is None:
1572 1571 length = len(self.series) - start
1573 1572 if not missing:
1574 1573 if self.ui.verbose:
1575 1574 idxwidth = len(str(start + length - 1))
1576 1575 for i in xrange(start, start + length):
1577 1576 patch = self.series[i]
1578 1577 if patch in applied:
1579 1578 char, state = 'A', 'applied'
1580 1579 elif self.pushable(i)[0]:
1581 1580 char, state = 'U', 'unapplied'
1582 1581 else:
1583 1582 char, state = 'G', 'guarded'
1584 1583 pfx = ''
1585 1584 if self.ui.verbose:
1586 1585 pfx = '%*d %s ' % (idxwidth, i, char)
1587 1586 elif status and status != char:
1588 1587 continue
1589 1588 displayname(pfx, patch, state)
1590 1589 else:
1591 1590 msng_list = []
1592 1591 for root, dirs, files in os.walk(self.path):
1593 1592 d = root[len(self.path) + 1:]
1594 1593 for f in files:
1595 1594 fl = os.path.join(d, f)
1596 1595 if (fl not in self.series and
1597 1596 fl not in (self.status_path, self.series_path,
1598 1597 self.guards_path)
1599 1598 and not fl.startswith('.')):
1600 1599 msng_list.append(fl)
1601 1600 for x in sorted(msng_list):
1602 1601 pfx = self.ui.verbose and ('D ') or ''
1603 1602 displayname(pfx, x, 'missing')
1604 1603
1605 1604 def issaveline(self, l):
1606 1605 if l.name == '.hg.patches.save.line':
1607 1606 return True
1608 1607
1609 1608 def qrepo(self, create=False):
1610 1609 ui = self.ui.copy()
1611 1610 ui.setconfig('paths', 'default', '', overlay=False)
1612 1611 ui.setconfig('paths', 'default-push', '', overlay=False)
1613 1612 if create or os.path.isdir(self.join(".hg")):
1614 1613 return hg.repository(ui, path=self.path, create=create)
1615 1614
1616 1615 def restore(self, repo, rev, delete=None, qupdate=None):
1617 1616 desc = repo[rev].description().strip()
1618 1617 lines = desc.splitlines()
1619 1618 i = 0
1620 1619 datastart = None
1621 1620 series = []
1622 1621 applied = []
1623 1622 qpp = None
1624 1623 for i, line in enumerate(lines):
1625 1624 if line == 'Patch Data:':
1626 1625 datastart = i + 1
1627 1626 elif line.startswith('Dirstate:'):
1628 1627 l = line.rstrip()
1629 1628 l = l[10:].split(' ')
1630 1629 qpp = [bin(x) for x in l]
1631 1630 elif datastart is not None:
1632 1631 l = line.rstrip()
1633 1632 n, name = l.split(':', 1)
1634 1633 if n:
1635 1634 applied.append(statusentry(bin(n), name))
1636 1635 else:
1637 1636 series.append(l)
1638 1637 if datastart is None:
1639 1638 self.ui.warn(_("No saved patch data found\n"))
1640 1639 return 1
1641 1640 self.ui.warn(_("restoring status: %s\n") % lines[0])
1642 1641 self.full_series = series
1643 1642 self.applied = applied
1644 1643 self.parse_series()
1645 1644 self.series_dirty = 1
1646 1645 self.applied_dirty = 1
1647 1646 heads = repo.changelog.heads()
1648 1647 if delete:
1649 1648 if rev not in heads:
1650 1649 self.ui.warn(_("save entry has children, leaving it alone\n"))
1651 1650 else:
1652 1651 self.ui.warn(_("removing save entry %s\n") % short(rev))
1653 1652 pp = repo.dirstate.parents()
1654 1653 if rev in pp:
1655 1654 update = True
1656 1655 else:
1657 1656 update = False
1658 1657 self.strip(repo, [rev], update=update, backup='strip')
1659 1658 if qpp:
1660 1659 self.ui.warn(_("saved queue repository parents: %s %s\n") %
1661 1660 (short(qpp[0]), short(qpp[1])))
1662 1661 if qupdate:
1663 1662 self.ui.status(_("updating queue directory\n"))
1664 1663 r = self.qrepo()
1665 1664 if not r:
1666 1665 self.ui.warn(_("Unable to load queue repository\n"))
1667 1666 return 1
1668 1667 hg.clean(r, qpp[0])
1669 1668
1670 1669 def save(self, repo, msg=None):
1671 1670 if not self.applied:
1672 1671 self.ui.warn(_("save: no patches applied, exiting\n"))
1673 1672 return 1
1674 1673 if self.issaveline(self.applied[-1]):
1675 1674 self.ui.warn(_("status is already saved\n"))
1676 1675 return 1
1677 1676
1678 1677 if not msg:
1679 1678 msg = _("hg patches saved state")
1680 1679 else:
1681 1680 msg = "hg patches: " + msg.rstrip('\r\n')
1682 1681 r = self.qrepo()
1683 1682 if r:
1684 1683 pp = r.dirstate.parents()
1685 1684 msg += "\nDirstate: %s %s" % (hex(pp[0]), hex(pp[1]))
1686 1685 msg += "\n\nPatch Data:\n"
1687 1686 msg += ''.join('%s\n' % x for x in self.applied)
1688 1687 msg += ''.join(':%s\n' % x for x in self.full_series)
1689 1688 n = repo.commit(msg, force=True)
1690 1689 if not n:
1691 1690 self.ui.warn(_("repo commit failed\n"))
1692 1691 return 1
1693 1692 self.applied.append(statusentry(n, '.hg.patches.save.line'))
1694 1693 self.applied_dirty = 1
1695 1694 self.removeundo(repo)
1696 1695
1697 1696 def full_series_end(self):
1698 1697 if self.applied:
1699 1698 p = self.applied[-1].name
1700 1699 end = self.find_series(p)
1701 1700 if end is None:
1702 1701 return len(self.full_series)
1703 1702 return end + 1
1704 1703 return 0
1705 1704
1706 1705 def series_end(self, all_patches=False):
1707 1706 """If all_patches is False, return the index of the next pushable patch
1708 1707 in the series, or the series length. If all_patches is True, return the
1709 1708 index of the first patch past the last applied one.
1710 1709 """
1711 1710 end = 0
1712 1711 def next(start):
1713 1712 if all_patches or start >= len(self.series):
1714 1713 return start
1715 1714 for i in xrange(start, len(self.series)):
1716 1715 p, reason = self.pushable(i)
1717 1716 if p:
1718 1717 break
1719 1718 self.explain_pushable(i)
1720 1719 return i
1721 1720 if self.applied:
1722 1721 p = self.applied[-1].name
1723 1722 try:
1724 1723 end = self.series.index(p)
1725 1724 except ValueError:
1726 1725 return 0
1727 1726 return next(end + 1)
1728 1727 return next(end)
1729 1728
1730 1729 def appliedname(self, index):
1731 1730 pname = self.applied[index].name
1732 1731 if not self.ui.verbose:
1733 1732 p = pname
1734 1733 else:
1735 1734 p = str(self.series.index(pname)) + " " + pname
1736 1735 return p
1737 1736
1738 1737 def qimport(self, repo, files, patchname=None, rev=None, existing=None,
1739 1738 force=None, git=False):
1740 1739 def checkseries(patchname):
1741 1740 if patchname in self.series:
1742 1741 raise util.Abort(_('patch %s is already in the series file')
1743 1742 % patchname)
1744 1743
1745 1744 if rev:
1746 1745 if files:
1747 1746 raise util.Abort(_('option "-r" not valid when importing '
1748 1747 'files'))
1749 1748 rev = scmutil.revrange(repo, rev)
1750 1749 rev.sort(reverse=True)
1751 1750 if (len(files) > 1 or len(rev) > 1) and patchname:
1752 1751 raise util.Abort(_('option "-n" not valid when importing multiple '
1753 1752 'patches'))
1754 1753 if rev:
1755 1754 # If mq patches are applied, we can only import revisions
1756 1755 # that form a linear path to qbase.
1757 1756 # Otherwise, they should form a linear path to a head.
1758 1757 heads = repo.changelog.heads(repo.changelog.node(rev[-1]))
1759 1758 if len(heads) > 1:
1760 1759 raise util.Abort(_('revision %d is the root of more than one '
1761 1760 'branch') % rev[-1])
1762 1761 if self.applied:
1763 1762 base = repo.changelog.node(rev[0])
1764 1763 if base in [n.node for n in self.applied]:
1765 1764 raise util.Abort(_('revision %d is already managed')
1766 1765 % rev[0])
1767 1766 if heads != [self.applied[-1].node]:
1768 1767 raise util.Abort(_('revision %d is not the parent of '
1769 1768 'the queue') % rev[0])
1770 1769 base = repo.changelog.rev(self.applied[0].node)
1771 1770 lastparent = repo.changelog.parentrevs(base)[0]
1772 1771 else:
1773 1772 if heads != [repo.changelog.node(rev[0])]:
1774 1773 raise util.Abort(_('revision %d has unmanaged children')
1775 1774 % rev[0])
1776 1775 lastparent = None
1777 1776
1778 1777 diffopts = self.diffopts({'git': git})
1779 1778 for r in rev:
1780 1779 p1, p2 = repo.changelog.parentrevs(r)
1781 1780 n = repo.changelog.node(r)
1782 1781 if p2 != nullrev:
1783 1782 raise util.Abort(_('cannot import merge revision %d') % r)
1784 1783 if lastparent and lastparent != r:
1785 1784 raise util.Abort(_('revision %d is not the parent of %d')
1786 1785 % (r, lastparent))
1787 1786 lastparent = p1
1788 1787
1789 1788 if not patchname:
1790 1789 patchname = normname('%d.diff' % r)
1791 1790 checkseries(patchname)
1792 1791 self.checkpatchname(patchname, force)
1793 1792 self.full_series.insert(0, patchname)
1794 1793
1795 1794 patchf = self.opener(patchname, "w")
1796 1795 cmdutil.export(repo, [n], fp=patchf, opts=diffopts)
1797 1796 patchf.close()
1798 1797
1799 1798 se = statusentry(n, patchname)
1800 1799 self.applied.insert(0, se)
1801 1800
1802 1801 self.added.append(patchname)
1803 1802 patchname = None
1804 1803 self.parse_series()
1805 1804 self.applied_dirty = 1
1806 1805 self.series_dirty = True
1807 1806
1808 1807 for i, filename in enumerate(files):
1809 1808 if existing:
1810 1809 if filename == '-':
1811 1810 raise util.Abort(_('-e is incompatible with import from -'))
1812 1811 filename = normname(filename)
1813 1812 self.check_reserved_name(filename)
1814 1813 originpath = self.join(filename)
1815 1814 if not os.path.isfile(originpath):
1816 1815 raise util.Abort(_("patch %s does not exist") % filename)
1817 1816
1818 1817 if patchname:
1819 1818 self.checkpatchname(patchname, force)
1820 1819
1821 1820 self.ui.write(_('renaming %s to %s\n')
1822 1821 % (filename, patchname))
1823 1822 util.rename(originpath, self.join(patchname))
1824 1823 else:
1825 1824 patchname = filename
1826 1825
1827 1826 else:
1828 1827 if filename == '-' and not patchname:
1829 1828 raise util.Abort(_('need --name to import a patch from -'))
1830 1829 elif not patchname:
1831 1830 patchname = normname(os.path.basename(filename.rstrip('/')))
1832 1831 self.checkpatchname(patchname, force)
1833 1832 try:
1834 1833 if filename == '-':
1835 1834 text = sys.stdin.read()
1836 1835 else:
1837 1836 fp = url.open(self.ui, filename)
1838 1837 text = fp.read()
1839 1838 fp.close()
1840 1839 except (OSError, IOError):
1841 1840 raise util.Abort(_("unable to read file %s") % filename)
1842 1841 patchf = self.opener(patchname, "w")
1843 1842 patchf.write(text)
1844 1843 patchf.close()
1845 1844 if not force:
1846 1845 checkseries(patchname)
1847 1846 if patchname not in self.series:
1848 1847 index = self.full_series_end() + i
1849 1848 self.full_series[index:index] = [patchname]
1850 1849 self.parse_series()
1851 1850 self.series_dirty = True
1852 1851 self.ui.warn(_("adding %s to series file\n") % patchname)
1853 1852 self.added.append(patchname)
1854 1853 patchname = None
1855 1854
1856 1855 self.removeundo(repo)
1857 1856
1858 1857 @command("qdelete|qremove|qrm",
1859 1858 [('k', 'keep', None, _('keep patch file')),
1860 1859 ('r', 'rev', [],
1861 1860 _('stop managing a revision (DEPRECATED)'), _('REV'))],
1862 1861 _('hg qdelete [-k] [PATCH]...'))
1863 1862 def delete(ui, repo, *patches, **opts):
1864 1863 """remove patches from queue
1865 1864
1866 1865 The patches must not be applied, and at least one patch is required. With
1867 1866 -k/--keep, the patch files are preserved in the patch directory.
1868 1867
1869 1868 To stop managing a patch and move it into permanent history,
1870 1869 use the :hg:`qfinish` command."""
1871 1870 q = repo.mq
1872 1871 q.delete(repo, patches, opts)
1873 1872 q.save_dirty()
1874 1873 return 0
1875 1874
1876 1875 @command("qapplied",
1877 1876 [('1', 'last', None, _('show only the last patch'))
1878 1877 ] + seriesopts,
1879 1878 _('hg qapplied [-1] [-s] [PATCH]'))
1880 1879 def applied(ui, repo, patch=None, **opts):
1881 1880 """print the patches already applied
1882 1881
1883 1882 Returns 0 on success."""
1884 1883
1885 1884 q = repo.mq
1886 1885
1887 1886 if patch:
1888 1887 if patch not in q.series:
1889 1888 raise util.Abort(_("patch %s is not in series file") % patch)
1890 1889 end = q.series.index(patch) + 1
1891 1890 else:
1892 1891 end = q.series_end(True)
1893 1892
1894 1893 if opts.get('last') and not end:
1895 1894 ui.write(_("no patches applied\n"))
1896 1895 return 1
1897 1896 elif opts.get('last') and end == 1:
1898 1897 ui.write(_("only one patch applied\n"))
1899 1898 return 1
1900 1899 elif opts.get('last'):
1901 1900 start = end - 2
1902 1901 end = 1
1903 1902 else:
1904 1903 start = 0
1905 1904
1906 1905 q.qseries(repo, length=end, start=start, status='A',
1907 1906 summary=opts.get('summary'))
1908 1907
1909 1908
1910 1909 @command("qunapplied",
1911 1910 [('1', 'first', None, _('show only the first patch'))] + seriesopts,
1912 1911 _('hg qunapplied [-1] [-s] [PATCH]'))
1913 1912 def unapplied(ui, repo, patch=None, **opts):
1914 1913 """print the patches not yet applied
1915 1914
1916 1915 Returns 0 on success."""
1917 1916
1918 1917 q = repo.mq
1919 1918 if patch:
1920 1919 if patch not in q.series:
1921 1920 raise util.Abort(_("patch %s is not in series file") % patch)
1922 1921 start = q.series.index(patch) + 1
1923 1922 else:
1924 1923 start = q.series_end(True)
1925 1924
1926 1925 if start == len(q.series) and opts.get('first'):
1927 1926 ui.write(_("all patches applied\n"))
1928 1927 return 1
1929 1928
1930 1929 length = opts.get('first') and 1 or None
1931 1930 q.qseries(repo, start=start, length=length, status='U',
1932 1931 summary=opts.get('summary'))
1933 1932
1934 1933 @command("qimport",
1935 1934 [('e', 'existing', None, _('import file in patch directory')),
1936 1935 ('n', 'name', '',
1937 1936 _('name of patch file'), _('NAME')),
1938 1937 ('f', 'force', None, _('overwrite existing files')),
1939 1938 ('r', 'rev', [],
1940 1939 _('place existing revisions under mq control'), _('REV')),
1941 1940 ('g', 'git', None, _('use git extended diff format')),
1942 1941 ('P', 'push', None, _('qpush after importing'))],
1943 1942 _('hg qimport [-e] [-n NAME] [-f] [-g] [-P] [-r REV]... FILE...'))
1944 1943 def qimport(ui, repo, *filename, **opts):
1945 1944 """import a patch
1946 1945
1947 1946 The patch is inserted into the series after the last applied
1948 1947 patch. If no patches have been applied, qimport prepends the patch
1949 1948 to the series.
1950 1949
1951 1950 The patch will have the same name as its source file unless you
1952 1951 give it a new one with -n/--name.
1953 1952
1954 1953 You can register an existing patch inside the patch directory with
1955 1954 the -e/--existing flag.
1956 1955
1957 1956 With -f/--force, an existing patch of the same name will be
1958 1957 overwritten.
1959 1958
1960 1959 An existing changeset may be placed under mq control with -r/--rev
1961 1960 (e.g. qimport --rev tip -n patch will place tip under mq control).
1962 1961 With -g/--git, patches imported with --rev will use the git diff
1963 1962 format. See the diffs help topic for information on why this is
1964 1963 important for preserving rename/copy information and permission
1965 1964 changes. Use :hg:`qfinish` to remove changesets from mq control.
1966 1965
1967 1966 To import a patch from standard input, pass - as the patch file.
1968 1967 When importing from standard input, a patch name must be specified
1969 1968 using the --name flag.
1970 1969
1971 1970 To import an existing patch while renaming it::
1972 1971
1973 1972 hg qimport -e existing-patch -n new-name
1974 1973
1975 1974 Returns 0 if import succeeded.
1976 1975 """
1977 1976 q = repo.mq
1978 1977 try:
1979 1978 q.qimport(repo, filename, patchname=opts.get('name'),
1980 1979 existing=opts.get('existing'), force=opts.get('force'),
1981 1980 rev=opts.get('rev'), git=opts.get('git'))
1982 1981 finally:
1983 1982 q.save_dirty()
1984 1983
1985 1984 if opts.get('push') and not opts.get('rev'):
1986 1985 return q.push(repo, None)
1987 1986 return 0
1988 1987
1989 1988 def qinit(ui, repo, create):
1990 1989 """initialize a new queue repository
1991 1990
1992 1991 This command also creates a series file for ordering patches, and
1993 1992 an mq-specific .hgignore file in the queue repository, to exclude
1994 1993 the status and guards files (these contain mostly transient state).
1995 1994
1996 1995 Returns 0 if initialization succeeded."""
1997 1996 q = repo.mq
1998 1997 r = q.init(repo, create)
1999 1998 q.save_dirty()
2000 1999 if r:
2001 2000 if not os.path.exists(r.wjoin('.hgignore')):
2002 2001 fp = r.wopener('.hgignore', 'w')
2003 2002 fp.write('^\\.hg\n')
2004 2003 fp.write('^\\.mq\n')
2005 2004 fp.write('syntax: glob\n')
2006 2005 fp.write('status\n')
2007 2006 fp.write('guards\n')
2008 2007 fp.close()
2009 2008 if not os.path.exists(r.wjoin('series')):
2010 2009 r.wopener('series', 'w').close()
2011 2010 r[None].add(['.hgignore', 'series'])
2012 2011 commands.add(ui, r)
2013 2012 return 0
2014 2013
2015 2014 @command("^qinit",
2016 2015 [('c', 'create-repo', None, _('create queue repository'))],
2017 2016 _('hg qinit [-c]'))
2018 2017 def init(ui, repo, **opts):
2019 2018 """init a new queue repository (DEPRECATED)
2020 2019
2021 2020 The queue repository is unversioned by default. If
2022 2021 -c/--create-repo is specified, qinit will create a separate nested
2023 2022 repository for patches (qinit -c may also be run later to convert
2024 2023 an unversioned patch repository into a versioned one). You can use
2025 2024 qcommit to commit changes to this queue repository.
2026 2025
2027 2026 This command is deprecated. Without -c, it's implied by other relevant
2028 2027 commands. With -c, use :hg:`init --mq` instead."""
2029 2028 return qinit(ui, repo, create=opts.get('create_repo'))
2030 2029
2031 2030 @command("qclone",
2032 2031 [('', 'pull', None, _('use pull protocol to copy metadata')),
2033 2032 ('U', 'noupdate', None, _('do not update the new working directories')),
2034 2033 ('', 'uncompressed', None,
2035 2034 _('use uncompressed transfer (fast over LAN)')),
2036 2035 ('p', 'patches', '',
2037 2036 _('location of source patch repository'), _('REPO')),
2038 2037 ] + commands.remoteopts,
2039 2038 _('hg qclone [OPTION]... SOURCE [DEST]'))
2040 2039 def clone(ui, source, dest=None, **opts):
2041 2040 '''clone main and patch repository at same time
2042 2041
2043 2042 If source is local, destination will have no patches applied. If
2044 2043 source is remote, this command can not check if patches are
2045 2044 applied in source, so cannot guarantee that patches are not
2046 2045 applied in destination. If you clone remote repository, be sure
2047 2046 before that it has no patches applied.
2048 2047
2049 2048 Source patch repository is looked for in <src>/.hg/patches by
2050 2049 default. Use -p <url> to change.
2051 2050
2052 2051 The patch directory must be a nested Mercurial repository, as
2053 2052 would be created by :hg:`init --mq`.
2054 2053
2055 2054 Return 0 on success.
2056 2055 '''
2057 2056 def patchdir(repo):
2058 2057 url = repo.url()
2059 2058 if url.endswith('/'):
2060 2059 url = url[:-1]
2061 2060 return url + '/.hg/patches'
2062 2061 if dest is None:
2063 2062 dest = hg.defaultdest(source)
2064 2063 sr = hg.repository(hg.remoteui(ui, opts), ui.expandpath(source))
2065 2064 if opts.get('patches'):
2066 2065 patchespath = ui.expandpath(opts.get('patches'))
2067 2066 else:
2068 2067 patchespath = patchdir(sr)
2069 2068 try:
2070 2069 hg.repository(ui, patchespath)
2071 2070 except error.RepoError:
2072 2071 raise util.Abort(_('versioned patch repository not found'
2073 2072 ' (see init --mq)'))
2074 2073 qbase, destrev = None, None
2075 2074 if sr.local():
2076 2075 if sr.mq.applied:
2077 2076 qbase = sr.mq.applied[0].node
2078 2077 if not hg.islocal(dest):
2079 2078 heads = set(sr.heads())
2080 2079 destrev = list(heads.difference(sr.heads(qbase)))
2081 2080 destrev.append(sr.changelog.parents(qbase)[0])
2082 2081 elif sr.capable('lookup'):
2083 2082 try:
2084 2083 qbase = sr.lookup('qbase')
2085 2084 except error.RepoError:
2086 2085 pass
2087 2086 ui.note(_('cloning main repository\n'))
2088 2087 sr, dr = hg.clone(ui, sr.url(), dest,
2089 2088 pull=opts.get('pull'),
2090 2089 rev=destrev,
2091 2090 update=False,
2092 2091 stream=opts.get('uncompressed'))
2093 2092 ui.note(_('cloning patch repository\n'))
2094 2093 hg.clone(ui, opts.get('patches') or patchdir(sr), patchdir(dr),
2095 2094 pull=opts.get('pull'), update=not opts.get('noupdate'),
2096 2095 stream=opts.get('uncompressed'))
2097 2096 if dr.local():
2098 2097 if qbase:
2099 2098 ui.note(_('stripping applied patches from destination '
2100 2099 'repository\n'))
2101 2100 dr.mq.strip(dr, [qbase], update=False, backup=None)
2102 2101 if not opts.get('noupdate'):
2103 2102 ui.note(_('updating destination repository\n'))
2104 2103 hg.update(dr, dr.changelog.tip())
2105 2104
2106 2105 @command("qcommit|qci",
2107 2106 commands.table["^commit|ci"][1],
2108 2107 _('hg qcommit [OPTION]... [FILE]...'))
2109 2108 def commit(ui, repo, *pats, **opts):
2110 2109 """commit changes in the queue repository (DEPRECATED)
2111 2110
2112 2111 This command is deprecated; use :hg:`commit --mq` instead."""
2113 2112 q = repo.mq
2114 2113 r = q.qrepo()
2115 2114 if not r:
2116 2115 raise util.Abort('no queue repository')
2117 2116 commands.commit(r.ui, r, *pats, **opts)
2118 2117
2119 2118 @command("qseries",
2120 2119 [('m', 'missing', None, _('print patches not in series')),
2121 2120 ] + seriesopts,
2122 2121 _('hg qseries [-ms]'))
2123 2122 def series(ui, repo, **opts):
2124 2123 """print the entire series file
2125 2124
2126 2125 Returns 0 on success."""
2127 2126 repo.mq.qseries(repo, missing=opts.get('missing'), summary=opts.get('summary'))
2128 2127 return 0
2129 2128
2130 2129 @command("qtop", [] + seriesopts, _('hg qtop [-s]'))
2131 2130 def top(ui, repo, **opts):
2132 2131 """print the name of the current patch
2133 2132
2134 2133 Returns 0 on success."""
2135 2134 q = repo.mq
2136 2135 t = q.applied and q.series_end(True) or 0
2137 2136 if t:
2138 2137 q.qseries(repo, start=t - 1, length=1, status='A',
2139 2138 summary=opts.get('summary'))
2140 2139 else:
2141 2140 ui.write(_("no patches applied\n"))
2142 2141 return 1
2143 2142
2144 2143 @command("qnext", [] + seriesopts, _('hg qnext [-s]'))
2145 2144 def next(ui, repo, **opts):
2146 2145 """print the name of the next patch
2147 2146
2148 2147 Returns 0 on success."""
2149 2148 q = repo.mq
2150 2149 end = q.series_end()
2151 2150 if end == len(q.series):
2152 2151 ui.write(_("all patches applied\n"))
2153 2152 return 1
2154 2153 q.qseries(repo, start=end, length=1, summary=opts.get('summary'))
2155 2154
2156 2155 @command("qprev", [] + seriesopts, _('hg qprev [-s]'))
2157 2156 def prev(ui, repo, **opts):
2158 2157 """print the name of the previous patch
2159 2158
2160 2159 Returns 0 on success."""
2161 2160 q = repo.mq
2162 2161 l = len(q.applied)
2163 2162 if l == 1:
2164 2163 ui.write(_("only one patch applied\n"))
2165 2164 return 1
2166 2165 if not l:
2167 2166 ui.write(_("no patches applied\n"))
2168 2167 return 1
2169 2168 q.qseries(repo, start=l - 2, length=1, status='A',
2170 2169 summary=opts.get('summary'))
2171 2170
2172 2171 def setupheaderopts(ui, opts):
2173 2172 if not opts.get('user') and opts.get('currentuser'):
2174 2173 opts['user'] = ui.username()
2175 2174 if not opts.get('date') and opts.get('currentdate'):
2176 2175 opts['date'] = "%d %d" % util.makedate()
2177 2176
2178 2177 @command("^qnew",
2179 2178 [('e', 'edit', None, _('edit commit message')),
2180 2179 ('f', 'force', None, _('import uncommitted changes (DEPRECATED)')),
2181 2180 ('g', 'git', None, _('use git extended diff format')),
2182 2181 ('U', 'currentuser', None, _('add "From: <current user>" to patch')),
2183 2182 ('u', 'user', '',
2184 2183 _('add "From: <USER>" to patch'), _('USER')),
2185 2184 ('D', 'currentdate', None, _('add "Date: <current date>" to patch')),
2186 2185 ('d', 'date', '',
2187 2186 _('add "Date: <DATE>" to patch'), _('DATE'))
2188 2187 ] + commands.walkopts + commands.commitopts,
2189 2188 _('hg qnew [-e] [-m TEXT] [-l FILE] PATCH [FILE]...'))
2190 2189 def new(ui, repo, patch, *args, **opts):
2191 2190 """create a new patch
2192 2191
2193 2192 qnew creates a new patch on top of the currently-applied patch (if
2194 2193 any). The patch will be initialized with any outstanding changes
2195 2194 in the working directory. You may also use -I/--include,
2196 2195 -X/--exclude, and/or a list of files after the patch name to add
2197 2196 only changes to matching files to the new patch, leaving the rest
2198 2197 as uncommitted modifications.
2199 2198
2200 2199 -u/--user and -d/--date can be used to set the (given) user and
2201 2200 date, respectively. -U/--currentuser and -D/--currentdate set user
2202 2201 to current user and date to current date.
2203 2202
2204 2203 -e/--edit, -m/--message or -l/--logfile set the patch header as
2205 2204 well as the commit message. If none is specified, the header is
2206 2205 empty and the commit message is '[mq]: PATCH'.
2207 2206
2208 2207 Use the -g/--git option to keep the patch in the git extended diff
2209 2208 format. Read the diffs help topic for more information on why this
2210 2209 is important for preserving permission changes and copy/rename
2211 2210 information.
2212 2211
2213 2212 Returns 0 on successful creation of a new patch.
2214 2213 """
2215 2214 msg = cmdutil.logmessage(opts)
2216 2215 def getmsg():
2217 2216 return ui.edit(msg, opts.get('user') or ui.username())
2218 2217 q = repo.mq
2219 2218 opts['msg'] = msg
2220 2219 if opts.get('edit'):
2221 2220 opts['msg'] = getmsg
2222 2221 else:
2223 2222 opts['msg'] = msg
2224 2223 setupheaderopts(ui, opts)
2225 2224 q.new(repo, patch, *args, **opts)
2226 2225 q.save_dirty()
2227 2226 return 0
2228 2227
2229 2228 @command("^qrefresh",
2230 2229 [('e', 'edit', None, _('edit commit message')),
2231 2230 ('g', 'git', None, _('use git extended diff format')),
2232 2231 ('s', 'short', None,
2233 2232 _('refresh only files already in the patch and specified files')),
2234 2233 ('U', 'currentuser', None,
2235 2234 _('add/update author field in patch with current user')),
2236 2235 ('u', 'user', '',
2237 2236 _('add/update author field in patch with given user'), _('USER')),
2238 2237 ('D', 'currentdate', None,
2239 2238 _('add/update date field in patch with current date')),
2240 2239 ('d', 'date', '',
2241 2240 _('add/update date field in patch with given date'), _('DATE'))
2242 2241 ] + commands.walkopts + commands.commitopts,
2243 2242 _('hg qrefresh [-I] [-X] [-e] [-m TEXT] [-l FILE] [-s] [FILE]...'))
2244 2243 def refresh(ui, repo, *pats, **opts):
2245 2244 """update the current patch
2246 2245
2247 2246 If any file patterns are provided, the refreshed patch will
2248 2247 contain only the modifications that match those patterns; the
2249 2248 remaining modifications will remain in the working directory.
2250 2249
2251 2250 If -s/--short is specified, files currently included in the patch
2252 2251 will be refreshed just like matched files and remain in the patch.
2253 2252
2254 2253 If -e/--edit is specified, Mercurial will start your configured editor for
2255 2254 you to enter a message. In case qrefresh fails, you will find a backup of
2256 2255 your message in ``.hg/last-message.txt``.
2257 2256
2258 2257 hg add/remove/copy/rename work as usual, though you might want to
2259 2258 use git-style patches (-g/--git or [diff] git=1) to track copies
2260 2259 and renames. See the diffs help topic for more information on the
2261 2260 git diff format.
2262 2261
2263 2262 Returns 0 on success.
2264 2263 """
2265 2264 q = repo.mq
2266 2265 message = cmdutil.logmessage(opts)
2267 2266 if opts.get('edit'):
2268 2267 if not q.applied:
2269 2268 ui.write(_("no patches applied\n"))
2270 2269 return 1
2271 2270 if message:
2272 2271 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
2273 2272 patch = q.applied[-1].name
2274 2273 ph = patchheader(q.join(patch), q.plainmode)
2275 2274 message = ui.edit('\n'.join(ph.message), ph.user or ui.username())
2276 2275 # We don't want to lose the patch message if qrefresh fails (issue2062)
2277 2276 msgfile = repo.opener('last-message.txt', 'wb')
2278 2277 msgfile.write(message)
2279 2278 msgfile.close()
2280 2279 setupheaderopts(ui, opts)
2281 2280 ret = q.refresh(repo, pats, msg=message, **opts)
2282 2281 q.save_dirty()
2283 2282 return ret
2284 2283
2285 2284 @command("^qdiff",
2286 2285 commands.diffopts + commands.diffopts2 + commands.walkopts,
2287 2286 _('hg qdiff [OPTION]... [FILE]...'))
2288 2287 def diff(ui, repo, *pats, **opts):
2289 2288 """diff of the current patch and subsequent modifications
2290 2289
2291 2290 Shows a diff which includes the current patch as well as any
2292 2291 changes which have been made in the working directory since the
2293 2292 last refresh (thus showing what the current patch would become
2294 2293 after a qrefresh).
2295 2294
2296 2295 Use :hg:`diff` if you only want to see the changes made since the
2297 2296 last qrefresh, or :hg:`export qtip` if you want to see changes
2298 2297 made by the current patch without including changes made since the
2299 2298 qrefresh.
2300 2299
2301 2300 Returns 0 on success.
2302 2301 """
2303 2302 repo.mq.diff(repo, pats, opts)
2304 2303 return 0
2305 2304
2306 2305 @command('qfold',
2307 2306 [('e', 'edit', None, _('edit patch header')),
2308 2307 ('k', 'keep', None, _('keep folded patch files')),
2309 2308 ] + commands.commitopts,
2310 2309 _('hg qfold [-e] [-k] [-m TEXT] [-l FILE] PATCH...'))
2311 2310 def fold(ui, repo, *files, **opts):
2312 2311 """fold the named patches into the current patch
2313 2312
2314 2313 Patches must not yet be applied. Each patch will be successively
2315 2314 applied to the current patch in the order given. If all the
2316 2315 patches apply successfully, the current patch will be refreshed
2317 2316 with the new cumulative patch, and the folded patches will be
2318 2317 deleted. With -k/--keep, the folded patch files will not be
2319 2318 removed afterwards.
2320 2319
2321 2320 The header for each folded patch will be concatenated with the
2322 2321 current patch header, separated by a line of ``* * *``.
2323 2322
2324 2323 Returns 0 on success."""
2325 2324
2326 2325 q = repo.mq
2327 2326
2328 2327 if not files:
2329 2328 raise util.Abort(_('qfold requires at least one patch name'))
2330 2329 if not q.check_toppatch(repo)[0]:
2331 2330 raise util.Abort(_('no patches applied'))
2332 2331 q.check_localchanges(repo)
2333 2332
2334 2333 message = cmdutil.logmessage(opts)
2335 2334 if opts.get('edit'):
2336 2335 if message:
2337 2336 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
2338 2337
2339 2338 parent = q.lookup('qtip')
2340 2339 patches = []
2341 2340 messages = []
2342 2341 for f in files:
2343 2342 p = q.lookup(f)
2344 2343 if p in patches or p == parent:
2345 2344 ui.warn(_('Skipping already folded patch %s\n') % p)
2346 2345 if q.isapplied(p):
2347 2346 raise util.Abort(_('qfold cannot fold already applied patch %s') % p)
2348 2347 patches.append(p)
2349 2348
2350 2349 for p in patches:
2351 2350 if not message:
2352 2351 ph = patchheader(q.join(p), q.plainmode)
2353 2352 if ph.message:
2354 2353 messages.append(ph.message)
2355 2354 pf = q.join(p)
2356 2355 (patchsuccess, files, fuzz) = q.patch(repo, pf)
2357 2356 if not patchsuccess:
2358 2357 raise util.Abort(_('error folding patch %s') % p)
2359 2358
2360 2359 if not message:
2361 2360 ph = patchheader(q.join(parent), q.plainmode)
2362 2361 message, user = ph.message, ph.user
2363 2362 for msg in messages:
2364 2363 message.append('* * *')
2365 2364 message.extend(msg)
2366 2365 message = '\n'.join(message)
2367 2366
2368 2367 if opts.get('edit'):
2369 2368 message = ui.edit(message, user or ui.username())
2370 2369
2371 2370 diffopts = q.patchopts(q.diffopts(), *patches)
2372 2371 q.refresh(repo, msg=message, git=diffopts.git)
2373 2372 q.delete(repo, patches, opts)
2374 2373 q.save_dirty()
2375 2374
2376 2375 @command("qgoto",
2377 2376 [('f', 'force', None, _('overwrite any local changes'))],
2378 2377 _('hg qgoto [OPTION]... PATCH'))
2379 2378 def goto(ui, repo, patch, **opts):
2380 2379 '''push or pop patches until named patch is at top of stack
2381 2380
2382 2381 Returns 0 on success.'''
2383 2382 q = repo.mq
2384 2383 patch = q.lookup(patch)
2385 2384 if q.isapplied(patch):
2386 2385 ret = q.pop(repo, patch, force=opts.get('force'))
2387 2386 else:
2388 2387 ret = q.push(repo, patch, force=opts.get('force'))
2389 2388 q.save_dirty()
2390 2389 return ret
2391 2390
2392 2391 @command("qguard",
2393 2392 [('l', 'list', None, _('list all patches and guards')),
2394 2393 ('n', 'none', None, _('drop all guards'))],
2395 2394 _('hg qguard [-l] [-n] [PATCH] [-- [+GUARD]... [-GUARD]...]'))
2396 2395 def guard(ui, repo, *args, **opts):
2397 2396 '''set or print guards for a patch
2398 2397
2399 2398 Guards control whether a patch can be pushed. A patch with no
2400 2399 guards is always pushed. A patch with a positive guard ("+foo") is
2401 2400 pushed only if the :hg:`qselect` command has activated it. A patch with
2402 2401 a negative guard ("-foo") is never pushed if the :hg:`qselect` command
2403 2402 has activated it.
2404 2403
2405 2404 With no arguments, print the currently active guards.
2406 2405 With arguments, set guards for the named patch.
2407 2406
2408 2407 .. note::
2409 2408 Specifying negative guards now requires '--'.
2410 2409
2411 2410 To set guards on another patch::
2412 2411
2413 2412 hg qguard other.patch -- +2.6.17 -stable
2414 2413
2415 2414 Returns 0 on success.
2416 2415 '''
2417 2416 def status(idx):
2418 2417 guards = q.series_guards[idx] or ['unguarded']
2419 2418 if q.series[idx] in applied:
2420 2419 state = 'applied'
2421 2420 elif q.pushable(idx)[0]:
2422 2421 state = 'unapplied'
2423 2422 else:
2424 2423 state = 'guarded'
2425 2424 label = 'qguard.patch qguard.%s qseries.%s' % (state, state)
2426 2425 ui.write('%s: ' % ui.label(q.series[idx], label))
2427 2426
2428 2427 for i, guard in enumerate(guards):
2429 2428 if guard.startswith('+'):
2430 2429 ui.write(guard, label='qguard.positive')
2431 2430 elif guard.startswith('-'):
2432 2431 ui.write(guard, label='qguard.negative')
2433 2432 else:
2434 2433 ui.write(guard, label='qguard.unguarded')
2435 2434 if i != len(guards) - 1:
2436 2435 ui.write(' ')
2437 2436 ui.write('\n')
2438 2437 q = repo.mq
2439 2438 applied = set(p.name for p in q.applied)
2440 2439 patch = None
2441 2440 args = list(args)
2442 2441 if opts.get('list'):
2443 2442 if args or opts.get('none'):
2444 2443 raise util.Abort(_('cannot mix -l/--list with options or arguments'))
2445 2444 for i in xrange(len(q.series)):
2446 2445 status(i)
2447 2446 return
2448 2447 if not args or args[0][0:1] in '-+':
2449 2448 if not q.applied:
2450 2449 raise util.Abort(_('no patches applied'))
2451 2450 patch = q.applied[-1].name
2452 2451 if patch is None and args[0][0:1] not in '-+':
2453 2452 patch = args.pop(0)
2454 2453 if patch is None:
2455 2454 raise util.Abort(_('no patch to work with'))
2456 2455 if args or opts.get('none'):
2457 2456 idx = q.find_series(patch)
2458 2457 if idx is None:
2459 2458 raise util.Abort(_('no patch named %s') % patch)
2460 2459 q.set_guards(idx, args)
2461 2460 q.save_dirty()
2462 2461 else:
2463 2462 status(q.series.index(q.lookup(patch)))
2464 2463
2465 2464 @command("qheader", [], _('hg qheader [PATCH]'))
2466 2465 def header(ui, repo, patch=None):
2467 2466 """print the header of the topmost or specified patch
2468 2467
2469 2468 Returns 0 on success."""
2470 2469 q = repo.mq
2471 2470
2472 2471 if patch:
2473 2472 patch = q.lookup(patch)
2474 2473 else:
2475 2474 if not q.applied:
2476 2475 ui.write(_('no patches applied\n'))
2477 2476 return 1
2478 2477 patch = q.lookup('qtip')
2479 2478 ph = patchheader(q.join(patch), q.plainmode)
2480 2479
2481 2480 ui.write('\n'.join(ph.message) + '\n')
2482 2481
2483 2482 def lastsavename(path):
2484 2483 (directory, base) = os.path.split(path)
2485 2484 names = os.listdir(directory)
2486 2485 namere = re.compile("%s.([0-9]+)" % base)
2487 2486 maxindex = None
2488 2487 maxname = None
2489 2488 for f in names:
2490 2489 m = namere.match(f)
2491 2490 if m:
2492 2491 index = int(m.group(1))
2493 2492 if maxindex is None or index > maxindex:
2494 2493 maxindex = index
2495 2494 maxname = f
2496 2495 if maxname:
2497 2496 return (os.path.join(directory, maxname), maxindex)
2498 2497 return (None, None)
2499 2498
2500 2499 def savename(path):
2501 2500 (last, index) = lastsavename(path)
2502 2501 if last is None:
2503 2502 index = 0
2504 2503 newpath = path + ".%d" % (index + 1)
2505 2504 return newpath
2506 2505
2507 2506 @command("^qpush",
2508 2507 [('f', 'force', None, _('apply on top of local changes')),
2509 2508 ('e', 'exact', None, _('apply the target patch to its recorded parent')),
2510 2509 ('l', 'list', None, _('list patch name in commit text')),
2511 2510 ('a', 'all', None, _('apply all patches')),
2512 2511 ('m', 'merge', None, _('merge from another queue (DEPRECATED)')),
2513 2512 ('n', 'name', '',
2514 2513 _('merge queue name (DEPRECATED)'), _('NAME')),
2515 2514 ('', 'move', None, _('reorder patch series and apply only the patch'))],
2516 2515 _('hg qpush [-f] [-l] [-a] [--move] [PATCH | INDEX]'))
2517 2516 def push(ui, repo, patch=None, **opts):
2518 2517 """push the next patch onto the stack
2519 2518
2520 2519 When -f/--force is applied, all local changes in patched files
2521 2520 will be lost.
2522 2521
2523 2522 Return 0 on success.
2524 2523 """
2525 2524 q = repo.mq
2526 2525 mergeq = None
2527 2526
2528 2527 if opts.get('merge'):
2529 2528 if opts.get('name'):
2530 2529 newpath = repo.join(opts.get('name'))
2531 2530 else:
2532 2531 newpath, i = lastsavename(q.path)
2533 2532 if not newpath:
2534 2533 ui.warn(_("no saved queues found, please use -n\n"))
2535 2534 return 1
2536 2535 mergeq = queue(ui, repo.join(""), newpath)
2537 2536 ui.warn(_("merging with queue at: %s\n") % mergeq.path)
2538 2537 ret = q.push(repo, patch, force=opts.get('force'), list=opts.get('list'),
2539 2538 mergeq=mergeq, all=opts.get('all'), move=opts.get('move'),
2540 2539 exact=opts.get('exact'))
2541 2540 return ret
2542 2541
2543 2542 @command("^qpop",
2544 2543 [('a', 'all', None, _('pop all patches')),
2545 2544 ('n', 'name', '',
2546 2545 _('queue name to pop (DEPRECATED)'), _('NAME')),
2547 2546 ('f', 'force', None, _('forget any local changes to patched files'))],
2548 2547 _('hg qpop [-a] [-f] [PATCH | INDEX]'))
2549 2548 def pop(ui, repo, patch=None, **opts):
2550 2549 """pop the current patch off the stack
2551 2550
2552 2551 By default, pops off the top of the patch stack. If given a patch
2553 2552 name, keeps popping off patches until the named patch is at the
2554 2553 top of the stack.
2555 2554
2556 2555 Return 0 on success.
2557 2556 """
2558 2557 localupdate = True
2559 2558 if opts.get('name'):
2560 2559 q = queue(ui, repo.join(""), repo.join(opts.get('name')))
2561 2560 ui.warn(_('using patch queue: %s\n') % q.path)
2562 2561 localupdate = False
2563 2562 else:
2564 2563 q = repo.mq
2565 2564 ret = q.pop(repo, patch, force=opts.get('force'), update=localupdate,
2566 2565 all=opts.get('all'))
2567 2566 q.save_dirty()
2568 2567 return ret
2569 2568
2570 2569 @command("qrename|qmv", [], _('hg qrename PATCH1 [PATCH2]'))
2571 2570 def rename(ui, repo, patch, name=None, **opts):
2572 2571 """rename a patch
2573 2572
2574 2573 With one argument, renames the current patch to PATCH1.
2575 2574 With two arguments, renames PATCH1 to PATCH2.
2576 2575
2577 2576 Returns 0 on success."""
2578 2577
2579 2578 q = repo.mq
2580 2579
2581 2580 if not name:
2582 2581 name = patch
2583 2582 patch = None
2584 2583
2585 2584 if patch:
2586 2585 patch = q.lookup(patch)
2587 2586 else:
2588 2587 if not q.applied:
2589 2588 ui.write(_('no patches applied\n'))
2590 2589 return
2591 2590 patch = q.lookup('qtip')
2592 2591 absdest = q.join(name)
2593 2592 if os.path.isdir(absdest):
2594 2593 name = normname(os.path.join(name, os.path.basename(patch)))
2595 2594 absdest = q.join(name)
2596 2595 q.checkpatchname(name)
2597 2596
2598 2597 ui.note(_('renaming %s to %s\n') % (patch, name))
2599 2598 i = q.find_series(patch)
2600 2599 guards = q.guard_re.findall(q.full_series[i])
2601 2600 q.full_series[i] = name + ''.join([' #' + g for g in guards])
2602 2601 q.parse_series()
2603 2602 q.series_dirty = 1
2604 2603
2605 2604 info = q.isapplied(patch)
2606 2605 if info:
2607 2606 q.applied[info[0]] = statusentry(info[1], name)
2608 2607 q.applied_dirty = 1
2609 2608
2610 2609 destdir = os.path.dirname(absdest)
2611 2610 if not os.path.isdir(destdir):
2612 2611 os.makedirs(destdir)
2613 2612 util.rename(q.join(patch), absdest)
2614 2613 r = q.qrepo()
2615 2614 if r and patch in r.dirstate:
2616 2615 wctx = r[None]
2617 2616 wlock = r.wlock()
2618 2617 try:
2619 2618 if r.dirstate[patch] == 'a':
2620 2619 r.dirstate.drop(patch)
2621 2620 r.dirstate.add(name)
2622 2621 else:
2623 2622 if r.dirstate[name] == 'r':
2624 2623 wctx.undelete([name])
2625 2624 wctx.copy(patch, name)
2626 wctx.remove([patch], False)
2625 wctx.forget([patch])
2627 2626 finally:
2628 2627 wlock.release()
2629 2628
2630 2629 q.save_dirty()
2631 2630
2632 2631 @command("qrestore",
2633 2632 [('d', 'delete', None, _('delete save entry')),
2634 2633 ('u', 'update', None, _('update queue working directory'))],
2635 2634 _('hg qrestore [-d] [-u] REV'))
2636 2635 def restore(ui, repo, rev, **opts):
2637 2636 """restore the queue state saved by a revision (DEPRECATED)
2638 2637
2639 2638 This command is deprecated, use :hg:`rebase` instead."""
2640 2639 rev = repo.lookup(rev)
2641 2640 q = repo.mq
2642 2641 q.restore(repo, rev, delete=opts.get('delete'),
2643 2642 qupdate=opts.get('update'))
2644 2643 q.save_dirty()
2645 2644 return 0
2646 2645
2647 2646 @command("qsave",
2648 2647 [('c', 'copy', None, _('copy patch directory')),
2649 2648 ('n', 'name', '',
2650 2649 _('copy directory name'), _('NAME')),
2651 2650 ('e', 'empty', None, _('clear queue status file')),
2652 2651 ('f', 'force', None, _('force copy'))] + commands.commitopts,
2653 2652 _('hg qsave [-m TEXT] [-l FILE] [-c] [-n NAME] [-e] [-f]'))
2654 2653 def save(ui, repo, **opts):
2655 2654 """save current queue state (DEPRECATED)
2656 2655
2657 2656 This command is deprecated, use :hg:`rebase` instead."""
2658 2657 q = repo.mq
2659 2658 message = cmdutil.logmessage(opts)
2660 2659 ret = q.save(repo, msg=message)
2661 2660 if ret:
2662 2661 return ret
2663 2662 q.save_dirty()
2664 2663 if opts.get('copy'):
2665 2664 path = q.path
2666 2665 if opts.get('name'):
2667 2666 newpath = os.path.join(q.basepath, opts.get('name'))
2668 2667 if os.path.exists(newpath):
2669 2668 if not os.path.isdir(newpath):
2670 2669 raise util.Abort(_('destination %s exists and is not '
2671 2670 'a directory') % newpath)
2672 2671 if not opts.get('force'):
2673 2672 raise util.Abort(_('destination %s exists, '
2674 2673 'use -f to force') % newpath)
2675 2674 else:
2676 2675 newpath = savename(path)
2677 2676 ui.warn(_("copy %s to %s\n") % (path, newpath))
2678 2677 util.copyfiles(path, newpath)
2679 2678 if opts.get('empty'):
2680 2679 try:
2681 2680 os.unlink(q.join(q.status_path))
2682 2681 except:
2683 2682 pass
2684 2683 return 0
2685 2684
2686 2685 @command("strip",
2687 2686 [('f', 'force', None, _('force removal of changesets, discard '
2688 2687 'uncommitted changes (no backup)')),
2689 2688 ('b', 'backup', None, _('bundle only changesets with local revision'
2690 2689 ' number greater than REV which are not'
2691 2690 ' descendants of REV (DEPRECATED)')),
2692 2691 ('n', 'no-backup', None, _('no backups')),
2693 2692 ('', 'nobackup', None, _('no backups (DEPRECATED)')),
2694 2693 ('k', 'keep', None, _("do not modify working copy during strip"))],
2695 2694 _('hg strip [-k] [-f] [-n] REV...'))
2696 2695 def strip(ui, repo, *revs, **opts):
2697 2696 """strip changesets and all their descendants from the repository
2698 2697
2699 2698 The strip command removes the specified changesets and all their
2700 2699 descendants. If the working directory has uncommitted changes, the
2701 2700 operation is aborted unless the --force flag is supplied, in which
2702 2701 case changes will be discarded.
2703 2702
2704 2703 If a parent of the working directory is stripped, then the working
2705 2704 directory will automatically be updated to the most recent
2706 2705 available ancestor of the stripped parent after the operation
2707 2706 completes.
2708 2707
2709 2708 Any stripped changesets are stored in ``.hg/strip-backup`` as a
2710 2709 bundle (see :hg:`help bundle` and :hg:`help unbundle`). They can
2711 2710 be restored by running :hg:`unbundle .hg/strip-backup/BUNDLE`,
2712 2711 where BUNDLE is the bundle file created by the strip. Note that
2713 2712 the local revision numbers will in general be different after the
2714 2713 restore.
2715 2714
2716 2715 Use the --no-backup option to discard the backup bundle once the
2717 2716 operation completes.
2718 2717
2719 2718 Return 0 on success.
2720 2719 """
2721 2720 backup = 'all'
2722 2721 if opts.get('backup'):
2723 2722 backup = 'strip'
2724 2723 elif opts.get('no_backup') or opts.get('nobackup'):
2725 2724 backup = 'none'
2726 2725
2727 2726 cl = repo.changelog
2728 2727 revs = set(scmutil.revrange(repo, revs))
2729 2728 if not revs:
2730 2729 raise util.Abort(_('empty revision set'))
2731 2730
2732 2731 descendants = set(cl.descendants(*revs))
2733 2732 strippedrevs = revs.union(descendants)
2734 2733 roots = revs.difference(descendants)
2735 2734
2736 2735 update = False
2737 2736 # if one of the wdir parent is stripped we'll need
2738 2737 # to update away to an earlier revision
2739 2738 for p in repo.dirstate.parents():
2740 2739 if p != nullid and cl.rev(p) in strippedrevs:
2741 2740 update = True
2742 2741 break
2743 2742
2744 2743 rootnodes = set(cl.node(r) for r in roots)
2745 2744
2746 2745 q = repo.mq
2747 2746 if q.applied:
2748 2747 # refresh queue state if we're about to strip
2749 2748 # applied patches
2750 2749 if cl.rev(repo.lookup('qtip')) in strippedrevs:
2751 2750 q.applied_dirty = True
2752 2751 start = 0
2753 2752 end = len(q.applied)
2754 2753 for i, statusentry in enumerate(q.applied):
2755 2754 if statusentry.node in rootnodes:
2756 2755 # if one of the stripped roots is an applied
2757 2756 # patch, only part of the queue is stripped
2758 2757 start = i
2759 2758 break
2760 2759 del q.applied[start:end]
2761 2760 q.save_dirty()
2762 2761
2763 2762 revs = list(rootnodes)
2764 2763 if update and opts.get('keep'):
2765 2764 wlock = repo.wlock()
2766 2765 try:
2767 2766 urev = repo.mq.qparents(repo, revs[0])
2768 2767 repo.dirstate.rebuild(urev, repo[urev].manifest())
2769 2768 repo.dirstate.write()
2770 2769 update = False
2771 2770 finally:
2772 2771 wlock.release()
2773 2772
2774 2773 repo.mq.strip(repo, revs, backup=backup, update=update,
2775 2774 force=opts.get('force'))
2776 2775 return 0
2777 2776
2778 2777 @command("qselect",
2779 2778 [('n', 'none', None, _('disable all guards')),
2780 2779 ('s', 'series', None, _('list all guards in series file')),
2781 2780 ('', 'pop', None, _('pop to before first guarded applied patch')),
2782 2781 ('', 'reapply', None, _('pop, then reapply patches'))],
2783 2782 _('hg qselect [OPTION]... [GUARD]...'))
2784 2783 def select(ui, repo, *args, **opts):
2785 2784 '''set or print guarded patches to push
2786 2785
2787 2786 Use the :hg:`qguard` command to set or print guards on patch, then use
2788 2787 qselect to tell mq which guards to use. A patch will be pushed if
2789 2788 it has no guards or any positive guards match the currently
2790 2789 selected guard, but will not be pushed if any negative guards
2791 2790 match the current guard. For example::
2792 2791
2793 2792 qguard foo.patch -- -stable (negative guard)
2794 2793 qguard bar.patch +stable (positive guard)
2795 2794 qselect stable
2796 2795
2797 2796 This activates the "stable" guard. mq will skip foo.patch (because
2798 2797 it has a negative match) but push bar.patch (because it has a
2799 2798 positive match).
2800 2799
2801 2800 With no arguments, prints the currently active guards.
2802 2801 With one argument, sets the active guard.
2803 2802
2804 2803 Use -n/--none to deactivate guards (no other arguments needed).
2805 2804 When no guards are active, patches with positive guards are
2806 2805 skipped and patches with negative guards are pushed.
2807 2806
2808 2807 qselect can change the guards on applied patches. It does not pop
2809 2808 guarded patches by default. Use --pop to pop back to the last
2810 2809 applied patch that is not guarded. Use --reapply (which implies
2811 2810 --pop) to push back to the current patch afterwards, but skip
2812 2811 guarded patches.
2813 2812
2814 2813 Use -s/--series to print a list of all guards in the series file
2815 2814 (no other arguments needed). Use -v for more information.
2816 2815
2817 2816 Returns 0 on success.'''
2818 2817
2819 2818 q = repo.mq
2820 2819 guards = q.active()
2821 2820 if args or opts.get('none'):
2822 2821 old_unapplied = q.unapplied(repo)
2823 2822 old_guarded = [i for i in xrange(len(q.applied)) if
2824 2823 not q.pushable(i)[0]]
2825 2824 q.set_active(args)
2826 2825 q.save_dirty()
2827 2826 if not args:
2828 2827 ui.status(_('guards deactivated\n'))
2829 2828 if not opts.get('pop') and not opts.get('reapply'):
2830 2829 unapplied = q.unapplied(repo)
2831 2830 guarded = [i for i in xrange(len(q.applied))
2832 2831 if not q.pushable(i)[0]]
2833 2832 if len(unapplied) != len(old_unapplied):
2834 2833 ui.status(_('number of unguarded, unapplied patches has '
2835 2834 'changed from %d to %d\n') %
2836 2835 (len(old_unapplied), len(unapplied)))
2837 2836 if len(guarded) != len(old_guarded):
2838 2837 ui.status(_('number of guarded, applied patches has changed '
2839 2838 'from %d to %d\n') %
2840 2839 (len(old_guarded), len(guarded)))
2841 2840 elif opts.get('series'):
2842 2841 guards = {}
2843 2842 noguards = 0
2844 2843 for gs in q.series_guards:
2845 2844 if not gs:
2846 2845 noguards += 1
2847 2846 for g in gs:
2848 2847 guards.setdefault(g, 0)
2849 2848 guards[g] += 1
2850 2849 if ui.verbose:
2851 2850 guards['NONE'] = noguards
2852 2851 guards = guards.items()
2853 2852 guards.sort(key=lambda x: x[0][1:])
2854 2853 if guards:
2855 2854 ui.note(_('guards in series file:\n'))
2856 2855 for guard, count in guards:
2857 2856 ui.note('%2d ' % count)
2858 2857 ui.write(guard, '\n')
2859 2858 else:
2860 2859 ui.note(_('no guards in series file\n'))
2861 2860 else:
2862 2861 if guards:
2863 2862 ui.note(_('active guards:\n'))
2864 2863 for g in guards:
2865 2864 ui.write(g, '\n')
2866 2865 else:
2867 2866 ui.write(_('no active guards\n'))
2868 2867 reapply = opts.get('reapply') and q.applied and q.appliedname(-1)
2869 2868 popped = False
2870 2869 if opts.get('pop') or opts.get('reapply'):
2871 2870 for i in xrange(len(q.applied)):
2872 2871 pushable, reason = q.pushable(i)
2873 2872 if not pushable:
2874 2873 ui.status(_('popping guarded patches\n'))
2875 2874 popped = True
2876 2875 if i == 0:
2877 2876 q.pop(repo, all=True)
2878 2877 else:
2879 2878 q.pop(repo, i - 1)
2880 2879 break
2881 2880 if popped:
2882 2881 try:
2883 2882 if reapply:
2884 2883 ui.status(_('reapplying unguarded patches\n'))
2885 2884 q.push(repo, reapply)
2886 2885 finally:
2887 2886 q.save_dirty()
2888 2887
2889 2888 @command("qfinish",
2890 2889 [('a', 'applied', None, _('finish all applied changesets'))],
2891 2890 _('hg qfinish [-a] [REV]...'))
2892 2891 def finish(ui, repo, *revrange, **opts):
2893 2892 """move applied patches into repository history
2894 2893
2895 2894 Finishes the specified revisions (corresponding to applied
2896 2895 patches) by moving them out of mq control into regular repository
2897 2896 history.
2898 2897
2899 2898 Accepts a revision range or the -a/--applied option. If --applied
2900 2899 is specified, all applied mq revisions are removed from mq
2901 2900 control. Otherwise, the given revisions must be at the base of the
2902 2901 stack of applied patches.
2903 2902
2904 2903 This can be especially useful if your changes have been applied to
2905 2904 an upstream repository, or if you are about to push your changes
2906 2905 to upstream.
2907 2906
2908 2907 Returns 0 on success.
2909 2908 """
2910 2909 if not opts.get('applied') and not revrange:
2911 2910 raise util.Abort(_('no revisions specified'))
2912 2911 elif opts.get('applied'):
2913 2912 revrange = ('qbase::qtip',) + revrange
2914 2913
2915 2914 q = repo.mq
2916 2915 if not q.applied:
2917 2916 ui.status(_('no patches applied\n'))
2918 2917 return 0
2919 2918
2920 2919 revs = scmutil.revrange(repo, revrange)
2921 2920 q.finish(repo, revs)
2922 2921 q.save_dirty()
2923 2922 return 0
2924 2923
2925 2924 @command("qqueue",
2926 2925 [('l', 'list', False, _('list all available queues')),
2927 2926 ('c', 'create', False, _('create new queue')),
2928 2927 ('', 'rename', False, _('rename active queue')),
2929 2928 ('', 'delete', False, _('delete reference to queue')),
2930 2929 ('', 'purge', False, _('delete queue, and remove patch dir')),
2931 2930 ],
2932 2931 _('[OPTION] [QUEUE]'))
2933 2932 def qqueue(ui, repo, name=None, **opts):
2934 2933 '''manage multiple patch queues
2935 2934
2936 2935 Supports switching between different patch queues, as well as creating
2937 2936 new patch queues and deleting existing ones.
2938 2937
2939 2938 Omitting a queue name or specifying -l/--list will show you the registered
2940 2939 queues - by default the "normal" patches queue is registered. The currently
2941 2940 active queue will be marked with "(active)".
2942 2941
2943 2942 To create a new queue, use -c/--create. The queue is automatically made
2944 2943 active, except in the case where there are applied patches from the
2945 2944 currently active queue in the repository. Then the queue will only be
2946 2945 created and switching will fail.
2947 2946
2948 2947 To delete an existing queue, use --delete. You cannot delete the currently
2949 2948 active queue.
2950 2949
2951 2950 Returns 0 on success.
2952 2951 '''
2953 2952
2954 2953 q = repo.mq
2955 2954
2956 2955 _defaultqueue = 'patches'
2957 2956 _allqueues = 'patches.queues'
2958 2957 _activequeue = 'patches.queue'
2959 2958
2960 2959 def _getcurrent():
2961 2960 cur = os.path.basename(q.path)
2962 2961 if cur.startswith('patches-'):
2963 2962 cur = cur[8:]
2964 2963 return cur
2965 2964
2966 2965 def _noqueues():
2967 2966 try:
2968 2967 fh = repo.opener(_allqueues, 'r')
2969 2968 fh.close()
2970 2969 except IOError:
2971 2970 return True
2972 2971
2973 2972 return False
2974 2973
2975 2974 def _getqueues():
2976 2975 current = _getcurrent()
2977 2976
2978 2977 try:
2979 2978 fh = repo.opener(_allqueues, 'r')
2980 2979 queues = [queue.strip() for queue in fh if queue.strip()]
2981 2980 fh.close()
2982 2981 if current not in queues:
2983 2982 queues.append(current)
2984 2983 except IOError:
2985 2984 queues = [_defaultqueue]
2986 2985
2987 2986 return sorted(queues)
2988 2987
2989 2988 def _setactive(name):
2990 2989 if q.applied:
2991 2990 raise util.Abort(_('patches applied - cannot set new queue active'))
2992 2991 _setactivenocheck(name)
2993 2992
2994 2993 def _setactivenocheck(name):
2995 2994 fh = repo.opener(_activequeue, 'w')
2996 2995 if name != 'patches':
2997 2996 fh.write(name)
2998 2997 fh.close()
2999 2998
3000 2999 def _addqueue(name):
3001 3000 fh = repo.opener(_allqueues, 'a')
3002 3001 fh.write('%s\n' % (name,))
3003 3002 fh.close()
3004 3003
3005 3004 def _queuedir(name):
3006 3005 if name == 'patches':
3007 3006 return repo.join('patches')
3008 3007 else:
3009 3008 return repo.join('patches-' + name)
3010 3009
3011 3010 def _validname(name):
3012 3011 for n in name:
3013 3012 if n in ':\\/.':
3014 3013 return False
3015 3014 return True
3016 3015
3017 3016 def _delete(name):
3018 3017 if name not in existing:
3019 3018 raise util.Abort(_('cannot delete queue that does not exist'))
3020 3019
3021 3020 current = _getcurrent()
3022 3021
3023 3022 if name == current:
3024 3023 raise util.Abort(_('cannot delete currently active queue'))
3025 3024
3026 3025 fh = repo.opener('patches.queues.new', 'w')
3027 3026 for queue in existing:
3028 3027 if queue == name:
3029 3028 continue
3030 3029 fh.write('%s\n' % (queue,))
3031 3030 fh.close()
3032 3031 util.rename(repo.join('patches.queues.new'), repo.join(_allqueues))
3033 3032
3034 3033 if not name or opts.get('list'):
3035 3034 current = _getcurrent()
3036 3035 for queue in _getqueues():
3037 3036 ui.write('%s' % (queue,))
3038 3037 if queue == current and not ui.quiet:
3039 3038 ui.write(_(' (active)\n'))
3040 3039 else:
3041 3040 ui.write('\n')
3042 3041 return
3043 3042
3044 3043 if not _validname(name):
3045 3044 raise util.Abort(
3046 3045 _('invalid queue name, may not contain the characters ":\\/."'))
3047 3046
3048 3047 existing = _getqueues()
3049 3048
3050 3049 if opts.get('create'):
3051 3050 if name in existing:
3052 3051 raise util.Abort(_('queue "%s" already exists') % name)
3053 3052 if _noqueues():
3054 3053 _addqueue(_defaultqueue)
3055 3054 _addqueue(name)
3056 3055 _setactive(name)
3057 3056 elif opts.get('rename'):
3058 3057 current = _getcurrent()
3059 3058 if name == current:
3060 3059 raise util.Abort(_('can\'t rename "%s" to its current name') % name)
3061 3060 if name in existing:
3062 3061 raise util.Abort(_('queue "%s" already exists') % name)
3063 3062
3064 3063 olddir = _queuedir(current)
3065 3064 newdir = _queuedir(name)
3066 3065
3067 3066 if os.path.exists(newdir):
3068 3067 raise util.Abort(_('non-queue directory "%s" already exists') %
3069 3068 newdir)
3070 3069
3071 3070 fh = repo.opener('patches.queues.new', 'w')
3072 3071 for queue in existing:
3073 3072 if queue == current:
3074 3073 fh.write('%s\n' % (name,))
3075 3074 if os.path.exists(olddir):
3076 3075 util.rename(olddir, newdir)
3077 3076 else:
3078 3077 fh.write('%s\n' % (queue,))
3079 3078 fh.close()
3080 3079 util.rename(repo.join('patches.queues.new'), repo.join(_allqueues))
3081 3080 _setactivenocheck(name)
3082 3081 elif opts.get('delete'):
3083 3082 _delete(name)
3084 3083 elif opts.get('purge'):
3085 3084 if name in existing:
3086 3085 _delete(name)
3087 3086 qdir = _queuedir(name)
3088 3087 if os.path.exists(qdir):
3089 3088 shutil.rmtree(qdir)
3090 3089 else:
3091 3090 if name not in existing:
3092 3091 raise util.Abort(_('use --create to create a new queue'))
3093 3092 _setactive(name)
3094 3093
3095 3094 def reposetup(ui, repo):
3096 3095 class mqrepo(repo.__class__):
3097 3096 @util.propertycache
3098 3097 def mq(self):
3099 3098 return queue(self.ui, self.join(""))
3100 3099
3101 3100 def abort_if_wdir_patched(self, errmsg, force=False):
3102 3101 if self.mq.applied and not force:
3103 3102 parents = self.dirstate.parents()
3104 3103 patches = [s.node for s in self.mq.applied]
3105 3104 if parents[0] in patches or parents[1] in patches:
3106 3105 raise util.Abort(errmsg)
3107 3106
3108 3107 def commit(self, text="", user=None, date=None, match=None,
3109 3108 force=False, editor=False, extra={}):
3110 3109 self.abort_if_wdir_patched(
3111 3110 _('cannot commit over an applied mq patch'),
3112 3111 force)
3113 3112
3114 3113 return super(mqrepo, self).commit(text, user, date, match, force,
3115 3114 editor, extra)
3116 3115
3117 3116 def checkpush(self, force, revs):
3118 3117 if self.mq.applied and not force:
3119 3118 haspatches = True
3120 3119 if revs:
3121 3120 # Assume applied patches have no non-patch descendants
3122 3121 # and are not on remote already. If they appear in the
3123 3122 # set of resolved 'revs', bail out.
3124 3123 applied = set(e.node for e in self.mq.applied)
3125 3124 haspatches = bool([n for n in revs if n in applied])
3126 3125 if haspatches:
3127 3126 raise util.Abort(_('source has mq patches applied'))
3128 3127 super(mqrepo, self).checkpush(force, revs)
3129 3128
3130 3129 def _findtags(self):
3131 3130 '''augment tags from base class with patch tags'''
3132 3131 result = super(mqrepo, self)._findtags()
3133 3132
3134 3133 q = self.mq
3135 3134 if not q.applied:
3136 3135 return result
3137 3136
3138 3137 mqtags = [(patch.node, patch.name) for patch in q.applied]
3139 3138
3140 3139 try:
3141 3140 self.changelog.rev(mqtags[-1][0])
3142 3141 except error.RepoLookupError:
3143 3142 self.ui.warn(_('mq status file refers to unknown node %s\n')
3144 3143 % short(mqtags[-1][0]))
3145 3144 return result
3146 3145
3147 3146 mqtags.append((mqtags[-1][0], 'qtip'))
3148 3147 mqtags.append((mqtags[0][0], 'qbase'))
3149 3148 mqtags.append((self.changelog.parents(mqtags[0][0])[0], 'qparent'))
3150 3149 tags = result[0]
3151 3150 for patch in mqtags:
3152 3151 if patch[1] in tags:
3153 3152 self.ui.warn(_('Tag %s overrides mq patch of the same name\n')
3154 3153 % patch[1])
3155 3154 else:
3156 3155 tags[patch[1]] = patch[0]
3157 3156
3158 3157 return result
3159 3158
3160 3159 def _branchtags(self, partial, lrev):
3161 3160 q = self.mq
3162 3161 if not q.applied:
3163 3162 return super(mqrepo, self)._branchtags(partial, lrev)
3164 3163
3165 3164 cl = self.changelog
3166 3165 qbasenode = q.applied[0].node
3167 3166 try:
3168 3167 qbase = cl.rev(qbasenode)
3169 3168 except error.LookupError:
3170 3169 self.ui.warn(_('mq status file refers to unknown node %s\n')
3171 3170 % short(qbasenode))
3172 3171 return super(mqrepo, self)._branchtags(partial, lrev)
3173 3172
3174 3173 start = lrev + 1
3175 3174 if start < qbase:
3176 3175 # update the cache (excluding the patches) and save it
3177 3176 ctxgen = (self[r] for r in xrange(lrev + 1, qbase))
3178 3177 self._updatebranchcache(partial, ctxgen)
3179 3178 self._writebranchcache(partial, cl.node(qbase - 1), qbase - 1)
3180 3179 start = qbase
3181 3180 # if start = qbase, the cache is as updated as it should be.
3182 3181 # if start > qbase, the cache includes (part of) the patches.
3183 3182 # we might as well use it, but we won't save it.
3184 3183
3185 3184 # update the cache up to the tip
3186 3185 ctxgen = (self[r] for r in xrange(start, len(cl)))
3187 3186 self._updatebranchcache(partial, ctxgen)
3188 3187
3189 3188 return partial
3190 3189
3191 3190 if repo.local():
3192 3191 repo.__class__ = mqrepo
3193 3192
3194 3193 def mqimport(orig, ui, repo, *args, **kwargs):
3195 3194 if (hasattr(repo, 'abort_if_wdir_patched')
3196 3195 and not kwargs.get('no_commit', False)):
3197 3196 repo.abort_if_wdir_patched(_('cannot import over an applied patch'),
3198 3197 kwargs.get('force'))
3199 3198 return orig(ui, repo, *args, **kwargs)
3200 3199
3201 3200 def mqinit(orig, ui, *args, **kwargs):
3202 3201 mq = kwargs.pop('mq', None)
3203 3202
3204 3203 if not mq:
3205 3204 return orig(ui, *args, **kwargs)
3206 3205
3207 3206 if args:
3208 3207 repopath = args[0]
3209 3208 if not hg.islocal(repopath):
3210 3209 raise util.Abort(_('only a local queue repository '
3211 3210 'may be initialized'))
3212 3211 else:
3213 3212 repopath = cmdutil.findrepo(os.getcwd())
3214 3213 if not repopath:
3215 3214 raise util.Abort(_('there is no Mercurial repository here '
3216 3215 '(.hg not found)'))
3217 3216 repo = hg.repository(ui, repopath)
3218 3217 return qinit(ui, repo, True)
3219 3218
3220 3219 def mqcommand(orig, ui, repo, *args, **kwargs):
3221 3220 """Add --mq option to operate on patch repository instead of main"""
3222 3221
3223 3222 # some commands do not like getting unknown options
3224 3223 mq = kwargs.pop('mq', None)
3225 3224
3226 3225 if not mq:
3227 3226 return orig(ui, repo, *args, **kwargs)
3228 3227
3229 3228 q = repo.mq
3230 3229 r = q.qrepo()
3231 3230 if not r:
3232 3231 raise util.Abort(_('no queue repository'))
3233 3232 return orig(r.ui, r, *args, **kwargs)
3234 3233
3235 3234 def summary(orig, ui, repo, *args, **kwargs):
3236 3235 r = orig(ui, repo, *args, **kwargs)
3237 3236 q = repo.mq
3238 3237 m = []
3239 3238 a, u = len(q.applied), len(q.unapplied(repo))
3240 3239 if a:
3241 3240 m.append(ui.label(_("%d applied"), 'qseries.applied') % a)
3242 3241 if u:
3243 3242 m.append(ui.label(_("%d unapplied"), 'qseries.unapplied') % u)
3244 3243 if m:
3245 3244 ui.write("mq: %s\n" % ', '.join(m))
3246 3245 else:
3247 3246 ui.note(_("mq: (empty queue)\n"))
3248 3247 return r
3249 3248
3250 3249 def revsetmq(repo, subset, x):
3251 3250 """``mq()``
3252 3251 Changesets managed by MQ.
3253 3252 """
3254 3253 revset.getargs(x, 0, 0, _("mq takes no arguments"))
3255 3254 applied = set([repo[r.node].rev() for r in repo.mq.applied])
3256 3255 return [r for r in subset if r in applied]
3257 3256
3258 3257 def extsetup(ui):
3259 3258 revset.symbols['mq'] = revsetmq
3260 3259
3261 3260 # tell hggettext to extract docstrings from these functions:
3262 3261 i18nfunctions = [revsetmq]
3263 3262
3264 3263 def uisetup(ui):
3265 3264 mqopt = [('', 'mq', None, _("operate on patch repository"))]
3266 3265
3267 3266 extensions.wrapcommand(commands.table, 'import', mqimport)
3268 3267 extensions.wrapcommand(commands.table, 'summary', summary)
3269 3268
3270 3269 entry = extensions.wrapcommand(commands.table, 'init', mqinit)
3271 3270 entry[1].extend(mqopt)
3272 3271
3273 3272 nowrap = set(commands.norepo.split(" ") + ['qrecord'])
3274 3273
3275 3274 def dotable(cmdtable):
3276 3275 for cmd in cmdtable.keys():
3277 3276 cmd = cmdutil.parsealiases(cmd)[0]
3278 3277 if cmd in nowrap:
3279 3278 continue
3280 3279 entry = extensions.wrapcommand(cmdtable, cmd, mqcommand)
3281 3280 entry[1].extend(mqopt)
3282 3281
3283 3282 dotable(commands.table)
3284 3283
3285 3284 for extname, extmodule in extensions.extensions():
3286 3285 if extmodule.__file__ != __file__:
3287 3286 dotable(getattr(extmodule, 'cmdtable', {}))
3288 3287
3289 3288
3290 3289 colortable = {'qguard.negative': 'red',
3291 3290 'qguard.positive': 'yellow',
3292 3291 'qguard.unguarded': 'green',
3293 3292 'qseries.applied': 'blue bold underline',
3294 3293 'qseries.guarded': 'black bold',
3295 3294 'qseries.missing': 'red bold',
3296 3295 'qseries.unapplied': 'black bold'}
@@ -1,5077 +1,5077 b''
1 1 # commands.py - command processing for mercurial
2 2 #
3 3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 from node import hex, bin, nullid, nullrev, short
9 9 from lock import release
10 10 from i18n import _, gettext
11 11 import os, re, sys, difflib, time, tempfile
12 12 import hg, scmutil, util, revlog, extensions, copies, error, bookmarks
13 13 import patch, help, url, encoding, templatekw, discovery
14 14 import archival, changegroup, cmdutil, sshserver, hbisect, hgweb, hgweb.server
15 15 import merge as mergemod
16 16 import minirst, revset
17 17 import dagparser, context, simplemerge
18 18 import random, setdiscovery, treediscovery, dagutil
19 19
20 20 table = {}
21 21
22 22 command = cmdutil.command(table)
23 23
24 24 # common command options
25 25
26 26 globalopts = [
27 27 ('R', 'repository', '',
28 28 _('repository root directory or name of overlay bundle file'),
29 29 _('REPO')),
30 30 ('', 'cwd', '',
31 31 _('change working directory'), _('DIR')),
32 32 ('y', 'noninteractive', None,
33 33 _('do not prompt, assume \'yes\' for any required answers')),
34 34 ('q', 'quiet', None, _('suppress output')),
35 35 ('v', 'verbose', None, _('enable additional output')),
36 36 ('', 'config', [],
37 37 _('set/override config option (use \'section.name=value\')'),
38 38 _('CONFIG')),
39 39 ('', 'debug', None, _('enable debugging output')),
40 40 ('', 'debugger', None, _('start debugger')),
41 41 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
42 42 _('ENCODE')),
43 43 ('', 'encodingmode', encoding.encodingmode,
44 44 _('set the charset encoding mode'), _('MODE')),
45 45 ('', 'traceback', None, _('always print a traceback on exception')),
46 46 ('', 'time', None, _('time how long the command takes')),
47 47 ('', 'profile', None, _('print command execution profile')),
48 48 ('', 'version', None, _('output version information and exit')),
49 49 ('h', 'help', None, _('display help and exit')),
50 50 ]
51 51
52 52 dryrunopts = [('n', 'dry-run', None,
53 53 _('do not perform actions, just print output'))]
54 54
55 55 remoteopts = [
56 56 ('e', 'ssh', '',
57 57 _('specify ssh command to use'), _('CMD')),
58 58 ('', 'remotecmd', '',
59 59 _('specify hg command to run on the remote side'), _('CMD')),
60 60 ('', 'insecure', None,
61 61 _('do not verify server certificate (ignoring web.cacerts config)')),
62 62 ]
63 63
64 64 walkopts = [
65 65 ('I', 'include', [],
66 66 _('include names matching the given patterns'), _('PATTERN')),
67 67 ('X', 'exclude', [],
68 68 _('exclude names matching the given patterns'), _('PATTERN')),
69 69 ]
70 70
71 71 commitopts = [
72 72 ('m', 'message', '',
73 73 _('use text as commit message'), _('TEXT')),
74 74 ('l', 'logfile', '',
75 75 _('read commit message from file'), _('FILE')),
76 76 ]
77 77
78 78 commitopts2 = [
79 79 ('d', 'date', '',
80 80 _('record the specified date as commit date'), _('DATE')),
81 81 ('u', 'user', '',
82 82 _('record the specified user as committer'), _('USER')),
83 83 ]
84 84
85 85 templateopts = [
86 86 ('', 'style', '',
87 87 _('display using template map file'), _('STYLE')),
88 88 ('', 'template', '',
89 89 _('display with template'), _('TEMPLATE')),
90 90 ]
91 91
92 92 logopts = [
93 93 ('p', 'patch', None, _('show patch')),
94 94 ('g', 'git', None, _('use git extended diff format')),
95 95 ('l', 'limit', '',
96 96 _('limit number of changes displayed'), _('NUM')),
97 97 ('M', 'no-merges', None, _('do not show merges')),
98 98 ('', 'stat', None, _('output diffstat-style summary of changes')),
99 99 ] + templateopts
100 100
101 101 diffopts = [
102 102 ('a', 'text', None, _('treat all files as text')),
103 103 ('g', 'git', None, _('use git extended diff format')),
104 104 ('', 'nodates', None, _('omit dates from diff headers'))
105 105 ]
106 106
107 107 diffopts2 = [
108 108 ('p', 'show-function', None, _('show which function each change is in')),
109 109 ('', 'reverse', None, _('produce a diff that undoes the changes')),
110 110 ('w', 'ignore-all-space', None,
111 111 _('ignore white space when comparing lines')),
112 112 ('b', 'ignore-space-change', None,
113 113 _('ignore changes in the amount of white space')),
114 114 ('B', 'ignore-blank-lines', None,
115 115 _('ignore changes whose lines are all blank')),
116 116 ('U', 'unified', '',
117 117 _('number of lines of context to show'), _('NUM')),
118 118 ('', 'stat', None, _('output diffstat-style summary of changes')),
119 119 ]
120 120
121 121 similarityopts = [
122 122 ('s', 'similarity', '',
123 123 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
124 124 ]
125 125
126 126 subrepoopts = [
127 127 ('S', 'subrepos', None,
128 128 _('recurse into subrepositories'))
129 129 ]
130 130
131 131 # Commands start here, listed alphabetically
132 132
133 133 @command('^add',
134 134 walkopts + subrepoopts + dryrunopts,
135 135 _('[OPTION]... [FILE]...'))
136 136 def add(ui, repo, *pats, **opts):
137 137 """add the specified files on the next commit
138 138
139 139 Schedule files to be version controlled and added to the
140 140 repository.
141 141
142 142 The files will be added to the repository at the next commit. To
143 143 undo an add before that, see :hg:`forget`.
144 144
145 145 If no names are given, add all files to the repository.
146 146
147 147 .. container:: verbose
148 148
149 149 An example showing how new (unknown) files are added
150 150 automatically by :hg:`add`::
151 151
152 152 $ ls
153 153 foo.c
154 154 $ hg status
155 155 ? foo.c
156 156 $ hg add
157 157 adding foo.c
158 158 $ hg status
159 159 A foo.c
160 160
161 161 Returns 0 if all files are successfully added.
162 162 """
163 163
164 164 m = scmutil.match(repo, pats, opts)
165 165 rejected = cmdutil.add(ui, repo, m, opts.get('dry_run'),
166 166 opts.get('subrepos'), prefix="")
167 167 return rejected and 1 or 0
168 168
169 169 @command('addremove',
170 170 similarityopts + walkopts + dryrunopts,
171 171 _('[OPTION]... [FILE]...'))
172 172 def addremove(ui, repo, *pats, **opts):
173 173 """add all new files, delete all missing files
174 174
175 175 Add all new files and remove all missing files from the
176 176 repository.
177 177
178 178 New files are ignored if they match any of the patterns in
179 179 ``.hgignore``. As with add, these changes take effect at the next
180 180 commit.
181 181
182 182 Use the -s/--similarity option to detect renamed files. With a
183 183 parameter greater than 0, this compares every removed file with
184 184 every added file and records those similar enough as renames. This
185 185 option takes a percentage between 0 (disabled) and 100 (files must
186 186 be identical) as its parameter. Detecting renamed files this way
187 187 can be expensive. After using this option, :hg:`status -C` can be
188 188 used to check which files were identified as moved or renamed.
189 189
190 190 Returns 0 if all files are successfully added.
191 191 """
192 192 try:
193 193 sim = float(opts.get('similarity') or 100)
194 194 except ValueError:
195 195 raise util.Abort(_('similarity must be a number'))
196 196 if sim < 0 or sim > 100:
197 197 raise util.Abort(_('similarity must be between 0 and 100'))
198 198 return scmutil.addremove(repo, pats, opts, similarity=sim / 100.0)
199 199
200 200 @command('^annotate|blame',
201 201 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
202 202 ('', 'follow', None,
203 203 _('follow copies/renames and list the filename (DEPRECATED)')),
204 204 ('', 'no-follow', None, _("don't follow copies and renames")),
205 205 ('a', 'text', None, _('treat all files as text')),
206 206 ('u', 'user', None, _('list the author (long with -v)')),
207 207 ('f', 'file', None, _('list the filename')),
208 208 ('d', 'date', None, _('list the date (short with -q)')),
209 209 ('n', 'number', None, _('list the revision number (default)')),
210 210 ('c', 'changeset', None, _('list the changeset')),
211 211 ('l', 'line-number', None, _('show line number at the first appearance'))
212 212 ] + walkopts,
213 213 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'))
214 214 def annotate(ui, repo, *pats, **opts):
215 215 """show changeset information by line for each file
216 216
217 217 List changes in files, showing the revision id responsible for
218 218 each line
219 219
220 220 This command is useful for discovering when a change was made and
221 221 by whom.
222 222
223 223 Without the -a/--text option, annotate will avoid processing files
224 224 it detects as binary. With -a, annotate will annotate the file
225 225 anyway, although the results will probably be neither useful
226 226 nor desirable.
227 227
228 228 Returns 0 on success.
229 229 """
230 230 if opts.get('follow'):
231 231 # --follow is deprecated and now just an alias for -f/--file
232 232 # to mimic the behavior of Mercurial before version 1.5
233 233 opts['file'] = True
234 234
235 235 datefunc = ui.quiet and util.shortdate or util.datestr
236 236 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
237 237
238 238 if not pats:
239 239 raise util.Abort(_('at least one filename or pattern is required'))
240 240
241 241 opmap = [('user', ' ', lambda x: ui.shortuser(x[0].user())),
242 242 ('number', ' ', lambda x: str(x[0].rev())),
243 243 ('changeset', ' ', lambda x: short(x[0].node())),
244 244 ('date', ' ', getdate),
245 245 ('file', ' ', lambda x: x[0].path()),
246 246 ('line_number', ':', lambda x: str(x[1])),
247 247 ]
248 248
249 249 if (not opts.get('user') and not opts.get('changeset')
250 250 and not opts.get('date') and not opts.get('file')):
251 251 opts['number'] = True
252 252
253 253 linenumber = opts.get('line_number') is not None
254 254 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
255 255 raise util.Abort(_('at least one of -n/-c is required for -l'))
256 256
257 257 funcmap = [(func, sep) for op, sep, func in opmap if opts.get(op)]
258 258 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
259 259
260 260 def bad(x, y):
261 261 raise util.Abort("%s: %s" % (x, y))
262 262
263 263 ctx = scmutil.revsingle(repo, opts.get('rev'))
264 264 m = scmutil.match(repo, pats, opts)
265 265 m.bad = bad
266 266 follow = not opts.get('no_follow')
267 267 for abs in ctx.walk(m):
268 268 fctx = ctx[abs]
269 269 if not opts.get('text') and util.binary(fctx.data()):
270 270 ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
271 271 continue
272 272
273 273 lines = fctx.annotate(follow=follow, linenumber=linenumber)
274 274 pieces = []
275 275
276 276 for f, sep in funcmap:
277 277 l = [f(n) for n, dummy in lines]
278 278 if l:
279 279 sized = [(x, encoding.colwidth(x)) for x in l]
280 280 ml = max([w for x, w in sized])
281 281 pieces.append(["%s%s%s" % (sep, ' ' * (ml - w), x)
282 282 for x, w in sized])
283 283
284 284 if pieces:
285 285 for p, l in zip(zip(*pieces), lines):
286 286 ui.write("%s: %s" % ("".join(p), l[1]))
287 287
288 288 @command('archive',
289 289 [('', 'no-decode', None, _('do not pass files through decoders')),
290 290 ('p', 'prefix', '', _('directory prefix for files in archive'),
291 291 _('PREFIX')),
292 292 ('r', 'rev', '', _('revision to distribute'), _('REV')),
293 293 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
294 294 ] + subrepoopts + walkopts,
295 295 _('[OPTION]... DEST'))
296 296 def archive(ui, repo, dest, **opts):
297 297 '''create an unversioned archive of a repository revision
298 298
299 299 By default, the revision used is the parent of the working
300 300 directory; use -r/--rev to specify a different revision.
301 301
302 302 The archive type is automatically detected based on file
303 303 extension (or override using -t/--type).
304 304
305 305 Valid types are:
306 306
307 307 :``files``: a directory full of files (default)
308 308 :``tar``: tar archive, uncompressed
309 309 :``tbz2``: tar archive, compressed using bzip2
310 310 :``tgz``: tar archive, compressed using gzip
311 311 :``uzip``: zip archive, uncompressed
312 312 :``zip``: zip archive, compressed using deflate
313 313
314 314 The exact name of the destination archive or directory is given
315 315 using a format string; see :hg:`help export` for details.
316 316
317 317 Each member added to an archive file has a directory prefix
318 318 prepended. Use -p/--prefix to specify a format string for the
319 319 prefix. The default is the basename of the archive, with suffixes
320 320 removed.
321 321
322 322 Returns 0 on success.
323 323 '''
324 324
325 325 ctx = scmutil.revsingle(repo, opts.get('rev'))
326 326 if not ctx:
327 327 raise util.Abort(_('no working directory: please specify a revision'))
328 328 node = ctx.node()
329 329 dest = cmdutil.makefilename(repo, dest, node)
330 330 if os.path.realpath(dest) == repo.root:
331 331 raise util.Abort(_('repository root cannot be destination'))
332 332
333 333 kind = opts.get('type') or archival.guesskind(dest) or 'files'
334 334 prefix = opts.get('prefix')
335 335
336 336 if dest == '-':
337 337 if kind == 'files':
338 338 raise util.Abort(_('cannot archive plain files to stdout'))
339 339 dest = sys.stdout
340 340 if not prefix:
341 341 prefix = os.path.basename(repo.root) + '-%h'
342 342
343 343 prefix = cmdutil.makefilename(repo, prefix, node)
344 344 matchfn = scmutil.match(repo, [], opts)
345 345 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
346 346 matchfn, prefix, subrepos=opts.get('subrepos'))
347 347
348 348 @command('backout',
349 349 [('', 'merge', None, _('merge with old dirstate parent after backout')),
350 350 ('', 'parent', '', _('parent to choose when backing out merge'), _('REV')),
351 351 ('t', 'tool', '', _('specify merge tool')),
352 352 ('r', 'rev', '', _('revision to backout'), _('REV')),
353 353 ] + walkopts + commitopts + commitopts2,
354 354 _('[OPTION]... [-r] REV'))
355 355 def backout(ui, repo, node=None, rev=None, **opts):
356 356 '''reverse effect of earlier changeset
357 357
358 358 Prepare a new changeset with the effect of REV undone in the
359 359 current working directory.
360 360
361 361 If REV is the parent of the working directory, then this new changeset
362 362 is committed automatically. Otherwise, hg needs to merge the
363 363 changes and the merged result is left uncommitted.
364 364
365 365 By default, the pending changeset will have one parent,
366 366 maintaining a linear history. With --merge, the pending changeset
367 367 will instead have two parents: the old parent of the working
368 368 directory and a new child of REV that simply undoes REV.
369 369
370 370 Before version 1.7, the behavior without --merge was equivalent to
371 371 specifying --merge followed by :hg:`update --clean .` to cancel
372 372 the merge and leave the child of REV as a head to be merged
373 373 separately.
374 374
375 375 See :hg:`help dates` for a list of formats valid for -d/--date.
376 376
377 377 Returns 0 on success.
378 378 '''
379 379 if rev and node:
380 380 raise util.Abort(_("please specify just one revision"))
381 381
382 382 if not rev:
383 383 rev = node
384 384
385 385 if not rev:
386 386 raise util.Abort(_("please specify a revision to backout"))
387 387
388 388 date = opts.get('date')
389 389 if date:
390 390 opts['date'] = util.parsedate(date)
391 391
392 392 cmdutil.bailifchanged(repo)
393 393 node = scmutil.revsingle(repo, rev).node()
394 394
395 395 op1, op2 = repo.dirstate.parents()
396 396 a = repo.changelog.ancestor(op1, node)
397 397 if a != node:
398 398 raise util.Abort(_('cannot backout change on a different branch'))
399 399
400 400 p1, p2 = repo.changelog.parents(node)
401 401 if p1 == nullid:
402 402 raise util.Abort(_('cannot backout a change with no parents'))
403 403 if p2 != nullid:
404 404 if not opts.get('parent'):
405 405 raise util.Abort(_('cannot backout a merge changeset without '
406 406 '--parent'))
407 407 p = repo.lookup(opts['parent'])
408 408 if p not in (p1, p2):
409 409 raise util.Abort(_('%s is not a parent of %s') %
410 410 (short(p), short(node)))
411 411 parent = p
412 412 else:
413 413 if opts.get('parent'):
414 414 raise util.Abort(_('cannot use --parent on non-merge changeset'))
415 415 parent = p1
416 416
417 417 # the backout should appear on the same branch
418 418 branch = repo.dirstate.branch()
419 419 hg.clean(repo, node, show_stats=False)
420 420 repo.dirstate.setbranch(branch)
421 421 revert_opts = opts.copy()
422 422 revert_opts['date'] = None
423 423 revert_opts['all'] = True
424 424 revert_opts['rev'] = hex(parent)
425 425 revert_opts['no_backup'] = None
426 426 revert(ui, repo, **revert_opts)
427 427 if not opts.get('merge') and op1 != node:
428 428 try:
429 429 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
430 430 return hg.update(repo, op1)
431 431 finally:
432 432 ui.setconfig('ui', 'forcemerge', '')
433 433
434 434 commit_opts = opts.copy()
435 435 commit_opts['addremove'] = False
436 436 if not commit_opts['message'] and not commit_opts['logfile']:
437 437 # we don't translate commit messages
438 438 commit_opts['message'] = "Backed out changeset %s" % short(node)
439 439 commit_opts['force_editor'] = True
440 440 commit(ui, repo, **commit_opts)
441 441 def nice(node):
442 442 return '%d:%s' % (repo.changelog.rev(node), short(node))
443 443 ui.status(_('changeset %s backs out changeset %s\n') %
444 444 (nice(repo.changelog.tip()), nice(node)))
445 445 if opts.get('merge') and op1 != node:
446 446 hg.clean(repo, op1, show_stats=False)
447 447 ui.status(_('merging with changeset %s\n')
448 448 % nice(repo.changelog.tip()))
449 449 try:
450 450 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
451 451 return hg.merge(repo, hex(repo.changelog.tip()))
452 452 finally:
453 453 ui.setconfig('ui', 'forcemerge', '')
454 454 return 0
455 455
456 456 @command('bisect',
457 457 [('r', 'reset', False, _('reset bisect state')),
458 458 ('g', 'good', False, _('mark changeset good')),
459 459 ('b', 'bad', False, _('mark changeset bad')),
460 460 ('s', 'skip', False, _('skip testing changeset')),
461 461 ('e', 'extend', False, _('extend the bisect range')),
462 462 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
463 463 ('U', 'noupdate', False, _('do not update to target'))],
464 464 _("[-gbsr] [-U] [-c CMD] [REV]"))
465 465 def bisect(ui, repo, rev=None, extra=None, command=None,
466 466 reset=None, good=None, bad=None, skip=None, extend=None,
467 467 noupdate=None):
468 468 """subdivision search of changesets
469 469
470 470 This command helps to find changesets which introduce problems. To
471 471 use, mark the earliest changeset you know exhibits the problem as
472 472 bad, then mark the latest changeset which is free from the problem
473 473 as good. Bisect will update your working directory to a revision
474 474 for testing (unless the -U/--noupdate option is specified). Once
475 475 you have performed tests, mark the working directory as good or
476 476 bad, and bisect will either update to another candidate changeset
477 477 or announce that it has found the bad revision.
478 478
479 479 As a shortcut, you can also use the revision argument to mark a
480 480 revision as good or bad without checking it out first.
481 481
482 482 If you supply a command, it will be used for automatic bisection.
483 483 Its exit status will be used to mark revisions as good or bad:
484 484 status 0 means good, 125 means to skip the revision, 127
485 485 (command not found) will abort the bisection, and any other
486 486 non-zero exit status means the revision is bad.
487 487
488 488 Returns 0 on success.
489 489 """
490 490 def extendbisectrange(nodes, good):
491 491 # bisect is incomplete when it ends on a merge node and
492 492 # one of the parent was not checked.
493 493 parents = repo[nodes[0]].parents()
494 494 if len(parents) > 1:
495 495 side = good and state['bad'] or state['good']
496 496 num = len(set(i.node() for i in parents) & set(side))
497 497 if num == 1:
498 498 return parents[0].ancestor(parents[1])
499 499 return None
500 500
501 501 def print_result(nodes, good):
502 502 displayer = cmdutil.show_changeset(ui, repo, {})
503 503 if len(nodes) == 1:
504 504 # narrowed it down to a single revision
505 505 if good:
506 506 ui.write(_("The first good revision is:\n"))
507 507 else:
508 508 ui.write(_("The first bad revision is:\n"))
509 509 displayer.show(repo[nodes[0]])
510 510 extendnode = extendbisectrange(nodes, good)
511 511 if extendnode is not None:
512 512 ui.write(_('Not all ancestors of this changeset have been'
513 513 ' checked.\nUse bisect --extend to continue the '
514 514 'bisection from\nthe common ancestor, %s.\n')
515 515 % extendnode)
516 516 else:
517 517 # multiple possible revisions
518 518 if good:
519 519 ui.write(_("Due to skipped revisions, the first "
520 520 "good revision could be any of:\n"))
521 521 else:
522 522 ui.write(_("Due to skipped revisions, the first "
523 523 "bad revision could be any of:\n"))
524 524 for n in nodes:
525 525 displayer.show(repo[n])
526 526 displayer.close()
527 527
528 528 def check_state(state, interactive=True):
529 529 if not state['good'] or not state['bad']:
530 530 if (good or bad or skip or reset) and interactive:
531 531 return
532 532 if not state['good']:
533 533 raise util.Abort(_('cannot bisect (no known good revisions)'))
534 534 else:
535 535 raise util.Abort(_('cannot bisect (no known bad revisions)'))
536 536 return True
537 537
538 538 # backward compatibility
539 539 if rev in "good bad reset init".split():
540 540 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
541 541 cmd, rev, extra = rev, extra, None
542 542 if cmd == "good":
543 543 good = True
544 544 elif cmd == "bad":
545 545 bad = True
546 546 else:
547 547 reset = True
548 548 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
549 549 raise util.Abort(_('incompatible arguments'))
550 550
551 551 if reset:
552 552 p = repo.join("bisect.state")
553 553 if os.path.exists(p):
554 554 os.unlink(p)
555 555 return
556 556
557 557 state = hbisect.load_state(repo)
558 558
559 559 if command:
560 560 changesets = 1
561 561 try:
562 562 while changesets:
563 563 # update state
564 564 status = util.system(command)
565 565 if status == 125:
566 566 transition = "skip"
567 567 elif status == 0:
568 568 transition = "good"
569 569 # status < 0 means process was killed
570 570 elif status == 127:
571 571 raise util.Abort(_("failed to execute %s") % command)
572 572 elif status < 0:
573 573 raise util.Abort(_("%s killed") % command)
574 574 else:
575 575 transition = "bad"
576 576 ctx = scmutil.revsingle(repo, rev)
577 577 rev = None # clear for future iterations
578 578 state[transition].append(ctx.node())
579 579 ui.status(_('Changeset %d:%s: %s\n') % (ctx, ctx, transition))
580 580 check_state(state, interactive=False)
581 581 # bisect
582 582 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
583 583 # update to next check
584 584 cmdutil.bailifchanged(repo)
585 585 hg.clean(repo, nodes[0], show_stats=False)
586 586 finally:
587 587 hbisect.save_state(repo, state)
588 588 print_result(nodes, good)
589 589 return
590 590
591 591 # update state
592 592
593 593 if rev:
594 594 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
595 595 else:
596 596 nodes = [repo.lookup('.')]
597 597
598 598 if good or bad or skip:
599 599 if good:
600 600 state['good'] += nodes
601 601 elif bad:
602 602 state['bad'] += nodes
603 603 elif skip:
604 604 state['skip'] += nodes
605 605 hbisect.save_state(repo, state)
606 606
607 607 if not check_state(state):
608 608 return
609 609
610 610 # actually bisect
611 611 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
612 612 if extend:
613 613 if not changesets:
614 614 extendnode = extendbisectrange(nodes, good)
615 615 if extendnode is not None:
616 616 ui.write(_("Extending search to changeset %d:%s\n"
617 617 % (extendnode.rev(), extendnode)))
618 618 if noupdate:
619 619 return
620 620 cmdutil.bailifchanged(repo)
621 621 return hg.clean(repo, extendnode.node())
622 622 raise util.Abort(_("nothing to extend"))
623 623
624 624 if changesets == 0:
625 625 print_result(nodes, good)
626 626 else:
627 627 assert len(nodes) == 1 # only a single node can be tested next
628 628 node = nodes[0]
629 629 # compute the approximate number of remaining tests
630 630 tests, size = 0, 2
631 631 while size <= changesets:
632 632 tests, size = tests + 1, size * 2
633 633 rev = repo.changelog.rev(node)
634 634 ui.write(_("Testing changeset %d:%s "
635 635 "(%d changesets remaining, ~%d tests)\n")
636 636 % (rev, short(node), changesets, tests))
637 637 if not noupdate:
638 638 cmdutil.bailifchanged(repo)
639 639 return hg.clean(repo, node)
640 640
641 641 @command('bookmarks',
642 642 [('f', 'force', False, _('force')),
643 643 ('r', 'rev', '', _('revision'), _('REV')),
644 644 ('d', 'delete', False, _('delete a given bookmark')),
645 645 ('m', 'rename', '', _('rename a given bookmark'), _('NAME')),
646 646 ('i', 'inactive', False, _('do not mark a new bookmark active'))],
647 647 _('hg bookmarks [-f] [-d] [-i] [-m NAME] [-r REV] [NAME]'))
648 648 def bookmark(ui, repo, mark=None, rev=None, force=False, delete=False,
649 649 rename=None, inactive=False):
650 650 '''track a line of development with movable markers
651 651
652 652 Bookmarks are pointers to certain commits that move when
653 653 committing. Bookmarks are local. They can be renamed, copied and
654 654 deleted. It is possible to use bookmark names in :hg:`merge` and
655 655 :hg:`update` to merge and update respectively to a given bookmark.
656 656
657 657 You can use :hg:`bookmark NAME` to set a bookmark on the working
658 658 directory's parent revision with the given name. If you specify
659 659 a revision using -r REV (where REV may be an existing bookmark),
660 660 the bookmark is assigned to that revision.
661 661
662 662 Bookmarks can be pushed and pulled between repositories (see :hg:`help
663 663 push` and :hg:`help pull`). This requires both the local and remote
664 664 repositories to support bookmarks. For versions prior to 1.8, this means
665 665 the bookmarks extension must be enabled.
666 666 '''
667 667 hexfn = ui.debugflag and hex or short
668 668 marks = repo._bookmarks
669 669 cur = repo.changectx('.').node()
670 670
671 671 if rename:
672 672 if rename not in marks:
673 673 raise util.Abort(_("bookmark '%s' does not exist") % rename)
674 674 if mark in marks and not force:
675 675 raise util.Abort(_("bookmark '%s' already exists "
676 676 "(use -f to force)") % mark)
677 677 if mark is None:
678 678 raise util.Abort(_("new bookmark name required"))
679 679 marks[mark] = marks[rename]
680 680 if repo._bookmarkcurrent == rename and not inactive:
681 681 bookmarks.setcurrent(repo, mark)
682 682 del marks[rename]
683 683 bookmarks.write(repo)
684 684 return
685 685
686 686 if delete:
687 687 if mark is None:
688 688 raise util.Abort(_("bookmark name required"))
689 689 if mark not in marks:
690 690 raise util.Abort(_("bookmark '%s' does not exist") % mark)
691 691 if mark == repo._bookmarkcurrent:
692 692 bookmarks.setcurrent(repo, None)
693 693 del marks[mark]
694 694 bookmarks.write(repo)
695 695 return
696 696
697 697 if mark is not None:
698 698 if "\n" in mark:
699 699 raise util.Abort(_("bookmark name cannot contain newlines"))
700 700 mark = mark.strip()
701 701 if not mark:
702 702 raise util.Abort(_("bookmark names cannot consist entirely of "
703 703 "whitespace"))
704 704 if inactive and mark == repo._bookmarkcurrent:
705 705 bookmarks.setcurrent(repo, None)
706 706 return
707 707 if mark in marks and not force:
708 708 raise util.Abort(_("bookmark '%s' already exists "
709 709 "(use -f to force)") % mark)
710 710 if ((mark in repo.branchtags() or mark == repo.dirstate.branch())
711 711 and not force):
712 712 raise util.Abort(
713 713 _("a bookmark cannot have the name of an existing branch"))
714 714 if rev:
715 715 marks[mark] = repo.lookup(rev)
716 716 else:
717 717 marks[mark] = repo.changectx('.').node()
718 718 if not inactive and repo.changectx('.').node() == marks[mark]:
719 719 bookmarks.setcurrent(repo, mark)
720 720 bookmarks.write(repo)
721 721 return
722 722
723 723 if mark is None:
724 724 if rev:
725 725 raise util.Abort(_("bookmark name required"))
726 726 if len(marks) == 0:
727 727 ui.status(_("no bookmarks set\n"))
728 728 else:
729 729 for bmark, n in sorted(marks.iteritems()):
730 730 current = repo._bookmarkcurrent
731 731 if bmark == current and n == cur:
732 732 prefix, label = '*', 'bookmarks.current'
733 733 else:
734 734 prefix, label = ' ', ''
735 735
736 736 if ui.quiet:
737 737 ui.write("%s\n" % bmark, label=label)
738 738 else:
739 739 ui.write(" %s %-25s %d:%s\n" % (
740 740 prefix, bmark, repo.changelog.rev(n), hexfn(n)),
741 741 label=label)
742 742 return
743 743
744 744 @command('branch',
745 745 [('f', 'force', None,
746 746 _('set branch name even if it shadows an existing branch')),
747 747 ('C', 'clean', None, _('reset branch name to parent branch name'))],
748 748 _('[-fC] [NAME]'))
749 749 def branch(ui, repo, label=None, **opts):
750 750 """set or show the current branch name
751 751
752 752 With no argument, show the current branch name. With one argument,
753 753 set the working directory branch name (the branch will not exist
754 754 in the repository until the next commit). Standard practice
755 755 recommends that primary development take place on the 'default'
756 756 branch.
757 757
758 758 Unless -f/--force is specified, branch will not let you set a
759 759 branch name that already exists, even if it's inactive.
760 760
761 761 Use -C/--clean to reset the working directory branch to that of
762 762 the parent of the working directory, negating a previous branch
763 763 change.
764 764
765 765 Use the command :hg:`update` to switch to an existing branch. Use
766 766 :hg:`commit --close-branch` to mark this branch as closed.
767 767
768 768 Returns 0 on success.
769 769 """
770 770
771 771 if opts.get('clean'):
772 772 label = repo[None].p1().branch()
773 773 repo.dirstate.setbranch(label)
774 774 ui.status(_('reset working directory to branch %s\n') % label)
775 775 elif label:
776 776 if not opts.get('force') and label in repo.branchtags():
777 777 if label not in [p.branch() for p in repo.parents()]:
778 778 raise util.Abort(_('a branch of the same name already exists'),
779 779 # i18n: "it" refers to an existing branch
780 780 hint=_("use 'hg update' to switch to it"))
781 781 repo.dirstate.setbranch(label)
782 782 ui.status(_('marked working directory as branch %s\n') % label)
783 783 else:
784 784 ui.write("%s\n" % repo.dirstate.branch())
785 785
786 786 @command('branches',
787 787 [('a', 'active', False, _('show only branches that have unmerged heads')),
788 788 ('c', 'closed', False, _('show normal and closed branches'))],
789 789 _('[-ac]'))
790 790 def branches(ui, repo, active=False, closed=False):
791 791 """list repository named branches
792 792
793 793 List the repository's named branches, indicating which ones are
794 794 inactive. If -c/--closed is specified, also list branches which have
795 795 been marked closed (see :hg:`commit --close-branch`).
796 796
797 797 If -a/--active is specified, only show active branches. A branch
798 798 is considered active if it contains repository heads.
799 799
800 800 Use the command :hg:`update` to switch to an existing branch.
801 801
802 802 Returns 0.
803 803 """
804 804
805 805 hexfunc = ui.debugflag and hex or short
806 806 activebranches = [repo[n].branch() for n in repo.heads()]
807 807 def testactive(tag, node):
808 808 realhead = tag in activebranches
809 809 open = node in repo.branchheads(tag, closed=False)
810 810 return realhead and open
811 811 branches = sorted([(testactive(tag, node), repo.changelog.rev(node), tag)
812 812 for tag, node in repo.branchtags().items()],
813 813 reverse=True)
814 814
815 815 for isactive, node, tag in branches:
816 816 if (not active) or isactive:
817 817 if ui.quiet:
818 818 ui.write("%s\n" % tag)
819 819 else:
820 820 hn = repo.lookup(node)
821 821 if isactive:
822 822 label = 'branches.active'
823 823 notice = ''
824 824 elif hn not in repo.branchheads(tag, closed=False):
825 825 if not closed:
826 826 continue
827 827 label = 'branches.closed'
828 828 notice = _(' (closed)')
829 829 else:
830 830 label = 'branches.inactive'
831 831 notice = _(' (inactive)')
832 832 if tag == repo.dirstate.branch():
833 833 label = 'branches.current'
834 834 rev = str(node).rjust(31 - encoding.colwidth(tag))
835 835 rev = ui.label('%s:%s' % (rev, hexfunc(hn)), 'log.changeset')
836 836 tag = ui.label(tag, label)
837 837 ui.write("%s %s%s\n" % (tag, rev, notice))
838 838
839 839 @command('bundle',
840 840 [('f', 'force', None, _('run even when the destination is unrelated')),
841 841 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
842 842 _('REV')),
843 843 ('b', 'branch', [], _('a specific branch you would like to bundle'),
844 844 _('BRANCH')),
845 845 ('', 'base', [],
846 846 _('a base changeset assumed to be available at the destination'),
847 847 _('REV')),
848 848 ('a', 'all', None, _('bundle all changesets in the repository')),
849 849 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
850 850 ] + remoteopts,
851 851 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
852 852 def bundle(ui, repo, fname, dest=None, **opts):
853 853 """create a changegroup file
854 854
855 855 Generate a compressed changegroup file collecting changesets not
856 856 known to be in another repository.
857 857
858 858 If you omit the destination repository, then hg assumes the
859 859 destination will have all the nodes you specify with --base
860 860 parameters. To create a bundle containing all changesets, use
861 861 -a/--all (or --base null).
862 862
863 863 You can change compression method with the -t/--type option.
864 864 The available compression methods are: none, bzip2, and
865 865 gzip (by default, bundles are compressed using bzip2).
866 866
867 867 The bundle file can then be transferred using conventional means
868 868 and applied to another repository with the unbundle or pull
869 869 command. This is useful when direct push and pull are not
870 870 available or when exporting an entire repository is undesirable.
871 871
872 872 Applying bundles preserves all changeset contents including
873 873 permissions, copy/rename information, and revision history.
874 874
875 875 Returns 0 on success, 1 if no changes found.
876 876 """
877 877 revs = None
878 878 if 'rev' in opts:
879 879 revs = scmutil.revrange(repo, opts['rev'])
880 880
881 881 if opts.get('all'):
882 882 base = ['null']
883 883 else:
884 884 base = scmutil.revrange(repo, opts.get('base'))
885 885 if base:
886 886 if dest:
887 887 raise util.Abort(_("--base is incompatible with specifying "
888 888 "a destination"))
889 889 common = [repo.lookup(rev) for rev in base]
890 890 heads = revs and map(repo.lookup, revs) or revs
891 891 else:
892 892 dest = ui.expandpath(dest or 'default-push', dest or 'default')
893 893 dest, branches = hg.parseurl(dest, opts.get('branch'))
894 894 other = hg.repository(hg.remoteui(repo, opts), dest)
895 895 revs, checkout = hg.addbranchrevs(repo, other, branches, revs)
896 896 heads = revs and map(repo.lookup, revs) or revs
897 897 common, outheads = discovery.findcommonoutgoing(repo, other,
898 898 onlyheads=heads,
899 899 force=opts.get('force'))
900 900
901 901 cg = repo.getbundle('bundle', common=common, heads=heads)
902 902 if not cg:
903 903 ui.status(_("no changes found\n"))
904 904 return 1
905 905
906 906 bundletype = opts.get('type', 'bzip2').lower()
907 907 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
908 908 bundletype = btypes.get(bundletype)
909 909 if bundletype not in changegroup.bundletypes:
910 910 raise util.Abort(_('unknown bundle type specified with --type'))
911 911
912 912 changegroup.writebundle(cg, fname, bundletype)
913 913
914 914 @command('cat',
915 915 [('o', 'output', '',
916 916 _('print output to file with formatted name'), _('FORMAT')),
917 917 ('r', 'rev', '', _('print the given revision'), _('REV')),
918 918 ('', 'decode', None, _('apply any matching decode filter')),
919 919 ] + walkopts,
920 920 _('[OPTION]... FILE...'))
921 921 def cat(ui, repo, file1, *pats, **opts):
922 922 """output the current or given revision of files
923 923
924 924 Print the specified files as they were at the given revision. If
925 925 no revision is given, the parent of the working directory is used,
926 926 or tip if no revision is checked out.
927 927
928 928 Output may be to a file, in which case the name of the file is
929 929 given using a format string. The formatting rules are the same as
930 930 for the export command, with the following additions:
931 931
932 932 :``%s``: basename of file being printed
933 933 :``%d``: dirname of file being printed, or '.' if in repository root
934 934 :``%p``: root-relative path name of file being printed
935 935
936 936 Returns 0 on success.
937 937 """
938 938 ctx = scmutil.revsingle(repo, opts.get('rev'))
939 939 err = 1
940 940 m = scmutil.match(repo, (file1,) + pats, opts)
941 941 for abs in ctx.walk(m):
942 942 fp = cmdutil.makefileobj(repo, opts.get('output'), ctx.node(),
943 943 pathname=abs)
944 944 data = ctx[abs].data()
945 945 if opts.get('decode'):
946 946 data = repo.wwritedata(abs, data)
947 947 fp.write(data)
948 948 fp.close()
949 949 err = 0
950 950 return err
951 951
952 952 @command('^clone',
953 953 [('U', 'noupdate', None,
954 954 _('the clone will include an empty working copy (only a repository)')),
955 955 ('u', 'updaterev', '', _('revision, tag or branch to check out'), _('REV')),
956 956 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
957 957 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
958 958 ('', 'pull', None, _('use pull protocol to copy metadata')),
959 959 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
960 960 ] + remoteopts,
961 961 _('[OPTION]... SOURCE [DEST]'))
962 962 def clone(ui, source, dest=None, **opts):
963 963 """make a copy of an existing repository
964 964
965 965 Create a copy of an existing repository in a new directory.
966 966
967 967 If no destination directory name is specified, it defaults to the
968 968 basename of the source.
969 969
970 970 The location of the source is added to the new repository's
971 971 ``.hg/hgrc`` file, as the default to be used for future pulls.
972 972
973 973 See :hg:`help urls` for valid source format details.
974 974
975 975 It is possible to specify an ``ssh://`` URL as the destination, but no
976 976 ``.hg/hgrc`` and working directory will be created on the remote side.
977 977 Please see :hg:`help urls` for important details about ``ssh://`` URLs.
978 978
979 979 A set of changesets (tags, or branch names) to pull may be specified
980 980 by listing each changeset (tag, or branch name) with -r/--rev.
981 981 If -r/--rev is used, the cloned repository will contain only a subset
982 982 of the changesets of the source repository. Only the set of changesets
983 983 defined by all -r/--rev options (including all their ancestors)
984 984 will be pulled into the destination repository.
985 985 No subsequent changesets (including subsequent tags) will be present
986 986 in the destination.
987 987
988 988 Using -r/--rev (or 'clone src#rev dest') implies --pull, even for
989 989 local source repositories.
990 990
991 991 For efficiency, hardlinks are used for cloning whenever the source
992 992 and destination are on the same filesystem (note this applies only
993 993 to the repository data, not to the working directory). Some
994 994 filesystems, such as AFS, implement hardlinking incorrectly, but
995 995 do not report errors. In these cases, use the --pull option to
996 996 avoid hardlinking.
997 997
998 998 In some cases, you can clone repositories and the working directory
999 999 using full hardlinks with ::
1000 1000
1001 1001 $ cp -al REPO REPOCLONE
1002 1002
1003 1003 This is the fastest way to clone, but it is not always safe. The
1004 1004 operation is not atomic (making sure REPO is not modified during
1005 1005 the operation is up to you) and you have to make sure your editor
1006 1006 breaks hardlinks (Emacs and most Linux Kernel tools do so). Also,
1007 1007 this is not compatible with certain extensions that place their
1008 1008 metadata under the .hg directory, such as mq.
1009 1009
1010 1010 Mercurial will update the working directory to the first applicable
1011 1011 revision from this list:
1012 1012
1013 1013 a) null if -U or the source repository has no changesets
1014 1014 b) if -u . and the source repository is local, the first parent of
1015 1015 the source repository's working directory
1016 1016 c) the changeset specified with -u (if a branch name, this means the
1017 1017 latest head of that branch)
1018 1018 d) the changeset specified with -r
1019 1019 e) the tipmost head specified with -b
1020 1020 f) the tipmost head specified with the url#branch source syntax
1021 1021 g) the tipmost head of the default branch
1022 1022 h) tip
1023 1023
1024 1024 Returns 0 on success.
1025 1025 """
1026 1026 if opts.get('noupdate') and opts.get('updaterev'):
1027 1027 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
1028 1028
1029 1029 r = hg.clone(hg.remoteui(ui, opts), source, dest,
1030 1030 pull=opts.get('pull'),
1031 1031 stream=opts.get('uncompressed'),
1032 1032 rev=opts.get('rev'),
1033 1033 update=opts.get('updaterev') or not opts.get('noupdate'),
1034 1034 branch=opts.get('branch'))
1035 1035
1036 1036 return r is None
1037 1037
1038 1038 @command('^commit|ci',
1039 1039 [('A', 'addremove', None,
1040 1040 _('mark new/missing files as added/removed before committing')),
1041 1041 ('', 'close-branch', None,
1042 1042 _('mark a branch as closed, hiding it from the branch list')),
1043 1043 ] + walkopts + commitopts + commitopts2,
1044 1044 _('[OPTION]... [FILE]...'))
1045 1045 def commit(ui, repo, *pats, **opts):
1046 1046 """commit the specified files or all outstanding changes
1047 1047
1048 1048 Commit changes to the given files into the repository. Unlike a
1049 1049 centralized SCM, this operation is a local operation. See
1050 1050 :hg:`push` for a way to actively distribute your changes.
1051 1051
1052 1052 If a list of files is omitted, all changes reported by :hg:`status`
1053 1053 will be committed.
1054 1054
1055 1055 If you are committing the result of a merge, do not provide any
1056 1056 filenames or -I/-X filters.
1057 1057
1058 1058 If no commit message is specified, Mercurial starts your
1059 1059 configured editor where you can enter a message. In case your
1060 1060 commit fails, you will find a backup of your message in
1061 1061 ``.hg/last-message.txt``.
1062 1062
1063 1063 See :hg:`help dates` for a list of formats valid for -d/--date.
1064 1064
1065 1065 Returns 0 on success, 1 if nothing changed.
1066 1066 """
1067 1067 extra = {}
1068 1068 if opts.get('close_branch'):
1069 1069 if repo['.'].node() not in repo.branchheads():
1070 1070 # The topo heads set is included in the branch heads set of the
1071 1071 # current branch, so it's sufficient to test branchheads
1072 1072 raise util.Abort(_('can only close branch heads'))
1073 1073 extra['close'] = 1
1074 1074 e = cmdutil.commiteditor
1075 1075 if opts.get('force_editor'):
1076 1076 e = cmdutil.commitforceeditor
1077 1077
1078 1078 def commitfunc(ui, repo, message, match, opts):
1079 1079 return repo.commit(message, opts.get('user'), opts.get('date'), match,
1080 1080 editor=e, extra=extra)
1081 1081
1082 1082 branch = repo[None].branch()
1083 1083 bheads = repo.branchheads(branch)
1084 1084
1085 1085 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1086 1086 if not node:
1087 1087 stat = repo.status(match=scmutil.match(repo, pats, opts))
1088 1088 if stat[3]:
1089 1089 ui.status(_("nothing changed (%d missing files, see 'hg status')\n")
1090 1090 % len(stat[3]))
1091 1091 else:
1092 1092 ui.status(_("nothing changed\n"))
1093 1093 return 1
1094 1094
1095 1095 ctx = repo[node]
1096 1096 parents = ctx.parents()
1097 1097
1098 1098 if bheads and not [x for x in parents
1099 1099 if x.node() in bheads and x.branch() == branch]:
1100 1100 ui.status(_('created new head\n'))
1101 1101 # The message is not printed for initial roots. For the other
1102 1102 # changesets, it is printed in the following situations:
1103 1103 #
1104 1104 # Par column: for the 2 parents with ...
1105 1105 # N: null or no parent
1106 1106 # B: parent is on another named branch
1107 1107 # C: parent is a regular non head changeset
1108 1108 # H: parent was a branch head of the current branch
1109 1109 # Msg column: whether we print "created new head" message
1110 1110 # In the following, it is assumed that there already exists some
1111 1111 # initial branch heads of the current branch, otherwise nothing is
1112 1112 # printed anyway.
1113 1113 #
1114 1114 # Par Msg Comment
1115 1115 # NN y additional topo root
1116 1116 #
1117 1117 # BN y additional branch root
1118 1118 # CN y additional topo head
1119 1119 # HN n usual case
1120 1120 #
1121 1121 # BB y weird additional branch root
1122 1122 # CB y branch merge
1123 1123 # HB n merge with named branch
1124 1124 #
1125 1125 # CC y additional head from merge
1126 1126 # CH n merge with a head
1127 1127 #
1128 1128 # HH n head merge: head count decreases
1129 1129
1130 1130 if not opts.get('close_branch'):
1131 1131 for r in parents:
1132 1132 if r.extra().get('close') and r.branch() == branch:
1133 1133 ui.status(_('reopening closed branch head %d\n') % r)
1134 1134
1135 1135 if ui.debugflag:
1136 1136 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
1137 1137 elif ui.verbose:
1138 1138 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
1139 1139
1140 1140 @command('copy|cp',
1141 1141 [('A', 'after', None, _('record a copy that has already occurred')),
1142 1142 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1143 1143 ] + walkopts + dryrunopts,
1144 1144 _('[OPTION]... [SOURCE]... DEST'))
1145 1145 def copy(ui, repo, *pats, **opts):
1146 1146 """mark files as copied for the next commit
1147 1147
1148 1148 Mark dest as having copies of source files. If dest is a
1149 1149 directory, copies are put in that directory. If dest is a file,
1150 1150 the source must be a single file.
1151 1151
1152 1152 By default, this command copies the contents of files as they
1153 1153 exist in the working directory. If invoked with -A/--after, the
1154 1154 operation is recorded, but no copying is performed.
1155 1155
1156 1156 This command takes effect with the next commit. To undo a copy
1157 1157 before that, see :hg:`revert`.
1158 1158
1159 1159 Returns 0 on success, 1 if errors are encountered.
1160 1160 """
1161 1161 wlock = repo.wlock(False)
1162 1162 try:
1163 1163 return cmdutil.copy(ui, repo, pats, opts)
1164 1164 finally:
1165 1165 wlock.release()
1166 1166
1167 1167 @command('debugancestor', [], _('[INDEX] REV1 REV2'))
1168 1168 def debugancestor(ui, repo, *args):
1169 1169 """find the ancestor revision of two revisions in a given index"""
1170 1170 if len(args) == 3:
1171 1171 index, rev1, rev2 = args
1172 1172 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
1173 1173 lookup = r.lookup
1174 1174 elif len(args) == 2:
1175 1175 if not repo:
1176 1176 raise util.Abort(_("there is no Mercurial repository here "
1177 1177 "(.hg not found)"))
1178 1178 rev1, rev2 = args
1179 1179 r = repo.changelog
1180 1180 lookup = repo.lookup
1181 1181 else:
1182 1182 raise util.Abort(_('either two or three arguments required'))
1183 1183 a = r.ancestor(lookup(rev1), lookup(rev2))
1184 1184 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1185 1185
1186 1186 @command('debugbuilddag',
1187 1187 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
1188 1188 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
1189 1189 ('n', 'new-file', None, _('add new file at each rev'))],
1190 1190 _('[OPTION]... [TEXT]'))
1191 1191 def debugbuilddag(ui, repo, text=None,
1192 1192 mergeable_file=False,
1193 1193 overwritten_file=False,
1194 1194 new_file=False):
1195 1195 """builds a repo with a given DAG from scratch in the current empty repo
1196 1196
1197 1197 The description of the DAG is read from stdin if not given on the
1198 1198 command line.
1199 1199
1200 1200 Elements:
1201 1201
1202 1202 - "+n" is a linear run of n nodes based on the current default parent
1203 1203 - "." is a single node based on the current default parent
1204 1204 - "$" resets the default parent to null (implied at the start);
1205 1205 otherwise the default parent is always the last node created
1206 1206 - "<p" sets the default parent to the backref p
1207 1207 - "*p" is a fork at parent p, which is a backref
1208 1208 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
1209 1209 - "/p2" is a merge of the preceding node and p2
1210 1210 - ":tag" defines a local tag for the preceding node
1211 1211 - "@branch" sets the named branch for subsequent nodes
1212 1212 - "#...\\n" is a comment up to the end of the line
1213 1213
1214 1214 Whitespace between the above elements is ignored.
1215 1215
1216 1216 A backref is either
1217 1217
1218 1218 - a number n, which references the node curr-n, where curr is the current
1219 1219 node, or
1220 1220 - the name of a local tag you placed earlier using ":tag", or
1221 1221 - empty to denote the default parent.
1222 1222
1223 1223 All string valued-elements are either strictly alphanumeric, or must
1224 1224 be enclosed in double quotes ("..."), with "\\" as escape character.
1225 1225 """
1226 1226
1227 1227 if text is None:
1228 1228 ui.status(_("reading DAG from stdin\n"))
1229 1229 text = sys.stdin.read()
1230 1230
1231 1231 cl = repo.changelog
1232 1232 if len(cl) > 0:
1233 1233 raise util.Abort(_('repository is not empty'))
1234 1234
1235 1235 # determine number of revs in DAG
1236 1236 total = 0
1237 1237 for type, data in dagparser.parsedag(text):
1238 1238 if type == 'n':
1239 1239 total += 1
1240 1240
1241 1241 if mergeable_file:
1242 1242 linesperrev = 2
1243 1243 # make a file with k lines per rev
1244 1244 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
1245 1245 initialmergedlines.append("")
1246 1246
1247 1247 tags = []
1248 1248
1249 1249 tr = repo.transaction("builddag")
1250 1250 try:
1251 1251
1252 1252 at = -1
1253 1253 atbranch = 'default'
1254 1254 nodeids = []
1255 1255 ui.progress(_('building'), 0, unit=_('revisions'), total=total)
1256 1256 for type, data in dagparser.parsedag(text):
1257 1257 if type == 'n':
1258 1258 ui.note('node %s\n' % str(data))
1259 1259 id, ps = data
1260 1260
1261 1261 files = []
1262 1262 fctxs = {}
1263 1263
1264 1264 p2 = None
1265 1265 if mergeable_file:
1266 1266 fn = "mf"
1267 1267 p1 = repo[ps[0]]
1268 1268 if len(ps) > 1:
1269 1269 p2 = repo[ps[1]]
1270 1270 pa = p1.ancestor(p2)
1271 1271 base, local, other = [x[fn].data() for x in pa, p1, p2]
1272 1272 m3 = simplemerge.Merge3Text(base, local, other)
1273 1273 ml = [l.strip() for l in m3.merge_lines()]
1274 1274 ml.append("")
1275 1275 elif at > 0:
1276 1276 ml = p1[fn].data().split("\n")
1277 1277 else:
1278 1278 ml = initialmergedlines
1279 1279 ml[id * linesperrev] += " r%i" % id
1280 1280 mergedtext = "\n".join(ml)
1281 1281 files.append(fn)
1282 1282 fctxs[fn] = context.memfilectx(fn, mergedtext)
1283 1283
1284 1284 if overwritten_file:
1285 1285 fn = "of"
1286 1286 files.append(fn)
1287 1287 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1288 1288
1289 1289 if new_file:
1290 1290 fn = "nf%i" % id
1291 1291 files.append(fn)
1292 1292 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1293 1293 if len(ps) > 1:
1294 1294 if not p2:
1295 1295 p2 = repo[ps[1]]
1296 1296 for fn in p2:
1297 1297 if fn.startswith("nf"):
1298 1298 files.append(fn)
1299 1299 fctxs[fn] = p2[fn]
1300 1300
1301 1301 def fctxfn(repo, cx, path):
1302 1302 return fctxs.get(path)
1303 1303
1304 1304 if len(ps) == 0 or ps[0] < 0:
1305 1305 pars = [None, None]
1306 1306 elif len(ps) == 1:
1307 1307 pars = [nodeids[ps[0]], None]
1308 1308 else:
1309 1309 pars = [nodeids[p] for p in ps]
1310 1310 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
1311 1311 date=(id, 0),
1312 1312 user="debugbuilddag",
1313 1313 extra={'branch': atbranch})
1314 1314 nodeid = repo.commitctx(cx)
1315 1315 nodeids.append(nodeid)
1316 1316 at = id
1317 1317 elif type == 'l':
1318 1318 id, name = data
1319 1319 ui.note('tag %s\n' % name)
1320 1320 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
1321 1321 elif type == 'a':
1322 1322 ui.note('branch %s\n' % data)
1323 1323 atbranch = data
1324 1324 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1325 1325 tr.close()
1326 1326 finally:
1327 1327 ui.progress(_('building'), None)
1328 1328 tr.release()
1329 1329
1330 1330 if tags:
1331 1331 repo.opener.write("localtags", "".join(tags))
1332 1332
1333 1333 @command('debugbundle', [('a', 'all', None, _('show all details'))], _('FILE'))
1334 1334 def debugbundle(ui, bundlepath, all=None, **opts):
1335 1335 """lists the contents of a bundle"""
1336 1336 f = url.open(ui, bundlepath)
1337 1337 try:
1338 1338 gen = changegroup.readbundle(f, bundlepath)
1339 1339 if all:
1340 1340 ui.write("format: id, p1, p2, cset, delta base, len(delta)\n")
1341 1341
1342 1342 def showchunks(named):
1343 1343 ui.write("\n%s\n" % named)
1344 1344 chain = None
1345 1345 while 1:
1346 1346 chunkdata = gen.deltachunk(chain)
1347 1347 if not chunkdata:
1348 1348 break
1349 1349 node = chunkdata['node']
1350 1350 p1 = chunkdata['p1']
1351 1351 p2 = chunkdata['p2']
1352 1352 cs = chunkdata['cs']
1353 1353 deltabase = chunkdata['deltabase']
1354 1354 delta = chunkdata['delta']
1355 1355 ui.write("%s %s %s %s %s %s\n" %
1356 1356 (hex(node), hex(p1), hex(p2),
1357 1357 hex(cs), hex(deltabase), len(delta)))
1358 1358 chain = node
1359 1359
1360 1360 chunkdata = gen.changelogheader()
1361 1361 showchunks("changelog")
1362 1362 chunkdata = gen.manifestheader()
1363 1363 showchunks("manifest")
1364 1364 while 1:
1365 1365 chunkdata = gen.filelogheader()
1366 1366 if not chunkdata:
1367 1367 break
1368 1368 fname = chunkdata['filename']
1369 1369 showchunks(fname)
1370 1370 else:
1371 1371 chunkdata = gen.changelogheader()
1372 1372 chain = None
1373 1373 while 1:
1374 1374 chunkdata = gen.deltachunk(chain)
1375 1375 if not chunkdata:
1376 1376 break
1377 1377 node = chunkdata['node']
1378 1378 ui.write("%s\n" % hex(node))
1379 1379 chain = node
1380 1380 finally:
1381 1381 f.close()
1382 1382
1383 1383 @command('debugcheckstate', [], '')
1384 1384 def debugcheckstate(ui, repo):
1385 1385 """validate the correctness of the current dirstate"""
1386 1386 parent1, parent2 = repo.dirstate.parents()
1387 1387 m1 = repo[parent1].manifest()
1388 1388 m2 = repo[parent2].manifest()
1389 1389 errors = 0
1390 1390 for f in repo.dirstate:
1391 1391 state = repo.dirstate[f]
1392 1392 if state in "nr" and f not in m1:
1393 1393 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1394 1394 errors += 1
1395 1395 if state in "a" and f in m1:
1396 1396 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1397 1397 errors += 1
1398 1398 if state in "m" and f not in m1 and f not in m2:
1399 1399 ui.warn(_("%s in state %s, but not in either manifest\n") %
1400 1400 (f, state))
1401 1401 errors += 1
1402 1402 for f in m1:
1403 1403 state = repo.dirstate[f]
1404 1404 if state not in "nrm":
1405 1405 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1406 1406 errors += 1
1407 1407 if errors:
1408 1408 error = _(".hg/dirstate inconsistent with current parent's manifest")
1409 1409 raise util.Abort(error)
1410 1410
1411 1411 @command('debugcommands', [], _('[COMMAND]'))
1412 1412 def debugcommands(ui, cmd='', *args):
1413 1413 """list all available commands and options"""
1414 1414 for cmd, vals in sorted(table.iteritems()):
1415 1415 cmd = cmd.split('|')[0].strip('^')
1416 1416 opts = ', '.join([i[1] for i in vals[1]])
1417 1417 ui.write('%s: %s\n' % (cmd, opts))
1418 1418
1419 1419 @command('debugcomplete',
1420 1420 [('o', 'options', None, _('show the command options'))],
1421 1421 _('[-o] CMD'))
1422 1422 def debugcomplete(ui, cmd='', **opts):
1423 1423 """returns the completion list associated with the given command"""
1424 1424
1425 1425 if opts.get('options'):
1426 1426 options = []
1427 1427 otables = [globalopts]
1428 1428 if cmd:
1429 1429 aliases, entry = cmdutil.findcmd(cmd, table, False)
1430 1430 otables.append(entry[1])
1431 1431 for t in otables:
1432 1432 for o in t:
1433 1433 if "(DEPRECATED)" in o[3]:
1434 1434 continue
1435 1435 if o[0]:
1436 1436 options.append('-%s' % o[0])
1437 1437 options.append('--%s' % o[1])
1438 1438 ui.write("%s\n" % "\n".join(options))
1439 1439 return
1440 1440
1441 1441 cmdlist = cmdutil.findpossible(cmd, table)
1442 1442 if ui.verbose:
1443 1443 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1444 1444 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1445 1445
1446 1446 @command('debugdag',
1447 1447 [('t', 'tags', None, _('use tags as labels')),
1448 1448 ('b', 'branches', None, _('annotate with branch names')),
1449 1449 ('', 'dots', None, _('use dots for runs')),
1450 1450 ('s', 'spaces', None, _('separate elements by spaces'))],
1451 1451 _('[OPTION]... [FILE [REV]...]'))
1452 1452 def debugdag(ui, repo, file_=None, *revs, **opts):
1453 1453 """format the changelog or an index DAG as a concise textual description
1454 1454
1455 1455 If you pass a revlog index, the revlog's DAG is emitted. If you list
1456 1456 revision numbers, they get labelled in the output as rN.
1457 1457
1458 1458 Otherwise, the changelog DAG of the current repo is emitted.
1459 1459 """
1460 1460 spaces = opts.get('spaces')
1461 1461 dots = opts.get('dots')
1462 1462 if file_:
1463 1463 rlog = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1464 1464 revs = set((int(r) for r in revs))
1465 1465 def events():
1466 1466 for r in rlog:
1467 1467 yield 'n', (r, list(set(p for p in rlog.parentrevs(r) if p != -1)))
1468 1468 if r in revs:
1469 1469 yield 'l', (r, "r%i" % r)
1470 1470 elif repo:
1471 1471 cl = repo.changelog
1472 1472 tags = opts.get('tags')
1473 1473 branches = opts.get('branches')
1474 1474 if tags:
1475 1475 labels = {}
1476 1476 for l, n in repo.tags().items():
1477 1477 labels.setdefault(cl.rev(n), []).append(l)
1478 1478 def events():
1479 1479 b = "default"
1480 1480 for r in cl:
1481 1481 if branches:
1482 1482 newb = cl.read(cl.node(r))[5]['branch']
1483 1483 if newb != b:
1484 1484 yield 'a', newb
1485 1485 b = newb
1486 1486 yield 'n', (r, list(set(p for p in cl.parentrevs(r) if p != -1)))
1487 1487 if tags:
1488 1488 ls = labels.get(r)
1489 1489 if ls:
1490 1490 for l in ls:
1491 1491 yield 'l', (r, l)
1492 1492 else:
1493 1493 raise util.Abort(_('need repo for changelog dag'))
1494 1494
1495 1495 for line in dagparser.dagtextlines(events(),
1496 1496 addspaces=spaces,
1497 1497 wraplabels=True,
1498 1498 wrapannotations=True,
1499 1499 wrapnonlinear=dots,
1500 1500 usedots=dots,
1501 1501 maxlinewidth=70):
1502 1502 ui.write(line)
1503 1503 ui.write("\n")
1504 1504
1505 1505 @command('debugdata',
1506 1506 [('c', 'changelog', False, _('open changelog')),
1507 1507 ('m', 'manifest', False, _('open manifest'))],
1508 1508 _('-c|-m|FILE REV'))
1509 1509 def debugdata(ui, repo, file_, rev = None, **opts):
1510 1510 """dump the contents of a data file revision"""
1511 1511 if opts.get('changelog') or opts.get('manifest'):
1512 1512 file_, rev = None, file_
1513 1513 elif rev is None:
1514 1514 raise error.CommandError('debugdata', _('invalid arguments'))
1515 1515 r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
1516 1516 try:
1517 1517 ui.write(r.revision(r.lookup(rev)))
1518 1518 except KeyError:
1519 1519 raise util.Abort(_('invalid revision identifier %s') % rev)
1520 1520
1521 1521 @command('debugdate',
1522 1522 [('e', 'extended', None, _('try extended date formats'))],
1523 1523 _('[-e] DATE [RANGE]'))
1524 1524 def debugdate(ui, date, range=None, **opts):
1525 1525 """parse and display a date"""
1526 1526 if opts["extended"]:
1527 1527 d = util.parsedate(date, util.extendeddateformats)
1528 1528 else:
1529 1529 d = util.parsedate(date)
1530 1530 ui.write("internal: %s %s\n" % d)
1531 1531 ui.write("standard: %s\n" % util.datestr(d))
1532 1532 if range:
1533 1533 m = util.matchdate(range)
1534 1534 ui.write("match: %s\n" % m(d[0]))
1535 1535
1536 1536 @command('debugdiscovery',
1537 1537 [('', 'old', None, _('use old-style discovery')),
1538 1538 ('', 'nonheads', None,
1539 1539 _('use old-style discovery with non-heads included')),
1540 1540 ] + remoteopts,
1541 1541 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
1542 1542 def debugdiscovery(ui, repo, remoteurl="default", **opts):
1543 1543 """runs the changeset discovery protocol in isolation"""
1544 1544 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl), opts.get('branch'))
1545 1545 remote = hg.repository(hg.remoteui(repo, opts), remoteurl)
1546 1546 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
1547 1547
1548 1548 # make sure tests are repeatable
1549 1549 random.seed(12323)
1550 1550
1551 1551 def doit(localheads, remoteheads):
1552 1552 if opts.get('old'):
1553 1553 if localheads:
1554 1554 raise util.Abort('cannot use localheads with old style discovery')
1555 1555 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
1556 1556 force=True)
1557 1557 common = set(common)
1558 1558 if not opts.get('nonheads'):
1559 1559 ui.write("unpruned common: %s\n" % " ".join([short(n)
1560 1560 for n in common]))
1561 1561 dag = dagutil.revlogdag(repo.changelog)
1562 1562 all = dag.ancestorset(dag.internalizeall(common))
1563 1563 common = dag.externalizeall(dag.headsetofconnecteds(all))
1564 1564 else:
1565 1565 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
1566 1566 common = set(common)
1567 1567 rheads = set(hds)
1568 1568 lheads = set(repo.heads())
1569 1569 ui.write("common heads: %s\n" % " ".join([short(n) for n in common]))
1570 1570 if lheads <= common:
1571 1571 ui.write("local is subset\n")
1572 1572 elif rheads <= common:
1573 1573 ui.write("remote is subset\n")
1574 1574
1575 1575 serverlogs = opts.get('serverlog')
1576 1576 if serverlogs:
1577 1577 for filename in serverlogs:
1578 1578 logfile = open(filename, 'r')
1579 1579 try:
1580 1580 line = logfile.readline()
1581 1581 while line:
1582 1582 parts = line.strip().split(';')
1583 1583 op = parts[1]
1584 1584 if op == 'cg':
1585 1585 pass
1586 1586 elif op == 'cgss':
1587 1587 doit(parts[2].split(' '), parts[3].split(' '))
1588 1588 elif op == 'unb':
1589 1589 doit(parts[3].split(' '), parts[2].split(' '))
1590 1590 line = logfile.readline()
1591 1591 finally:
1592 1592 logfile.close()
1593 1593
1594 1594 else:
1595 1595 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
1596 1596 opts.get('remote_head'))
1597 1597 localrevs = opts.get('local_head')
1598 1598 doit(localrevs, remoterevs)
1599 1599
1600 1600 @command('debugfsinfo', [], _('[PATH]'))
1601 1601 def debugfsinfo(ui, path = "."):
1602 1602 """show information detected about current filesystem"""
1603 1603 util.writefile('.debugfsinfo', '')
1604 1604 ui.write('exec: %s\n' % (util.checkexec(path) and 'yes' or 'no'))
1605 1605 ui.write('symlink: %s\n' % (util.checklink(path) and 'yes' or 'no'))
1606 1606 ui.write('case-sensitive: %s\n' % (util.checkcase('.debugfsinfo')
1607 1607 and 'yes' or 'no'))
1608 1608 os.unlink('.debugfsinfo')
1609 1609
1610 1610 @command('debuggetbundle',
1611 1611 [('H', 'head', [], _('id of head node'), _('ID')),
1612 1612 ('C', 'common', [], _('id of common node'), _('ID')),
1613 1613 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
1614 1614 _('REPO FILE [-H|-C ID]...'))
1615 1615 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
1616 1616 """retrieves a bundle from a repo
1617 1617
1618 1618 Every ID must be a full-length hex node id string. Saves the bundle to the
1619 1619 given file.
1620 1620 """
1621 1621 repo = hg.repository(ui, repopath)
1622 1622 if not repo.capable('getbundle'):
1623 1623 raise util.Abort("getbundle() not supported by target repository")
1624 1624 args = {}
1625 1625 if common:
1626 1626 args['common'] = [bin(s) for s in common]
1627 1627 if head:
1628 1628 args['heads'] = [bin(s) for s in head]
1629 1629 bundle = repo.getbundle('debug', **args)
1630 1630
1631 1631 bundletype = opts.get('type', 'bzip2').lower()
1632 1632 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1633 1633 bundletype = btypes.get(bundletype)
1634 1634 if bundletype not in changegroup.bundletypes:
1635 1635 raise util.Abort(_('unknown bundle type specified with --type'))
1636 1636 changegroup.writebundle(bundle, bundlepath, bundletype)
1637 1637
1638 1638 @command('debugignore', [], '')
1639 1639 def debugignore(ui, repo, *values, **opts):
1640 1640 """display the combined ignore pattern"""
1641 1641 ignore = repo.dirstate._ignore
1642 1642 if hasattr(ignore, 'includepat'):
1643 1643 ui.write("%s\n" % ignore.includepat)
1644 1644 else:
1645 1645 raise util.Abort(_("no ignore patterns found"))
1646 1646
1647 1647 @command('debugindex',
1648 1648 [('c', 'changelog', False, _('open changelog')),
1649 1649 ('m', 'manifest', False, _('open manifest')),
1650 1650 ('f', 'format', 0, _('revlog format'), _('FORMAT'))],
1651 1651 _('[-f FORMAT] -c|-m|FILE'))
1652 1652 def debugindex(ui, repo, file_ = None, **opts):
1653 1653 """dump the contents of an index file"""
1654 1654 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
1655 1655 format = opts.get('format', 0)
1656 1656 if format not in (0, 1):
1657 1657 raise util.Abort(_("unknown format %d") % format)
1658 1658
1659 1659 generaldelta = r.version & revlog.REVLOGGENERALDELTA
1660 1660 if generaldelta:
1661 1661 basehdr = ' delta'
1662 1662 else:
1663 1663 basehdr = ' base'
1664 1664
1665 1665 if format == 0:
1666 1666 ui.write(" rev offset length " + basehdr + " linkrev"
1667 1667 " nodeid p1 p2\n")
1668 1668 elif format == 1:
1669 1669 ui.write(" rev flag offset length"
1670 1670 " size " + basehdr + " link p1 p2 nodeid\n")
1671 1671
1672 1672 for i in r:
1673 1673 node = r.node(i)
1674 1674 if generaldelta:
1675 1675 base = r.deltaparent(i)
1676 1676 else:
1677 1677 base = r.chainbase(i)
1678 1678 if format == 0:
1679 1679 try:
1680 1680 pp = r.parents(node)
1681 1681 except:
1682 1682 pp = [nullid, nullid]
1683 1683 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
1684 1684 i, r.start(i), r.length(i), base, r.linkrev(i),
1685 1685 short(node), short(pp[0]), short(pp[1])))
1686 1686 elif format == 1:
1687 1687 pr = r.parentrevs(i)
1688 1688 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
1689 1689 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
1690 1690 base, r.linkrev(i), pr[0], pr[1], short(node)))
1691 1691
1692 1692 @command('debugindexdot', [], _('FILE'))
1693 1693 def debugindexdot(ui, repo, file_):
1694 1694 """dump an index DAG as a graphviz dot file"""
1695 1695 r = None
1696 1696 if repo:
1697 1697 filelog = repo.file(file_)
1698 1698 if len(filelog):
1699 1699 r = filelog
1700 1700 if not r:
1701 1701 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1702 1702 ui.write("digraph G {\n")
1703 1703 for i in r:
1704 1704 node = r.node(i)
1705 1705 pp = r.parents(node)
1706 1706 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
1707 1707 if pp[1] != nullid:
1708 1708 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
1709 1709 ui.write("}\n")
1710 1710
1711 1711 @command('debuginstall', [], '')
1712 1712 def debuginstall(ui):
1713 1713 '''test Mercurial installation
1714 1714
1715 1715 Returns 0 on success.
1716 1716 '''
1717 1717
1718 1718 def writetemp(contents):
1719 1719 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
1720 1720 f = os.fdopen(fd, "wb")
1721 1721 f.write(contents)
1722 1722 f.close()
1723 1723 return name
1724 1724
1725 1725 problems = 0
1726 1726
1727 1727 # encoding
1728 1728 ui.status(_("Checking encoding (%s)...\n") % encoding.encoding)
1729 1729 try:
1730 1730 encoding.fromlocal("test")
1731 1731 except util.Abort, inst:
1732 1732 ui.write(" %s\n" % inst)
1733 1733 ui.write(_(" (check that your locale is properly set)\n"))
1734 1734 problems += 1
1735 1735
1736 1736 # compiled modules
1737 1737 ui.status(_("Checking installed modules (%s)...\n")
1738 1738 % os.path.dirname(__file__))
1739 1739 try:
1740 1740 import bdiff, mpatch, base85, osutil
1741 1741 except Exception, inst:
1742 1742 ui.write(" %s\n" % inst)
1743 1743 ui.write(_(" One or more extensions could not be found"))
1744 1744 ui.write(_(" (check that you compiled the extensions)\n"))
1745 1745 problems += 1
1746 1746
1747 1747 # templates
1748 1748 ui.status(_("Checking templates...\n"))
1749 1749 try:
1750 1750 import templater
1751 1751 templater.templater(templater.templatepath("map-cmdline.default"))
1752 1752 except Exception, inst:
1753 1753 ui.write(" %s\n" % inst)
1754 1754 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
1755 1755 problems += 1
1756 1756
1757 1757 # editor
1758 1758 ui.status(_("Checking commit editor...\n"))
1759 1759 editor = ui.geteditor()
1760 1760 cmdpath = util.findexe(editor) or util.findexe(editor.split()[0])
1761 1761 if not cmdpath:
1762 1762 if editor == 'vi':
1763 1763 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
1764 1764 ui.write(_(" (specify a commit editor in your configuration"
1765 1765 " file)\n"))
1766 1766 else:
1767 1767 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
1768 1768 ui.write(_(" (specify a commit editor in your configuration"
1769 1769 " file)\n"))
1770 1770 problems += 1
1771 1771
1772 1772 # check username
1773 1773 ui.status(_("Checking username...\n"))
1774 1774 try:
1775 1775 ui.username()
1776 1776 except util.Abort, e:
1777 1777 ui.write(" %s\n" % e)
1778 1778 ui.write(_(" (specify a username in your configuration file)\n"))
1779 1779 problems += 1
1780 1780
1781 1781 if not problems:
1782 1782 ui.status(_("No problems detected\n"))
1783 1783 else:
1784 1784 ui.write(_("%s problems detected,"
1785 1785 " please check your install!\n") % problems)
1786 1786
1787 1787 return problems
1788 1788
1789 1789 @command('debugknown', [], _('REPO ID...'))
1790 1790 def debugknown(ui, repopath, *ids, **opts):
1791 1791 """test whether node ids are known to a repo
1792 1792
1793 1793 Every ID must be a full-length hex node id string. Returns a list of 0s and 1s
1794 1794 indicating unknown/known.
1795 1795 """
1796 1796 repo = hg.repository(ui, repopath)
1797 1797 if not repo.capable('known'):
1798 1798 raise util.Abort("known() not supported by target repository")
1799 1799 flags = repo.known([bin(s) for s in ids])
1800 1800 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
1801 1801
1802 1802 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'))
1803 1803 def debugpushkey(ui, repopath, namespace, *keyinfo):
1804 1804 '''access the pushkey key/value protocol
1805 1805
1806 1806 With two args, list the keys in the given namespace.
1807 1807
1808 1808 With five args, set a key to new if it currently is set to old.
1809 1809 Reports success or failure.
1810 1810 '''
1811 1811
1812 1812 target = hg.repository(ui, repopath)
1813 1813 if keyinfo:
1814 1814 key, old, new = keyinfo
1815 1815 r = target.pushkey(namespace, key, old, new)
1816 1816 ui.status(str(r) + '\n')
1817 1817 return not r
1818 1818 else:
1819 1819 for k, v in target.listkeys(namespace).iteritems():
1820 1820 ui.write("%s\t%s\n" % (k.encode('string-escape'),
1821 1821 v.encode('string-escape')))
1822 1822
1823 1823 @command('debugrebuildstate',
1824 1824 [('r', 'rev', '', _('revision to rebuild to'), _('REV'))],
1825 1825 _('[-r REV] [REV]'))
1826 1826 def debugrebuildstate(ui, repo, rev="tip"):
1827 1827 """rebuild the dirstate as it would look like for the given revision"""
1828 1828 ctx = scmutil.revsingle(repo, rev)
1829 1829 wlock = repo.wlock()
1830 1830 try:
1831 1831 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1832 1832 finally:
1833 1833 wlock.release()
1834 1834
1835 1835 @command('debugrename',
1836 1836 [('r', 'rev', '', _('revision to debug'), _('REV'))],
1837 1837 _('[-r REV] FILE'))
1838 1838 def debugrename(ui, repo, file1, *pats, **opts):
1839 1839 """dump rename information"""
1840 1840
1841 1841 ctx = scmutil.revsingle(repo, opts.get('rev'))
1842 1842 m = scmutil.match(repo, (file1,) + pats, opts)
1843 1843 for abs in ctx.walk(m):
1844 1844 fctx = ctx[abs]
1845 1845 o = fctx.filelog().renamed(fctx.filenode())
1846 1846 rel = m.rel(abs)
1847 1847 if o:
1848 1848 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
1849 1849 else:
1850 1850 ui.write(_("%s not renamed\n") % rel)
1851 1851
1852 1852 @command('debugrevlog',
1853 1853 [('c', 'changelog', False, _('open changelog')),
1854 1854 ('m', 'manifest', False, _('open manifest')),
1855 1855 ('d', 'dump', False, _('dump index data'))],
1856 1856 _('-c|-m|FILE'))
1857 1857 def debugrevlog(ui, repo, file_ = None, **opts):
1858 1858 """show data and statistics about a revlog"""
1859 1859 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
1860 1860
1861 1861 if opts.get("dump"):
1862 1862 numrevs = len(r)
1863 1863 ui.write("# rev p1rev p2rev start end deltastart base p1 p2"
1864 1864 " rawsize totalsize compression heads\n")
1865 1865 ts = 0
1866 1866 heads = set()
1867 1867 for rev in xrange(numrevs):
1868 1868 dbase = r.deltaparent(rev)
1869 1869 if dbase == -1:
1870 1870 dbase = rev
1871 1871 cbase = r.chainbase(rev)
1872 1872 p1, p2 = r.parentrevs(rev)
1873 1873 rs = r.rawsize(rev)
1874 1874 ts = ts + rs
1875 1875 heads -= set(r.parentrevs(rev))
1876 1876 heads.add(rev)
1877 1877 ui.write("%d %d %d %d %d %d %d %d %d %d %d %d %d\n" %
1878 1878 (rev, p1, p2, r.start(rev), r.end(rev),
1879 1879 r.start(dbase), r.start(cbase),
1880 1880 r.start(p1), r.start(p2),
1881 1881 rs, ts, ts / r.end(rev), len(heads)))
1882 1882 return 0
1883 1883
1884 1884 v = r.version
1885 1885 format = v & 0xFFFF
1886 1886 flags = []
1887 1887 gdelta = False
1888 1888 if v & revlog.REVLOGNGINLINEDATA:
1889 1889 flags.append('inline')
1890 1890 if v & revlog.REVLOGGENERALDELTA:
1891 1891 gdelta = True
1892 1892 flags.append('generaldelta')
1893 1893 if not flags:
1894 1894 flags = ['(none)']
1895 1895
1896 1896 nummerges = 0
1897 1897 numfull = 0
1898 1898 numprev = 0
1899 1899 nump1 = 0
1900 1900 nump2 = 0
1901 1901 numother = 0
1902 1902 nump1prev = 0
1903 1903 nump2prev = 0
1904 1904 chainlengths = []
1905 1905
1906 1906 datasize = [None, 0, 0L]
1907 1907 fullsize = [None, 0, 0L]
1908 1908 deltasize = [None, 0, 0L]
1909 1909
1910 1910 def addsize(size, l):
1911 1911 if l[0] is None or size < l[0]:
1912 1912 l[0] = size
1913 1913 if size > l[1]:
1914 1914 l[1] = size
1915 1915 l[2] += size
1916 1916
1917 1917 numrevs = len(r)
1918 1918 for rev in xrange(numrevs):
1919 1919 p1, p2 = r.parentrevs(rev)
1920 1920 delta = r.deltaparent(rev)
1921 1921 if format > 0:
1922 1922 addsize(r.rawsize(rev), datasize)
1923 1923 if p2 != nullrev:
1924 1924 nummerges += 1
1925 1925 size = r.length(rev)
1926 1926 if delta == nullrev:
1927 1927 chainlengths.append(0)
1928 1928 numfull += 1
1929 1929 addsize(size, fullsize)
1930 1930 else:
1931 1931 chainlengths.append(chainlengths[delta] + 1)
1932 1932 addsize(size, deltasize)
1933 1933 if delta == rev - 1:
1934 1934 numprev += 1
1935 1935 if delta == p1:
1936 1936 nump1prev += 1
1937 1937 elif delta == p2:
1938 1938 nump2prev += 1
1939 1939 elif delta == p1:
1940 1940 nump1 += 1
1941 1941 elif delta == p2:
1942 1942 nump2 += 1
1943 1943 elif delta != nullrev:
1944 1944 numother += 1
1945 1945
1946 1946 numdeltas = numrevs - numfull
1947 1947 numoprev = numprev - nump1prev - nump2prev
1948 1948 totalrawsize = datasize[2]
1949 1949 datasize[2] /= numrevs
1950 1950 fulltotal = fullsize[2]
1951 1951 fullsize[2] /= numfull
1952 1952 deltatotal = deltasize[2]
1953 1953 deltasize[2] /= numrevs - numfull
1954 1954 totalsize = fulltotal + deltatotal
1955 1955 avgchainlen = sum(chainlengths) / numrevs
1956 1956 compratio = totalrawsize / totalsize
1957 1957
1958 1958 basedfmtstr = '%%%dd\n'
1959 1959 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
1960 1960
1961 1961 def dfmtstr(max):
1962 1962 return basedfmtstr % len(str(max))
1963 1963 def pcfmtstr(max, padding=0):
1964 1964 return basepcfmtstr % (len(str(max)), ' ' * padding)
1965 1965
1966 1966 def pcfmt(value, total):
1967 1967 return (value, 100 * float(value) / total)
1968 1968
1969 1969 ui.write('format : %d\n' % format)
1970 1970 ui.write('flags : %s\n' % ', '.join(flags))
1971 1971
1972 1972 ui.write('\n')
1973 1973 fmt = pcfmtstr(totalsize)
1974 1974 fmt2 = dfmtstr(totalsize)
1975 1975 ui.write('revisions : ' + fmt2 % numrevs)
1976 1976 ui.write(' merges : ' + fmt % pcfmt(nummerges, numrevs))
1977 1977 ui.write(' normal : ' + fmt % pcfmt(numrevs - nummerges, numrevs))
1978 1978 ui.write('revisions : ' + fmt2 % numrevs)
1979 1979 ui.write(' full : ' + fmt % pcfmt(numfull, numrevs))
1980 1980 ui.write(' deltas : ' + fmt % pcfmt(numdeltas, numrevs))
1981 1981 ui.write('revision size : ' + fmt2 % totalsize)
1982 1982 ui.write(' full : ' + fmt % pcfmt(fulltotal, totalsize))
1983 1983 ui.write(' deltas : ' + fmt % pcfmt(deltatotal, totalsize))
1984 1984
1985 1985 ui.write('\n')
1986 1986 fmt = dfmtstr(max(avgchainlen, compratio))
1987 1987 ui.write('avg chain length : ' + fmt % avgchainlen)
1988 1988 ui.write('compression ratio : ' + fmt % compratio)
1989 1989
1990 1990 if format > 0:
1991 1991 ui.write('\n')
1992 1992 ui.write('uncompressed data size (min/max/avg) : %d / %d / %d\n'
1993 1993 % tuple(datasize))
1994 1994 ui.write('full revision size (min/max/avg) : %d / %d / %d\n'
1995 1995 % tuple(fullsize))
1996 1996 ui.write('delta size (min/max/avg) : %d / %d / %d\n'
1997 1997 % tuple(deltasize))
1998 1998
1999 1999 if numdeltas > 0:
2000 2000 ui.write('\n')
2001 2001 fmt = pcfmtstr(numdeltas)
2002 2002 fmt2 = pcfmtstr(numdeltas, 4)
2003 2003 ui.write('deltas against prev : ' + fmt % pcfmt(numprev, numdeltas))
2004 2004 if numprev > 0:
2005 2005 ui.write(' where prev = p1 : ' + fmt2 % pcfmt(nump1prev, numprev))
2006 2006 ui.write(' where prev = p2 : ' + fmt2 % pcfmt(nump2prev, numprev))
2007 2007 ui.write(' other : ' + fmt2 % pcfmt(numoprev, numprev))
2008 2008 if gdelta:
2009 2009 ui.write('deltas against p1 : ' + fmt % pcfmt(nump1, numdeltas))
2010 2010 ui.write('deltas against p2 : ' + fmt % pcfmt(nump2, numdeltas))
2011 2011 ui.write('deltas against other : ' + fmt % pcfmt(numother, numdeltas))
2012 2012
2013 2013 @command('debugrevspec', [], ('REVSPEC'))
2014 2014 def debugrevspec(ui, repo, expr):
2015 2015 '''parse and apply a revision specification'''
2016 2016 if ui.verbose:
2017 2017 tree = revset.parse(expr)[0]
2018 2018 ui.note(tree, "\n")
2019 2019 newtree = revset.findaliases(ui, tree)
2020 2020 if newtree != tree:
2021 2021 ui.note(newtree, "\n")
2022 2022 func = revset.match(ui, expr)
2023 2023 for c in func(repo, range(len(repo))):
2024 2024 ui.write("%s\n" % c)
2025 2025
2026 2026 @command('debugsetparents', [], _('REV1 [REV2]'))
2027 2027 def debugsetparents(ui, repo, rev1, rev2=None):
2028 2028 """manually set the parents of the current working directory
2029 2029
2030 2030 This is useful for writing repository conversion tools, but should
2031 2031 be used with care.
2032 2032
2033 2033 Returns 0 on success.
2034 2034 """
2035 2035
2036 2036 r1 = scmutil.revsingle(repo, rev1).node()
2037 2037 r2 = scmutil.revsingle(repo, rev2, 'null').node()
2038 2038
2039 2039 wlock = repo.wlock()
2040 2040 try:
2041 2041 repo.dirstate.setparents(r1, r2)
2042 2042 finally:
2043 2043 wlock.release()
2044 2044
2045 2045 @command('debugstate',
2046 2046 [('', 'nodates', None, _('do not display the saved mtime')),
2047 2047 ('', 'datesort', None, _('sort by saved mtime'))],
2048 2048 _('[OPTION]...'))
2049 2049 def debugstate(ui, repo, nodates=None, datesort=None):
2050 2050 """show the contents of the current dirstate"""
2051 2051 timestr = ""
2052 2052 showdate = not nodates
2053 2053 if datesort:
2054 2054 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
2055 2055 else:
2056 2056 keyfunc = None # sort by filename
2057 2057 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
2058 2058 if showdate:
2059 2059 if ent[3] == -1:
2060 2060 # Pad or slice to locale representation
2061 2061 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
2062 2062 time.localtime(0)))
2063 2063 timestr = 'unset'
2064 2064 timestr = (timestr[:locale_len] +
2065 2065 ' ' * (locale_len - len(timestr)))
2066 2066 else:
2067 2067 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
2068 2068 time.localtime(ent[3]))
2069 2069 if ent[1] & 020000:
2070 2070 mode = 'lnk'
2071 2071 else:
2072 2072 mode = '%3o' % (ent[1] & 0777)
2073 2073 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
2074 2074 for f in repo.dirstate.copies():
2075 2075 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
2076 2076
2077 2077 @command('debugsub',
2078 2078 [('r', 'rev', '',
2079 2079 _('revision to check'), _('REV'))],
2080 2080 _('[-r REV] [REV]'))
2081 2081 def debugsub(ui, repo, rev=None):
2082 2082 ctx = scmutil.revsingle(repo, rev, None)
2083 2083 for k, v in sorted(ctx.substate.items()):
2084 2084 ui.write('path %s\n' % k)
2085 2085 ui.write(' source %s\n' % v[0])
2086 2086 ui.write(' revision %s\n' % v[1])
2087 2087
2088 2088 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'))
2089 2089 def debugwalk(ui, repo, *pats, **opts):
2090 2090 """show how files match on given patterns"""
2091 2091 m = scmutil.match(repo, pats, opts)
2092 2092 items = list(repo.walk(m))
2093 2093 if not items:
2094 2094 return
2095 2095 fmt = 'f %%-%ds %%-%ds %%s' % (
2096 2096 max([len(abs) for abs in items]),
2097 2097 max([len(m.rel(abs)) for abs in items]))
2098 2098 for abs in items:
2099 2099 line = fmt % (abs, m.rel(abs), m.exact(abs) and 'exact' or '')
2100 2100 ui.write("%s\n" % line.rstrip())
2101 2101
2102 2102 @command('debugwireargs',
2103 2103 [('', 'three', '', 'three'),
2104 2104 ('', 'four', '', 'four'),
2105 2105 ('', 'five', '', 'five'),
2106 2106 ] + remoteopts,
2107 2107 _('REPO [OPTIONS]... [ONE [TWO]]'))
2108 2108 def debugwireargs(ui, repopath, *vals, **opts):
2109 2109 repo = hg.repository(hg.remoteui(ui, opts), repopath)
2110 2110 for opt in remoteopts:
2111 2111 del opts[opt[1]]
2112 2112 args = {}
2113 2113 for k, v in opts.iteritems():
2114 2114 if v:
2115 2115 args[k] = v
2116 2116 # run twice to check that we don't mess up the stream for the next command
2117 2117 res1 = repo.debugwireargs(*vals, **args)
2118 2118 res2 = repo.debugwireargs(*vals, **args)
2119 2119 ui.write("%s\n" % res1)
2120 2120 if res1 != res2:
2121 2121 ui.warn("%s\n" % res2)
2122 2122
2123 2123 @command('^diff',
2124 2124 [('r', 'rev', [], _('revision'), _('REV')),
2125 2125 ('c', 'change', '', _('change made by revision'), _('REV'))
2126 2126 ] + diffopts + diffopts2 + walkopts + subrepoopts,
2127 2127 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'))
2128 2128 def diff(ui, repo, *pats, **opts):
2129 2129 """diff repository (or selected files)
2130 2130
2131 2131 Show differences between revisions for the specified files.
2132 2132
2133 2133 Differences between files are shown using the unified diff format.
2134 2134
2135 2135 .. note::
2136 2136 diff may generate unexpected results for merges, as it will
2137 2137 default to comparing against the working directory's first
2138 2138 parent changeset if no revisions are specified.
2139 2139
2140 2140 When two revision arguments are given, then changes are shown
2141 2141 between those revisions. If only one revision is specified then
2142 2142 that revision is compared to the working directory, and, when no
2143 2143 revisions are specified, the working directory files are compared
2144 2144 to its parent.
2145 2145
2146 2146 Alternatively you can specify -c/--change with a revision to see
2147 2147 the changes in that changeset relative to its first parent.
2148 2148
2149 2149 Without the -a/--text option, diff will avoid generating diffs of
2150 2150 files it detects as binary. With -a, diff will generate a diff
2151 2151 anyway, probably with undesirable results.
2152 2152
2153 2153 Use the -g/--git option to generate diffs in the git extended diff
2154 2154 format. For more information, read :hg:`help diffs`.
2155 2155
2156 2156 Returns 0 on success.
2157 2157 """
2158 2158
2159 2159 revs = opts.get('rev')
2160 2160 change = opts.get('change')
2161 2161 stat = opts.get('stat')
2162 2162 reverse = opts.get('reverse')
2163 2163
2164 2164 if revs and change:
2165 2165 msg = _('cannot specify --rev and --change at the same time')
2166 2166 raise util.Abort(msg)
2167 2167 elif change:
2168 2168 node2 = scmutil.revsingle(repo, change, None).node()
2169 2169 node1 = repo[node2].p1().node()
2170 2170 else:
2171 2171 node1, node2 = scmutil.revpair(repo, revs)
2172 2172
2173 2173 if reverse:
2174 2174 node1, node2 = node2, node1
2175 2175
2176 2176 diffopts = patch.diffopts(ui, opts)
2177 2177 m = scmutil.match(repo, pats, opts)
2178 2178 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
2179 2179 listsubrepos=opts.get('subrepos'))
2180 2180
2181 2181 @command('^export',
2182 2182 [('o', 'output', '',
2183 2183 _('print output to file with formatted name'), _('FORMAT')),
2184 2184 ('', 'switch-parent', None, _('diff against the second parent')),
2185 2185 ('r', 'rev', [], _('revisions to export'), _('REV')),
2186 2186 ] + diffopts,
2187 2187 _('[OPTION]... [-o OUTFILESPEC] REV...'))
2188 2188 def export(ui, repo, *changesets, **opts):
2189 2189 """dump the header and diffs for one or more changesets
2190 2190
2191 2191 Print the changeset header and diffs for one or more revisions.
2192 2192
2193 2193 The information shown in the changeset header is: author, date,
2194 2194 branch name (if non-default), changeset hash, parent(s) and commit
2195 2195 comment.
2196 2196
2197 2197 .. note::
2198 2198 export may generate unexpected diff output for merge
2199 2199 changesets, as it will compare the merge changeset against its
2200 2200 first parent only.
2201 2201
2202 2202 Output may be to a file, in which case the name of the file is
2203 2203 given using a format string. The formatting rules are as follows:
2204 2204
2205 2205 :``%%``: literal "%" character
2206 2206 :``%H``: changeset hash (40 hexadecimal digits)
2207 2207 :``%N``: number of patches being generated
2208 2208 :``%R``: changeset revision number
2209 2209 :``%b``: basename of the exporting repository
2210 2210 :``%h``: short-form changeset hash (12 hexadecimal digits)
2211 2211 :``%n``: zero-padded sequence number, starting at 1
2212 2212 :``%r``: zero-padded changeset revision number
2213 2213
2214 2214 Without the -a/--text option, export will avoid generating diffs
2215 2215 of files it detects as binary. With -a, export will generate a
2216 2216 diff anyway, probably with undesirable results.
2217 2217
2218 2218 Use the -g/--git option to generate diffs in the git extended diff
2219 2219 format. See :hg:`help diffs` for more information.
2220 2220
2221 2221 With the --switch-parent option, the diff will be against the
2222 2222 second parent. It can be useful to review a merge.
2223 2223
2224 2224 Returns 0 on success.
2225 2225 """
2226 2226 changesets += tuple(opts.get('rev', []))
2227 2227 if not changesets:
2228 2228 raise util.Abort(_("export requires at least one changeset"))
2229 2229 revs = scmutil.revrange(repo, changesets)
2230 2230 if len(revs) > 1:
2231 2231 ui.note(_('exporting patches:\n'))
2232 2232 else:
2233 2233 ui.note(_('exporting patch:\n'))
2234 2234 cmdutil.export(repo, revs, template=opts.get('output'),
2235 2235 switch_parent=opts.get('switch_parent'),
2236 2236 opts=patch.diffopts(ui, opts))
2237 2237
2238 2238 @command('^forget', walkopts, _('[OPTION]... FILE...'))
2239 2239 def forget(ui, repo, *pats, **opts):
2240 2240 """forget the specified files on the next commit
2241 2241
2242 2242 Mark the specified files so they will no longer be tracked
2243 2243 after the next commit.
2244 2244
2245 2245 This only removes files from the current branch, not from the
2246 2246 entire project history, and it does not delete them from the
2247 2247 working directory.
2248 2248
2249 2249 To undo a forget before the next commit, see :hg:`add`.
2250 2250
2251 2251 Returns 0 on success.
2252 2252 """
2253 2253
2254 2254 if not pats:
2255 2255 raise util.Abort(_('no files specified'))
2256 2256
2257 2257 m = scmutil.match(repo, pats, opts)
2258 2258 s = repo.status(match=m, clean=True)
2259 2259 forget = sorted(s[0] + s[1] + s[3] + s[6])
2260 2260 errs = 0
2261 2261
2262 2262 for f in m.files():
2263 2263 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
2264 2264 ui.warn(_('not removing %s: file is already untracked\n')
2265 2265 % m.rel(f))
2266 2266 errs = 1
2267 2267
2268 2268 for f in forget:
2269 2269 if ui.verbose or not m.exact(f):
2270 2270 ui.status(_('removing %s\n') % m.rel(f))
2271 2271
2272 repo[None].remove(forget, unlink=False)
2272 repo[None].forget(forget)
2273 2273 return errs
2274 2274
2275 2275 @command('grep',
2276 2276 [('0', 'print0', None, _('end fields with NUL')),
2277 2277 ('', 'all', None, _('print all revisions that match')),
2278 2278 ('a', 'text', None, _('treat all files as text')),
2279 2279 ('f', 'follow', None,
2280 2280 _('follow changeset history,'
2281 2281 ' or file history across copies and renames')),
2282 2282 ('i', 'ignore-case', None, _('ignore case when matching')),
2283 2283 ('l', 'files-with-matches', None,
2284 2284 _('print only filenames and revisions that match')),
2285 2285 ('n', 'line-number', None, _('print matching line numbers')),
2286 2286 ('r', 'rev', [],
2287 2287 _('only search files changed within revision range'), _('REV')),
2288 2288 ('u', 'user', None, _('list the author (long with -v)')),
2289 2289 ('d', 'date', None, _('list the date (short with -q)')),
2290 2290 ] + walkopts,
2291 2291 _('[OPTION]... PATTERN [FILE]...'))
2292 2292 def grep(ui, repo, pattern, *pats, **opts):
2293 2293 """search for a pattern in specified files and revisions
2294 2294
2295 2295 Search revisions of files for a regular expression.
2296 2296
2297 2297 This command behaves differently than Unix grep. It only accepts
2298 2298 Python/Perl regexps. It searches repository history, not the
2299 2299 working directory. It always prints the revision number in which a
2300 2300 match appears.
2301 2301
2302 2302 By default, grep only prints output for the first revision of a
2303 2303 file in which it finds a match. To get it to print every revision
2304 2304 that contains a change in match status ("-" for a match that
2305 2305 becomes a non-match, or "+" for a non-match that becomes a match),
2306 2306 use the --all flag.
2307 2307
2308 2308 Returns 0 if a match is found, 1 otherwise.
2309 2309 """
2310 2310 reflags = 0
2311 2311 if opts.get('ignore_case'):
2312 2312 reflags |= re.I
2313 2313 try:
2314 2314 regexp = re.compile(pattern, reflags)
2315 2315 except re.error, inst:
2316 2316 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
2317 2317 return 1
2318 2318 sep, eol = ':', '\n'
2319 2319 if opts.get('print0'):
2320 2320 sep = eol = '\0'
2321 2321
2322 2322 getfile = util.lrucachefunc(repo.file)
2323 2323
2324 2324 def matchlines(body):
2325 2325 begin = 0
2326 2326 linenum = 0
2327 2327 while True:
2328 2328 match = regexp.search(body, begin)
2329 2329 if not match:
2330 2330 break
2331 2331 mstart, mend = match.span()
2332 2332 linenum += body.count('\n', begin, mstart) + 1
2333 2333 lstart = body.rfind('\n', begin, mstart) + 1 or begin
2334 2334 begin = body.find('\n', mend) + 1 or len(body)
2335 2335 lend = begin - 1
2336 2336 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
2337 2337
2338 2338 class linestate(object):
2339 2339 def __init__(self, line, linenum, colstart, colend):
2340 2340 self.line = line
2341 2341 self.linenum = linenum
2342 2342 self.colstart = colstart
2343 2343 self.colend = colend
2344 2344
2345 2345 def __hash__(self):
2346 2346 return hash((self.linenum, self.line))
2347 2347
2348 2348 def __eq__(self, other):
2349 2349 return self.line == other.line
2350 2350
2351 2351 matches = {}
2352 2352 copies = {}
2353 2353 def grepbody(fn, rev, body):
2354 2354 matches[rev].setdefault(fn, [])
2355 2355 m = matches[rev][fn]
2356 2356 for lnum, cstart, cend, line in matchlines(body):
2357 2357 s = linestate(line, lnum, cstart, cend)
2358 2358 m.append(s)
2359 2359
2360 2360 def difflinestates(a, b):
2361 2361 sm = difflib.SequenceMatcher(None, a, b)
2362 2362 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2363 2363 if tag == 'insert':
2364 2364 for i in xrange(blo, bhi):
2365 2365 yield ('+', b[i])
2366 2366 elif tag == 'delete':
2367 2367 for i in xrange(alo, ahi):
2368 2368 yield ('-', a[i])
2369 2369 elif tag == 'replace':
2370 2370 for i in xrange(alo, ahi):
2371 2371 yield ('-', a[i])
2372 2372 for i in xrange(blo, bhi):
2373 2373 yield ('+', b[i])
2374 2374
2375 2375 def display(fn, ctx, pstates, states):
2376 2376 rev = ctx.rev()
2377 2377 datefunc = ui.quiet and util.shortdate or util.datestr
2378 2378 found = False
2379 2379 filerevmatches = {}
2380 2380 def binary():
2381 2381 flog = getfile(fn)
2382 2382 return util.binary(flog.read(ctx.filenode(fn)))
2383 2383
2384 2384 if opts.get('all'):
2385 2385 iter = difflinestates(pstates, states)
2386 2386 else:
2387 2387 iter = [('', l) for l in states]
2388 2388 for change, l in iter:
2389 2389 cols = [fn, str(rev)]
2390 2390 before, match, after = None, None, None
2391 2391 if opts.get('line_number'):
2392 2392 cols.append(str(l.linenum))
2393 2393 if opts.get('all'):
2394 2394 cols.append(change)
2395 2395 if opts.get('user'):
2396 2396 cols.append(ui.shortuser(ctx.user()))
2397 2397 if opts.get('date'):
2398 2398 cols.append(datefunc(ctx.date()))
2399 2399 if opts.get('files_with_matches'):
2400 2400 c = (fn, rev)
2401 2401 if c in filerevmatches:
2402 2402 continue
2403 2403 filerevmatches[c] = 1
2404 2404 else:
2405 2405 before = l.line[:l.colstart]
2406 2406 match = l.line[l.colstart:l.colend]
2407 2407 after = l.line[l.colend:]
2408 2408 ui.write(sep.join(cols))
2409 2409 if before is not None:
2410 2410 if not opts.get('text') and binary():
2411 2411 ui.write(sep + " Binary file matches")
2412 2412 else:
2413 2413 ui.write(sep + before)
2414 2414 ui.write(match, label='grep.match')
2415 2415 ui.write(after)
2416 2416 ui.write(eol)
2417 2417 found = True
2418 2418 return found
2419 2419
2420 2420 skip = {}
2421 2421 revfiles = {}
2422 2422 matchfn = scmutil.match(repo, pats, opts)
2423 2423 found = False
2424 2424 follow = opts.get('follow')
2425 2425
2426 2426 def prep(ctx, fns):
2427 2427 rev = ctx.rev()
2428 2428 pctx = ctx.p1()
2429 2429 parent = pctx.rev()
2430 2430 matches.setdefault(rev, {})
2431 2431 matches.setdefault(parent, {})
2432 2432 files = revfiles.setdefault(rev, [])
2433 2433 for fn in fns:
2434 2434 flog = getfile(fn)
2435 2435 try:
2436 2436 fnode = ctx.filenode(fn)
2437 2437 except error.LookupError:
2438 2438 continue
2439 2439
2440 2440 copied = flog.renamed(fnode)
2441 2441 copy = follow and copied and copied[0]
2442 2442 if copy:
2443 2443 copies.setdefault(rev, {})[fn] = copy
2444 2444 if fn in skip:
2445 2445 if copy:
2446 2446 skip[copy] = True
2447 2447 continue
2448 2448 files.append(fn)
2449 2449
2450 2450 if fn not in matches[rev]:
2451 2451 grepbody(fn, rev, flog.read(fnode))
2452 2452
2453 2453 pfn = copy or fn
2454 2454 if pfn not in matches[parent]:
2455 2455 try:
2456 2456 fnode = pctx.filenode(pfn)
2457 2457 grepbody(pfn, parent, flog.read(fnode))
2458 2458 except error.LookupError:
2459 2459 pass
2460 2460
2461 2461 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
2462 2462 rev = ctx.rev()
2463 2463 parent = ctx.p1().rev()
2464 2464 for fn in sorted(revfiles.get(rev, [])):
2465 2465 states = matches[rev][fn]
2466 2466 copy = copies.get(rev, {}).get(fn)
2467 2467 if fn in skip:
2468 2468 if copy:
2469 2469 skip[copy] = True
2470 2470 continue
2471 2471 pstates = matches.get(parent, {}).get(copy or fn, [])
2472 2472 if pstates or states:
2473 2473 r = display(fn, ctx, pstates, states)
2474 2474 found = found or r
2475 2475 if r and not opts.get('all'):
2476 2476 skip[fn] = True
2477 2477 if copy:
2478 2478 skip[copy] = True
2479 2479 del matches[rev]
2480 2480 del revfiles[rev]
2481 2481
2482 2482 return not found
2483 2483
2484 2484 @command('heads',
2485 2485 [('r', 'rev', '',
2486 2486 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
2487 2487 ('t', 'topo', False, _('show topological heads only')),
2488 2488 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
2489 2489 ('c', 'closed', False, _('show normal and closed branch heads')),
2490 2490 ] + templateopts,
2491 2491 _('[-ac] [-r STARTREV] [REV]...'))
2492 2492 def heads(ui, repo, *branchrevs, **opts):
2493 2493 """show current repository heads or show branch heads
2494 2494
2495 2495 With no arguments, show all repository branch heads.
2496 2496
2497 2497 Repository "heads" are changesets with no child changesets. They are
2498 2498 where development generally takes place and are the usual targets
2499 2499 for update and merge operations. Branch heads are changesets that have
2500 2500 no child changeset on the same branch.
2501 2501
2502 2502 If one or more REVs are given, only branch heads on the branches
2503 2503 associated with the specified changesets are shown.
2504 2504
2505 2505 If -c/--closed is specified, also show branch heads marked closed
2506 2506 (see :hg:`commit --close-branch`).
2507 2507
2508 2508 If STARTREV is specified, only those heads that are descendants of
2509 2509 STARTREV will be displayed.
2510 2510
2511 2511 If -t/--topo is specified, named branch mechanics will be ignored and only
2512 2512 changesets without children will be shown.
2513 2513
2514 2514 Returns 0 if matching heads are found, 1 if not.
2515 2515 """
2516 2516
2517 2517 start = None
2518 2518 if 'rev' in opts:
2519 2519 start = scmutil.revsingle(repo, opts['rev'], None).node()
2520 2520
2521 2521 if opts.get('topo'):
2522 2522 heads = [repo[h] for h in repo.heads(start)]
2523 2523 else:
2524 2524 heads = []
2525 2525 for b, ls in repo.branchmap().iteritems():
2526 2526 if start is None:
2527 2527 heads += [repo[h] for h in ls]
2528 2528 continue
2529 2529 startrev = repo.changelog.rev(start)
2530 2530 descendants = set(repo.changelog.descendants(startrev))
2531 2531 descendants.add(startrev)
2532 2532 rev = repo.changelog.rev
2533 2533 heads += [repo[h] for h in ls if rev(h) in descendants]
2534 2534
2535 2535 if branchrevs:
2536 2536 branches = set(repo[br].branch() for br in branchrevs)
2537 2537 heads = [h for h in heads if h.branch() in branches]
2538 2538
2539 2539 if not opts.get('closed'):
2540 2540 heads = [h for h in heads if not h.extra().get('close')]
2541 2541
2542 2542 if opts.get('active') and branchrevs:
2543 2543 dagheads = repo.heads(start)
2544 2544 heads = [h for h in heads if h.node() in dagheads]
2545 2545
2546 2546 if branchrevs:
2547 2547 haveheads = set(h.branch() for h in heads)
2548 2548 if branches - haveheads:
2549 2549 headless = ', '.join(b for b in branches - haveheads)
2550 2550 msg = _('no open branch heads found on branches %s')
2551 2551 if opts.get('rev'):
2552 2552 msg += _(' (started at %s)' % opts['rev'])
2553 2553 ui.warn((msg + '\n') % headless)
2554 2554
2555 2555 if not heads:
2556 2556 return 1
2557 2557
2558 2558 heads = sorted(heads, key=lambda x: -x.rev())
2559 2559 displayer = cmdutil.show_changeset(ui, repo, opts)
2560 2560 for ctx in heads:
2561 2561 displayer.show(ctx)
2562 2562 displayer.close()
2563 2563
2564 2564 @command('help',
2565 2565 [('e', 'extension', None, _('show only help for extensions')),
2566 2566 ('c', 'command', None, _('show only help for commands'))],
2567 2567 _('[-ec] [TOPIC]'))
2568 2568 def help_(ui, name=None, with_version=False, unknowncmd=False, full=True, **opts):
2569 2569 """show help for a given topic or a help overview
2570 2570
2571 2571 With no arguments, print a list of commands with short help messages.
2572 2572
2573 2573 Given a topic, extension, or command name, print help for that
2574 2574 topic.
2575 2575
2576 2576 Returns 0 if successful.
2577 2577 """
2578 2578 option_lists = []
2579 2579 textwidth = min(ui.termwidth(), 80) - 2
2580 2580
2581 2581 def addglobalopts(aliases):
2582 2582 if ui.verbose:
2583 2583 option_lists.append((_("global options:"), globalopts))
2584 2584 if name == 'shortlist':
2585 2585 option_lists.append((_('use "hg help" for the full list '
2586 2586 'of commands'), ()))
2587 2587 else:
2588 2588 if name == 'shortlist':
2589 2589 msg = _('use "hg help" for the full list of commands '
2590 2590 'or "hg -v" for details')
2591 2591 elif name and not full:
2592 2592 msg = _('use "hg help %s" to show the full help text' % name)
2593 2593 elif aliases:
2594 2594 msg = _('use "hg -v help%s" to show builtin aliases and '
2595 2595 'global options') % (name and " " + name or "")
2596 2596 else:
2597 2597 msg = _('use "hg -v help %s" to show global options') % name
2598 2598 option_lists.append((msg, ()))
2599 2599
2600 2600 def helpcmd(name):
2601 2601 if with_version:
2602 2602 version_(ui)
2603 2603 ui.write('\n')
2604 2604
2605 2605 try:
2606 2606 aliases, entry = cmdutil.findcmd(name, table, strict=unknowncmd)
2607 2607 except error.AmbiguousCommand, inst:
2608 2608 # py3k fix: except vars can't be used outside the scope of the
2609 2609 # except block, nor can be used inside a lambda. python issue4617
2610 2610 prefix = inst.args[0]
2611 2611 select = lambda c: c.lstrip('^').startswith(prefix)
2612 2612 helplist(_('list of commands:\n\n'), select)
2613 2613 return
2614 2614
2615 2615 # check if it's an invalid alias and display its error if it is
2616 2616 if getattr(entry[0], 'badalias', False):
2617 2617 if not unknowncmd:
2618 2618 entry[0](ui)
2619 2619 return
2620 2620
2621 2621 # synopsis
2622 2622 if len(entry) > 2:
2623 2623 if entry[2].startswith('hg'):
2624 2624 ui.write("%s\n" % entry[2])
2625 2625 else:
2626 2626 ui.write('hg %s %s\n' % (aliases[0], entry[2]))
2627 2627 else:
2628 2628 ui.write('hg %s\n' % aliases[0])
2629 2629
2630 2630 # aliases
2631 2631 if full and not ui.quiet and len(aliases) > 1:
2632 2632 ui.write(_("\naliases: %s\n") % ', '.join(aliases[1:]))
2633 2633
2634 2634 # description
2635 2635 doc = gettext(entry[0].__doc__)
2636 2636 if not doc:
2637 2637 doc = _("(no help text available)")
2638 2638 if hasattr(entry[0], 'definition'): # aliased command
2639 2639 if entry[0].definition.startswith('!'): # shell alias
2640 2640 doc = _('shell alias for::\n\n %s') % entry[0].definition[1:]
2641 2641 else:
2642 2642 doc = _('alias for: hg %s\n\n%s') % (entry[0].definition, doc)
2643 2643 if ui.quiet or not full:
2644 2644 doc = doc.splitlines()[0]
2645 2645 keep = ui.verbose and ['verbose'] or []
2646 2646 formatted, pruned = minirst.format(doc, textwidth, keep=keep)
2647 2647 ui.write("\n%s\n" % formatted)
2648 2648 if pruned:
2649 2649 ui.write(_('\nuse "hg -v help %s" to show verbose help\n') % name)
2650 2650
2651 2651 if not ui.quiet:
2652 2652 # options
2653 2653 if entry[1]:
2654 2654 option_lists.append((_("options:\n"), entry[1]))
2655 2655
2656 2656 addglobalopts(False)
2657 2657
2658 2658 # check if this command shadows a non-trivial (multi-line)
2659 2659 # extension help text
2660 2660 try:
2661 2661 mod = extensions.find(name)
2662 2662 doc = gettext(mod.__doc__) or ''
2663 2663 if '\n' in doc.strip():
2664 2664 msg = _('use "hg help -e %s" to show help for '
2665 2665 'the %s extension') % (name, name)
2666 2666 ui.write('\n%s\n' % msg)
2667 2667 except KeyError:
2668 2668 pass
2669 2669
2670 2670 def helplist(header, select=None):
2671 2671 h = {}
2672 2672 cmds = {}
2673 2673 for c, e in table.iteritems():
2674 2674 f = c.split("|", 1)[0]
2675 2675 if select and not select(f):
2676 2676 continue
2677 2677 if (not select and name != 'shortlist' and
2678 2678 e[0].__module__ != __name__):
2679 2679 continue
2680 2680 if name == "shortlist" and not f.startswith("^"):
2681 2681 continue
2682 2682 f = f.lstrip("^")
2683 2683 if not ui.debugflag and f.startswith("debug"):
2684 2684 continue
2685 2685 doc = e[0].__doc__
2686 2686 if doc and 'DEPRECATED' in doc and not ui.verbose:
2687 2687 continue
2688 2688 doc = gettext(doc)
2689 2689 if not doc:
2690 2690 doc = _("(no help text available)")
2691 2691 h[f] = doc.splitlines()[0].rstrip()
2692 2692 cmds[f] = c.lstrip("^")
2693 2693
2694 2694 if not h:
2695 2695 ui.status(_('no commands defined\n'))
2696 2696 return
2697 2697
2698 2698 ui.status(header)
2699 2699 fns = sorted(h)
2700 2700 m = max(map(len, fns))
2701 2701 for f in fns:
2702 2702 if ui.verbose:
2703 2703 commands = cmds[f].replace("|",", ")
2704 2704 ui.write(" %s:\n %s\n"%(commands, h[f]))
2705 2705 else:
2706 2706 ui.write('%s\n' % (util.wrap(h[f], textwidth,
2707 2707 initindent=' %-*s ' % (m, f),
2708 2708 hangindent=' ' * (m + 4))))
2709 2709
2710 2710 if not ui.quiet:
2711 2711 addglobalopts(True)
2712 2712
2713 2713 def helptopic(name):
2714 2714 for names, header, doc in help.helptable:
2715 2715 if name in names:
2716 2716 break
2717 2717 else:
2718 2718 raise error.UnknownCommand(name)
2719 2719
2720 2720 # description
2721 2721 if not doc:
2722 2722 doc = _("(no help text available)")
2723 2723 if hasattr(doc, '__call__'):
2724 2724 doc = doc()
2725 2725
2726 2726 ui.write("%s\n\n" % header)
2727 2727 ui.write("%s\n" % minirst.format(doc, textwidth, indent=4))
2728 2728 try:
2729 2729 cmdutil.findcmd(name, table)
2730 2730 ui.write(_('\nuse "hg help -c %s" to see help for '
2731 2731 'the %s command\n') % (name, name))
2732 2732 except error.UnknownCommand:
2733 2733 pass
2734 2734
2735 2735 def helpext(name):
2736 2736 try:
2737 2737 mod = extensions.find(name)
2738 2738 doc = gettext(mod.__doc__) or _('no help text available')
2739 2739 except KeyError:
2740 2740 mod = None
2741 2741 doc = extensions.disabledext(name)
2742 2742 if not doc:
2743 2743 raise error.UnknownCommand(name)
2744 2744
2745 2745 if '\n' not in doc:
2746 2746 head, tail = doc, ""
2747 2747 else:
2748 2748 head, tail = doc.split('\n', 1)
2749 2749 ui.write(_('%s extension - %s\n\n') % (name.split('.')[-1], head))
2750 2750 if tail:
2751 2751 ui.write(minirst.format(tail, textwidth))
2752 2752 ui.status('\n\n')
2753 2753
2754 2754 if mod:
2755 2755 try:
2756 2756 ct = mod.cmdtable
2757 2757 except AttributeError:
2758 2758 ct = {}
2759 2759 modcmds = set([c.split('|', 1)[0] for c in ct])
2760 2760 helplist(_('list of commands:\n\n'), modcmds.__contains__)
2761 2761 else:
2762 2762 ui.write(_('use "hg help extensions" for information on enabling '
2763 2763 'extensions\n'))
2764 2764
2765 2765 def helpextcmd(name):
2766 2766 cmd, ext, mod = extensions.disabledcmd(ui, name, ui.config('ui', 'strict'))
2767 2767 doc = gettext(mod.__doc__).splitlines()[0]
2768 2768
2769 2769 msg = help.listexts(_("'%s' is provided by the following "
2770 2770 "extension:") % cmd, {ext: doc}, indent=4)
2771 2771 ui.write(minirst.format(msg, textwidth))
2772 2772 ui.write('\n\n')
2773 2773 ui.write(_('use "hg help extensions" for information on enabling '
2774 2774 'extensions\n'))
2775 2775
2776 2776 if name and name != 'shortlist':
2777 2777 i = None
2778 2778 if unknowncmd:
2779 2779 queries = (helpextcmd,)
2780 2780 elif opts.get('extension'):
2781 2781 queries = (helpext,)
2782 2782 elif opts.get('command'):
2783 2783 queries = (helpcmd,)
2784 2784 else:
2785 2785 queries = (helptopic, helpcmd, helpext, helpextcmd)
2786 2786 for f in queries:
2787 2787 try:
2788 2788 f(name)
2789 2789 i = None
2790 2790 break
2791 2791 except error.UnknownCommand, inst:
2792 2792 i = inst
2793 2793 if i:
2794 2794 raise i
2795 2795
2796 2796 else:
2797 2797 # program name
2798 2798 if ui.verbose or with_version:
2799 2799 version_(ui)
2800 2800 else:
2801 2801 ui.status(_("Mercurial Distributed SCM\n"))
2802 2802 ui.status('\n')
2803 2803
2804 2804 # list of commands
2805 2805 if name == "shortlist":
2806 2806 header = _('basic commands:\n\n')
2807 2807 else:
2808 2808 header = _('list of commands:\n\n')
2809 2809
2810 2810 helplist(header)
2811 2811 if name != 'shortlist':
2812 2812 text = help.listexts(_('enabled extensions:'), extensions.enabled())
2813 2813 if text:
2814 2814 ui.write("\n%s\n" % minirst.format(text, textwidth))
2815 2815
2816 2816 # list all option lists
2817 2817 opt_output = []
2818 2818 multioccur = False
2819 2819 for title, options in option_lists:
2820 2820 opt_output.append(("\n%s" % title, None))
2821 2821 for option in options:
2822 2822 if len(option) == 5:
2823 2823 shortopt, longopt, default, desc, optlabel = option
2824 2824 else:
2825 2825 shortopt, longopt, default, desc = option
2826 2826 optlabel = _("VALUE") # default label
2827 2827
2828 2828 if _("DEPRECATED") in desc and not ui.verbose:
2829 2829 continue
2830 2830 if isinstance(default, list):
2831 2831 numqualifier = " %s [+]" % optlabel
2832 2832 multioccur = True
2833 2833 elif (default is not None) and not isinstance(default, bool):
2834 2834 numqualifier = " %s" % optlabel
2835 2835 else:
2836 2836 numqualifier = ""
2837 2837 opt_output.append(("%2s%s" %
2838 2838 (shortopt and "-%s" % shortopt,
2839 2839 longopt and " --%s%s" %
2840 2840 (longopt, numqualifier)),
2841 2841 "%s%s" % (desc,
2842 2842 default
2843 2843 and _(" (default: %s)") % default
2844 2844 or "")))
2845 2845 if multioccur:
2846 2846 msg = _("\n[+] marked option can be specified multiple times")
2847 2847 if ui.verbose and name != 'shortlist':
2848 2848 opt_output.append((msg, None))
2849 2849 else:
2850 2850 opt_output.insert(-1, (msg, None))
2851 2851
2852 2852 if not name:
2853 2853 ui.write(_("\nadditional help topics:\n\n"))
2854 2854 topics = []
2855 2855 for names, header, doc in help.helptable:
2856 2856 topics.append((sorted(names, key=len, reverse=True)[0], header))
2857 2857 topics_len = max([len(s[0]) for s in topics])
2858 2858 for t, desc in topics:
2859 2859 ui.write(" %-*s %s\n" % (topics_len, t, desc))
2860 2860
2861 2861 if opt_output:
2862 2862 colwidth = encoding.colwidth
2863 2863 # normalize: (opt or message, desc or None, width of opt)
2864 2864 entries = [desc and (opt, desc, colwidth(opt)) or (opt, None, 0)
2865 2865 for opt, desc in opt_output]
2866 2866 hanging = max([e[2] for e in entries])
2867 2867 for opt, desc, width in entries:
2868 2868 if desc:
2869 2869 initindent = ' %s%s ' % (opt, ' ' * (hanging - width))
2870 2870 hangindent = ' ' * (hanging + 3)
2871 2871 ui.write('%s\n' % (util.wrap(desc, textwidth,
2872 2872 initindent=initindent,
2873 2873 hangindent=hangindent)))
2874 2874 else:
2875 2875 ui.write("%s\n" % opt)
2876 2876
2877 2877 @command('identify|id',
2878 2878 [('r', 'rev', '',
2879 2879 _('identify the specified revision'), _('REV')),
2880 2880 ('n', 'num', None, _('show local revision number')),
2881 2881 ('i', 'id', None, _('show global revision id')),
2882 2882 ('b', 'branch', None, _('show branch')),
2883 2883 ('t', 'tags', None, _('show tags')),
2884 2884 ('B', 'bookmarks', None, _('show bookmarks'))],
2885 2885 _('[-nibtB] [-r REV] [SOURCE]'))
2886 2886 def identify(ui, repo, source=None, rev=None,
2887 2887 num=None, id=None, branch=None, tags=None, bookmarks=None):
2888 2888 """identify the working copy or specified revision
2889 2889
2890 2890 Print a summary identifying the repository state at REV using one or
2891 2891 two parent hash identifiers, followed by a "+" if the working
2892 2892 directory has uncommitted changes, the branch name (if not default),
2893 2893 a list of tags, and a list of bookmarks.
2894 2894
2895 2895 When REV is not given, print a summary of the current state of the
2896 2896 repository.
2897 2897
2898 2898 Specifying a path to a repository root or Mercurial bundle will
2899 2899 cause lookup to operate on that repository/bundle.
2900 2900
2901 2901 Returns 0 if successful.
2902 2902 """
2903 2903
2904 2904 if not repo and not source:
2905 2905 raise util.Abort(_("there is no Mercurial repository here "
2906 2906 "(.hg not found)"))
2907 2907
2908 2908 hexfunc = ui.debugflag and hex or short
2909 2909 default = not (num or id or branch or tags or bookmarks)
2910 2910 output = []
2911 2911 revs = []
2912 2912
2913 2913 if source:
2914 2914 source, branches = hg.parseurl(ui.expandpath(source))
2915 2915 repo = hg.repository(ui, source)
2916 2916 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
2917 2917
2918 2918 if not repo.local():
2919 2919 if num or branch or tags:
2920 2920 raise util.Abort(
2921 2921 _("can't query remote revision number, branch, or tags"))
2922 2922 if not rev and revs:
2923 2923 rev = revs[0]
2924 2924 if not rev:
2925 2925 rev = "tip"
2926 2926
2927 2927 remoterev = repo.lookup(rev)
2928 2928 if default or id:
2929 2929 output = [hexfunc(remoterev)]
2930 2930
2931 2931 def getbms():
2932 2932 bms = []
2933 2933
2934 2934 if 'bookmarks' in repo.listkeys('namespaces'):
2935 2935 hexremoterev = hex(remoterev)
2936 2936 bms = [bm for bm, bmr in repo.listkeys('bookmarks').iteritems()
2937 2937 if bmr == hexremoterev]
2938 2938
2939 2939 return bms
2940 2940
2941 2941 if bookmarks:
2942 2942 output.extend(getbms())
2943 2943 elif default and not ui.quiet:
2944 2944 # multiple bookmarks for a single parent separated by '/'
2945 2945 bm = '/'.join(getbms())
2946 2946 if bm:
2947 2947 output.append(bm)
2948 2948 else:
2949 2949 if not rev:
2950 2950 ctx = repo[None]
2951 2951 parents = ctx.parents()
2952 2952 changed = ""
2953 2953 if default or id or num:
2954 2954 changed = util.any(repo.status()) and "+" or ""
2955 2955 if default or id:
2956 2956 output = ["%s%s" %
2957 2957 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
2958 2958 if num:
2959 2959 output.append("%s%s" %
2960 2960 ('+'.join([str(p.rev()) for p in parents]), changed))
2961 2961 else:
2962 2962 ctx = scmutil.revsingle(repo, rev)
2963 2963 if default or id:
2964 2964 output = [hexfunc(ctx.node())]
2965 2965 if num:
2966 2966 output.append(str(ctx.rev()))
2967 2967
2968 2968 if default and not ui.quiet:
2969 2969 b = ctx.branch()
2970 2970 if b != 'default':
2971 2971 output.append("(%s)" % b)
2972 2972
2973 2973 # multiple tags for a single parent separated by '/'
2974 2974 t = '/'.join(ctx.tags())
2975 2975 if t:
2976 2976 output.append(t)
2977 2977
2978 2978 # multiple bookmarks for a single parent separated by '/'
2979 2979 bm = '/'.join(ctx.bookmarks())
2980 2980 if bm:
2981 2981 output.append(bm)
2982 2982 else:
2983 2983 if branch:
2984 2984 output.append(ctx.branch())
2985 2985
2986 2986 if tags:
2987 2987 output.extend(ctx.tags())
2988 2988
2989 2989 if bookmarks:
2990 2990 output.extend(ctx.bookmarks())
2991 2991
2992 2992 ui.write("%s\n" % ' '.join(output))
2993 2993
2994 2994 @command('import|patch',
2995 2995 [('p', 'strip', 1,
2996 2996 _('directory strip option for patch. This has the same '
2997 2997 'meaning as the corresponding patch option'), _('NUM')),
2998 2998 ('b', 'base', '', _('base path'), _('PATH')),
2999 2999 ('f', 'force', None, _('skip check for outstanding uncommitted changes')),
3000 3000 ('', 'no-commit', None,
3001 3001 _("don't commit, just update the working directory")),
3002 3002 ('', 'exact', None,
3003 3003 _('apply patch to the nodes from which it was generated')),
3004 3004 ('', 'import-branch', None,
3005 3005 _('use any branch information in patch (implied by --exact)'))] +
3006 3006 commitopts + commitopts2 + similarityopts,
3007 3007 _('[OPTION]... PATCH...'))
3008 3008 def import_(ui, repo, patch1, *patches, **opts):
3009 3009 """import an ordered set of patches
3010 3010
3011 3011 Import a list of patches and commit them individually (unless
3012 3012 --no-commit is specified).
3013 3013
3014 3014 If there are outstanding changes in the working directory, import
3015 3015 will abort unless given the -f/--force flag.
3016 3016
3017 3017 You can import a patch straight from a mail message. Even patches
3018 3018 as attachments work (to use the body part, it must have type
3019 3019 text/plain or text/x-patch). From and Subject headers of email
3020 3020 message are used as default committer and commit message. All
3021 3021 text/plain body parts before first diff are added to commit
3022 3022 message.
3023 3023
3024 3024 If the imported patch was generated by :hg:`export`, user and
3025 3025 description from patch override values from message headers and
3026 3026 body. Values given on command line with -m/--message and -u/--user
3027 3027 override these.
3028 3028
3029 3029 If --exact is specified, import will set the working directory to
3030 3030 the parent of each patch before applying it, and will abort if the
3031 3031 resulting changeset has a different ID than the one recorded in
3032 3032 the patch. This may happen due to character set problems or other
3033 3033 deficiencies in the text patch format.
3034 3034
3035 3035 With -s/--similarity, hg will attempt to discover renames and
3036 3036 copies in the patch in the same way as 'addremove'.
3037 3037
3038 3038 To read a patch from standard input, use "-" as the patch name. If
3039 3039 a URL is specified, the patch will be downloaded from it.
3040 3040 See :hg:`help dates` for a list of formats valid for -d/--date.
3041 3041
3042 3042 Returns 0 on success.
3043 3043 """
3044 3044 patches = (patch1,) + patches
3045 3045
3046 3046 date = opts.get('date')
3047 3047 if date:
3048 3048 opts['date'] = util.parsedate(date)
3049 3049
3050 3050 try:
3051 3051 sim = float(opts.get('similarity') or 0)
3052 3052 except ValueError:
3053 3053 raise util.Abort(_('similarity must be a number'))
3054 3054 if sim < 0 or sim > 100:
3055 3055 raise util.Abort(_('similarity must be between 0 and 100'))
3056 3056
3057 3057 if opts.get('exact') or not opts.get('force'):
3058 3058 cmdutil.bailifchanged(repo)
3059 3059
3060 3060 d = opts["base"]
3061 3061 strip = opts["strip"]
3062 3062 wlock = lock = None
3063 3063 msgs = []
3064 3064
3065 3065 def tryone(ui, hunk):
3066 3066 tmpname, message, user, date, branch, nodeid, p1, p2 = \
3067 3067 patch.extract(ui, hunk)
3068 3068
3069 3069 if not tmpname:
3070 3070 return None
3071 3071 commitid = _('to working directory')
3072 3072
3073 3073 try:
3074 3074 cmdline_message = cmdutil.logmessage(opts)
3075 3075 if cmdline_message:
3076 3076 # pickup the cmdline msg
3077 3077 message = cmdline_message
3078 3078 elif message:
3079 3079 # pickup the patch msg
3080 3080 message = message.strip()
3081 3081 else:
3082 3082 # launch the editor
3083 3083 message = None
3084 3084 ui.debug('message:\n%s\n' % message)
3085 3085
3086 3086 wp = repo.parents()
3087 3087 if opts.get('exact'):
3088 3088 if not nodeid or not p1:
3089 3089 raise util.Abort(_('not a Mercurial patch'))
3090 3090 p1 = repo.lookup(p1)
3091 3091 p2 = repo.lookup(p2 or hex(nullid))
3092 3092
3093 3093 if p1 != wp[0].node():
3094 3094 hg.clean(repo, p1)
3095 3095 repo.dirstate.setparents(p1, p2)
3096 3096 elif p2:
3097 3097 try:
3098 3098 p1 = repo.lookup(p1)
3099 3099 p2 = repo.lookup(p2)
3100 3100 if p1 == wp[0].node():
3101 3101 repo.dirstate.setparents(p1, p2)
3102 3102 except error.RepoError:
3103 3103 pass
3104 3104 if opts.get('exact') or opts.get('import_branch'):
3105 3105 repo.dirstate.setbranch(branch or 'default')
3106 3106
3107 3107 files = {}
3108 3108 patch.patch(ui, repo, tmpname, strip=strip, files=files,
3109 3109 eolmode=None, similarity=sim / 100.0)
3110 3110 files = list(files)
3111 3111 if opts.get('no_commit'):
3112 3112 if message:
3113 3113 msgs.append(message)
3114 3114 else:
3115 3115 if opts.get('exact'):
3116 3116 m = None
3117 3117 else:
3118 3118 m = scmutil.matchfiles(repo, files or [])
3119 3119 n = repo.commit(message, opts.get('user') or user,
3120 3120 opts.get('date') or date, match=m,
3121 3121 editor=cmdutil.commiteditor)
3122 3122 if opts.get('exact'):
3123 3123 if hex(n) != nodeid:
3124 3124 repo.rollback()
3125 3125 raise util.Abort(_('patch is damaged'
3126 3126 ' or loses information'))
3127 3127 # Force a dirstate write so that the next transaction
3128 3128 # backups an up-do-date file.
3129 3129 repo.dirstate.write()
3130 3130 if n:
3131 3131 commitid = short(n)
3132 3132
3133 3133 return commitid
3134 3134 finally:
3135 3135 os.unlink(tmpname)
3136 3136
3137 3137 try:
3138 3138 wlock = repo.wlock()
3139 3139 lock = repo.lock()
3140 3140 lastcommit = None
3141 3141 for p in patches:
3142 3142 pf = os.path.join(d, p)
3143 3143
3144 3144 if pf == '-':
3145 3145 ui.status(_("applying patch from stdin\n"))
3146 3146 pf = sys.stdin
3147 3147 else:
3148 3148 ui.status(_("applying %s\n") % p)
3149 3149 pf = url.open(ui, pf)
3150 3150
3151 3151 haspatch = False
3152 3152 for hunk in patch.split(pf):
3153 3153 commitid = tryone(ui, hunk)
3154 3154 if commitid:
3155 3155 haspatch = True
3156 3156 if lastcommit:
3157 3157 ui.status(_('applied %s\n') % lastcommit)
3158 3158 lastcommit = commitid
3159 3159
3160 3160 if not haspatch:
3161 3161 raise util.Abort(_('no diffs found'))
3162 3162
3163 3163 if msgs:
3164 3164 repo.opener.write('last-message.txt', '\n* * *\n'.join(msgs))
3165 3165 finally:
3166 3166 release(lock, wlock)
3167 3167
3168 3168 @command('incoming|in',
3169 3169 [('f', 'force', None,
3170 3170 _('run even if remote repository is unrelated')),
3171 3171 ('n', 'newest-first', None, _('show newest record first')),
3172 3172 ('', 'bundle', '',
3173 3173 _('file to store the bundles into'), _('FILE')),
3174 3174 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3175 3175 ('B', 'bookmarks', False, _("compare bookmarks")),
3176 3176 ('b', 'branch', [],
3177 3177 _('a specific branch you would like to pull'), _('BRANCH')),
3178 3178 ] + logopts + remoteopts + subrepoopts,
3179 3179 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3180 3180 def incoming(ui, repo, source="default", **opts):
3181 3181 """show new changesets found in source
3182 3182
3183 3183 Show new changesets found in the specified path/URL or the default
3184 3184 pull location. These are the changesets that would have been pulled
3185 3185 if a pull at the time you issued this command.
3186 3186
3187 3187 For remote repository, using --bundle avoids downloading the
3188 3188 changesets twice if the incoming is followed by a pull.
3189 3189
3190 3190 See pull for valid source format details.
3191 3191
3192 3192 Returns 0 if there are incoming changes, 1 otherwise.
3193 3193 """
3194 3194 if opts.get('bundle') and opts.get('subrepos'):
3195 3195 raise util.Abort(_('cannot combine --bundle and --subrepos'))
3196 3196
3197 3197 if opts.get('bookmarks'):
3198 3198 source, branches = hg.parseurl(ui.expandpath(source),
3199 3199 opts.get('branch'))
3200 3200 other = hg.repository(hg.remoteui(repo, opts), source)
3201 3201 if 'bookmarks' not in other.listkeys('namespaces'):
3202 3202 ui.warn(_("remote doesn't support bookmarks\n"))
3203 3203 return 0
3204 3204 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3205 3205 return bookmarks.diff(ui, repo, other)
3206 3206
3207 3207 repo._subtoppath = ui.expandpath(source)
3208 3208 try:
3209 3209 return hg.incoming(ui, repo, source, opts)
3210 3210 finally:
3211 3211 del repo._subtoppath
3212 3212
3213 3213
3214 3214 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'))
3215 3215 def init(ui, dest=".", **opts):
3216 3216 """create a new repository in the given directory
3217 3217
3218 3218 Initialize a new repository in the given directory. If the given
3219 3219 directory does not exist, it will be created.
3220 3220
3221 3221 If no directory is given, the current directory is used.
3222 3222
3223 3223 It is possible to specify an ``ssh://`` URL as the destination.
3224 3224 See :hg:`help urls` for more information.
3225 3225
3226 3226 Returns 0 on success.
3227 3227 """
3228 3228 hg.repository(hg.remoteui(ui, opts), ui.expandpath(dest), create=True)
3229 3229
3230 3230 @command('locate',
3231 3231 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3232 3232 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3233 3233 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3234 3234 ] + walkopts,
3235 3235 _('[OPTION]... [PATTERN]...'))
3236 3236 def locate(ui, repo, *pats, **opts):
3237 3237 """locate files matching specific patterns
3238 3238
3239 3239 Print files under Mercurial control in the working directory whose
3240 3240 names match the given patterns.
3241 3241
3242 3242 By default, this command searches all directories in the working
3243 3243 directory. To search just the current directory and its
3244 3244 subdirectories, use "--include .".
3245 3245
3246 3246 If no patterns are given to match, this command prints the names
3247 3247 of all files under Mercurial control in the working directory.
3248 3248
3249 3249 If you want to feed the output of this command into the "xargs"
3250 3250 command, use the -0 option to both this command and "xargs". This
3251 3251 will avoid the problem of "xargs" treating single filenames that
3252 3252 contain whitespace as multiple filenames.
3253 3253
3254 3254 Returns 0 if a match is found, 1 otherwise.
3255 3255 """
3256 3256 end = opts.get('print0') and '\0' or '\n'
3257 3257 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
3258 3258
3259 3259 ret = 1
3260 3260 m = scmutil.match(repo, pats, opts, default='relglob')
3261 3261 m.bad = lambda x, y: False
3262 3262 for abs in repo[rev].walk(m):
3263 3263 if not rev and abs not in repo.dirstate:
3264 3264 continue
3265 3265 if opts.get('fullpath'):
3266 3266 ui.write(repo.wjoin(abs), end)
3267 3267 else:
3268 3268 ui.write(((pats and m.rel(abs)) or abs), end)
3269 3269 ret = 0
3270 3270
3271 3271 return ret
3272 3272
3273 3273 @command('^log|history',
3274 3274 [('f', 'follow', None,
3275 3275 _('follow changeset history, or file history across copies and renames')),
3276 3276 ('', 'follow-first', None,
3277 3277 _('only follow the first parent of merge changesets')),
3278 3278 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3279 3279 ('C', 'copies', None, _('show copied files')),
3280 3280 ('k', 'keyword', [],
3281 3281 _('do case-insensitive search for a given text'), _('TEXT')),
3282 3282 ('r', 'rev', [], _('show the specified revision or range'), _('REV')),
3283 3283 ('', 'removed', None, _('include revisions where files were removed')),
3284 3284 ('m', 'only-merges', None, _('show only merges')),
3285 3285 ('u', 'user', [], _('revisions committed by user'), _('USER')),
3286 3286 ('', 'only-branch', [],
3287 3287 _('show only changesets within the given named branch (DEPRECATED)'),
3288 3288 _('BRANCH')),
3289 3289 ('b', 'branch', [],
3290 3290 _('show changesets within the given named branch'), _('BRANCH')),
3291 3291 ('P', 'prune', [],
3292 3292 _('do not display revision or any of its ancestors'), _('REV')),
3293 3293 ] + logopts + walkopts,
3294 3294 _('[OPTION]... [FILE]'))
3295 3295 def log(ui, repo, *pats, **opts):
3296 3296 """show revision history of entire repository or files
3297 3297
3298 3298 Print the revision history of the specified files or the entire
3299 3299 project.
3300 3300
3301 3301 File history is shown without following rename or copy history of
3302 3302 files. Use -f/--follow with a filename to follow history across
3303 3303 renames and copies. --follow without a filename will only show
3304 3304 ancestors or descendants of the starting revision. --follow-first
3305 3305 only follows the first parent of merge revisions.
3306 3306
3307 3307 If no revision range is specified, the default is ``tip:0`` unless
3308 3308 --follow is set, in which case the working directory parent is
3309 3309 used as the starting revision. You can specify a revision set for
3310 3310 log, see :hg:`help revsets` for more information.
3311 3311
3312 3312 See :hg:`help dates` for a list of formats valid for -d/--date.
3313 3313
3314 3314 By default this command prints revision number and changeset id,
3315 3315 tags, non-trivial parents, user, date and time, and a summary for
3316 3316 each commit. When the -v/--verbose switch is used, the list of
3317 3317 changed files and full commit message are shown.
3318 3318
3319 3319 .. note::
3320 3320 log -p/--patch may generate unexpected diff output for merge
3321 3321 changesets, as it will only compare the merge changeset against
3322 3322 its first parent. Also, only files different from BOTH parents
3323 3323 will appear in files:.
3324 3324
3325 3325 Returns 0 on success.
3326 3326 """
3327 3327
3328 3328 matchfn = scmutil.match(repo, pats, opts)
3329 3329 limit = cmdutil.loglimit(opts)
3330 3330 count = 0
3331 3331
3332 3332 endrev = None
3333 3333 if opts.get('copies') and opts.get('rev'):
3334 3334 endrev = max(scmutil.revrange(repo, opts.get('rev'))) + 1
3335 3335
3336 3336 df = False
3337 3337 if opts["date"]:
3338 3338 df = util.matchdate(opts["date"])
3339 3339
3340 3340 branches = opts.get('branch', []) + opts.get('only_branch', [])
3341 3341 opts['branch'] = [repo.lookupbranch(b) for b in branches]
3342 3342
3343 3343 displayer = cmdutil.show_changeset(ui, repo, opts, True)
3344 3344 def prep(ctx, fns):
3345 3345 rev = ctx.rev()
3346 3346 parents = [p for p in repo.changelog.parentrevs(rev)
3347 3347 if p != nullrev]
3348 3348 if opts.get('no_merges') and len(parents) == 2:
3349 3349 return
3350 3350 if opts.get('only_merges') and len(parents) != 2:
3351 3351 return
3352 3352 if opts.get('branch') and ctx.branch() not in opts['branch']:
3353 3353 return
3354 3354 if df and not df(ctx.date()[0]):
3355 3355 return
3356 3356 if opts['user'] and not [k for k in opts['user']
3357 3357 if k.lower() in ctx.user().lower()]:
3358 3358 return
3359 3359 if opts.get('keyword'):
3360 3360 for k in [kw.lower() for kw in opts['keyword']]:
3361 3361 if (k in ctx.user().lower() or
3362 3362 k in ctx.description().lower() or
3363 3363 k in " ".join(ctx.files()).lower()):
3364 3364 break
3365 3365 else:
3366 3366 return
3367 3367
3368 3368 copies = None
3369 3369 if opts.get('copies') and rev:
3370 3370 copies = []
3371 3371 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
3372 3372 for fn in ctx.files():
3373 3373 rename = getrenamed(fn, rev)
3374 3374 if rename:
3375 3375 copies.append((fn, rename[0]))
3376 3376
3377 3377 revmatchfn = None
3378 3378 if opts.get('patch') or opts.get('stat'):
3379 3379 if opts.get('follow') or opts.get('follow_first'):
3380 3380 # note: this might be wrong when following through merges
3381 3381 revmatchfn = scmutil.match(repo, fns, default='path')
3382 3382 else:
3383 3383 revmatchfn = matchfn
3384 3384
3385 3385 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
3386 3386
3387 3387 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
3388 3388 if count == limit:
3389 3389 break
3390 3390 if displayer.flush(ctx.rev()):
3391 3391 count += 1
3392 3392 displayer.close()
3393 3393
3394 3394 @command('manifest',
3395 3395 [('r', 'rev', '', _('revision to display'), _('REV')),
3396 3396 ('', 'all', False, _("list files from all revisions"))],
3397 3397 _('[-r REV]'))
3398 3398 def manifest(ui, repo, node=None, rev=None, **opts):
3399 3399 """output the current or given revision of the project manifest
3400 3400
3401 3401 Print a list of version controlled files for the given revision.
3402 3402 If no revision is given, the first parent of the working directory
3403 3403 is used, or the null revision if no revision is checked out.
3404 3404
3405 3405 With -v, print file permissions, symlink and executable bits.
3406 3406 With --debug, print file revision hashes.
3407 3407
3408 3408 If option --all is specified, the list of all files from all revisions
3409 3409 is printed. This includes deleted and renamed files.
3410 3410
3411 3411 Returns 0 on success.
3412 3412 """
3413 3413 if opts.get('all'):
3414 3414 if rev or node:
3415 3415 raise util.Abort(_("can't specify a revision with --all"))
3416 3416
3417 3417 res = []
3418 3418 prefix = "data/"
3419 3419 suffix = ".i"
3420 3420 plen = len(prefix)
3421 3421 slen = len(suffix)
3422 3422 lock = repo.lock()
3423 3423 try:
3424 3424 for fn, b, size in repo.store.datafiles():
3425 3425 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
3426 3426 res.append(fn[plen:-slen])
3427 3427 finally:
3428 3428 lock.release()
3429 3429 for f in sorted(res):
3430 3430 ui.write("%s\n" % f)
3431 3431 return
3432 3432
3433 3433 if rev and node:
3434 3434 raise util.Abort(_("please specify just one revision"))
3435 3435
3436 3436 if not node:
3437 3437 node = rev
3438 3438
3439 3439 decor = {'l':'644 @ ', 'x':'755 * ', '':'644 '}
3440 3440 ctx = scmutil.revsingle(repo, node)
3441 3441 for f in ctx:
3442 3442 if ui.debugflag:
3443 3443 ui.write("%40s " % hex(ctx.manifest()[f]))
3444 3444 if ui.verbose:
3445 3445 ui.write(decor[ctx.flags(f)])
3446 3446 ui.write("%s\n" % f)
3447 3447
3448 3448 @command('^merge',
3449 3449 [('f', 'force', None, _('force a merge with outstanding changes')),
3450 3450 ('t', 'tool', '', _('specify merge tool')),
3451 3451 ('r', 'rev', '', _('revision to merge'), _('REV')),
3452 3452 ('P', 'preview', None,
3453 3453 _('review revisions to merge (no merge is performed)'))],
3454 3454 _('[-P] [-f] [[-r] REV]'))
3455 3455 def merge(ui, repo, node=None, **opts):
3456 3456 """merge working directory with another revision
3457 3457
3458 3458 The current working directory is updated with all changes made in
3459 3459 the requested revision since the last common predecessor revision.
3460 3460
3461 3461 Files that changed between either parent are marked as changed for
3462 3462 the next commit and a commit must be performed before any further
3463 3463 updates to the repository are allowed. The next commit will have
3464 3464 two parents.
3465 3465
3466 3466 ``--tool`` can be used to specify the merge tool used for file
3467 3467 merges. It overrides the HGMERGE environment variable and your
3468 3468 configuration files. See :hg:`help merge-tools` for options.
3469 3469
3470 3470 If no revision is specified, the working directory's parent is a
3471 3471 head revision, and the current branch contains exactly one other
3472 3472 head, the other head is merged with by default. Otherwise, an
3473 3473 explicit revision with which to merge with must be provided.
3474 3474
3475 3475 :hg:`resolve` must be used to resolve unresolved files.
3476 3476
3477 3477 To undo an uncommitted merge, use :hg:`update --clean .` which
3478 3478 will check out a clean copy of the original merge parent, losing
3479 3479 all changes.
3480 3480
3481 3481 Returns 0 on success, 1 if there are unresolved files.
3482 3482 """
3483 3483
3484 3484 if opts.get('rev') and node:
3485 3485 raise util.Abort(_("please specify just one revision"))
3486 3486 if not node:
3487 3487 node = opts.get('rev')
3488 3488
3489 3489 if not node:
3490 3490 branch = repo[None].branch()
3491 3491 bheads = repo.branchheads(branch)
3492 3492 if len(bheads) > 2:
3493 3493 raise util.Abort(_("branch '%s' has %d heads - "
3494 3494 "please merge with an explicit rev")
3495 3495 % (branch, len(bheads)),
3496 3496 hint=_("run 'hg heads .' to see heads"))
3497 3497
3498 3498 parent = repo.dirstate.p1()
3499 3499 if len(bheads) == 1:
3500 3500 if len(repo.heads()) > 1:
3501 3501 raise util.Abort(_("branch '%s' has one head - "
3502 3502 "please merge with an explicit rev")
3503 3503 % branch,
3504 3504 hint=_("run 'hg heads' to see all heads"))
3505 3505 msg = _('there is nothing to merge')
3506 3506 if parent != repo.lookup(repo[None].branch()):
3507 3507 msg = _('%s - use "hg update" instead') % msg
3508 3508 raise util.Abort(msg)
3509 3509
3510 3510 if parent not in bheads:
3511 3511 raise util.Abort(_('working directory not at a head revision'),
3512 3512 hint=_("use 'hg update' or merge with an "
3513 3513 "explicit revision"))
3514 3514 node = parent == bheads[0] and bheads[-1] or bheads[0]
3515 3515 else:
3516 3516 node = scmutil.revsingle(repo, node).node()
3517 3517
3518 3518 if opts.get('preview'):
3519 3519 # find nodes that are ancestors of p2 but not of p1
3520 3520 p1 = repo.lookup('.')
3521 3521 p2 = repo.lookup(node)
3522 3522 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
3523 3523
3524 3524 displayer = cmdutil.show_changeset(ui, repo, opts)
3525 3525 for node in nodes:
3526 3526 displayer.show(repo[node])
3527 3527 displayer.close()
3528 3528 return 0
3529 3529
3530 3530 try:
3531 3531 # ui.forcemerge is an internal variable, do not document
3532 3532 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
3533 3533 return hg.merge(repo, node, force=opts.get('force'))
3534 3534 finally:
3535 3535 ui.setconfig('ui', 'forcemerge', '')
3536 3536
3537 3537 @command('outgoing|out',
3538 3538 [('f', 'force', None, _('run even when the destination is unrelated')),
3539 3539 ('r', 'rev', [],
3540 3540 _('a changeset intended to be included in the destination'), _('REV')),
3541 3541 ('n', 'newest-first', None, _('show newest record first')),
3542 3542 ('B', 'bookmarks', False, _('compare bookmarks')),
3543 3543 ('b', 'branch', [], _('a specific branch you would like to push'),
3544 3544 _('BRANCH')),
3545 3545 ] + logopts + remoteopts + subrepoopts,
3546 3546 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
3547 3547 def outgoing(ui, repo, dest=None, **opts):
3548 3548 """show changesets not found in the destination
3549 3549
3550 3550 Show changesets not found in the specified destination repository
3551 3551 or the default push location. These are the changesets that would
3552 3552 be pushed if a push was requested.
3553 3553
3554 3554 See pull for details of valid destination formats.
3555 3555
3556 3556 Returns 0 if there are outgoing changes, 1 otherwise.
3557 3557 """
3558 3558
3559 3559 if opts.get('bookmarks'):
3560 3560 dest = ui.expandpath(dest or 'default-push', dest or 'default')
3561 3561 dest, branches = hg.parseurl(dest, opts.get('branch'))
3562 3562 other = hg.repository(hg.remoteui(repo, opts), dest)
3563 3563 if 'bookmarks' not in other.listkeys('namespaces'):
3564 3564 ui.warn(_("remote doesn't support bookmarks\n"))
3565 3565 return 0
3566 3566 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
3567 3567 return bookmarks.diff(ui, other, repo)
3568 3568
3569 3569 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
3570 3570 try:
3571 3571 return hg.outgoing(ui, repo, dest, opts)
3572 3572 finally:
3573 3573 del repo._subtoppath
3574 3574
3575 3575 @command('parents',
3576 3576 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
3577 3577 ] + templateopts,
3578 3578 _('[-r REV] [FILE]'))
3579 3579 def parents(ui, repo, file_=None, **opts):
3580 3580 """show the parents of the working directory or revision
3581 3581
3582 3582 Print the working directory's parent revisions. If a revision is
3583 3583 given via -r/--rev, the parent of that revision will be printed.
3584 3584 If a file argument is given, the revision in which the file was
3585 3585 last changed (before the working directory revision or the
3586 3586 argument to --rev if given) is printed.
3587 3587
3588 3588 Returns 0 on success.
3589 3589 """
3590 3590
3591 3591 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
3592 3592
3593 3593 if file_:
3594 3594 m = scmutil.match(repo, (file_,), opts)
3595 3595 if m.anypats() or len(m.files()) != 1:
3596 3596 raise util.Abort(_('can only specify an explicit filename'))
3597 3597 file_ = m.files()[0]
3598 3598 filenodes = []
3599 3599 for cp in ctx.parents():
3600 3600 if not cp:
3601 3601 continue
3602 3602 try:
3603 3603 filenodes.append(cp.filenode(file_))
3604 3604 except error.LookupError:
3605 3605 pass
3606 3606 if not filenodes:
3607 3607 raise util.Abort(_("'%s' not found in manifest!") % file_)
3608 3608 fl = repo.file(file_)
3609 3609 p = [repo.lookup(fl.linkrev(fl.rev(fn))) for fn in filenodes]
3610 3610 else:
3611 3611 p = [cp.node() for cp in ctx.parents()]
3612 3612
3613 3613 displayer = cmdutil.show_changeset(ui, repo, opts)
3614 3614 for n in p:
3615 3615 if n != nullid:
3616 3616 displayer.show(repo[n])
3617 3617 displayer.close()
3618 3618
3619 3619 @command('paths', [], _('[NAME]'))
3620 3620 def paths(ui, repo, search=None):
3621 3621 """show aliases for remote repositories
3622 3622
3623 3623 Show definition of symbolic path name NAME. If no name is given,
3624 3624 show definition of all available names.
3625 3625
3626 3626 Option -q/--quiet suppresses all output when searching for NAME
3627 3627 and shows only the path names when listing all definitions.
3628 3628
3629 3629 Path names are defined in the [paths] section of your
3630 3630 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
3631 3631 repository, ``.hg/hgrc`` is used, too.
3632 3632
3633 3633 The path names ``default`` and ``default-push`` have a special
3634 3634 meaning. When performing a push or pull operation, they are used
3635 3635 as fallbacks if no location is specified on the command-line.
3636 3636 When ``default-push`` is set, it will be used for push and
3637 3637 ``default`` will be used for pull; otherwise ``default`` is used
3638 3638 as the fallback for both. When cloning a repository, the clone
3639 3639 source is written as ``default`` in ``.hg/hgrc``. Note that
3640 3640 ``default`` and ``default-push`` apply to all inbound (e.g.
3641 3641 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
3642 3642 :hg:`bundle`) operations.
3643 3643
3644 3644 See :hg:`help urls` for more information.
3645 3645
3646 3646 Returns 0 on success.
3647 3647 """
3648 3648 if search:
3649 3649 for name, path in ui.configitems("paths"):
3650 3650 if name == search:
3651 3651 ui.status("%s\n" % util.hidepassword(path))
3652 3652 return
3653 3653 if not ui.quiet:
3654 3654 ui.warn(_("not found!\n"))
3655 3655 return 1
3656 3656 else:
3657 3657 for name, path in ui.configitems("paths"):
3658 3658 if ui.quiet:
3659 3659 ui.write("%s\n" % name)
3660 3660 else:
3661 3661 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
3662 3662
3663 3663 def postincoming(ui, repo, modheads, optupdate, checkout):
3664 3664 if modheads == 0:
3665 3665 return
3666 3666 if optupdate:
3667 3667 if (modheads <= 1 or len(repo.branchheads()) == 1) or checkout:
3668 3668 return hg.update(repo, checkout)
3669 3669 else:
3670 3670 ui.status(_("not updating, since new heads added\n"))
3671 3671 if modheads > 1:
3672 3672 currentbranchheads = len(repo.branchheads())
3673 3673 if currentbranchheads == modheads:
3674 3674 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
3675 3675 elif currentbranchheads > 1:
3676 3676 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to merge)\n"))
3677 3677 else:
3678 3678 ui.status(_("(run 'hg heads' to see heads)\n"))
3679 3679 else:
3680 3680 ui.status(_("(run 'hg update' to get a working copy)\n"))
3681 3681
3682 3682 @command('^pull',
3683 3683 [('u', 'update', None,
3684 3684 _('update to new branch head if changesets were pulled')),
3685 3685 ('f', 'force', None, _('run even when remote repository is unrelated')),
3686 3686 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3687 3687 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
3688 3688 ('b', 'branch', [], _('a specific branch you would like to pull'),
3689 3689 _('BRANCH')),
3690 3690 ] + remoteopts,
3691 3691 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
3692 3692 def pull(ui, repo, source="default", **opts):
3693 3693 """pull changes from the specified source
3694 3694
3695 3695 Pull changes from a remote repository to a local one.
3696 3696
3697 3697 This finds all changes from the repository at the specified path
3698 3698 or URL and adds them to a local repository (the current one unless
3699 3699 -R is specified). By default, this does not update the copy of the
3700 3700 project in the working directory.
3701 3701
3702 3702 Use :hg:`incoming` if you want to see what would have been added
3703 3703 by a pull at the time you issued this command. If you then decide
3704 3704 to add those changes to the repository, you should use :hg:`pull
3705 3705 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
3706 3706
3707 3707 If SOURCE is omitted, the 'default' path will be used.
3708 3708 See :hg:`help urls` for more information.
3709 3709
3710 3710 Returns 0 on success, 1 if an update had unresolved files.
3711 3711 """
3712 3712 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
3713 3713 other = hg.repository(hg.remoteui(repo, opts), source)
3714 3714 ui.status(_('pulling from %s\n') % util.hidepassword(source))
3715 3715 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
3716 3716
3717 3717 if opts.get('bookmark'):
3718 3718 if not revs:
3719 3719 revs = []
3720 3720 rb = other.listkeys('bookmarks')
3721 3721 for b in opts['bookmark']:
3722 3722 if b not in rb:
3723 3723 raise util.Abort(_('remote bookmark %s not found!') % b)
3724 3724 revs.append(rb[b])
3725 3725
3726 3726 if revs:
3727 3727 try:
3728 3728 revs = [other.lookup(rev) for rev in revs]
3729 3729 except error.CapabilityError:
3730 3730 err = _("other repository doesn't support revision lookup, "
3731 3731 "so a rev cannot be specified.")
3732 3732 raise util.Abort(err)
3733 3733
3734 3734 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
3735 3735 bookmarks.updatefromremote(ui, repo, other)
3736 3736 if checkout:
3737 3737 checkout = str(repo.changelog.rev(other.lookup(checkout)))
3738 3738 repo._subtoppath = source
3739 3739 try:
3740 3740 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
3741 3741
3742 3742 finally:
3743 3743 del repo._subtoppath
3744 3744
3745 3745 # update specified bookmarks
3746 3746 if opts.get('bookmark'):
3747 3747 for b in opts['bookmark']:
3748 3748 # explicit pull overrides local bookmark if any
3749 3749 ui.status(_("importing bookmark %s\n") % b)
3750 3750 repo._bookmarks[b] = repo[rb[b]].node()
3751 3751 bookmarks.write(repo)
3752 3752
3753 3753 return ret
3754 3754
3755 3755 @command('^push',
3756 3756 [('f', 'force', None, _('force push')),
3757 3757 ('r', 'rev', [],
3758 3758 _('a changeset intended to be included in the destination'),
3759 3759 _('REV')),
3760 3760 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
3761 3761 ('b', 'branch', [],
3762 3762 _('a specific branch you would like to push'), _('BRANCH')),
3763 3763 ('', 'new-branch', False, _('allow pushing a new branch')),
3764 3764 ] + remoteopts,
3765 3765 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
3766 3766 def push(ui, repo, dest=None, **opts):
3767 3767 """push changes to the specified destination
3768 3768
3769 3769 Push changesets from the local repository to the specified
3770 3770 destination.
3771 3771
3772 3772 This operation is symmetrical to pull: it is identical to a pull
3773 3773 in the destination repository from the current one.
3774 3774
3775 3775 By default, push will not allow creation of new heads at the
3776 3776 destination, since multiple heads would make it unclear which head
3777 3777 to use. In this situation, it is recommended to pull and merge
3778 3778 before pushing.
3779 3779
3780 3780 Use --new-branch if you want to allow push to create a new named
3781 3781 branch that is not present at the destination. This allows you to
3782 3782 only create a new branch without forcing other changes.
3783 3783
3784 3784 Use -f/--force to override the default behavior and push all
3785 3785 changesets on all branches.
3786 3786
3787 3787 If -r/--rev is used, the specified revision and all its ancestors
3788 3788 will be pushed to the remote repository.
3789 3789
3790 3790 Please see :hg:`help urls` for important details about ``ssh://``
3791 3791 URLs. If DESTINATION is omitted, a default path will be used.
3792 3792
3793 3793 Returns 0 if push was successful, 1 if nothing to push.
3794 3794 """
3795 3795
3796 3796 if opts.get('bookmark'):
3797 3797 for b in opts['bookmark']:
3798 3798 # translate -B options to -r so changesets get pushed
3799 3799 if b in repo._bookmarks:
3800 3800 opts.setdefault('rev', []).append(b)
3801 3801 else:
3802 3802 # if we try to push a deleted bookmark, translate it to null
3803 3803 # this lets simultaneous -r, -b options continue working
3804 3804 opts.setdefault('rev', []).append("null")
3805 3805
3806 3806 dest = ui.expandpath(dest or 'default-push', dest or 'default')
3807 3807 dest, branches = hg.parseurl(dest, opts.get('branch'))
3808 3808 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
3809 3809 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
3810 3810 other = hg.repository(hg.remoteui(repo, opts), dest)
3811 3811 if revs:
3812 3812 revs = [repo.lookup(rev) for rev in revs]
3813 3813
3814 3814 repo._subtoppath = dest
3815 3815 try:
3816 3816 # push subrepos depth-first for coherent ordering
3817 3817 c = repo['']
3818 3818 subs = c.substate # only repos that are committed
3819 3819 for s in sorted(subs):
3820 3820 if not c.sub(s).push(opts.get('force')):
3821 3821 return False
3822 3822 finally:
3823 3823 del repo._subtoppath
3824 3824 result = repo.push(other, opts.get('force'), revs=revs,
3825 3825 newbranch=opts.get('new_branch'))
3826 3826
3827 3827 result = (result == 0)
3828 3828
3829 3829 if opts.get('bookmark'):
3830 3830 rb = other.listkeys('bookmarks')
3831 3831 for b in opts['bookmark']:
3832 3832 # explicit push overrides remote bookmark if any
3833 3833 if b in repo._bookmarks:
3834 3834 ui.status(_("exporting bookmark %s\n") % b)
3835 3835 new = repo[b].hex()
3836 3836 elif b in rb:
3837 3837 ui.status(_("deleting remote bookmark %s\n") % b)
3838 3838 new = '' # delete
3839 3839 else:
3840 3840 ui.warn(_('bookmark %s does not exist on the local '
3841 3841 'or remote repository!\n') % b)
3842 3842 return 2
3843 3843 old = rb.get(b, '')
3844 3844 r = other.pushkey('bookmarks', b, old, new)
3845 3845 if not r:
3846 3846 ui.warn(_('updating bookmark %s failed!\n') % b)
3847 3847 if not result:
3848 3848 result = 2
3849 3849
3850 3850 return result
3851 3851
3852 3852 @command('recover', [])
3853 3853 def recover(ui, repo):
3854 3854 """roll back an interrupted transaction
3855 3855
3856 3856 Recover from an interrupted commit or pull.
3857 3857
3858 3858 This command tries to fix the repository status after an
3859 3859 interrupted operation. It should only be necessary when Mercurial
3860 3860 suggests it.
3861 3861
3862 3862 Returns 0 if successful, 1 if nothing to recover or verify fails.
3863 3863 """
3864 3864 if repo.recover():
3865 3865 return hg.verify(repo)
3866 3866 return 1
3867 3867
3868 3868 @command('^remove|rm',
3869 3869 [('A', 'after', None, _('record delete for missing files')),
3870 3870 ('f', 'force', None,
3871 3871 _('remove (and delete) file even if added or modified')),
3872 3872 ] + walkopts,
3873 3873 _('[OPTION]... FILE...'))
3874 3874 def remove(ui, repo, *pats, **opts):
3875 3875 """remove the specified files on the next commit
3876 3876
3877 3877 Schedule the indicated files for removal from the repository.
3878 3878
3879 3879 This only removes files from the current branch, not from the
3880 3880 entire project history. -A/--after can be used to remove only
3881 3881 files that have already been deleted, -f/--force can be used to
3882 3882 force deletion, and -Af can be used to remove files from the next
3883 3883 revision without deleting them from the working directory.
3884 3884
3885 3885 The following table details the behavior of remove for different
3886 3886 file states (columns) and option combinations (rows). The file
3887 3887 states are Added [A], Clean [C], Modified [M] and Missing [!] (as
3888 3888 reported by :hg:`status`). The actions are Warn, Remove (from
3889 3889 branch) and Delete (from disk)::
3890 3890
3891 3891 A C M !
3892 3892 none W RD W R
3893 3893 -f R RD RD R
3894 3894 -A W W W R
3895 3895 -Af R R R R
3896 3896
3897 3897 Note that remove never deletes files in Added [A] state from the
3898 3898 working directory, not even if option --force is specified.
3899 3899
3900 3900 This command schedules the files to be removed at the next commit.
3901 3901 To undo a remove before that, see :hg:`revert`.
3902 3902
3903 3903 Returns 0 on success, 1 if any warnings encountered.
3904 3904 """
3905 3905
3906 3906 ret = 0
3907 3907 after, force = opts.get('after'), opts.get('force')
3908 3908 if not pats and not after:
3909 3909 raise util.Abort(_('no files specified'))
3910 3910
3911 3911 m = scmutil.match(repo, pats, opts)
3912 3912 s = repo.status(match=m, clean=True)
3913 3913 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
3914 3914
3915 3915 for f in m.files():
3916 3916 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
3917 3917 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
3918 3918 ret = 1
3919 3919
3920 3920 if force:
3921 3921 remove, forget = modified + deleted + clean, added
3922 3922 elif after:
3923 3923 remove, forget = deleted, []
3924 3924 for f in modified + added + clean:
3925 3925 ui.warn(_('not removing %s: file still exists (use -f'
3926 3926 ' to force removal)\n') % m.rel(f))
3927 3927 ret = 1
3928 3928 else:
3929 3929 remove, forget = deleted + clean, []
3930 3930 for f in modified:
3931 3931 ui.warn(_('not removing %s: file is modified (use -f'
3932 3932 ' to force removal)\n') % m.rel(f))
3933 3933 ret = 1
3934 3934 for f in added:
3935 3935 ui.warn(_('not removing %s: file has been marked for add (use -f'
3936 3936 ' to force removal)\n') % m.rel(f))
3937 3937 ret = 1
3938 3938
3939 3939 for f in sorted(remove + forget):
3940 3940 if ui.verbose or not m.exact(f):
3941 3941 ui.status(_('removing %s\n') % m.rel(f))
3942 3942
3943 3943 repo[None].forget(forget)
3944 3944 repo[None].remove(remove, unlink=not after)
3945 3945 return ret
3946 3946
3947 3947 @command('rename|move|mv',
3948 3948 [('A', 'after', None, _('record a rename that has already occurred')),
3949 3949 ('f', 'force', None, _('forcibly copy over an existing managed file')),
3950 3950 ] + walkopts + dryrunopts,
3951 3951 _('[OPTION]... SOURCE... DEST'))
3952 3952 def rename(ui, repo, *pats, **opts):
3953 3953 """rename files; equivalent of copy + remove
3954 3954
3955 3955 Mark dest as copies of sources; mark sources for deletion. If dest
3956 3956 is a directory, copies are put in that directory. If dest is a
3957 3957 file, there can only be one source.
3958 3958
3959 3959 By default, this command copies the contents of files as they
3960 3960 exist in the working directory. If invoked with -A/--after, the
3961 3961 operation is recorded, but no copying is performed.
3962 3962
3963 3963 This command takes effect at the next commit. To undo a rename
3964 3964 before that, see :hg:`revert`.
3965 3965
3966 3966 Returns 0 on success, 1 if errors are encountered.
3967 3967 """
3968 3968 wlock = repo.wlock(False)
3969 3969 try:
3970 3970 return cmdutil.copy(ui, repo, pats, opts, rename=True)
3971 3971 finally:
3972 3972 wlock.release()
3973 3973
3974 3974 @command('resolve',
3975 3975 [('a', 'all', None, _('select all unresolved files')),
3976 3976 ('l', 'list', None, _('list state of files needing merge')),
3977 3977 ('m', 'mark', None, _('mark files as resolved')),
3978 3978 ('u', 'unmark', None, _('mark files as unresolved')),
3979 3979 ('t', 'tool', '', _('specify merge tool')),
3980 3980 ('n', 'no-status', None, _('hide status prefix'))]
3981 3981 + walkopts,
3982 3982 _('[OPTION]... [FILE]...'))
3983 3983 def resolve(ui, repo, *pats, **opts):
3984 3984 """redo merges or set/view the merge status of files
3985 3985
3986 3986 Merges with unresolved conflicts are often the result of
3987 3987 non-interactive merging using the ``internal:merge`` configuration
3988 3988 setting, or a command-line merge tool like ``diff3``. The resolve
3989 3989 command is used to manage the files involved in a merge, after
3990 3990 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
3991 3991 working directory must have two parents).
3992 3992
3993 3993 The resolve command can be used in the following ways:
3994 3994
3995 3995 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
3996 3996 files, discarding any previous merge attempts. Re-merging is not
3997 3997 performed for files already marked as resolved. Use ``--all/-a``
3998 3998 to selects all unresolved files. ``--tool`` can be used to specify
3999 3999 the merge tool used for the given files. It overrides the HGMERGE
4000 4000 environment variable and your configuration files.
4001 4001
4002 4002 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4003 4003 (e.g. after having manually fixed-up the files). The default is
4004 4004 to mark all unresolved files.
4005 4005
4006 4006 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4007 4007 default is to mark all resolved files.
4008 4008
4009 4009 - :hg:`resolve -l`: list files which had or still have conflicts.
4010 4010 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4011 4011
4012 4012 Note that Mercurial will not let you commit files with unresolved
4013 4013 merge conflicts. You must use :hg:`resolve -m ...` before you can
4014 4014 commit after a conflicting merge.
4015 4015
4016 4016 Returns 0 on success, 1 if any files fail a resolve attempt.
4017 4017 """
4018 4018
4019 4019 all, mark, unmark, show, nostatus = \
4020 4020 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
4021 4021
4022 4022 if (show and (mark or unmark)) or (mark and unmark):
4023 4023 raise util.Abort(_("too many options specified"))
4024 4024 if pats and all:
4025 4025 raise util.Abort(_("can't specify --all and patterns"))
4026 4026 if not (all or pats or show or mark or unmark):
4027 4027 raise util.Abort(_('no files or directories specified; '
4028 4028 'use --all to remerge all files'))
4029 4029
4030 4030 ms = mergemod.mergestate(repo)
4031 4031 m = scmutil.match(repo, pats, opts)
4032 4032 ret = 0
4033 4033
4034 4034 for f in ms:
4035 4035 if m(f):
4036 4036 if show:
4037 4037 if nostatus:
4038 4038 ui.write("%s\n" % f)
4039 4039 else:
4040 4040 ui.write("%s %s\n" % (ms[f].upper(), f),
4041 4041 label='resolve.' +
4042 4042 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
4043 4043 elif mark:
4044 4044 ms.mark(f, "r")
4045 4045 elif unmark:
4046 4046 ms.mark(f, "u")
4047 4047 else:
4048 4048 wctx = repo[None]
4049 4049 mctx = wctx.parents()[-1]
4050 4050
4051 4051 # backup pre-resolve (merge uses .orig for its own purposes)
4052 4052 a = repo.wjoin(f)
4053 4053 util.copyfile(a, a + ".resolve")
4054 4054
4055 4055 try:
4056 4056 # resolve file
4057 4057 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
4058 4058 if ms.resolve(f, wctx, mctx):
4059 4059 ret = 1
4060 4060 finally:
4061 4061 ui.setconfig('ui', 'forcemerge', '')
4062 4062
4063 4063 # replace filemerge's .orig file with our resolve file
4064 4064 util.rename(a + ".resolve", a + ".orig")
4065 4065
4066 4066 ms.commit()
4067 4067 return ret
4068 4068
4069 4069 @command('revert',
4070 4070 [('a', 'all', None, _('revert all changes when no arguments given')),
4071 4071 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4072 4072 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
4073 4073 ('', 'no-backup', None, _('do not save backup copies of files')),
4074 4074 ] + walkopts + dryrunopts,
4075 4075 _('[OPTION]... [-r REV] [NAME]...'))
4076 4076 def revert(ui, repo, *pats, **opts):
4077 4077 """restore individual files or directories to an earlier state
4078 4078
4079 4079 .. note::
4080 4080 This command is most likely not what you are looking for.
4081 4081 Revert will partially overwrite content in the working
4082 4082 directory without changing the working directory parents. Use
4083 4083 :hg:`update -r rev` to check out earlier revisions, or
4084 4084 :hg:`update --clean .` to undo a merge which has added another
4085 4085 parent.
4086 4086
4087 4087 With no revision specified, revert the named files or directories
4088 4088 to the contents they had in the parent of the working directory.
4089 4089 This restores the contents of the affected files to an unmodified
4090 4090 state and unschedules adds, removes, copies, and renames. If the
4091 4091 working directory has two parents, you must explicitly specify a
4092 4092 revision.
4093 4093
4094 4094 Using the -r/--rev option, revert the given files or directories
4095 4095 to their contents as of a specific revision. This can be helpful
4096 4096 to "roll back" some or all of an earlier change. See :hg:`help
4097 4097 dates` for a list of formats valid for -d/--date.
4098 4098
4099 4099 Revert modifies the working directory. It does not commit any
4100 4100 changes, or change the parent of the working directory. If you
4101 4101 revert to a revision other than the parent of the working
4102 4102 directory, the reverted files will thus appear modified
4103 4103 afterwards.
4104 4104
4105 4105 If a file has been deleted, it is restored. Files scheduled for
4106 4106 addition are just unscheduled and left as they are. If the
4107 4107 executable mode of a file was changed, it is reset.
4108 4108
4109 4109 If names are given, all files matching the names are reverted.
4110 4110 If no arguments are given, no files are reverted.
4111 4111
4112 4112 Modified files are saved with a .orig suffix before reverting.
4113 4113 To disable these backups, use --no-backup.
4114 4114
4115 4115 Returns 0 on success.
4116 4116 """
4117 4117
4118 4118 if opts.get("date"):
4119 4119 if opts.get("rev"):
4120 4120 raise util.Abort(_("you can't specify a revision and a date"))
4121 4121 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
4122 4122
4123 4123 parent, p2 = repo.dirstate.parents()
4124 4124 if not opts.get('rev') and p2 != nullid:
4125 4125 raise util.Abort(_('uncommitted merge - '
4126 4126 'use "hg update", see "hg help revert"'))
4127 4127
4128 4128 if not pats and not opts.get('all'):
4129 4129 raise util.Abort(_('no files or directories specified; '
4130 4130 'use --all to revert the whole repo'))
4131 4131
4132 4132 ctx = scmutil.revsingle(repo, opts.get('rev'))
4133 4133 node = ctx.node()
4134 4134 mf = ctx.manifest()
4135 4135 if node == parent:
4136 4136 pmf = mf
4137 4137 else:
4138 4138 pmf = None
4139 4139
4140 4140 # need all matching names in dirstate and manifest of target rev,
4141 4141 # so have to walk both. do not print errors if files exist in one
4142 4142 # but not other.
4143 4143
4144 4144 names = {}
4145 4145
4146 4146 wlock = repo.wlock()
4147 4147 try:
4148 4148 # walk dirstate.
4149 4149
4150 4150 m = scmutil.match(repo, pats, opts)
4151 4151 m.bad = lambda x, y: False
4152 4152 for abs in repo.walk(m):
4153 4153 names[abs] = m.rel(abs), m.exact(abs)
4154 4154
4155 4155 # walk target manifest.
4156 4156
4157 4157 def badfn(path, msg):
4158 4158 if path in names:
4159 4159 return
4160 4160 path_ = path + '/'
4161 4161 for f in names:
4162 4162 if f.startswith(path_):
4163 4163 return
4164 4164 ui.warn("%s: %s\n" % (m.rel(path), msg))
4165 4165
4166 4166 m = scmutil.match(repo, pats, opts)
4167 4167 m.bad = badfn
4168 4168 for abs in repo[node].walk(m):
4169 4169 if abs not in names:
4170 4170 names[abs] = m.rel(abs), m.exact(abs)
4171 4171
4172 4172 m = scmutil.matchfiles(repo, names)
4173 4173 changes = repo.status(match=m)[:4]
4174 4174 modified, added, removed, deleted = map(set, changes)
4175 4175
4176 4176 # if f is a rename, also revert the source
4177 4177 cwd = repo.getcwd()
4178 4178 for f in added:
4179 4179 src = repo.dirstate.copied(f)
4180 4180 if src and src not in names and repo.dirstate[src] == 'r':
4181 4181 removed.add(src)
4182 4182 names[src] = (repo.pathto(src, cwd), True)
4183 4183
4184 4184 def removeforget(abs):
4185 4185 if repo.dirstate[abs] == 'a':
4186 4186 return _('forgetting %s\n')
4187 4187 return _('removing %s\n')
4188 4188
4189 4189 revert = ([], _('reverting %s\n'))
4190 4190 add = ([], _('adding %s\n'))
4191 4191 remove = ([], removeforget)
4192 4192 undelete = ([], _('undeleting %s\n'))
4193 4193
4194 4194 disptable = (
4195 4195 # dispatch table:
4196 4196 # file state
4197 4197 # action if in target manifest
4198 4198 # action if not in target manifest
4199 4199 # make backup if in target manifest
4200 4200 # make backup if not in target manifest
4201 4201 (modified, revert, remove, True, True),
4202 4202 (added, revert, remove, True, False),
4203 4203 (removed, undelete, None, False, False),
4204 4204 (deleted, revert, remove, False, False),
4205 4205 )
4206 4206
4207 4207 for abs, (rel, exact) in sorted(names.items()):
4208 4208 mfentry = mf.get(abs)
4209 4209 target = repo.wjoin(abs)
4210 4210 def handle(xlist, dobackup):
4211 4211 xlist[0].append(abs)
4212 4212 if (dobackup and not opts.get('no_backup') and
4213 4213 os.path.lexists(target)):
4214 4214 bakname = "%s.orig" % rel
4215 4215 ui.note(_('saving current version of %s as %s\n') %
4216 4216 (rel, bakname))
4217 4217 if not opts.get('dry_run'):
4218 4218 util.rename(target, bakname)
4219 4219 if ui.verbose or not exact:
4220 4220 msg = xlist[1]
4221 4221 if not isinstance(msg, basestring):
4222 4222 msg = msg(abs)
4223 4223 ui.status(msg % rel)
4224 4224 for table, hitlist, misslist, backuphit, backupmiss in disptable:
4225 4225 if abs not in table:
4226 4226 continue
4227 4227 # file has changed in dirstate
4228 4228 if mfentry:
4229 4229 handle(hitlist, backuphit)
4230 4230 elif misslist is not None:
4231 4231 handle(misslist, backupmiss)
4232 4232 break
4233 4233 else:
4234 4234 if abs not in repo.dirstate:
4235 4235 if mfentry:
4236 4236 handle(add, True)
4237 4237 elif exact:
4238 4238 ui.warn(_('file not managed: %s\n') % rel)
4239 4239 continue
4240 4240 # file has not changed in dirstate
4241 4241 if node == parent:
4242 4242 if exact:
4243 4243 ui.warn(_('no changes needed to %s\n') % rel)
4244 4244 continue
4245 4245 if pmf is None:
4246 4246 # only need parent manifest in this unlikely case,
4247 4247 # so do not read by default
4248 4248 pmf = repo[parent].manifest()
4249 4249 if abs in pmf:
4250 4250 if mfentry:
4251 4251 # if version of file is same in parent and target
4252 4252 # manifests, do nothing
4253 4253 if (pmf[abs] != mfentry or
4254 4254 pmf.flags(abs) != mf.flags(abs)):
4255 4255 handle(revert, False)
4256 4256 else:
4257 4257 handle(remove, False)
4258 4258
4259 4259 if not opts.get('dry_run'):
4260 4260 def checkout(f):
4261 4261 fc = ctx[f]
4262 4262 repo.wwrite(f, fc.data(), fc.flags())
4263 4263
4264 4264 audit_path = scmutil.pathauditor(repo.root)
4265 4265 for f in remove[0]:
4266 4266 if repo.dirstate[f] == 'a':
4267 4267 repo.dirstate.drop(f)
4268 4268 continue
4269 4269 audit_path(f)
4270 4270 try:
4271 4271 util.unlinkpath(repo.wjoin(f))
4272 4272 except OSError:
4273 4273 pass
4274 4274 repo.dirstate.remove(f)
4275 4275
4276 4276 normal = None
4277 4277 if node == parent:
4278 4278 # We're reverting to our parent. If possible, we'd like status
4279 4279 # to report the file as clean. We have to use normallookup for
4280 4280 # merges to avoid losing information about merged/dirty files.
4281 4281 if p2 != nullid:
4282 4282 normal = repo.dirstate.normallookup
4283 4283 else:
4284 4284 normal = repo.dirstate.normal
4285 4285 for f in revert[0]:
4286 4286 checkout(f)
4287 4287 if normal:
4288 4288 normal(f)
4289 4289
4290 4290 for f in add[0]:
4291 4291 checkout(f)
4292 4292 repo.dirstate.add(f)
4293 4293
4294 4294 normal = repo.dirstate.normallookup
4295 4295 if node == parent and p2 == nullid:
4296 4296 normal = repo.dirstate.normal
4297 4297 for f in undelete[0]:
4298 4298 checkout(f)
4299 4299 normal(f)
4300 4300
4301 4301 finally:
4302 4302 wlock.release()
4303 4303
4304 4304 @command('rollback', dryrunopts)
4305 4305 def rollback(ui, repo, **opts):
4306 4306 """roll back the last transaction (dangerous)
4307 4307
4308 4308 This command should be used with care. There is only one level of
4309 4309 rollback, and there is no way to undo a rollback. It will also
4310 4310 restore the dirstate at the time of the last transaction, losing
4311 4311 any dirstate changes since that time. This command does not alter
4312 4312 the working directory.
4313 4313
4314 4314 Transactions are used to encapsulate the effects of all commands
4315 4315 that create new changesets or propagate existing changesets into a
4316 4316 repository. For example, the following commands are transactional,
4317 4317 and their effects can be rolled back:
4318 4318
4319 4319 - commit
4320 4320 - import
4321 4321 - pull
4322 4322 - push (with this repository as the destination)
4323 4323 - unbundle
4324 4324
4325 4325 This command is not intended for use on public repositories. Once
4326 4326 changes are visible for pull by other users, rolling a transaction
4327 4327 back locally is ineffective (someone else may already have pulled
4328 4328 the changes). Furthermore, a race is possible with readers of the
4329 4329 repository; for example an in-progress pull from the repository
4330 4330 may fail if a rollback is performed.
4331 4331
4332 4332 Returns 0 on success, 1 if no rollback data is available.
4333 4333 """
4334 4334 return repo.rollback(opts.get('dry_run'))
4335 4335
4336 4336 @command('root', [])
4337 4337 def root(ui, repo):
4338 4338 """print the root (top) of the current working directory
4339 4339
4340 4340 Print the root directory of the current repository.
4341 4341
4342 4342 Returns 0 on success.
4343 4343 """
4344 4344 ui.write(repo.root + "\n")
4345 4345
4346 4346 @command('^serve',
4347 4347 [('A', 'accesslog', '', _('name of access log file to write to'),
4348 4348 _('FILE')),
4349 4349 ('d', 'daemon', None, _('run server in background')),
4350 4350 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('NUM')),
4351 4351 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
4352 4352 # use string type, then we can check if something was passed
4353 4353 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
4354 4354 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
4355 4355 _('ADDR')),
4356 4356 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
4357 4357 _('PREFIX')),
4358 4358 ('n', 'name', '',
4359 4359 _('name to show in web pages (default: working directory)'), _('NAME')),
4360 4360 ('', 'web-conf', '',
4361 4361 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
4362 4362 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
4363 4363 _('FILE')),
4364 4364 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
4365 4365 ('', 'stdio', None, _('for remote clients')),
4366 4366 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
4367 4367 ('', 'style', '', _('template style to use'), _('STYLE')),
4368 4368 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
4369 4369 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
4370 4370 _('[OPTION]...'))
4371 4371 def serve(ui, repo, **opts):
4372 4372 """start stand-alone webserver
4373 4373
4374 4374 Start a local HTTP repository browser and pull server. You can use
4375 4375 this for ad-hoc sharing and browsing of repositories. It is
4376 4376 recommended to use a real web server to serve a repository for
4377 4377 longer periods of time.
4378 4378
4379 4379 Please note that the server does not implement access control.
4380 4380 This means that, by default, anybody can read from the server and
4381 4381 nobody can write to it by default. Set the ``web.allow_push``
4382 4382 option to ``*`` to allow everybody to push to the server. You
4383 4383 should use a real web server if you need to authenticate users.
4384 4384
4385 4385 By default, the server logs accesses to stdout and errors to
4386 4386 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
4387 4387 files.
4388 4388
4389 4389 To have the server choose a free port number to listen on, specify
4390 4390 a port number of 0; in this case, the server will print the port
4391 4391 number it uses.
4392 4392
4393 4393 Returns 0 on success.
4394 4394 """
4395 4395
4396 4396 if opts["stdio"]:
4397 4397 if repo is None:
4398 4398 raise error.RepoError(_("There is no Mercurial repository here"
4399 4399 " (.hg not found)"))
4400 4400 s = sshserver.sshserver(ui, repo)
4401 4401 s.serve_forever()
4402 4402
4403 4403 # this way we can check if something was given in the command-line
4404 4404 if opts.get('port'):
4405 4405 opts['port'] = util.getport(opts.get('port'))
4406 4406
4407 4407 baseui = repo and repo.baseui or ui
4408 4408 optlist = ("name templates style address port prefix ipv6"
4409 4409 " accesslog errorlog certificate encoding")
4410 4410 for o in optlist.split():
4411 4411 val = opts.get(o, '')
4412 4412 if val in (None, ''): # should check against default options instead
4413 4413 continue
4414 4414 baseui.setconfig("web", o, val)
4415 4415 if repo and repo.ui != baseui:
4416 4416 repo.ui.setconfig("web", o, val)
4417 4417
4418 4418 o = opts.get('web_conf') or opts.get('webdir_conf')
4419 4419 if not o:
4420 4420 if not repo:
4421 4421 raise error.RepoError(_("There is no Mercurial repository"
4422 4422 " here (.hg not found)"))
4423 4423 o = repo.root
4424 4424
4425 4425 app = hgweb.hgweb(o, baseui=ui)
4426 4426
4427 4427 class service(object):
4428 4428 def init(self):
4429 4429 util.setsignalhandler()
4430 4430 self.httpd = hgweb.server.create_server(ui, app)
4431 4431
4432 4432 if opts['port'] and not ui.verbose:
4433 4433 return
4434 4434
4435 4435 if self.httpd.prefix:
4436 4436 prefix = self.httpd.prefix.strip('/') + '/'
4437 4437 else:
4438 4438 prefix = ''
4439 4439
4440 4440 port = ':%d' % self.httpd.port
4441 4441 if port == ':80':
4442 4442 port = ''
4443 4443
4444 4444 bindaddr = self.httpd.addr
4445 4445 if bindaddr == '0.0.0.0':
4446 4446 bindaddr = '*'
4447 4447 elif ':' in bindaddr: # IPv6
4448 4448 bindaddr = '[%s]' % bindaddr
4449 4449
4450 4450 fqaddr = self.httpd.fqaddr
4451 4451 if ':' in fqaddr:
4452 4452 fqaddr = '[%s]' % fqaddr
4453 4453 if opts['port']:
4454 4454 write = ui.status
4455 4455 else:
4456 4456 write = ui.write
4457 4457 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
4458 4458 (fqaddr, port, prefix, bindaddr, self.httpd.port))
4459 4459
4460 4460 def run(self):
4461 4461 self.httpd.serve_forever()
4462 4462
4463 4463 service = service()
4464 4464
4465 4465 cmdutil.service(opts, initfn=service.init, runfn=service.run)
4466 4466
4467 4467 @command('showconfig|debugconfig',
4468 4468 [('u', 'untrusted', None, _('show untrusted configuration options'))],
4469 4469 _('[-u] [NAME]...'))
4470 4470 def showconfig(ui, repo, *values, **opts):
4471 4471 """show combined config settings from all hgrc files
4472 4472
4473 4473 With no arguments, print names and values of all config items.
4474 4474
4475 4475 With one argument of the form section.name, print just the value
4476 4476 of that config item.
4477 4477
4478 4478 With multiple arguments, print names and values of all config
4479 4479 items with matching section names.
4480 4480
4481 4481 With --debug, the source (filename and line number) is printed
4482 4482 for each config item.
4483 4483
4484 4484 Returns 0 on success.
4485 4485 """
4486 4486
4487 4487 for f in scmutil.rcpath():
4488 4488 ui.debug(_('read config from: %s\n') % f)
4489 4489 untrusted = bool(opts.get('untrusted'))
4490 4490 if values:
4491 4491 sections = [v for v in values if '.' not in v]
4492 4492 items = [v for v in values if '.' in v]
4493 4493 if len(items) > 1 or items and sections:
4494 4494 raise util.Abort(_('only one config item permitted'))
4495 4495 for section, name, value in ui.walkconfig(untrusted=untrusted):
4496 4496 value = str(value).replace('\n', '\\n')
4497 4497 sectname = section + '.' + name
4498 4498 if values:
4499 4499 for v in values:
4500 4500 if v == section:
4501 4501 ui.debug('%s: ' %
4502 4502 ui.configsource(section, name, untrusted))
4503 4503 ui.write('%s=%s\n' % (sectname, value))
4504 4504 elif v == sectname:
4505 4505 ui.debug('%s: ' %
4506 4506 ui.configsource(section, name, untrusted))
4507 4507 ui.write(value, '\n')
4508 4508 else:
4509 4509 ui.debug('%s: ' %
4510 4510 ui.configsource(section, name, untrusted))
4511 4511 ui.write('%s=%s\n' % (sectname, value))
4512 4512
4513 4513 @command('^status|st',
4514 4514 [('A', 'all', None, _('show status of all files')),
4515 4515 ('m', 'modified', None, _('show only modified files')),
4516 4516 ('a', 'added', None, _('show only added files')),
4517 4517 ('r', 'removed', None, _('show only removed files')),
4518 4518 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
4519 4519 ('c', 'clean', None, _('show only files without changes')),
4520 4520 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
4521 4521 ('i', 'ignored', None, _('show only ignored files')),
4522 4522 ('n', 'no-status', None, _('hide status prefix')),
4523 4523 ('C', 'copies', None, _('show source of copied files')),
4524 4524 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
4525 4525 ('', 'rev', [], _('show difference from revision'), _('REV')),
4526 4526 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
4527 4527 ] + walkopts + subrepoopts,
4528 4528 _('[OPTION]... [FILE]...'))
4529 4529 def status(ui, repo, *pats, **opts):
4530 4530 """show changed files in the working directory
4531 4531
4532 4532 Show status of files in the repository. If names are given, only
4533 4533 files that match are shown. Files that are clean or ignored or
4534 4534 the source of a copy/move operation, are not listed unless
4535 4535 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
4536 4536 Unless options described with "show only ..." are given, the
4537 4537 options -mardu are used.
4538 4538
4539 4539 Option -q/--quiet hides untracked (unknown and ignored) files
4540 4540 unless explicitly requested with -u/--unknown or -i/--ignored.
4541 4541
4542 4542 .. note::
4543 4543 status may appear to disagree with diff if permissions have
4544 4544 changed or a merge has occurred. The standard diff format does
4545 4545 not report permission changes and diff only reports changes
4546 4546 relative to one merge parent.
4547 4547
4548 4548 If one revision is given, it is used as the base revision.
4549 4549 If two revisions are given, the differences between them are
4550 4550 shown. The --change option can also be used as a shortcut to list
4551 4551 the changed files of a revision from its first parent.
4552 4552
4553 4553 The codes used to show the status of files are::
4554 4554
4555 4555 M = modified
4556 4556 A = added
4557 4557 R = removed
4558 4558 C = clean
4559 4559 ! = missing (deleted by non-hg command, but still tracked)
4560 4560 ? = not tracked
4561 4561 I = ignored
4562 4562 = origin of the previous file listed as A (added)
4563 4563
4564 4564 Returns 0 on success.
4565 4565 """
4566 4566
4567 4567 revs = opts.get('rev')
4568 4568 change = opts.get('change')
4569 4569
4570 4570 if revs and change:
4571 4571 msg = _('cannot specify --rev and --change at the same time')
4572 4572 raise util.Abort(msg)
4573 4573 elif change:
4574 4574 node2 = repo.lookup(change)
4575 4575 node1 = repo[node2].p1().node()
4576 4576 else:
4577 4577 node1, node2 = scmutil.revpair(repo, revs)
4578 4578
4579 4579 cwd = (pats and repo.getcwd()) or ''
4580 4580 end = opts.get('print0') and '\0' or '\n'
4581 4581 copy = {}
4582 4582 states = 'modified added removed deleted unknown ignored clean'.split()
4583 4583 show = [k for k in states if opts.get(k)]
4584 4584 if opts.get('all'):
4585 4585 show += ui.quiet and (states[:4] + ['clean']) or states
4586 4586 if not show:
4587 4587 show = ui.quiet and states[:4] or states[:5]
4588 4588
4589 4589 stat = repo.status(node1, node2, scmutil.match(repo, pats, opts),
4590 4590 'ignored' in show, 'clean' in show, 'unknown' in show,
4591 4591 opts.get('subrepos'))
4592 4592 changestates = zip(states, 'MAR!?IC', stat)
4593 4593
4594 4594 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
4595 4595 ctxn = repo[nullid]
4596 4596 ctx1 = repo[node1]
4597 4597 ctx2 = repo[node2]
4598 4598 added = stat[1]
4599 4599 if node2 is None:
4600 4600 added = stat[0] + stat[1] # merged?
4601 4601
4602 4602 for k, v in copies.copies(repo, ctx1, ctx2, ctxn)[0].iteritems():
4603 4603 if k in added:
4604 4604 copy[k] = v
4605 4605 elif v in added:
4606 4606 copy[v] = k
4607 4607
4608 4608 for state, char, files in changestates:
4609 4609 if state in show:
4610 4610 format = "%s %%s%s" % (char, end)
4611 4611 if opts.get('no_status'):
4612 4612 format = "%%s%s" % end
4613 4613
4614 4614 for f in files:
4615 4615 ui.write(format % repo.pathto(f, cwd),
4616 4616 label='status.' + state)
4617 4617 if f in copy:
4618 4618 ui.write(' %s%s' % (repo.pathto(copy[f], cwd), end),
4619 4619 label='status.copied')
4620 4620
4621 4621 @command('^summary|sum',
4622 4622 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
4623 4623 def summary(ui, repo, **opts):
4624 4624 """summarize working directory state
4625 4625
4626 4626 This generates a brief summary of the working directory state,
4627 4627 including parents, branch, commit status, and available updates.
4628 4628
4629 4629 With the --remote option, this will check the default paths for
4630 4630 incoming and outgoing changes. This can be time-consuming.
4631 4631
4632 4632 Returns 0 on success.
4633 4633 """
4634 4634
4635 4635 ctx = repo[None]
4636 4636 parents = ctx.parents()
4637 4637 pnode = parents[0].node()
4638 4638
4639 4639 for p in parents:
4640 4640 # label with log.changeset (instead of log.parent) since this
4641 4641 # shows a working directory parent *changeset*:
4642 4642 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
4643 4643 label='log.changeset')
4644 4644 ui.write(' '.join(p.tags()), label='log.tag')
4645 4645 if p.bookmarks():
4646 4646 ui.write(' ' + ' '.join(p.bookmarks()), label='log.bookmark')
4647 4647 if p.rev() == -1:
4648 4648 if not len(repo):
4649 4649 ui.write(_(' (empty repository)'))
4650 4650 else:
4651 4651 ui.write(_(' (no revision checked out)'))
4652 4652 ui.write('\n')
4653 4653 if p.description():
4654 4654 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
4655 4655 label='log.summary')
4656 4656
4657 4657 branch = ctx.branch()
4658 4658 bheads = repo.branchheads(branch)
4659 4659 m = _('branch: %s\n') % branch
4660 4660 if branch != 'default':
4661 4661 ui.write(m, label='log.branch')
4662 4662 else:
4663 4663 ui.status(m, label='log.branch')
4664 4664
4665 4665 st = list(repo.status(unknown=True))[:6]
4666 4666
4667 4667 c = repo.dirstate.copies()
4668 4668 copied, renamed = [], []
4669 4669 for d, s in c.iteritems():
4670 4670 if s in st[2]:
4671 4671 st[2].remove(s)
4672 4672 renamed.append(d)
4673 4673 else:
4674 4674 copied.append(d)
4675 4675 if d in st[1]:
4676 4676 st[1].remove(d)
4677 4677 st.insert(3, renamed)
4678 4678 st.insert(4, copied)
4679 4679
4680 4680 ms = mergemod.mergestate(repo)
4681 4681 st.append([f for f in ms if ms[f] == 'u'])
4682 4682
4683 4683 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
4684 4684 st.append(subs)
4685 4685
4686 4686 labels = [ui.label(_('%d modified'), 'status.modified'),
4687 4687 ui.label(_('%d added'), 'status.added'),
4688 4688 ui.label(_('%d removed'), 'status.removed'),
4689 4689 ui.label(_('%d renamed'), 'status.copied'),
4690 4690 ui.label(_('%d copied'), 'status.copied'),
4691 4691 ui.label(_('%d deleted'), 'status.deleted'),
4692 4692 ui.label(_('%d unknown'), 'status.unknown'),
4693 4693 ui.label(_('%d ignored'), 'status.ignored'),
4694 4694 ui.label(_('%d unresolved'), 'resolve.unresolved'),
4695 4695 ui.label(_('%d subrepos'), 'status.modified')]
4696 4696 t = []
4697 4697 for s, l in zip(st, labels):
4698 4698 if s:
4699 4699 t.append(l % len(s))
4700 4700
4701 4701 t = ', '.join(t)
4702 4702 cleanworkdir = False
4703 4703
4704 4704 if len(parents) > 1:
4705 4705 t += _(' (merge)')
4706 4706 elif branch != parents[0].branch():
4707 4707 t += _(' (new branch)')
4708 4708 elif (parents[0].extra().get('close') and
4709 4709 pnode in repo.branchheads(branch, closed=True)):
4710 4710 t += _(' (head closed)')
4711 4711 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[9]):
4712 4712 t += _(' (clean)')
4713 4713 cleanworkdir = True
4714 4714 elif pnode not in bheads:
4715 4715 t += _(' (new branch head)')
4716 4716
4717 4717 if cleanworkdir:
4718 4718 ui.status(_('commit: %s\n') % t.strip())
4719 4719 else:
4720 4720 ui.write(_('commit: %s\n') % t.strip())
4721 4721
4722 4722 # all ancestors of branch heads - all ancestors of parent = new csets
4723 4723 new = [0] * len(repo)
4724 4724 cl = repo.changelog
4725 4725 for a in [cl.rev(n) for n in bheads]:
4726 4726 new[a] = 1
4727 4727 for a in cl.ancestors(*[cl.rev(n) for n in bheads]):
4728 4728 new[a] = 1
4729 4729 for a in [p.rev() for p in parents]:
4730 4730 if a >= 0:
4731 4731 new[a] = 0
4732 4732 for a in cl.ancestors(*[p.rev() for p in parents]):
4733 4733 new[a] = 0
4734 4734 new = sum(new)
4735 4735
4736 4736 if new == 0:
4737 4737 ui.status(_('update: (current)\n'))
4738 4738 elif pnode not in bheads:
4739 4739 ui.write(_('update: %d new changesets (update)\n') % new)
4740 4740 else:
4741 4741 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
4742 4742 (new, len(bheads)))
4743 4743
4744 4744 if opts.get('remote'):
4745 4745 t = []
4746 4746 source, branches = hg.parseurl(ui.expandpath('default'))
4747 4747 other = hg.repository(hg.remoteui(repo, {}), source)
4748 4748 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
4749 4749 ui.debug('comparing with %s\n' % util.hidepassword(source))
4750 4750 repo.ui.pushbuffer()
4751 4751 commoninc = discovery.findcommonincoming(repo, other)
4752 4752 _common, incoming, _rheads = commoninc
4753 4753 repo.ui.popbuffer()
4754 4754 if incoming:
4755 4755 t.append(_('1 or more incoming'))
4756 4756
4757 4757 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
4758 4758 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
4759 4759 if source != dest:
4760 4760 other = hg.repository(hg.remoteui(repo, {}), dest)
4761 4761 commoninc = None
4762 4762 ui.debug('comparing with %s\n' % util.hidepassword(dest))
4763 4763 repo.ui.pushbuffer()
4764 4764 common, outheads = discovery.findcommonoutgoing(repo, other,
4765 4765 commoninc=commoninc)
4766 4766 repo.ui.popbuffer()
4767 4767 o = repo.changelog.findmissing(common=common, heads=outheads)
4768 4768 if o:
4769 4769 t.append(_('%d outgoing') % len(o))
4770 4770 if 'bookmarks' in other.listkeys('namespaces'):
4771 4771 lmarks = repo.listkeys('bookmarks')
4772 4772 rmarks = other.listkeys('bookmarks')
4773 4773 diff = set(rmarks) - set(lmarks)
4774 4774 if len(diff) > 0:
4775 4775 t.append(_('%d incoming bookmarks') % len(diff))
4776 4776 diff = set(lmarks) - set(rmarks)
4777 4777 if len(diff) > 0:
4778 4778 t.append(_('%d outgoing bookmarks') % len(diff))
4779 4779
4780 4780 if t:
4781 4781 ui.write(_('remote: %s\n') % (', '.join(t)))
4782 4782 else:
4783 4783 ui.status(_('remote: (synced)\n'))
4784 4784
4785 4785 @command('tag',
4786 4786 [('f', 'force', None, _('force tag')),
4787 4787 ('l', 'local', None, _('make the tag local')),
4788 4788 ('r', 'rev', '', _('revision to tag'), _('REV')),
4789 4789 ('', 'remove', None, _('remove a tag')),
4790 4790 # -l/--local is already there, commitopts cannot be used
4791 4791 ('e', 'edit', None, _('edit commit message')),
4792 4792 ('m', 'message', '', _('use <text> as commit message'), _('TEXT')),
4793 4793 ] + commitopts2,
4794 4794 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
4795 4795 def tag(ui, repo, name1, *names, **opts):
4796 4796 """add one or more tags for the current or given revision
4797 4797
4798 4798 Name a particular revision using <name>.
4799 4799
4800 4800 Tags are used to name particular revisions of the repository and are
4801 4801 very useful to compare different revisions, to go back to significant
4802 4802 earlier versions or to mark branch points as releases, etc. Changing
4803 4803 an existing tag is normally disallowed; use -f/--force to override.
4804 4804
4805 4805 If no revision is given, the parent of the working directory is
4806 4806 used, or tip if no revision is checked out.
4807 4807
4808 4808 To facilitate version control, distribution, and merging of tags,
4809 4809 they are stored as a file named ".hgtags" which is managed similarly
4810 4810 to other project files and can be hand-edited if necessary. This
4811 4811 also means that tagging creates a new commit. The file
4812 4812 ".hg/localtags" is used for local tags (not shared among
4813 4813 repositories).
4814 4814
4815 4815 Tag commits are usually made at the head of a branch. If the parent
4816 4816 of the working directory is not a branch head, :hg:`tag` aborts; use
4817 4817 -f/--force to force the tag commit to be based on a non-head
4818 4818 changeset.
4819 4819
4820 4820 See :hg:`help dates` for a list of formats valid for -d/--date.
4821 4821
4822 4822 Since tag names have priority over branch names during revision
4823 4823 lookup, using an existing branch name as a tag name is discouraged.
4824 4824
4825 4825 Returns 0 on success.
4826 4826 """
4827 4827
4828 4828 rev_ = "."
4829 4829 names = [t.strip() for t in (name1,) + names]
4830 4830 if len(names) != len(set(names)):
4831 4831 raise util.Abort(_('tag names must be unique'))
4832 4832 for n in names:
4833 4833 if n in ['tip', '.', 'null']:
4834 4834 raise util.Abort(_("the name '%s' is reserved") % n)
4835 4835 if not n:
4836 4836 raise util.Abort(_('tag names cannot consist entirely of whitespace'))
4837 4837 if opts.get('rev') and opts.get('remove'):
4838 4838 raise util.Abort(_("--rev and --remove are incompatible"))
4839 4839 if opts.get('rev'):
4840 4840 rev_ = opts['rev']
4841 4841 message = opts.get('message')
4842 4842 if opts.get('remove'):
4843 4843 expectedtype = opts.get('local') and 'local' or 'global'
4844 4844 for n in names:
4845 4845 if not repo.tagtype(n):
4846 4846 raise util.Abort(_("tag '%s' does not exist") % n)
4847 4847 if repo.tagtype(n) != expectedtype:
4848 4848 if expectedtype == 'global':
4849 4849 raise util.Abort(_("tag '%s' is not a global tag") % n)
4850 4850 else:
4851 4851 raise util.Abort(_("tag '%s' is not a local tag") % n)
4852 4852 rev_ = nullid
4853 4853 if not message:
4854 4854 # we don't translate commit messages
4855 4855 message = 'Removed tag %s' % ', '.join(names)
4856 4856 elif not opts.get('force'):
4857 4857 for n in names:
4858 4858 if n in repo.tags():
4859 4859 raise util.Abort(_("tag '%s' already exists "
4860 4860 "(use -f to force)") % n)
4861 4861 if not opts.get('local'):
4862 4862 p1, p2 = repo.dirstate.parents()
4863 4863 if p2 != nullid:
4864 4864 raise util.Abort(_('uncommitted merge'))
4865 4865 bheads = repo.branchheads()
4866 4866 if not opts.get('force') and bheads and p1 not in bheads:
4867 4867 raise util.Abort(_('not at a branch head (use -f to force)'))
4868 4868 r = scmutil.revsingle(repo, rev_).node()
4869 4869
4870 4870 if not message:
4871 4871 # we don't translate commit messages
4872 4872 message = ('Added tag %s for changeset %s' %
4873 4873 (', '.join(names), short(r)))
4874 4874
4875 4875 date = opts.get('date')
4876 4876 if date:
4877 4877 date = util.parsedate(date)
4878 4878
4879 4879 if opts.get('edit'):
4880 4880 message = ui.edit(message, ui.username())
4881 4881
4882 4882 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
4883 4883
4884 4884 @command('tags', [], '')
4885 4885 def tags(ui, repo):
4886 4886 """list repository tags
4887 4887
4888 4888 This lists both regular and local tags. When the -v/--verbose
4889 4889 switch is used, a third column "local" is printed for local tags.
4890 4890
4891 4891 Returns 0 on success.
4892 4892 """
4893 4893
4894 4894 hexfunc = ui.debugflag and hex or short
4895 4895 tagtype = ""
4896 4896
4897 4897 for t, n in reversed(repo.tagslist()):
4898 4898 if ui.quiet:
4899 4899 ui.write("%s\n" % t)
4900 4900 continue
4901 4901
4902 4902 hn = hexfunc(n)
4903 4903 r = "%5d:%s" % (repo.changelog.rev(n), hn)
4904 4904 spaces = " " * (30 - encoding.colwidth(t))
4905 4905
4906 4906 if ui.verbose:
4907 4907 if repo.tagtype(t) == 'local':
4908 4908 tagtype = " local"
4909 4909 else:
4910 4910 tagtype = ""
4911 4911 ui.write("%s%s %s%s\n" % (t, spaces, r, tagtype))
4912 4912
4913 4913 @command('tip',
4914 4914 [('p', 'patch', None, _('show patch')),
4915 4915 ('g', 'git', None, _('use git extended diff format')),
4916 4916 ] + templateopts,
4917 4917 _('[-p] [-g]'))
4918 4918 def tip(ui, repo, **opts):
4919 4919 """show the tip revision
4920 4920
4921 4921 The tip revision (usually just called the tip) is the changeset
4922 4922 most recently added to the repository (and therefore the most
4923 4923 recently changed head).
4924 4924
4925 4925 If you have just made a commit, that commit will be the tip. If
4926 4926 you have just pulled changes from another repository, the tip of
4927 4927 that repository becomes the current tip. The "tip" tag is special
4928 4928 and cannot be renamed or assigned to a different changeset.
4929 4929
4930 4930 Returns 0 on success.
4931 4931 """
4932 4932 displayer = cmdutil.show_changeset(ui, repo, opts)
4933 4933 displayer.show(repo[len(repo) - 1])
4934 4934 displayer.close()
4935 4935
4936 4936 @command('unbundle',
4937 4937 [('u', 'update', None,
4938 4938 _('update to new branch head if changesets were unbundled'))],
4939 4939 _('[-u] FILE...'))
4940 4940 def unbundle(ui, repo, fname1, *fnames, **opts):
4941 4941 """apply one or more changegroup files
4942 4942
4943 4943 Apply one or more compressed changegroup files generated by the
4944 4944 bundle command.
4945 4945
4946 4946 Returns 0 on success, 1 if an update has unresolved files.
4947 4947 """
4948 4948 fnames = (fname1,) + fnames
4949 4949
4950 4950 lock = repo.lock()
4951 4951 wc = repo['.']
4952 4952 try:
4953 4953 for fname in fnames:
4954 4954 f = url.open(ui, fname)
4955 4955 gen = changegroup.readbundle(f, fname)
4956 4956 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname,
4957 4957 lock=lock)
4958 4958 bookmarks.updatecurrentbookmark(repo, wc.node(), wc.branch())
4959 4959 finally:
4960 4960 lock.release()
4961 4961 return postincoming(ui, repo, modheads, opts.get('update'), None)
4962 4962
4963 4963 @command('^update|up|checkout|co',
4964 4964 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
4965 4965 ('c', 'check', None,
4966 4966 _('update across branches if no uncommitted changes')),
4967 4967 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4968 4968 ('r', 'rev', '', _('revision'), _('REV'))],
4969 4969 _('[-c] [-C] [-d DATE] [[-r] REV]'))
4970 4970 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
4971 4971 """update working directory (or switch revisions)
4972 4972
4973 4973 Update the repository's working directory to the specified
4974 4974 changeset. If no changeset is specified, update to the tip of the
4975 4975 current named branch.
4976 4976
4977 4977 If the changeset is not a descendant of the working directory's
4978 4978 parent, the update is aborted. With the -c/--check option, the
4979 4979 working directory is checked for uncommitted changes; if none are
4980 4980 found, the working directory is updated to the specified
4981 4981 changeset.
4982 4982
4983 4983 The following rules apply when the working directory contains
4984 4984 uncommitted changes:
4985 4985
4986 4986 1. If neither -c/--check nor -C/--clean is specified, and if
4987 4987 the requested changeset is an ancestor or descendant of
4988 4988 the working directory's parent, the uncommitted changes
4989 4989 are merged into the requested changeset and the merged
4990 4990 result is left uncommitted. If the requested changeset is
4991 4991 not an ancestor or descendant (that is, it is on another
4992 4992 branch), the update is aborted and the uncommitted changes
4993 4993 are preserved.
4994 4994
4995 4995 2. With the -c/--check option, the update is aborted and the
4996 4996 uncommitted changes are preserved.
4997 4997
4998 4998 3. With the -C/--clean option, uncommitted changes are discarded and
4999 4999 the working directory is updated to the requested changeset.
5000 5000
5001 5001 Use null as the changeset to remove the working directory (like
5002 5002 :hg:`clone -U`).
5003 5003
5004 5004 If you want to update just one file to an older changeset, use
5005 5005 :hg:`revert`.
5006 5006
5007 5007 See :hg:`help dates` for a list of formats valid for -d/--date.
5008 5008
5009 5009 Returns 0 on success, 1 if there are unresolved files.
5010 5010 """
5011 5011 if rev and node:
5012 5012 raise util.Abort(_("please specify just one revision"))
5013 5013
5014 5014 if rev is None or rev == '':
5015 5015 rev = node
5016 5016
5017 5017 # if we defined a bookmark, we have to remember the original bookmark name
5018 5018 brev = rev
5019 5019 rev = scmutil.revsingle(repo, rev, rev).rev()
5020 5020
5021 5021 if check and clean:
5022 5022 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
5023 5023
5024 5024 if check:
5025 5025 # we could use dirty() but we can ignore merge and branch trivia
5026 5026 c = repo[None]
5027 5027 if c.modified() or c.added() or c.removed():
5028 5028 raise util.Abort(_("uncommitted local changes"))
5029 5029
5030 5030 if date:
5031 5031 if rev is not None:
5032 5032 raise util.Abort(_("you can't specify a revision and a date"))
5033 5033 rev = cmdutil.finddate(ui, repo, date)
5034 5034
5035 5035 if clean or check:
5036 5036 ret = hg.clean(repo, rev)
5037 5037 else:
5038 5038 ret = hg.update(repo, rev)
5039 5039
5040 5040 if brev in repo._bookmarks:
5041 5041 bookmarks.setcurrent(repo, brev)
5042 5042
5043 5043 return ret
5044 5044
5045 5045 @command('verify', [])
5046 5046 def verify(ui, repo):
5047 5047 """verify the integrity of the repository
5048 5048
5049 5049 Verify the integrity of the current repository.
5050 5050
5051 5051 This will perform an extensive check of the repository's
5052 5052 integrity, validating the hashes and checksums of each entry in
5053 5053 the changelog, manifest, and tracked files, as well as the
5054 5054 integrity of their crosslinks and indices.
5055 5055
5056 5056 Returns 0 on success, 1 if errors are encountered.
5057 5057 """
5058 5058 return hg.verify(repo)
5059 5059
5060 5060 @command('version', [])
5061 5061 def version_(ui):
5062 5062 """output version and copyright information"""
5063 5063 ui.write(_("Mercurial Distributed SCM (version %s)\n")
5064 5064 % util.version())
5065 5065 ui.status(_(
5066 5066 "(see http://mercurial.selenic.com for more information)\n"
5067 5067 "\nCopyright (C) 2005-2011 Matt Mackall and others\n"
5068 5068 "This is free software; see the source for copying conditions. "
5069 5069 "There is NO\nwarranty; "
5070 5070 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5071 5071 ))
5072 5072
5073 5073 norepo = ("clone init version help debugcommands debugcomplete"
5074 5074 " debugdate debuginstall debugfsinfo debugpushkey debugwireargs"
5075 5075 " debugknown debuggetbundle debugbundle")
5076 5076 optionalrepo = ("identify paths serve showconfig debugancestor debugdag"
5077 5077 " debugdata debugindex debugindexdot debugrevlog")
@@ -1,1127 +1,1129 b''
1 1 # context.py - changeset and file context objects for mercurial
2 2 #
3 3 # Copyright 2006, 2007 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 from node import nullid, nullrev, short, hex
9 9 from i18n import _
10 10 import ancestor, bdiff, error, util, scmutil, subrepo, patch, encoding
11 11 import os, errno, stat
12 12
13 13 propertycache = util.propertycache
14 14
15 15 class changectx(object):
16 16 """A changecontext object makes access to data related to a particular
17 17 changeset convenient."""
18 18 def __init__(self, repo, changeid=''):
19 19 """changeid is a revision number, node, or tag"""
20 20 if changeid == '':
21 21 changeid = '.'
22 22 self._repo = repo
23 23 if isinstance(changeid, (long, int)):
24 24 self._rev = changeid
25 25 self._node = self._repo.changelog.node(changeid)
26 26 else:
27 27 self._node = self._repo.lookup(changeid)
28 28 self._rev = self._repo.changelog.rev(self._node)
29 29
30 30 def __str__(self):
31 31 return short(self.node())
32 32
33 33 def __int__(self):
34 34 return self.rev()
35 35
36 36 def __repr__(self):
37 37 return "<changectx %s>" % str(self)
38 38
39 39 def __hash__(self):
40 40 try:
41 41 return hash(self._rev)
42 42 except AttributeError:
43 43 return id(self)
44 44
45 45 def __eq__(self, other):
46 46 try:
47 47 return self._rev == other._rev
48 48 except AttributeError:
49 49 return False
50 50
51 51 def __ne__(self, other):
52 52 return not (self == other)
53 53
54 54 def __nonzero__(self):
55 55 return self._rev != nullrev
56 56
57 57 @propertycache
58 58 def _changeset(self):
59 59 return self._repo.changelog.read(self.node())
60 60
61 61 @propertycache
62 62 def _manifest(self):
63 63 return self._repo.manifest.read(self._changeset[0])
64 64
65 65 @propertycache
66 66 def _manifestdelta(self):
67 67 return self._repo.manifest.readdelta(self._changeset[0])
68 68
69 69 @propertycache
70 70 def _parents(self):
71 71 p = self._repo.changelog.parentrevs(self._rev)
72 72 if p[1] == nullrev:
73 73 p = p[:-1]
74 74 return [changectx(self._repo, x) for x in p]
75 75
76 76 @propertycache
77 77 def substate(self):
78 78 return subrepo.state(self, self._repo.ui)
79 79
80 80 def __contains__(self, key):
81 81 return key in self._manifest
82 82
83 83 def __getitem__(self, key):
84 84 return self.filectx(key)
85 85
86 86 def __iter__(self):
87 87 for f in sorted(self._manifest):
88 88 yield f
89 89
90 90 def changeset(self):
91 91 return self._changeset
92 92 def manifest(self):
93 93 return self._manifest
94 94 def manifestnode(self):
95 95 return self._changeset[0]
96 96
97 97 def rev(self):
98 98 return self._rev
99 99 def node(self):
100 100 return self._node
101 101 def hex(self):
102 102 return hex(self._node)
103 103 def user(self):
104 104 return self._changeset[1]
105 105 def date(self):
106 106 return self._changeset[2]
107 107 def files(self):
108 108 return self._changeset[3]
109 109 def description(self):
110 110 return self._changeset[4]
111 111 def branch(self):
112 112 return encoding.tolocal(self._changeset[5].get("branch"))
113 113 def extra(self):
114 114 return self._changeset[5]
115 115 def tags(self):
116 116 return self._repo.nodetags(self._node)
117 117 def bookmarks(self):
118 118 return self._repo.nodebookmarks(self._node)
119 119
120 120 def parents(self):
121 121 """return contexts for each parent changeset"""
122 122 return self._parents
123 123
124 124 def p1(self):
125 125 return self._parents[0]
126 126
127 127 def p2(self):
128 128 if len(self._parents) == 2:
129 129 return self._parents[1]
130 130 return changectx(self._repo, -1)
131 131
132 132 def children(self):
133 133 """return contexts for each child changeset"""
134 134 c = self._repo.changelog.children(self._node)
135 135 return [changectx(self._repo, x) for x in c]
136 136
137 137 def ancestors(self):
138 138 for a in self._repo.changelog.ancestors(self._rev):
139 139 yield changectx(self._repo, a)
140 140
141 141 def descendants(self):
142 142 for d in self._repo.changelog.descendants(self._rev):
143 143 yield changectx(self._repo, d)
144 144
145 145 def _fileinfo(self, path):
146 146 if '_manifest' in self.__dict__:
147 147 try:
148 148 return self._manifest[path], self._manifest.flags(path)
149 149 except KeyError:
150 150 raise error.LookupError(self._node, path,
151 151 _('not found in manifest'))
152 152 if '_manifestdelta' in self.__dict__ or path in self.files():
153 153 if path in self._manifestdelta:
154 154 return self._manifestdelta[path], self._manifestdelta.flags(path)
155 155 node, flag = self._repo.manifest.find(self._changeset[0], path)
156 156 if not node:
157 157 raise error.LookupError(self._node, path,
158 158 _('not found in manifest'))
159 159
160 160 return node, flag
161 161
162 162 def filenode(self, path):
163 163 return self._fileinfo(path)[0]
164 164
165 165 def flags(self, path):
166 166 try:
167 167 return self._fileinfo(path)[1]
168 168 except error.LookupError:
169 169 return ''
170 170
171 171 def filectx(self, path, fileid=None, filelog=None):
172 172 """get a file context from this changeset"""
173 173 if fileid is None:
174 174 fileid = self.filenode(path)
175 175 return filectx(self._repo, path, fileid=fileid,
176 176 changectx=self, filelog=filelog)
177 177
178 178 def ancestor(self, c2):
179 179 """
180 180 return the ancestor context of self and c2
181 181 """
182 182 # deal with workingctxs
183 183 n2 = c2._node
184 184 if n2 is None:
185 185 n2 = c2._parents[0]._node
186 186 n = self._repo.changelog.ancestor(self._node, n2)
187 187 return changectx(self._repo, n)
188 188
189 189 def walk(self, match):
190 190 fset = set(match.files())
191 191 # for dirstate.walk, files=['.'] means "walk the whole tree".
192 192 # follow that here, too
193 193 fset.discard('.')
194 194 for fn in self:
195 195 for ffn in fset:
196 196 # match if the file is the exact name or a directory
197 197 if ffn == fn or fn.startswith("%s/" % ffn):
198 198 fset.remove(ffn)
199 199 break
200 200 if match(fn):
201 201 yield fn
202 202 for fn in sorted(fset):
203 203 if match.bad(fn, _('no such file in rev %s') % self) and match(fn):
204 204 yield fn
205 205
206 206 def sub(self, path):
207 207 return subrepo.subrepo(self, path)
208 208
209 209 def diff(self, ctx2=None, match=None, **opts):
210 210 """Returns a diff generator for the given contexts and matcher"""
211 211 if ctx2 is None:
212 212 ctx2 = self.p1()
213 213 if ctx2 is not None and not isinstance(ctx2, changectx):
214 214 ctx2 = self._repo[ctx2]
215 215 diffopts = patch.diffopts(self._repo.ui, opts)
216 216 return patch.diff(self._repo, ctx2.node(), self.node(),
217 217 match=match, opts=diffopts)
218 218
219 219 class filectx(object):
220 220 """A filecontext object makes access to data related to a particular
221 221 filerevision convenient."""
222 222 def __init__(self, repo, path, changeid=None, fileid=None,
223 223 filelog=None, changectx=None):
224 224 """changeid can be a changeset revision, node, or tag.
225 225 fileid can be a file revision or node."""
226 226 self._repo = repo
227 227 self._path = path
228 228
229 229 assert (changeid is not None
230 230 or fileid is not None
231 231 or changectx is not None), \
232 232 ("bad args: changeid=%r, fileid=%r, changectx=%r"
233 233 % (changeid, fileid, changectx))
234 234
235 235 if filelog:
236 236 self._filelog = filelog
237 237
238 238 if changeid is not None:
239 239 self._changeid = changeid
240 240 if changectx is not None:
241 241 self._changectx = changectx
242 242 if fileid is not None:
243 243 self._fileid = fileid
244 244
245 245 @propertycache
246 246 def _changectx(self):
247 247 return changectx(self._repo, self._changeid)
248 248
249 249 @propertycache
250 250 def _filelog(self):
251 251 return self._repo.file(self._path)
252 252
253 253 @propertycache
254 254 def _changeid(self):
255 255 if '_changectx' in self.__dict__:
256 256 return self._changectx.rev()
257 257 else:
258 258 return self._filelog.linkrev(self._filerev)
259 259
260 260 @propertycache
261 261 def _filenode(self):
262 262 if '_fileid' in self.__dict__:
263 263 return self._filelog.lookup(self._fileid)
264 264 else:
265 265 return self._changectx.filenode(self._path)
266 266
267 267 @propertycache
268 268 def _filerev(self):
269 269 return self._filelog.rev(self._filenode)
270 270
271 271 @propertycache
272 272 def _repopath(self):
273 273 return self._path
274 274
275 275 def __nonzero__(self):
276 276 try:
277 277 self._filenode
278 278 return True
279 279 except error.LookupError:
280 280 # file is missing
281 281 return False
282 282
283 283 def __str__(self):
284 284 return "%s@%s" % (self.path(), short(self.node()))
285 285
286 286 def __repr__(self):
287 287 return "<filectx %s>" % str(self)
288 288
289 289 def __hash__(self):
290 290 try:
291 291 return hash((self._path, self._filenode))
292 292 except AttributeError:
293 293 return id(self)
294 294
295 295 def __eq__(self, other):
296 296 try:
297 297 return (self._path == other._path
298 298 and self._filenode == other._filenode)
299 299 except AttributeError:
300 300 return False
301 301
302 302 def __ne__(self, other):
303 303 return not (self == other)
304 304
305 305 def filectx(self, fileid):
306 306 '''opens an arbitrary revision of the file without
307 307 opening a new filelog'''
308 308 return filectx(self._repo, self._path, fileid=fileid,
309 309 filelog=self._filelog)
310 310
311 311 def filerev(self):
312 312 return self._filerev
313 313 def filenode(self):
314 314 return self._filenode
315 315 def flags(self):
316 316 return self._changectx.flags(self._path)
317 317 def filelog(self):
318 318 return self._filelog
319 319
320 320 def rev(self):
321 321 if '_changectx' in self.__dict__:
322 322 return self._changectx.rev()
323 323 if '_changeid' in self.__dict__:
324 324 return self._changectx.rev()
325 325 return self._filelog.linkrev(self._filerev)
326 326
327 327 def linkrev(self):
328 328 return self._filelog.linkrev(self._filerev)
329 329 def node(self):
330 330 return self._changectx.node()
331 331 def hex(self):
332 332 return hex(self.node())
333 333 def user(self):
334 334 return self._changectx.user()
335 335 def date(self):
336 336 return self._changectx.date()
337 337 def files(self):
338 338 return self._changectx.files()
339 339 def description(self):
340 340 return self._changectx.description()
341 341 def branch(self):
342 342 return self._changectx.branch()
343 343 def extra(self):
344 344 return self._changectx.extra()
345 345 def manifest(self):
346 346 return self._changectx.manifest()
347 347 def changectx(self):
348 348 return self._changectx
349 349
350 350 def data(self):
351 351 return self._filelog.read(self._filenode)
352 352 def path(self):
353 353 return self._path
354 354 def size(self):
355 355 return self._filelog.size(self._filerev)
356 356
357 357 def cmp(self, fctx):
358 358 """compare with other file context
359 359
360 360 returns True if different than fctx.
361 361 """
362 362 if (fctx._filerev is None and self._repo._encodefilterpats
363 363 or self.size() == fctx.size()):
364 364 return self._filelog.cmp(self._filenode, fctx.data())
365 365
366 366 return True
367 367
368 368 def renamed(self):
369 369 """check if file was actually renamed in this changeset revision
370 370
371 371 If rename logged in file revision, we report copy for changeset only
372 372 if file revisions linkrev points back to the changeset in question
373 373 or both changeset parents contain different file revisions.
374 374 """
375 375
376 376 renamed = self._filelog.renamed(self._filenode)
377 377 if not renamed:
378 378 return renamed
379 379
380 380 if self.rev() == self.linkrev():
381 381 return renamed
382 382
383 383 name = self.path()
384 384 fnode = self._filenode
385 385 for p in self._changectx.parents():
386 386 try:
387 387 if fnode == p.filenode(name):
388 388 return None
389 389 except error.LookupError:
390 390 pass
391 391 return renamed
392 392
393 393 def parents(self):
394 394 p = self._path
395 395 fl = self._filelog
396 396 pl = [(p, n, fl) for n in self._filelog.parents(self._filenode)]
397 397
398 398 r = self._filelog.renamed(self._filenode)
399 399 if r:
400 400 pl[0] = (r[0], r[1], None)
401 401
402 402 return [filectx(self._repo, p, fileid=n, filelog=l)
403 403 for p, n, l in pl if n != nullid]
404 404
405 405 def p1(self):
406 406 return self.parents()[0]
407 407
408 408 def p2(self):
409 409 p = self.parents()
410 410 if len(p) == 2:
411 411 return p[1]
412 412 return filectx(self._repo, self._path, fileid=-1, filelog=self._filelog)
413 413
414 414 def children(self):
415 415 # hard for renames
416 416 c = self._filelog.children(self._filenode)
417 417 return [filectx(self._repo, self._path, fileid=x,
418 418 filelog=self._filelog) for x in c]
419 419
420 420 def annotate(self, follow=False, linenumber=None):
421 421 '''returns a list of tuples of (ctx, line) for each line
422 422 in the file, where ctx is the filectx of the node where
423 423 that line was last changed.
424 424 This returns tuples of ((ctx, linenumber), line) for each line,
425 425 if "linenumber" parameter is NOT "None".
426 426 In such tuples, linenumber means one at the first appearance
427 427 in the managed file.
428 428 To reduce annotation cost,
429 429 this returns fixed value(False is used) as linenumber,
430 430 if "linenumber" parameter is "False".'''
431 431
432 432 def decorate_compat(text, rev):
433 433 return ([rev] * len(text.splitlines()), text)
434 434
435 435 def without_linenumber(text, rev):
436 436 return ([(rev, False)] * len(text.splitlines()), text)
437 437
438 438 def with_linenumber(text, rev):
439 439 size = len(text.splitlines())
440 440 return ([(rev, i) for i in xrange(1, size + 1)], text)
441 441
442 442 decorate = (((linenumber is None) and decorate_compat) or
443 443 (linenumber and with_linenumber) or
444 444 without_linenumber)
445 445
446 446 def pair(parent, child):
447 447 for a1, a2, b1, b2 in bdiff.blocks(parent[1], child[1]):
448 448 child[0][b1:b2] = parent[0][a1:a2]
449 449 return child
450 450
451 451 getlog = util.lrucachefunc(lambda x: self._repo.file(x))
452 452 def getctx(path, fileid):
453 453 log = path == self._path and self._filelog or getlog(path)
454 454 return filectx(self._repo, path, fileid=fileid, filelog=log)
455 455 getctx = util.lrucachefunc(getctx)
456 456
457 457 def parents(f):
458 458 # we want to reuse filectx objects as much as possible
459 459 p = f._path
460 460 if f._filerev is None: # working dir
461 461 pl = [(n.path(), n.filerev()) for n in f.parents()]
462 462 else:
463 463 pl = [(p, n) for n in f._filelog.parentrevs(f._filerev)]
464 464
465 465 if follow:
466 466 r = f.renamed()
467 467 if r:
468 468 pl[0] = (r[0], getlog(r[0]).rev(r[1]))
469 469
470 470 return [getctx(p, n) for p, n in pl if n != nullrev]
471 471
472 472 # use linkrev to find the first changeset where self appeared
473 473 if self.rev() != self.linkrev():
474 474 base = self.filectx(self.filerev())
475 475 else:
476 476 base = self
477 477
478 478 # This algorithm would prefer to be recursive, but Python is a
479 479 # bit recursion-hostile. Instead we do an iterative
480 480 # depth-first search.
481 481
482 482 visit = [base]
483 483 hist = {}
484 484 pcache = {}
485 485 needed = {base: 1}
486 486 while visit:
487 487 f = visit[-1]
488 488 if f not in pcache:
489 489 pcache[f] = parents(f)
490 490
491 491 ready = True
492 492 pl = pcache[f]
493 493 for p in pl:
494 494 if p not in hist:
495 495 ready = False
496 496 visit.append(p)
497 497 needed[p] = needed.get(p, 0) + 1
498 498 if ready:
499 499 visit.pop()
500 500 curr = decorate(f.data(), f)
501 501 for p in pl:
502 502 curr = pair(hist[p], curr)
503 503 if needed[p] == 1:
504 504 del hist[p]
505 505 else:
506 506 needed[p] -= 1
507 507
508 508 hist[f] = curr
509 509 pcache[f] = []
510 510
511 511 return zip(hist[base][0], hist[base][1].splitlines(True))
512 512
513 513 def ancestor(self, fc2, actx=None):
514 514 """
515 515 find the common ancestor file context, if any, of self, and fc2
516 516
517 517 If actx is given, it must be the changectx of the common ancestor
518 518 of self's and fc2's respective changesets.
519 519 """
520 520
521 521 if actx is None:
522 522 actx = self.changectx().ancestor(fc2.changectx())
523 523
524 524 # the trivial case: changesets are unrelated, files must be too
525 525 if not actx:
526 526 return None
527 527
528 528 # the easy case: no (relevant) renames
529 529 if fc2.path() == self.path() and self.path() in actx:
530 530 return actx[self.path()]
531 531 acache = {}
532 532
533 533 # prime the ancestor cache for the working directory
534 534 for c in (self, fc2):
535 535 if c._filerev is None:
536 536 pl = [(n.path(), n.filenode()) for n in c.parents()]
537 537 acache[(c._path, None)] = pl
538 538
539 539 flcache = {self._repopath:self._filelog, fc2._repopath:fc2._filelog}
540 540 def parents(vertex):
541 541 if vertex in acache:
542 542 return acache[vertex]
543 543 f, n = vertex
544 544 if f not in flcache:
545 545 flcache[f] = self._repo.file(f)
546 546 fl = flcache[f]
547 547 pl = [(f, p) for p in fl.parents(n) if p != nullid]
548 548 re = fl.renamed(n)
549 549 if re:
550 550 pl.append(re)
551 551 acache[vertex] = pl
552 552 return pl
553 553
554 554 a, b = (self._path, self._filenode), (fc2._path, fc2._filenode)
555 555 v = ancestor.ancestor(a, b, parents)
556 556 if v:
557 557 f, n = v
558 558 return filectx(self._repo, f, fileid=n, filelog=flcache[f])
559 559
560 560 return None
561 561
562 562 def ancestors(self):
563 563 visit = {}
564 564 c = self
565 565 while True:
566 566 for parent in c.parents():
567 567 visit[(parent.rev(), parent.node())] = parent
568 568 if not visit:
569 569 break
570 570 c = visit.pop(max(visit))
571 571 yield c
572 572
573 573 class workingctx(changectx):
574 574 """A workingctx object makes access to data related to
575 575 the current working directory convenient.
576 576 date - any valid date string or (unixtime, offset), or None.
577 577 user - username string, or None.
578 578 extra - a dictionary of extra values, or None.
579 579 changes - a list of file lists as returned by localrepo.status()
580 580 or None to use the repository status.
581 581 """
582 582 def __init__(self, repo, text="", user=None, date=None, extra=None,
583 583 changes=None):
584 584 self._repo = repo
585 585 self._rev = None
586 586 self._node = None
587 587 self._text = text
588 588 if date:
589 589 self._date = util.parsedate(date)
590 590 if user:
591 591 self._user = user
592 592 if changes:
593 593 self._status = list(changes[:4])
594 594 self._unknown = changes[4]
595 595 self._ignored = changes[5]
596 596 self._clean = changes[6]
597 597 else:
598 598 self._unknown = None
599 599 self._ignored = None
600 600 self._clean = None
601 601
602 602 self._extra = {}
603 603 if extra:
604 604 self._extra = extra.copy()
605 605 if 'branch' not in self._extra:
606 606 try:
607 607 branch = encoding.fromlocal(self._repo.dirstate.branch())
608 608 except UnicodeDecodeError:
609 609 raise util.Abort(_('branch name not in UTF-8!'))
610 610 self._extra['branch'] = branch
611 611 if self._extra['branch'] == '':
612 612 self._extra['branch'] = 'default'
613 613
614 614 def __str__(self):
615 615 return str(self._parents[0]) + "+"
616 616
617 617 def __repr__(self):
618 618 return "<workingctx %s>" % str(self)
619 619
620 620 def __nonzero__(self):
621 621 return True
622 622
623 623 def __contains__(self, key):
624 624 return self._repo.dirstate[key] not in "?r"
625 625
626 626 @propertycache
627 627 def _manifest(self):
628 628 """generate a manifest corresponding to the working directory"""
629 629
630 630 if self._unknown is None:
631 631 self.status(unknown=True)
632 632
633 633 man = self._parents[0].manifest().copy()
634 634 copied = self._repo.dirstate.copies()
635 635 if len(self._parents) > 1:
636 636 man2 = self.p2().manifest()
637 637 def getman(f):
638 638 if f in man:
639 639 return man
640 640 return man2
641 641 else:
642 642 getman = lambda f: man
643 643 def cf(f):
644 644 f = copied.get(f, f)
645 645 return getman(f).flags(f)
646 646 ff = self._repo.dirstate.flagfunc(cf)
647 647 modified, added, removed, deleted = self._status
648 648 unknown = self._unknown
649 649 for i, l in (("a", added), ("m", modified), ("u", unknown)):
650 650 for f in l:
651 651 orig = copied.get(f, f)
652 652 man[f] = getman(orig).get(orig, nullid) + i
653 653 try:
654 654 man.set(f, ff(f))
655 655 except OSError:
656 656 pass
657 657
658 658 for f in deleted + removed:
659 659 if f in man:
660 660 del man[f]
661 661
662 662 return man
663 663
664 664 def __iter__(self):
665 665 d = self._repo.dirstate
666 666 for f in d:
667 667 if d[f] != 'r':
668 668 yield f
669 669
670 670 @propertycache
671 671 def _status(self):
672 672 return self._repo.status()[:4]
673 673
674 674 @propertycache
675 675 def _user(self):
676 676 return self._repo.ui.username()
677 677
678 678 @propertycache
679 679 def _date(self):
680 680 return util.makedate()
681 681
682 682 @propertycache
683 683 def _parents(self):
684 684 p = self._repo.dirstate.parents()
685 685 if p[1] == nullid:
686 686 p = p[:-1]
687 687 self._parents = [changectx(self._repo, x) for x in p]
688 688 return self._parents
689 689
690 690 def status(self, ignored=False, clean=False, unknown=False):
691 691 """Explicit status query
692 692 Unless this method is used to query the working copy status, the
693 693 _status property will implicitly read the status using its default
694 694 arguments."""
695 695 stat = self._repo.status(ignored=ignored, clean=clean, unknown=unknown)
696 696 self._unknown = self._ignored = self._clean = None
697 697 if unknown:
698 698 self._unknown = stat[4]
699 699 if ignored:
700 700 self._ignored = stat[5]
701 701 if clean:
702 702 self._clean = stat[6]
703 703 self._status = stat[:4]
704 704 return stat
705 705
706 706 def manifest(self):
707 707 return self._manifest
708 708 def user(self):
709 709 return self._user or self._repo.ui.username()
710 710 def date(self):
711 711 return self._date
712 712 def description(self):
713 713 return self._text
714 714 def files(self):
715 715 return sorted(self._status[0] + self._status[1] + self._status[2])
716 716
717 717 def modified(self):
718 718 return self._status[0]
719 719 def added(self):
720 720 return self._status[1]
721 721 def removed(self):
722 722 return self._status[2]
723 723 def deleted(self):
724 724 return self._status[3]
725 725 def unknown(self):
726 726 assert self._unknown is not None # must call status first
727 727 return self._unknown
728 728 def ignored(self):
729 729 assert self._ignored is not None # must call status first
730 730 return self._ignored
731 731 def clean(self):
732 732 assert self._clean is not None # must call status first
733 733 return self._clean
734 734 def branch(self):
735 735 return encoding.tolocal(self._extra['branch'])
736 736 def extra(self):
737 737 return self._extra
738 738
739 739 def tags(self):
740 740 t = []
741 741 for p in self.parents():
742 742 t.extend(p.tags())
743 743 return t
744 744
745 745 def bookmarks(self):
746 746 b = []
747 747 for p in self.parents():
748 748 b.extend(p.bookmarks())
749 749 return b
750 750
751 751 def children(self):
752 752 return []
753 753
754 754 def flags(self, path):
755 755 if '_manifest' in self.__dict__:
756 756 try:
757 757 return self._manifest.flags(path)
758 758 except KeyError:
759 759 return ''
760 760
761 761 orig = self._repo.dirstate.copies().get(path, path)
762 762
763 763 def findflag(ctx):
764 764 mnode = ctx.changeset()[0]
765 765 node, flag = self._repo.manifest.find(mnode, orig)
766 766 ff = self._repo.dirstate.flagfunc(lambda x: flag or '')
767 767 try:
768 768 return ff(path)
769 769 except OSError:
770 770 pass
771 771
772 772 flag = findflag(self._parents[0])
773 773 if flag is None and len(self.parents()) > 1:
774 774 flag = findflag(self._parents[1])
775 775 if flag is None or self._repo.dirstate[path] == 'r':
776 776 return ''
777 777 return flag
778 778
779 779 def filectx(self, path, filelog=None):
780 780 """get a file context from the working directory"""
781 781 return workingfilectx(self._repo, path, workingctx=self,
782 782 filelog=filelog)
783 783
784 784 def ancestor(self, c2):
785 785 """return the ancestor context of self and c2"""
786 786 return self._parents[0].ancestor(c2) # punt on two parents for now
787 787
788 788 def walk(self, match):
789 789 return sorted(self._repo.dirstate.walk(match, self.substate.keys(),
790 790 True, False))
791 791
792 792 def dirty(self, missing=False):
793 793 "check whether a working directory is modified"
794 794 # check subrepos first
795 795 for s in self.substate:
796 796 if self.sub(s).dirty():
797 797 return True
798 798 # check current working dir
799 799 return (self.p2() or self.branch() != self.p1().branch() or
800 800 self.modified() or self.added() or self.removed() or
801 801 (missing and self.deleted()))
802 802
803 803 def add(self, list, prefix=""):
804 804 join = lambda f: os.path.join(prefix, f)
805 805 wlock = self._repo.wlock()
806 806 ui, ds = self._repo.ui, self._repo.dirstate
807 807 try:
808 808 rejected = []
809 809 for f in list:
810 810 scmutil.checkportable(ui, join(f))
811 811 p = self._repo.wjoin(f)
812 812 try:
813 813 st = os.lstat(p)
814 814 except OSError:
815 815 ui.warn(_("%s does not exist!\n") % join(f))
816 816 rejected.append(f)
817 817 continue
818 818 if st.st_size > 10000000:
819 819 ui.warn(_("%s: up to %d MB of RAM may be required "
820 820 "to manage this file\n"
821 821 "(use 'hg revert %s' to cancel the "
822 822 "pending addition)\n")
823 823 % (f, 3 * st.st_size // 1000000, join(f)))
824 824 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
825 825 ui.warn(_("%s not added: only files and symlinks "
826 826 "supported currently\n") % join(f))
827 827 rejected.append(p)
828 828 elif ds[f] in 'amn':
829 829 ui.warn(_("%s already tracked!\n") % join(f))
830 830 elif ds[f] == 'r':
831 831 ds.normallookup(f)
832 832 else:
833 833 ds.add(f)
834 834 return rejected
835 835 finally:
836 836 wlock.release()
837 837
838 def forget(self, list):
838 def forget(self, files):
839 839 wlock = self._repo.wlock()
840 840 try:
841 for f in list:
841 for f in files:
842 842 if self._repo.dirstate[f] != 'a':
843 self._repo.ui.warn(_("%s not added!\n") % f)
843 self._repo.dirstate.remove(f)
844 elif f not in self._repo.dirstate:
845 self._repo.ui.warn(_("%s not tracked!\n") % f)
844 846 else:
845 847 self._repo.dirstate.drop(f)
846 848 finally:
847 849 wlock.release()
848 850
849 851 def ancestors(self):
850 852 for a in self._repo.changelog.ancestors(
851 853 *[p.rev() for p in self._parents]):
852 854 yield changectx(self._repo, a)
853 855
854 856 def remove(self, list, unlink=False):
855 857 wlock = self._repo.wlock()
856 858 try:
857 859 if unlink:
858 860 for f in list:
859 861 try:
860 862 util.unlinkpath(self._repo.wjoin(f))
861 863 except OSError, inst:
862 864 if inst.errno != errno.ENOENT:
863 865 raise
864 866 for f in list:
865 867 if self._repo.dirstate[f] == 'a':
866 868 self._repo.dirstate.drop(f)
867 869 elif f not in self._repo.dirstate:
868 870 self._repo.ui.warn(_("%s not tracked!\n") % f)
869 871 else:
870 872 self._repo.dirstate.remove(f)
871 873 finally:
872 874 wlock.release()
873 875
874 876 def undelete(self, list):
875 877 pctxs = self.parents()
876 878 wlock = self._repo.wlock()
877 879 try:
878 880 for f in list:
879 881 if self._repo.dirstate[f] != 'r':
880 882 self._repo.ui.warn(_("%s not removed!\n") % f)
881 883 else:
882 884 fctx = f in pctxs[0] and pctxs[0][f] or pctxs[1][f]
883 885 t = fctx.data()
884 886 self._repo.wwrite(f, t, fctx.flags())
885 887 self._repo.dirstate.normal(f)
886 888 finally:
887 889 wlock.release()
888 890
889 891 def copy(self, source, dest):
890 892 p = self._repo.wjoin(dest)
891 893 if not os.path.lexists(p):
892 894 self._repo.ui.warn(_("%s does not exist!\n") % dest)
893 895 elif not (os.path.isfile(p) or os.path.islink(p)):
894 896 self._repo.ui.warn(_("copy failed: %s is not a file or a "
895 897 "symbolic link\n") % dest)
896 898 else:
897 899 wlock = self._repo.wlock()
898 900 try:
899 901 if self._repo.dirstate[dest] in '?r':
900 902 self._repo.dirstate.add(dest)
901 903 self._repo.dirstate.copy(source, dest)
902 904 finally:
903 905 wlock.release()
904 906
905 907 class workingfilectx(filectx):
906 908 """A workingfilectx object makes access to data related to a particular
907 909 file in the working directory convenient."""
908 910 def __init__(self, repo, path, filelog=None, workingctx=None):
909 911 """changeid can be a changeset revision, node, or tag.
910 912 fileid can be a file revision or node."""
911 913 self._repo = repo
912 914 self._path = path
913 915 self._changeid = None
914 916 self._filerev = self._filenode = None
915 917
916 918 if filelog:
917 919 self._filelog = filelog
918 920 if workingctx:
919 921 self._changectx = workingctx
920 922
921 923 @propertycache
922 924 def _changectx(self):
923 925 return workingctx(self._repo)
924 926
925 927 def __nonzero__(self):
926 928 return True
927 929
928 930 def __str__(self):
929 931 return "%s@%s" % (self.path(), self._changectx)
930 932
931 933 def __repr__(self):
932 934 return "<workingfilectx %s>" % str(self)
933 935
934 936 def data(self):
935 937 return self._repo.wread(self._path)
936 938 def renamed(self):
937 939 rp = self._repo.dirstate.copied(self._path)
938 940 if not rp:
939 941 return None
940 942 return rp, self._changectx._parents[0]._manifest.get(rp, nullid)
941 943
942 944 def parents(self):
943 945 '''return parent filectxs, following copies if necessary'''
944 946 def filenode(ctx, path):
945 947 return ctx._manifest.get(path, nullid)
946 948
947 949 path = self._path
948 950 fl = self._filelog
949 951 pcl = self._changectx._parents
950 952 renamed = self.renamed()
951 953
952 954 if renamed:
953 955 pl = [renamed + (None,)]
954 956 else:
955 957 pl = [(path, filenode(pcl[0], path), fl)]
956 958
957 959 for pc in pcl[1:]:
958 960 pl.append((path, filenode(pc, path), fl))
959 961
960 962 return [filectx(self._repo, p, fileid=n, filelog=l)
961 963 for p, n, l in pl if n != nullid]
962 964
963 965 def children(self):
964 966 return []
965 967
966 968 def size(self):
967 969 return os.lstat(self._repo.wjoin(self._path)).st_size
968 970 def date(self):
969 971 t, tz = self._changectx.date()
970 972 try:
971 973 return (int(os.lstat(self._repo.wjoin(self._path)).st_mtime), tz)
972 974 except OSError, err:
973 975 if err.errno != errno.ENOENT:
974 976 raise
975 977 return (t, tz)
976 978
977 979 def cmp(self, fctx):
978 980 """compare with other file context
979 981
980 982 returns True if different than fctx.
981 983 """
982 984 # fctx should be a filectx (not a wfctx)
983 985 # invert comparison to reuse the same code path
984 986 return fctx.cmp(self)
985 987
986 988 class memctx(object):
987 989 """Use memctx to perform in-memory commits via localrepo.commitctx().
988 990
989 991 Revision information is supplied at initialization time while
990 992 related files data and is made available through a callback
991 993 mechanism. 'repo' is the current localrepo, 'parents' is a
992 994 sequence of two parent revisions identifiers (pass None for every
993 995 missing parent), 'text' is the commit message and 'files' lists
994 996 names of files touched by the revision (normalized and relative to
995 997 repository root).
996 998
997 999 filectxfn(repo, memctx, path) is a callable receiving the
998 1000 repository, the current memctx object and the normalized path of
999 1001 requested file, relative to repository root. It is fired by the
1000 1002 commit function for every file in 'files', but calls order is
1001 1003 undefined. If the file is available in the revision being
1002 1004 committed (updated or added), filectxfn returns a memfilectx
1003 1005 object. If the file was removed, filectxfn raises an
1004 1006 IOError. Moved files are represented by marking the source file
1005 1007 removed and the new file added with copy information (see
1006 1008 memfilectx).
1007 1009
1008 1010 user receives the committer name and defaults to current
1009 1011 repository username, date is the commit date in any format
1010 1012 supported by util.parsedate() and defaults to current date, extra
1011 1013 is a dictionary of metadata or is left empty.
1012 1014 """
1013 1015 def __init__(self, repo, parents, text, files, filectxfn, user=None,
1014 1016 date=None, extra=None):
1015 1017 self._repo = repo
1016 1018 self._rev = None
1017 1019 self._node = None
1018 1020 self._text = text
1019 1021 self._date = date and util.parsedate(date) or util.makedate()
1020 1022 self._user = user
1021 1023 parents = [(p or nullid) for p in parents]
1022 1024 p1, p2 = parents
1023 1025 self._parents = [changectx(self._repo, p) for p in (p1, p2)]
1024 1026 files = sorted(set(files))
1025 1027 self._status = [files, [], [], [], []]
1026 1028 self._filectxfn = filectxfn
1027 1029
1028 1030 self._extra = extra and extra.copy() or {}
1029 1031 if 'branch' not in self._extra:
1030 1032 self._extra['branch'] = 'default'
1031 1033 elif self._extra.get('branch') == '':
1032 1034 self._extra['branch'] = 'default'
1033 1035
1034 1036 def __str__(self):
1035 1037 return str(self._parents[0]) + "+"
1036 1038
1037 1039 def __int__(self):
1038 1040 return self._rev
1039 1041
1040 1042 def __nonzero__(self):
1041 1043 return True
1042 1044
1043 1045 def __getitem__(self, key):
1044 1046 return self.filectx(key)
1045 1047
1046 1048 def p1(self):
1047 1049 return self._parents[0]
1048 1050 def p2(self):
1049 1051 return self._parents[1]
1050 1052
1051 1053 def user(self):
1052 1054 return self._user or self._repo.ui.username()
1053 1055 def date(self):
1054 1056 return self._date
1055 1057 def description(self):
1056 1058 return self._text
1057 1059 def files(self):
1058 1060 return self.modified()
1059 1061 def modified(self):
1060 1062 return self._status[0]
1061 1063 def added(self):
1062 1064 return self._status[1]
1063 1065 def removed(self):
1064 1066 return self._status[2]
1065 1067 def deleted(self):
1066 1068 return self._status[3]
1067 1069 def unknown(self):
1068 1070 return self._status[4]
1069 1071 def ignored(self):
1070 1072 return self._status[5]
1071 1073 def clean(self):
1072 1074 return self._status[6]
1073 1075 def branch(self):
1074 1076 return encoding.tolocal(self._extra['branch'])
1075 1077 def extra(self):
1076 1078 return self._extra
1077 1079 def flags(self, f):
1078 1080 return self[f].flags()
1079 1081
1080 1082 def parents(self):
1081 1083 """return contexts for each parent changeset"""
1082 1084 return self._parents
1083 1085
1084 1086 def filectx(self, path, filelog=None):
1085 1087 """get a file context from the working directory"""
1086 1088 return self._filectxfn(self._repo, self, path)
1087 1089
1088 1090 def commit(self):
1089 1091 """commit context to the repo"""
1090 1092 return self._repo.commitctx(self)
1091 1093
1092 1094 class memfilectx(object):
1093 1095 """memfilectx represents an in-memory file to commit.
1094 1096
1095 1097 See memctx for more details.
1096 1098 """
1097 1099 def __init__(self, path, data, islink=False, isexec=False, copied=None):
1098 1100 """
1099 1101 path is the normalized file path relative to repository root.
1100 1102 data is the file content as a string.
1101 1103 islink is True if the file is a symbolic link.
1102 1104 isexec is True if the file is executable.
1103 1105 copied is the source file path if current file was copied in the
1104 1106 revision being committed, or None."""
1105 1107 self._path = path
1106 1108 self._data = data
1107 1109 self._flags = (islink and 'l' or '') + (isexec and 'x' or '')
1108 1110 self._copied = None
1109 1111 if copied:
1110 1112 self._copied = (copied, nullid)
1111 1113
1112 1114 def __nonzero__(self):
1113 1115 return True
1114 1116 def __str__(self):
1115 1117 return "%s@%s" % (self.path(), self._changectx)
1116 1118 def path(self):
1117 1119 return self._path
1118 1120 def data(self):
1119 1121 return self._data
1120 1122 def flags(self):
1121 1123 return self._flags
1122 1124 def isexec(self):
1123 1125 return 'x' in self._flags
1124 1126 def islink(self):
1125 1127 return 'l' in self._flags
1126 1128 def renamed(self):
1127 1129 return self._copied
@@ -1,1767 +1,1767 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
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
15 15
16 16 gitre = re.compile('diff --git a/(.*) b/(.*)')
17 17
18 18 class PatchError(Exception):
19 19 pass
20 20
21 21
22 22 # public functions
23 23
24 24 def split(stream):
25 25 '''return an iterator of individual patches from a stream'''
26 26 def isheader(line, inheader):
27 27 if inheader and line[0] in (' ', '\t'):
28 28 # continuation
29 29 return True
30 30 if line[0] in (' ', '-', '+'):
31 31 # diff line - don't check for header pattern in there
32 32 return False
33 33 l = line.split(': ', 1)
34 34 return len(l) == 2 and ' ' not in l[0]
35 35
36 36 def chunk(lines):
37 37 return cStringIO.StringIO(''.join(lines))
38 38
39 39 def hgsplit(stream, cur):
40 40 inheader = True
41 41
42 42 for line in stream:
43 43 if not line.strip():
44 44 inheader = False
45 45 if not inheader and line.startswith('# HG changeset patch'):
46 46 yield chunk(cur)
47 47 cur = []
48 48 inheader = True
49 49
50 50 cur.append(line)
51 51
52 52 if cur:
53 53 yield chunk(cur)
54 54
55 55 def mboxsplit(stream, cur):
56 56 for line in stream:
57 57 if line.startswith('From '):
58 58 for c in split(chunk(cur[1:])):
59 59 yield c
60 60 cur = []
61 61
62 62 cur.append(line)
63 63
64 64 if cur:
65 65 for c in split(chunk(cur[1:])):
66 66 yield c
67 67
68 68 def mimesplit(stream, cur):
69 69 def msgfp(m):
70 70 fp = cStringIO.StringIO()
71 71 g = email.Generator.Generator(fp, mangle_from_=False)
72 72 g.flatten(m)
73 73 fp.seek(0)
74 74 return fp
75 75
76 76 for line in stream:
77 77 cur.append(line)
78 78 c = chunk(cur)
79 79
80 80 m = email.Parser.Parser().parse(c)
81 81 if not m.is_multipart():
82 82 yield msgfp(m)
83 83 else:
84 84 ok_types = ('text/plain', 'text/x-diff', 'text/x-patch')
85 85 for part in m.walk():
86 86 ct = part.get_content_type()
87 87 if ct not in ok_types:
88 88 continue
89 89 yield msgfp(part)
90 90
91 91 def headersplit(stream, cur):
92 92 inheader = False
93 93
94 94 for line in stream:
95 95 if not inheader and isheader(line, inheader):
96 96 yield chunk(cur)
97 97 cur = []
98 98 inheader = True
99 99 if inheader and not isheader(line, inheader):
100 100 inheader = False
101 101
102 102 cur.append(line)
103 103
104 104 if cur:
105 105 yield chunk(cur)
106 106
107 107 def remainder(cur):
108 108 yield chunk(cur)
109 109
110 110 class fiter(object):
111 111 def __init__(self, fp):
112 112 self.fp = fp
113 113
114 114 def __iter__(self):
115 115 return self
116 116
117 117 def next(self):
118 118 l = self.fp.readline()
119 119 if not l:
120 120 raise StopIteration
121 121 return l
122 122
123 123 inheader = False
124 124 cur = []
125 125
126 126 mimeheaders = ['content-type']
127 127
128 128 if not hasattr(stream, 'next'):
129 129 # http responses, for example, have readline but not next
130 130 stream = fiter(stream)
131 131
132 132 for line in stream:
133 133 cur.append(line)
134 134 if line.startswith('# HG changeset patch'):
135 135 return hgsplit(stream, cur)
136 136 elif line.startswith('From '):
137 137 return mboxsplit(stream, cur)
138 138 elif isheader(line, inheader):
139 139 inheader = True
140 140 if line.split(':', 1)[0].lower() in mimeheaders:
141 141 # let email parser handle this
142 142 return mimesplit(stream, cur)
143 143 elif line.startswith('--- ') and inheader:
144 144 # No evil headers seen by diff start, split by hand
145 145 return headersplit(stream, cur)
146 146 # Not enough info, keep reading
147 147
148 148 # if we are here, we have a very plain patch
149 149 return remainder(cur)
150 150
151 151 def extract(ui, fileobj):
152 152 '''extract patch from data read from fileobj.
153 153
154 154 patch can be a normal patch or contained in an email message.
155 155
156 156 return tuple (filename, message, user, date, branch, node, p1, p2).
157 157 Any item in the returned tuple can be None. If filename is None,
158 158 fileobj did not contain a patch. Caller must unlink filename when done.'''
159 159
160 160 # attempt to detect the start of a patch
161 161 # (this heuristic is borrowed from quilt)
162 162 diffre = re.compile(r'^(?:Index:[ \t]|diff[ \t]|RCS file: |'
163 163 r'retrieving revision [0-9]+(\.[0-9]+)*$|'
164 164 r'---[ \t].*?^\+\+\+[ \t]|'
165 165 r'\*\*\*[ \t].*?^---[ \t])', re.MULTILINE|re.DOTALL)
166 166
167 167 fd, tmpname = tempfile.mkstemp(prefix='hg-patch-')
168 168 tmpfp = os.fdopen(fd, 'w')
169 169 try:
170 170 msg = email.Parser.Parser().parse(fileobj)
171 171
172 172 subject = msg['Subject']
173 173 user = msg['From']
174 174 if not subject and not user:
175 175 # Not an email, restore parsed headers if any
176 176 subject = '\n'.join(': '.join(h) for h in msg.items()) + '\n'
177 177
178 178 gitsendmail = 'git-send-email' in msg.get('X-Mailer', '')
179 179 # should try to parse msg['Date']
180 180 date = None
181 181 nodeid = None
182 182 branch = None
183 183 parents = []
184 184
185 185 if subject:
186 186 if subject.startswith('[PATCH'):
187 187 pend = subject.find(']')
188 188 if pend >= 0:
189 189 subject = subject[pend + 1:].lstrip()
190 190 subject = subject.replace('\n\t', ' ')
191 191 ui.debug('Subject: %s\n' % subject)
192 192 if user:
193 193 ui.debug('From: %s\n' % user)
194 194 diffs_seen = 0
195 195 ok_types = ('text/plain', 'text/x-diff', 'text/x-patch')
196 196 message = ''
197 197 for part in msg.walk():
198 198 content_type = part.get_content_type()
199 199 ui.debug('Content-Type: %s\n' % content_type)
200 200 if content_type not in ok_types:
201 201 continue
202 202 payload = part.get_payload(decode=True)
203 203 m = diffre.search(payload)
204 204 if m:
205 205 hgpatch = False
206 206 hgpatchheader = False
207 207 ignoretext = False
208 208
209 209 ui.debug('found patch at byte %d\n' % m.start(0))
210 210 diffs_seen += 1
211 211 cfp = cStringIO.StringIO()
212 212 for line in payload[:m.start(0)].splitlines():
213 213 if line.startswith('# HG changeset patch') and not hgpatch:
214 214 ui.debug('patch generated by hg export\n')
215 215 hgpatch = True
216 216 hgpatchheader = True
217 217 # drop earlier commit message content
218 218 cfp.seek(0)
219 219 cfp.truncate()
220 220 subject = None
221 221 elif hgpatchheader:
222 222 if line.startswith('# User '):
223 223 user = line[7:]
224 224 ui.debug('From: %s\n' % user)
225 225 elif line.startswith("# Date "):
226 226 date = line[7:]
227 227 elif line.startswith("# Branch "):
228 228 branch = line[9:]
229 229 elif line.startswith("# Node ID "):
230 230 nodeid = line[10:]
231 231 elif line.startswith("# Parent "):
232 232 parents.append(line[10:])
233 233 elif not line.startswith("# "):
234 234 hgpatchheader = False
235 235 elif line == '---' and gitsendmail:
236 236 ignoretext = True
237 237 if not hgpatchheader and not ignoretext:
238 238 cfp.write(line)
239 239 cfp.write('\n')
240 240 message = cfp.getvalue()
241 241 if tmpfp:
242 242 tmpfp.write(payload)
243 243 if not payload.endswith('\n'):
244 244 tmpfp.write('\n')
245 245 elif not diffs_seen and message and content_type == 'text/plain':
246 246 message += '\n' + payload
247 247 except:
248 248 tmpfp.close()
249 249 os.unlink(tmpname)
250 250 raise
251 251
252 252 if subject and not message.startswith(subject):
253 253 message = '%s\n%s' % (subject, message)
254 254 tmpfp.close()
255 255 if not diffs_seen:
256 256 os.unlink(tmpname)
257 257 return None, message, user, date, branch, None, None, None
258 258 p1 = parents and parents.pop(0) or None
259 259 p2 = parents and parents.pop(0) or None
260 260 return tmpname, message, user, date, branch, nodeid, p1, p2
261 261
262 262 class patchmeta(object):
263 263 """Patched file metadata
264 264
265 265 'op' is the performed operation within ADD, DELETE, RENAME, MODIFY
266 266 or COPY. 'path' is patched file path. 'oldpath' is set to the
267 267 origin file when 'op' is either COPY or RENAME, None otherwise. If
268 268 file mode is changed, 'mode' is a tuple (islink, isexec) where
269 269 'islink' is True if the file is a symlink and 'isexec' is True if
270 270 the file is executable. Otherwise, 'mode' is None.
271 271 """
272 272 def __init__(self, path):
273 273 self.path = path
274 274 self.oldpath = None
275 275 self.mode = None
276 276 self.op = 'MODIFY'
277 277 self.binary = False
278 278
279 279 def setmode(self, mode):
280 280 islink = mode & 020000
281 281 isexec = mode & 0100
282 282 self.mode = (islink, isexec)
283 283
284 284 def __repr__(self):
285 285 return "<patchmeta %s %r>" % (self.op, self.path)
286 286
287 287 def readgitpatch(lr):
288 288 """extract git-style metadata about patches from <patchname>"""
289 289
290 290 # Filter patch for git information
291 291 gp = None
292 292 gitpatches = []
293 293 for line in lr:
294 294 line = line.rstrip(' \r\n')
295 295 if line.startswith('diff --git'):
296 296 m = gitre.match(line)
297 297 if m:
298 298 if gp:
299 299 gitpatches.append(gp)
300 300 dst = m.group(2)
301 301 gp = patchmeta(dst)
302 302 elif gp:
303 303 if line.startswith('--- '):
304 304 gitpatches.append(gp)
305 305 gp = None
306 306 continue
307 307 if line.startswith('rename from '):
308 308 gp.op = 'RENAME'
309 309 gp.oldpath = line[12:]
310 310 elif line.startswith('rename to '):
311 311 gp.path = line[10:]
312 312 elif line.startswith('copy from '):
313 313 gp.op = 'COPY'
314 314 gp.oldpath = line[10:]
315 315 elif line.startswith('copy to '):
316 316 gp.path = line[8:]
317 317 elif line.startswith('deleted file'):
318 318 gp.op = 'DELETE'
319 319 elif line.startswith('new file mode '):
320 320 gp.op = 'ADD'
321 321 gp.setmode(int(line[-6:], 8))
322 322 elif line.startswith('new mode '):
323 323 gp.setmode(int(line[-6:], 8))
324 324 elif line.startswith('GIT binary patch'):
325 325 gp.binary = True
326 326 if gp:
327 327 gitpatches.append(gp)
328 328
329 329 return gitpatches
330 330
331 331 class linereader(object):
332 332 # simple class to allow pushing lines back into the input stream
333 333 def __init__(self, fp):
334 334 self.fp = fp
335 335 self.buf = []
336 336
337 337 def push(self, line):
338 338 if line is not None:
339 339 self.buf.append(line)
340 340
341 341 def readline(self):
342 342 if self.buf:
343 343 l = self.buf[0]
344 344 del self.buf[0]
345 345 return l
346 346 return self.fp.readline()
347 347
348 348 def __iter__(self):
349 349 while 1:
350 350 l = self.readline()
351 351 if not l:
352 352 break
353 353 yield l
354 354
355 355 class abstractbackend(object):
356 356 def __init__(self, ui):
357 357 self.ui = ui
358 358
359 359 def getfile(self, fname):
360 360 """Return target file data and flags as a (data, (islink,
361 361 isexec)) tuple.
362 362 """
363 363 raise NotImplementedError
364 364
365 365 def setfile(self, fname, data, mode):
366 366 """Write data to target file fname and set its mode. mode is a
367 367 (islink, isexec) tuple. If data is None, the file content should
368 368 be left unchanged.
369 369 """
370 370 raise NotImplementedError
371 371
372 372 def unlink(self, fname):
373 373 """Unlink target file."""
374 374 raise NotImplementedError
375 375
376 376 def writerej(self, fname, failed, total, lines):
377 377 """Write rejected lines for fname. total is the number of hunks
378 378 which failed to apply and total the total number of hunks for this
379 379 files.
380 380 """
381 381 pass
382 382
383 383 def copy(self, src, dst):
384 384 """Copy src file into dst file. Create intermediate directories if
385 385 necessary. Files are specified relatively to the patching base
386 386 directory.
387 387 """
388 388 raise NotImplementedError
389 389
390 390 def exists(self, fname):
391 391 raise NotImplementedError
392 392
393 393 class fsbackend(abstractbackend):
394 394 def __init__(self, ui, basedir):
395 395 super(fsbackend, self).__init__(ui)
396 396 self.opener = scmutil.opener(basedir)
397 397
398 398 def _join(self, f):
399 399 return os.path.join(self.opener.base, f)
400 400
401 401 def getfile(self, fname):
402 402 path = self._join(fname)
403 403 if os.path.islink(path):
404 404 return (os.readlink(path), (True, False))
405 405 isexec, islink = False, False
406 406 try:
407 407 isexec = os.lstat(path).st_mode & 0100 != 0
408 408 islink = os.path.islink(path)
409 409 except OSError, e:
410 410 if e.errno != errno.ENOENT:
411 411 raise
412 412 return (self.opener.read(fname), (islink, isexec))
413 413
414 414 def setfile(self, fname, data, mode):
415 415 islink, isexec = mode
416 416 if data is None:
417 417 util.setflags(self._join(fname), islink, isexec)
418 418 return
419 419 if islink:
420 420 self.opener.symlink(data, fname)
421 421 else:
422 422 self.opener.write(fname, data)
423 423 if isexec:
424 424 util.setflags(self._join(fname), False, True)
425 425
426 426 def unlink(self, fname):
427 427 try:
428 428 util.unlinkpath(self._join(fname))
429 429 except OSError, inst:
430 430 if inst.errno != errno.ENOENT:
431 431 raise
432 432
433 433 def writerej(self, fname, failed, total, lines):
434 434 fname = fname + ".rej"
435 435 self.ui.warn(
436 436 _("%d out of %d hunks FAILED -- saving rejects to file %s\n") %
437 437 (failed, total, fname))
438 438 fp = self.opener(fname, 'w')
439 439 fp.writelines(lines)
440 440 fp.close()
441 441
442 442 def copy(self, src, dst):
443 443 basedir = self.opener.base
444 444 abssrc, absdst = [scmutil.canonpath(basedir, basedir, x)
445 445 for x in [src, dst]]
446 446 if os.path.lexists(absdst):
447 447 raise util.Abort(_("cannot create %s: destination already exists")
448 448 % dst)
449 449 dstdir = os.path.dirname(absdst)
450 450 if dstdir and not os.path.isdir(dstdir):
451 451 try:
452 452 os.makedirs(dstdir)
453 453 except IOError:
454 454 raise util.Abort(
455 455 _("cannot create %s: unable to create destination directory")
456 456 % dst)
457 457 util.copyfile(abssrc, absdst)
458 458
459 459 def exists(self, fname):
460 460 return os.path.lexists(self._join(fname))
461 461
462 462 class workingbackend(fsbackend):
463 463 def __init__(self, ui, repo, similarity):
464 464 super(workingbackend, self).__init__(ui, repo.root)
465 465 self.repo = repo
466 466 self.similarity = similarity
467 467 self.removed = set()
468 468 self.changed = set()
469 469 self.copied = []
470 470
471 471 def setfile(self, fname, data, mode):
472 472 super(workingbackend, self).setfile(fname, data, mode)
473 473 self.changed.add(fname)
474 474
475 475 def unlink(self, fname):
476 476 super(workingbackend, self).unlink(fname)
477 477 self.removed.add(fname)
478 478 self.changed.add(fname)
479 479
480 480 def copy(self, src, dst):
481 481 super(workingbackend, self).copy(src, dst)
482 482 self.copied.append((src, dst))
483 483 self.changed.add(dst)
484 484
485 485 def close(self):
486 486 wctx = self.repo[None]
487 487 addremoved = set(self.changed)
488 488 for src, dst in self.copied:
489 489 scmutil.dirstatecopy(self.ui, self.repo, wctx, src, dst)
490 490 addremoved.discard(src)
491 491 if (not self.similarity) and self.removed:
492 wctx.remove(sorted(self.removed))
492 wctx.forget(sorted(self.removed))
493 493 if addremoved:
494 494 cwd = self.repo.getcwd()
495 495 if cwd:
496 496 addremoved = [util.pathto(self.repo.root, cwd, f)
497 497 for f in addremoved]
498 498 scmutil.addremove(self.repo, addremoved, similarity=self.similarity)
499 499 return sorted(self.changed)
500 500
501 501 # @@ -start,len +start,len @@ or @@ -start +start @@ if len is 1
502 502 unidesc = re.compile('@@ -(\d+)(,(\d+))? \+(\d+)(,(\d+))? @@')
503 503 contextdesc = re.compile('(---|\*\*\*) (\d+)(,(\d+))? (---|\*\*\*)')
504 504 eolmodes = ['strict', 'crlf', 'lf', 'auto']
505 505
506 506 class patchfile(object):
507 507 def __init__(self, ui, fname, backend, mode, missing=False,
508 508 eolmode='strict'):
509 509 self.fname = fname
510 510 self.eolmode = eolmode
511 511 self.eol = None
512 512 self.backend = backend
513 513 self.ui = ui
514 514 self.lines = []
515 515 self.exists = False
516 516 self.missing = missing
517 517 self.mode = mode
518 518 if not missing:
519 519 try:
520 520 data, mode = self.backend.getfile(fname)
521 521 if data:
522 522 self.lines = data.splitlines(True)
523 523 if self.mode is None:
524 524 self.mode = mode
525 525 if self.lines:
526 526 # Normalize line endings
527 527 if self.lines[0].endswith('\r\n'):
528 528 self.eol = '\r\n'
529 529 elif self.lines[0].endswith('\n'):
530 530 self.eol = '\n'
531 531 if eolmode != 'strict':
532 532 nlines = []
533 533 for l in self.lines:
534 534 if l.endswith('\r\n'):
535 535 l = l[:-2] + '\n'
536 536 nlines.append(l)
537 537 self.lines = nlines
538 538 self.exists = True
539 539 except IOError:
540 540 if self.mode is None:
541 541 self.mode = (False, False)
542 542 else:
543 543 self.ui.warn(_("unable to find '%s' for patching\n") % self.fname)
544 544
545 545 self.hash = {}
546 546 self.dirty = 0
547 547 self.offset = 0
548 548 self.skew = 0
549 549 self.rej = []
550 550 self.fileprinted = False
551 551 self.printfile(False)
552 552 self.hunks = 0
553 553
554 554 def writelines(self, fname, lines, mode):
555 555 if self.eolmode == 'auto':
556 556 eol = self.eol
557 557 elif self.eolmode == 'crlf':
558 558 eol = '\r\n'
559 559 else:
560 560 eol = '\n'
561 561
562 562 if self.eolmode != 'strict' and eol and eol != '\n':
563 563 rawlines = []
564 564 for l in lines:
565 565 if l and l[-1] == '\n':
566 566 l = l[:-1] + eol
567 567 rawlines.append(l)
568 568 lines = rawlines
569 569
570 570 self.backend.setfile(fname, ''.join(lines), mode)
571 571
572 572 def printfile(self, warn):
573 573 if self.fileprinted:
574 574 return
575 575 if warn or self.ui.verbose:
576 576 self.fileprinted = True
577 577 s = _("patching file %s\n") % self.fname
578 578 if warn:
579 579 self.ui.warn(s)
580 580 else:
581 581 self.ui.note(s)
582 582
583 583
584 584 def findlines(self, l, linenum):
585 585 # looks through the hash and finds candidate lines. The
586 586 # result is a list of line numbers sorted based on distance
587 587 # from linenum
588 588
589 589 cand = self.hash.get(l, [])
590 590 if len(cand) > 1:
591 591 # resort our list of potentials forward then back.
592 592 cand.sort(key=lambda x: abs(x - linenum))
593 593 return cand
594 594
595 595 def write_rej(self):
596 596 # our rejects are a little different from patch(1). This always
597 597 # creates rejects in the same form as the original patch. A file
598 598 # header is inserted so that you can run the reject through patch again
599 599 # without having to type the filename.
600 600 if not self.rej:
601 601 return
602 602 base = os.path.basename(self.fname)
603 603 lines = ["--- %s\n+++ %s\n" % (base, base)]
604 604 for x in self.rej:
605 605 for l in x.hunk:
606 606 lines.append(l)
607 607 if l[-1] != '\n':
608 608 lines.append("\n\ No newline at end of file\n")
609 609 self.backend.writerej(self.fname, len(self.rej), self.hunks, lines)
610 610
611 611 def apply(self, h):
612 612 if not h.complete():
613 613 raise PatchError(_("bad hunk #%d %s (%d %d %d %d)") %
614 614 (h.number, h.desc, len(h.a), h.lena, len(h.b),
615 615 h.lenb))
616 616
617 617 self.hunks += 1
618 618
619 619 if self.missing:
620 620 self.rej.append(h)
621 621 return -1
622 622
623 623 if self.exists and h.createfile():
624 624 self.ui.warn(_("file %s already exists\n") % self.fname)
625 625 self.rej.append(h)
626 626 return -1
627 627
628 628 if isinstance(h, binhunk):
629 629 if h.rmfile():
630 630 self.backend.unlink(self.fname)
631 631 else:
632 632 self.lines[:] = h.new()
633 633 self.offset += len(h.new())
634 634 self.dirty = True
635 635 return 0
636 636
637 637 horig = h
638 638 if (self.eolmode in ('crlf', 'lf')
639 639 or self.eolmode == 'auto' and self.eol):
640 640 # If new eols are going to be normalized, then normalize
641 641 # hunk data before patching. Otherwise, preserve input
642 642 # line-endings.
643 643 h = h.getnormalized()
644 644
645 645 # fast case first, no offsets, no fuzz
646 646 old = h.old()
647 647 # patch starts counting at 1 unless we are adding the file
648 648 if h.starta == 0:
649 649 start = 0
650 650 else:
651 651 start = h.starta + self.offset - 1
652 652 orig_start = start
653 653 # if there's skew we want to emit the "(offset %d lines)" even
654 654 # when the hunk cleanly applies at start + skew, so skip the
655 655 # fast case code
656 656 if self.skew == 0 and diffhelpers.testhunk(old, self.lines, start) == 0:
657 657 if h.rmfile():
658 658 self.backend.unlink(self.fname)
659 659 else:
660 660 self.lines[start : start + h.lena] = h.new()
661 661 self.offset += h.lenb - h.lena
662 662 self.dirty = True
663 663 return 0
664 664
665 665 # ok, we couldn't match the hunk. Lets look for offsets and fuzz it
666 666 self.hash = {}
667 667 for x, s in enumerate(self.lines):
668 668 self.hash.setdefault(s, []).append(x)
669 669 if h.hunk[-1][0] != ' ':
670 670 # if the hunk tried to put something at the bottom of the file
671 671 # override the start line and use eof here
672 672 search_start = len(self.lines)
673 673 else:
674 674 search_start = orig_start + self.skew
675 675
676 676 for fuzzlen in xrange(3):
677 677 for toponly in [True, False]:
678 678 old = h.old(fuzzlen, toponly)
679 679
680 680 cand = self.findlines(old[0][1:], search_start)
681 681 for l in cand:
682 682 if diffhelpers.testhunk(old, self.lines, l) == 0:
683 683 newlines = h.new(fuzzlen, toponly)
684 684 self.lines[l : l + len(old)] = newlines
685 685 self.offset += len(newlines) - len(old)
686 686 self.skew = l - orig_start
687 687 self.dirty = True
688 688 offset = l - orig_start - fuzzlen
689 689 if fuzzlen:
690 690 msg = _("Hunk #%d succeeded at %d "
691 691 "with fuzz %d "
692 692 "(offset %d lines).\n")
693 693 self.printfile(True)
694 694 self.ui.warn(msg %
695 695 (h.number, l + 1, fuzzlen, offset))
696 696 else:
697 697 msg = _("Hunk #%d succeeded at %d "
698 698 "(offset %d lines).\n")
699 699 self.ui.note(msg % (h.number, l + 1, offset))
700 700 return fuzzlen
701 701 self.printfile(True)
702 702 self.ui.warn(_("Hunk #%d FAILED at %d\n") % (h.number, orig_start))
703 703 self.rej.append(horig)
704 704 return -1
705 705
706 706 def close(self):
707 707 if self.dirty:
708 708 self.writelines(self.fname, self.lines, self.mode)
709 709 self.write_rej()
710 710 return len(self.rej)
711 711
712 712 class hunk(object):
713 713 def __init__(self, desc, num, lr, context, create=False, remove=False):
714 714 self.number = num
715 715 self.desc = desc
716 716 self.hunk = [desc]
717 717 self.a = []
718 718 self.b = []
719 719 self.starta = self.lena = None
720 720 self.startb = self.lenb = None
721 721 if lr is not None:
722 722 if context:
723 723 self.read_context_hunk(lr)
724 724 else:
725 725 self.read_unified_hunk(lr)
726 726 self.create = create
727 727 self.remove = remove and not create
728 728
729 729 def getnormalized(self):
730 730 """Return a copy with line endings normalized to LF."""
731 731
732 732 def normalize(lines):
733 733 nlines = []
734 734 for line in lines:
735 735 if line.endswith('\r\n'):
736 736 line = line[:-2] + '\n'
737 737 nlines.append(line)
738 738 return nlines
739 739
740 740 # Dummy object, it is rebuilt manually
741 741 nh = hunk(self.desc, self.number, None, None, False, False)
742 742 nh.number = self.number
743 743 nh.desc = self.desc
744 744 nh.hunk = self.hunk
745 745 nh.a = normalize(self.a)
746 746 nh.b = normalize(self.b)
747 747 nh.starta = self.starta
748 748 nh.startb = self.startb
749 749 nh.lena = self.lena
750 750 nh.lenb = self.lenb
751 751 nh.create = self.create
752 752 nh.remove = self.remove
753 753 return nh
754 754
755 755 def read_unified_hunk(self, lr):
756 756 m = unidesc.match(self.desc)
757 757 if not m:
758 758 raise PatchError(_("bad hunk #%d") % self.number)
759 759 self.starta, foo, self.lena, self.startb, foo2, self.lenb = m.groups()
760 760 if self.lena is None:
761 761 self.lena = 1
762 762 else:
763 763 self.lena = int(self.lena)
764 764 if self.lenb is None:
765 765 self.lenb = 1
766 766 else:
767 767 self.lenb = int(self.lenb)
768 768 self.starta = int(self.starta)
769 769 self.startb = int(self.startb)
770 770 diffhelpers.addlines(lr, self.hunk, self.lena, self.lenb, self.a, self.b)
771 771 # if we hit eof before finishing out the hunk, the last line will
772 772 # be zero length. Lets try to fix it up.
773 773 while len(self.hunk[-1]) == 0:
774 774 del self.hunk[-1]
775 775 del self.a[-1]
776 776 del self.b[-1]
777 777 self.lena -= 1
778 778 self.lenb -= 1
779 779 self._fixnewline(lr)
780 780
781 781 def read_context_hunk(self, lr):
782 782 self.desc = lr.readline()
783 783 m = contextdesc.match(self.desc)
784 784 if not m:
785 785 raise PatchError(_("bad hunk #%d") % self.number)
786 786 foo, self.starta, foo2, aend, foo3 = m.groups()
787 787 self.starta = int(self.starta)
788 788 if aend is None:
789 789 aend = self.starta
790 790 self.lena = int(aend) - self.starta
791 791 if self.starta:
792 792 self.lena += 1
793 793 for x in xrange(self.lena):
794 794 l = lr.readline()
795 795 if l.startswith('---'):
796 796 # lines addition, old block is empty
797 797 lr.push(l)
798 798 break
799 799 s = l[2:]
800 800 if l.startswith('- ') or l.startswith('! '):
801 801 u = '-' + s
802 802 elif l.startswith(' '):
803 803 u = ' ' + s
804 804 else:
805 805 raise PatchError(_("bad hunk #%d old text line %d") %
806 806 (self.number, x))
807 807 self.a.append(u)
808 808 self.hunk.append(u)
809 809
810 810 l = lr.readline()
811 811 if l.startswith('\ '):
812 812 s = self.a[-1][:-1]
813 813 self.a[-1] = s
814 814 self.hunk[-1] = s
815 815 l = lr.readline()
816 816 m = contextdesc.match(l)
817 817 if not m:
818 818 raise PatchError(_("bad hunk #%d") % self.number)
819 819 foo, self.startb, foo2, bend, foo3 = m.groups()
820 820 self.startb = int(self.startb)
821 821 if bend is None:
822 822 bend = self.startb
823 823 self.lenb = int(bend) - self.startb
824 824 if self.startb:
825 825 self.lenb += 1
826 826 hunki = 1
827 827 for x in xrange(self.lenb):
828 828 l = lr.readline()
829 829 if l.startswith('\ '):
830 830 # XXX: the only way to hit this is with an invalid line range.
831 831 # The no-eol marker is not counted in the line range, but I
832 832 # guess there are diff(1) out there which behave differently.
833 833 s = self.b[-1][:-1]
834 834 self.b[-1] = s
835 835 self.hunk[hunki - 1] = s
836 836 continue
837 837 if not l:
838 838 # line deletions, new block is empty and we hit EOF
839 839 lr.push(l)
840 840 break
841 841 s = l[2:]
842 842 if l.startswith('+ ') or l.startswith('! '):
843 843 u = '+' + s
844 844 elif l.startswith(' '):
845 845 u = ' ' + s
846 846 elif len(self.b) == 0:
847 847 # line deletions, new block is empty
848 848 lr.push(l)
849 849 break
850 850 else:
851 851 raise PatchError(_("bad hunk #%d old text line %d") %
852 852 (self.number, x))
853 853 self.b.append(s)
854 854 while True:
855 855 if hunki >= len(self.hunk):
856 856 h = ""
857 857 else:
858 858 h = self.hunk[hunki]
859 859 hunki += 1
860 860 if h == u:
861 861 break
862 862 elif h.startswith('-'):
863 863 continue
864 864 else:
865 865 self.hunk.insert(hunki - 1, u)
866 866 break
867 867
868 868 if not self.a:
869 869 # this happens when lines were only added to the hunk
870 870 for x in self.hunk:
871 871 if x.startswith('-') or x.startswith(' '):
872 872 self.a.append(x)
873 873 if not self.b:
874 874 # this happens when lines were only deleted from the hunk
875 875 for x in self.hunk:
876 876 if x.startswith('+') or x.startswith(' '):
877 877 self.b.append(x[1:])
878 878 # @@ -start,len +start,len @@
879 879 self.desc = "@@ -%d,%d +%d,%d @@\n" % (self.starta, self.lena,
880 880 self.startb, self.lenb)
881 881 self.hunk[0] = self.desc
882 882 self._fixnewline(lr)
883 883
884 884 def _fixnewline(self, lr):
885 885 l = lr.readline()
886 886 if l.startswith('\ '):
887 887 diffhelpers.fix_newline(self.hunk, self.a, self.b)
888 888 else:
889 889 lr.push(l)
890 890
891 891 def complete(self):
892 892 return len(self.a) == self.lena and len(self.b) == self.lenb
893 893
894 894 def createfile(self):
895 895 return self.starta == 0 and self.lena == 0 and self.create
896 896
897 897 def rmfile(self):
898 898 return self.startb == 0 and self.lenb == 0 and self.remove
899 899
900 900 def fuzzit(self, l, fuzz, toponly):
901 901 # this removes context lines from the top and bottom of list 'l'. It
902 902 # checks the hunk to make sure only context lines are removed, and then
903 903 # returns a new shortened list of lines.
904 904 fuzz = min(fuzz, len(l)-1)
905 905 if fuzz:
906 906 top = 0
907 907 bot = 0
908 908 hlen = len(self.hunk)
909 909 for x in xrange(hlen - 1):
910 910 # the hunk starts with the @@ line, so use x+1
911 911 if self.hunk[x + 1][0] == ' ':
912 912 top += 1
913 913 else:
914 914 break
915 915 if not toponly:
916 916 for x in xrange(hlen - 1):
917 917 if self.hunk[hlen - bot - 1][0] == ' ':
918 918 bot += 1
919 919 else:
920 920 break
921 921
922 922 # top and bot now count context in the hunk
923 923 # adjust them if either one is short
924 924 context = max(top, bot, 3)
925 925 if bot < context:
926 926 bot = max(0, fuzz - (context - bot))
927 927 else:
928 928 bot = min(fuzz, bot)
929 929 if top < context:
930 930 top = max(0, fuzz - (context - top))
931 931 else:
932 932 top = min(fuzz, top)
933 933
934 934 return l[top:len(l)-bot]
935 935 return l
936 936
937 937 def old(self, fuzz=0, toponly=False):
938 938 return self.fuzzit(self.a, fuzz, toponly)
939 939
940 940 def new(self, fuzz=0, toponly=False):
941 941 return self.fuzzit(self.b, fuzz, toponly)
942 942
943 943 class binhunk:
944 944 'A binary patch file. Only understands literals so far.'
945 945 def __init__(self, gitpatch, lr):
946 946 self.gitpatch = gitpatch
947 947 self.text = None
948 948 self.hunk = ['GIT binary patch\n']
949 949 self._read(lr)
950 950
951 951 def createfile(self):
952 952 return self.gitpatch.op == 'ADD'
953 953
954 954 def rmfile(self):
955 955 return self.gitpatch.op == 'DELETE'
956 956
957 957 def complete(self):
958 958 return self.text is not None
959 959
960 960 def new(self):
961 961 return [self.text]
962 962
963 963 def _read(self, lr):
964 964 line = lr.readline()
965 965 self.hunk.append(line)
966 966 while line and not line.startswith('literal '):
967 967 line = lr.readline()
968 968 self.hunk.append(line)
969 969 if not line:
970 970 raise PatchError(_('could not extract binary patch'))
971 971 size = int(line[8:].rstrip())
972 972 dec = []
973 973 line = lr.readline()
974 974 self.hunk.append(line)
975 975 while len(line) > 1:
976 976 l = line[0]
977 977 if l <= 'Z' and l >= 'A':
978 978 l = ord(l) - ord('A') + 1
979 979 else:
980 980 l = ord(l) - ord('a') + 27
981 981 dec.append(base85.b85decode(line[1:-1])[:l])
982 982 line = lr.readline()
983 983 self.hunk.append(line)
984 984 text = zlib.decompress(''.join(dec))
985 985 if len(text) != size:
986 986 raise PatchError(_('binary patch is %d bytes, not %d') %
987 987 len(text), size)
988 988 self.text = text
989 989
990 990 def parsefilename(str):
991 991 # --- filename \t|space stuff
992 992 s = str[4:].rstrip('\r\n')
993 993 i = s.find('\t')
994 994 if i < 0:
995 995 i = s.find(' ')
996 996 if i < 0:
997 997 return s
998 998 return s[:i]
999 999
1000 1000 def pathstrip(path, strip):
1001 1001 pathlen = len(path)
1002 1002 i = 0
1003 1003 if strip == 0:
1004 1004 return '', path.rstrip()
1005 1005 count = strip
1006 1006 while count > 0:
1007 1007 i = path.find('/', i)
1008 1008 if i == -1:
1009 1009 raise PatchError(_("unable to strip away %d of %d dirs from %s") %
1010 1010 (count, strip, path))
1011 1011 i += 1
1012 1012 # consume '//' in the path
1013 1013 while i < pathlen - 1 and path[i] == '/':
1014 1014 i += 1
1015 1015 count -= 1
1016 1016 return path[:i].lstrip(), path[i:].rstrip()
1017 1017
1018 1018 def selectfile(backend, afile_orig, bfile_orig, hunk, strip, gp):
1019 1019 if gp:
1020 1020 # Git patches do not play games. Excluding copies from the
1021 1021 # following heuristic avoids a lot of confusion
1022 1022 fname = pathstrip(gp.path, strip - 1)[1]
1023 1023 missing = not hunk.createfile() and not backend.exists(fname)
1024 1024 return fname, missing
1025 1025 nulla = afile_orig == "/dev/null"
1026 1026 nullb = bfile_orig == "/dev/null"
1027 1027 abase, afile = pathstrip(afile_orig, strip)
1028 1028 gooda = not nulla and backend.exists(afile)
1029 1029 bbase, bfile = pathstrip(bfile_orig, strip)
1030 1030 if afile == bfile:
1031 1031 goodb = gooda
1032 1032 else:
1033 1033 goodb = not nullb and backend.exists(bfile)
1034 1034 createfunc = hunk.createfile
1035 1035 missing = not goodb and not gooda and not createfunc()
1036 1036
1037 1037 # some diff programs apparently produce patches where the afile is
1038 1038 # not /dev/null, but afile starts with bfile
1039 1039 abasedir = afile[:afile.rfind('/') + 1]
1040 1040 bbasedir = bfile[:bfile.rfind('/') + 1]
1041 1041 if missing and abasedir == bbasedir and afile.startswith(bfile):
1042 1042 # this isn't very pretty
1043 1043 hunk.create = True
1044 1044 if createfunc():
1045 1045 missing = False
1046 1046 else:
1047 1047 hunk.create = False
1048 1048
1049 1049 # If afile is "a/b/foo" and bfile is "a/b/foo.orig" we assume the
1050 1050 # diff is between a file and its backup. In this case, the original
1051 1051 # file should be patched (see original mpatch code).
1052 1052 isbackup = (abase == bbase and bfile.startswith(afile))
1053 1053 fname = None
1054 1054 if not missing:
1055 1055 if gooda and goodb:
1056 1056 fname = isbackup and afile or bfile
1057 1057 elif gooda:
1058 1058 fname = afile
1059 1059
1060 1060 if not fname:
1061 1061 if not nullb:
1062 1062 fname = isbackup and afile or bfile
1063 1063 elif not nulla:
1064 1064 fname = afile
1065 1065 else:
1066 1066 raise PatchError(_("undefined source and destination files"))
1067 1067
1068 1068 return fname, missing
1069 1069
1070 1070 def scangitpatch(lr, firstline):
1071 1071 """
1072 1072 Git patches can emit:
1073 1073 - rename a to b
1074 1074 - change b
1075 1075 - copy a to c
1076 1076 - change c
1077 1077
1078 1078 We cannot apply this sequence as-is, the renamed 'a' could not be
1079 1079 found for it would have been renamed already. And we cannot copy
1080 1080 from 'b' instead because 'b' would have been changed already. So
1081 1081 we scan the git patch for copy and rename commands so we can
1082 1082 perform the copies ahead of time.
1083 1083 """
1084 1084 pos = 0
1085 1085 try:
1086 1086 pos = lr.fp.tell()
1087 1087 fp = lr.fp
1088 1088 except IOError:
1089 1089 fp = cStringIO.StringIO(lr.fp.read())
1090 1090 gitlr = linereader(fp)
1091 1091 gitlr.push(firstline)
1092 1092 gitpatches = readgitpatch(gitlr)
1093 1093 fp.seek(pos)
1094 1094 return gitpatches
1095 1095
1096 1096 def iterhunks(fp):
1097 1097 """Read a patch and yield the following events:
1098 1098 - ("file", afile, bfile, firsthunk): select a new target file.
1099 1099 - ("hunk", hunk): a new hunk is ready to be applied, follows a
1100 1100 "file" event.
1101 1101 - ("git", gitchanges): current diff is in git format, gitchanges
1102 1102 maps filenames to gitpatch records. Unique event.
1103 1103 """
1104 1104 afile = ""
1105 1105 bfile = ""
1106 1106 state = None
1107 1107 hunknum = 0
1108 1108 emitfile = newfile = False
1109 1109 gitpatches = None
1110 1110
1111 1111 # our states
1112 1112 BFILE = 1
1113 1113 context = None
1114 1114 lr = linereader(fp)
1115 1115
1116 1116 while True:
1117 1117 x = lr.readline()
1118 1118 if not x:
1119 1119 break
1120 1120 if state == BFILE and (
1121 1121 (not context and x[0] == '@')
1122 1122 or (context is not False and x.startswith('***************'))
1123 1123 or x.startswith('GIT binary patch')):
1124 1124 gp = None
1125 1125 if gitpatches and gitpatches[-1][0] == bfile:
1126 1126 gp = gitpatches.pop()[1]
1127 1127 if x.startswith('GIT binary patch'):
1128 1128 h = binhunk(gp, lr)
1129 1129 else:
1130 1130 if context is None and x.startswith('***************'):
1131 1131 context = True
1132 1132 create = afile == '/dev/null' or gp and gp.op == 'ADD'
1133 1133 remove = bfile == '/dev/null' or gp and gp.op == 'DELETE'
1134 1134 h = hunk(x, hunknum + 1, lr, context, create, remove)
1135 1135 hunknum += 1
1136 1136 if emitfile:
1137 1137 emitfile = False
1138 1138 yield 'file', (afile, bfile, h, gp)
1139 1139 yield 'hunk', h
1140 1140 elif x.startswith('diff --git'):
1141 1141 m = gitre.match(x)
1142 1142 if not m:
1143 1143 continue
1144 1144 if gitpatches is None:
1145 1145 # scan whole input for git metadata
1146 1146 gitpatches = [('b/' + gp.path, gp) for gp
1147 1147 in scangitpatch(lr, x)]
1148 1148 yield 'git', [g[1] for g in gitpatches
1149 1149 if g[1].op in ('COPY', 'RENAME')]
1150 1150 gitpatches.reverse()
1151 1151 afile = 'a/' + m.group(1)
1152 1152 bfile = 'b/' + m.group(2)
1153 1153 while bfile != gitpatches[-1][0]:
1154 1154 gp = gitpatches.pop()[1]
1155 1155 yield 'file', ('a/' + gp.path, 'b/' + gp.path, None, gp)
1156 1156 gp = gitpatches[-1][1]
1157 1157 # copy/rename + modify should modify target, not source
1158 1158 if gp.op in ('COPY', 'DELETE', 'RENAME', 'ADD') or gp.mode:
1159 1159 afile = bfile
1160 1160 newfile = True
1161 1161 elif x.startswith('---'):
1162 1162 # check for a unified diff
1163 1163 l2 = lr.readline()
1164 1164 if not l2.startswith('+++'):
1165 1165 lr.push(l2)
1166 1166 continue
1167 1167 newfile = True
1168 1168 context = False
1169 1169 afile = parsefilename(x)
1170 1170 bfile = parsefilename(l2)
1171 1171 elif x.startswith('***'):
1172 1172 # check for a context diff
1173 1173 l2 = lr.readline()
1174 1174 if not l2.startswith('---'):
1175 1175 lr.push(l2)
1176 1176 continue
1177 1177 l3 = lr.readline()
1178 1178 lr.push(l3)
1179 1179 if not l3.startswith("***************"):
1180 1180 lr.push(l2)
1181 1181 continue
1182 1182 newfile = True
1183 1183 context = True
1184 1184 afile = parsefilename(x)
1185 1185 bfile = parsefilename(l2)
1186 1186
1187 1187 if newfile:
1188 1188 newfile = False
1189 1189 emitfile = True
1190 1190 state = BFILE
1191 1191 hunknum = 0
1192 1192
1193 1193 while gitpatches:
1194 1194 gp = gitpatches.pop()[1]
1195 1195 yield 'file', ('a/' + gp.path, 'b/' + gp.path, None, gp)
1196 1196
1197 1197 def applydiff(ui, fp, changed, backend, strip=1, eolmode='strict'):
1198 1198 """Reads a patch from fp and tries to apply it.
1199 1199
1200 1200 The dict 'changed' is filled in with all of the filenames changed
1201 1201 by the patch. Returns 0 for a clean patch, -1 if any rejects were
1202 1202 found and 1 if there was any fuzz.
1203 1203
1204 1204 If 'eolmode' is 'strict', the patch content and patched file are
1205 1205 read in binary mode. Otherwise, line endings are ignored when
1206 1206 patching then normalized according to 'eolmode'.
1207 1207 """
1208 1208 return _applydiff(ui, fp, patchfile, backend, changed, strip=strip,
1209 1209 eolmode=eolmode)
1210 1210
1211 1211 def _applydiff(ui, fp, patcher, backend, changed, strip=1, eolmode='strict'):
1212 1212
1213 1213 def pstrip(p):
1214 1214 return pathstrip(p, strip - 1)[1]
1215 1215
1216 1216 rejects = 0
1217 1217 err = 0
1218 1218 current_file = None
1219 1219
1220 1220 for state, values in iterhunks(fp):
1221 1221 if state == 'hunk':
1222 1222 if not current_file:
1223 1223 continue
1224 1224 ret = current_file.apply(values)
1225 1225 if ret >= 0:
1226 1226 changed.setdefault(current_file.fname, None)
1227 1227 if ret > 0:
1228 1228 err = 1
1229 1229 elif state == 'file':
1230 1230 if current_file:
1231 1231 rejects += current_file.close()
1232 1232 current_file = None
1233 1233 afile, bfile, first_hunk, gp = values
1234 1234 if gp:
1235 1235 path = pstrip(gp.path)
1236 1236 changed[path] = gp
1237 1237 if gp.op == 'DELETE':
1238 1238 backend.unlink(path)
1239 1239 continue
1240 1240 if gp.op == 'RENAME':
1241 1241 backend.unlink(pstrip(gp.oldpath))
1242 1242 if gp.mode and not first_hunk:
1243 1243 data = None
1244 1244 if gp.op == 'ADD':
1245 1245 # Added files without content have no hunk and
1246 1246 # must be created
1247 1247 data = ''
1248 1248 backend.setfile(path, data, gp.mode)
1249 1249 if not first_hunk:
1250 1250 continue
1251 1251 try:
1252 1252 mode = gp and gp.mode or None
1253 1253 current_file, missing = selectfile(backend, afile, bfile,
1254 1254 first_hunk, strip, gp)
1255 1255 current_file = patcher(ui, current_file, backend, mode,
1256 1256 missing=missing, eolmode=eolmode)
1257 1257 except PatchError, inst:
1258 1258 ui.warn(str(inst) + '\n')
1259 1259 current_file = None
1260 1260 rejects += 1
1261 1261 continue
1262 1262 elif state == 'git':
1263 1263 for gp in values:
1264 1264 backend.copy(pstrip(gp.oldpath), pstrip(gp.path))
1265 1265 else:
1266 1266 raise util.Abort(_('unsupported parser state: %s') % state)
1267 1267
1268 1268 if current_file:
1269 1269 rejects += current_file.close()
1270 1270
1271 1271 if rejects:
1272 1272 return -1
1273 1273 return err
1274 1274
1275 1275 def _externalpatch(ui, repo, patcher, patchname, strip, files,
1276 1276 similarity):
1277 1277 """use <patcher> to apply <patchname> to the working directory.
1278 1278 returns whether patch was applied with fuzz factor."""
1279 1279
1280 1280 fuzz = False
1281 1281 args = []
1282 1282 cwd = repo.root
1283 1283 if cwd:
1284 1284 args.append('-d %s' % util.shellquote(cwd))
1285 1285 fp = util.popen('%s %s -p%d < %s' % (patcher, ' '.join(args), strip,
1286 1286 util.shellquote(patchname)))
1287 1287 try:
1288 1288 for line in fp:
1289 1289 line = line.rstrip()
1290 1290 ui.note(line + '\n')
1291 1291 if line.startswith('patching file '):
1292 1292 pf = util.parsepatchoutput(line)
1293 1293 printed_file = False
1294 1294 files.setdefault(pf, None)
1295 1295 elif line.find('with fuzz') >= 0:
1296 1296 fuzz = True
1297 1297 if not printed_file:
1298 1298 ui.warn(pf + '\n')
1299 1299 printed_file = True
1300 1300 ui.warn(line + '\n')
1301 1301 elif line.find('saving rejects to file') >= 0:
1302 1302 ui.warn(line + '\n')
1303 1303 elif line.find('FAILED') >= 0:
1304 1304 if not printed_file:
1305 1305 ui.warn(pf + '\n')
1306 1306 printed_file = True
1307 1307 ui.warn(line + '\n')
1308 1308 finally:
1309 1309 if files:
1310 1310 cfiles = list(files)
1311 1311 cwd = repo.getcwd()
1312 1312 if cwd:
1313 1313 cfiles = [util.pathto(repo.root, cwd, f)
1314 1314 for f in cfile]
1315 1315 scmutil.addremove(repo, cfiles, similarity=similarity)
1316 1316 code = fp.close()
1317 1317 if code:
1318 1318 raise PatchError(_("patch command failed: %s") %
1319 1319 util.explainexit(code)[0])
1320 1320 return fuzz
1321 1321
1322 1322 def internalpatch(ui, repo, patchobj, strip, files=None, eolmode='strict',
1323 1323 similarity=0):
1324 1324 """use builtin patch to apply <patchobj> to the working directory.
1325 1325 returns whether patch was applied with fuzz factor."""
1326 1326
1327 1327 if files is None:
1328 1328 files = {}
1329 1329 if eolmode is None:
1330 1330 eolmode = ui.config('patch', 'eol', 'strict')
1331 1331 if eolmode.lower() not in eolmodes:
1332 1332 raise util.Abort(_('unsupported line endings type: %s') % eolmode)
1333 1333 eolmode = eolmode.lower()
1334 1334
1335 1335 backend = workingbackend(ui, repo, similarity)
1336 1336 try:
1337 1337 fp = open(patchobj, 'rb')
1338 1338 except TypeError:
1339 1339 fp = patchobj
1340 1340 try:
1341 1341 ret = applydiff(ui, fp, files, backend, strip=strip, eolmode=eolmode)
1342 1342 finally:
1343 1343 if fp != patchobj:
1344 1344 fp.close()
1345 1345 files.update(dict.fromkeys(backend.close()))
1346 1346 if ret < 0:
1347 1347 raise PatchError(_('patch failed to apply'))
1348 1348 return ret > 0
1349 1349
1350 1350 def patch(ui, repo, patchname, strip=1, files=None, eolmode='strict',
1351 1351 similarity=0):
1352 1352 """Apply <patchname> to the working directory.
1353 1353
1354 1354 'eolmode' specifies how end of lines should be handled. It can be:
1355 1355 - 'strict': inputs are read in binary mode, EOLs are preserved
1356 1356 - 'crlf': EOLs are ignored when patching and reset to CRLF
1357 1357 - 'lf': EOLs are ignored when patching and reset to LF
1358 1358 - None: get it from user settings, default to 'strict'
1359 1359 'eolmode' is ignored when using an external patcher program.
1360 1360
1361 1361 Returns whether patch was applied with fuzz factor.
1362 1362 """
1363 1363 patcher = ui.config('ui', 'patch')
1364 1364 if files is None:
1365 1365 files = {}
1366 1366 try:
1367 1367 if patcher:
1368 1368 return _externalpatch(ui, repo, patcher, patchname, strip,
1369 1369 files, similarity)
1370 1370 return internalpatch(ui, repo, patchname, strip, files, eolmode,
1371 1371 similarity)
1372 1372 except PatchError, err:
1373 1373 raise util.Abort(str(err))
1374 1374
1375 1375 def changedfiles(ui, repo, patchpath, strip=1):
1376 1376 backend = fsbackend(ui, repo.root)
1377 1377 fp = open(patchpath, 'rb')
1378 1378 try:
1379 1379 changed = set()
1380 1380 for state, values in iterhunks(fp):
1381 1381 if state == 'file':
1382 1382 afile, bfile, first_hunk, gp = values
1383 1383 if gp:
1384 1384 changed.add(pathstrip(gp.path, strip - 1)[1])
1385 1385 if gp.op == 'RENAME':
1386 1386 changed.add(pathstrip(gp.oldpath, strip - 1)[1])
1387 1387 if not first_hunk:
1388 1388 continue
1389 1389 current_file, missing = selectfile(backend, afile, bfile,
1390 1390 first_hunk, strip, gp)
1391 1391 changed.add(current_file)
1392 1392 elif state not in ('hunk', 'git'):
1393 1393 raise util.Abort(_('unsupported parser state: %s') % state)
1394 1394 return changed
1395 1395 finally:
1396 1396 fp.close()
1397 1397
1398 1398 def b85diff(to, tn):
1399 1399 '''print base85-encoded binary diff'''
1400 1400 def gitindex(text):
1401 1401 if not text:
1402 1402 return hex(nullid)
1403 1403 l = len(text)
1404 1404 s = util.sha1('blob %d\0' % l)
1405 1405 s.update(text)
1406 1406 return s.hexdigest()
1407 1407
1408 1408 def fmtline(line):
1409 1409 l = len(line)
1410 1410 if l <= 26:
1411 1411 l = chr(ord('A') + l - 1)
1412 1412 else:
1413 1413 l = chr(l - 26 + ord('a') - 1)
1414 1414 return '%c%s\n' % (l, base85.b85encode(line, True))
1415 1415
1416 1416 def chunk(text, csize=52):
1417 1417 l = len(text)
1418 1418 i = 0
1419 1419 while i < l:
1420 1420 yield text[i:i + csize]
1421 1421 i += csize
1422 1422
1423 1423 tohash = gitindex(to)
1424 1424 tnhash = gitindex(tn)
1425 1425 if tohash == tnhash:
1426 1426 return ""
1427 1427
1428 1428 # TODO: deltas
1429 1429 ret = ['index %s..%s\nGIT binary patch\nliteral %s\n' %
1430 1430 (tohash, tnhash, len(tn))]
1431 1431 for l in chunk(zlib.compress(tn)):
1432 1432 ret.append(fmtline(l))
1433 1433 ret.append('\n')
1434 1434 return ''.join(ret)
1435 1435
1436 1436 class GitDiffRequired(Exception):
1437 1437 pass
1438 1438
1439 1439 def diffopts(ui, opts=None, untrusted=False):
1440 1440 def get(key, name=None, getter=ui.configbool):
1441 1441 return ((opts and opts.get(key)) or
1442 1442 getter('diff', name or key, None, untrusted=untrusted))
1443 1443 return mdiff.diffopts(
1444 1444 text=opts and opts.get('text'),
1445 1445 git=get('git'),
1446 1446 nodates=get('nodates'),
1447 1447 showfunc=get('show_function', 'showfunc'),
1448 1448 ignorews=get('ignore_all_space', 'ignorews'),
1449 1449 ignorewsamount=get('ignore_space_change', 'ignorewsamount'),
1450 1450 ignoreblanklines=get('ignore_blank_lines', 'ignoreblanklines'),
1451 1451 context=get('unified', getter=ui.config))
1452 1452
1453 1453 def diff(repo, node1=None, node2=None, match=None, changes=None, opts=None,
1454 1454 losedatafn=None, prefix=''):
1455 1455 '''yields diff of changes to files between two nodes, or node and
1456 1456 working directory.
1457 1457
1458 1458 if node1 is None, use first dirstate parent instead.
1459 1459 if node2 is None, compare node1 with working directory.
1460 1460
1461 1461 losedatafn(**kwarg) is a callable run when opts.upgrade=True and
1462 1462 every time some change cannot be represented with the current
1463 1463 patch format. Return False to upgrade to git patch format, True to
1464 1464 accept the loss or raise an exception to abort the diff. It is
1465 1465 called with the name of current file being diffed as 'fn'. If set
1466 1466 to None, patches will always be upgraded to git format when
1467 1467 necessary.
1468 1468
1469 1469 prefix is a filename prefix that is prepended to all filenames on
1470 1470 display (used for subrepos).
1471 1471 '''
1472 1472
1473 1473 if opts is None:
1474 1474 opts = mdiff.defaultopts
1475 1475
1476 1476 if not node1 and not node2:
1477 1477 node1 = repo.dirstate.p1()
1478 1478
1479 1479 def lrugetfilectx():
1480 1480 cache = {}
1481 1481 order = []
1482 1482 def getfilectx(f, ctx):
1483 1483 fctx = ctx.filectx(f, filelog=cache.get(f))
1484 1484 if f not in cache:
1485 1485 if len(cache) > 20:
1486 1486 del cache[order.pop(0)]
1487 1487 cache[f] = fctx.filelog()
1488 1488 else:
1489 1489 order.remove(f)
1490 1490 order.append(f)
1491 1491 return fctx
1492 1492 return getfilectx
1493 1493 getfilectx = lrugetfilectx()
1494 1494
1495 1495 ctx1 = repo[node1]
1496 1496 ctx2 = repo[node2]
1497 1497
1498 1498 if not changes:
1499 1499 changes = repo.status(ctx1, ctx2, match=match)
1500 1500 modified, added, removed = changes[:3]
1501 1501
1502 1502 if not modified and not added and not removed:
1503 1503 return []
1504 1504
1505 1505 revs = None
1506 1506 if not repo.ui.quiet:
1507 1507 hexfunc = repo.ui.debugflag and hex or short
1508 1508 revs = [hexfunc(node) for node in [node1, node2] if node]
1509 1509
1510 1510 copy = {}
1511 1511 if opts.git or opts.upgrade:
1512 1512 copy = copies.copies(repo, ctx1, ctx2, repo[nullid])[0]
1513 1513
1514 1514 difffn = lambda opts, losedata: trydiff(repo, revs, ctx1, ctx2,
1515 1515 modified, added, removed, copy, getfilectx, opts, losedata, prefix)
1516 1516 if opts.upgrade and not opts.git:
1517 1517 try:
1518 1518 def losedata(fn):
1519 1519 if not losedatafn or not losedatafn(fn=fn):
1520 1520 raise GitDiffRequired()
1521 1521 # Buffer the whole output until we are sure it can be generated
1522 1522 return list(difffn(opts.copy(git=False), losedata))
1523 1523 except GitDiffRequired:
1524 1524 return difffn(opts.copy(git=True), None)
1525 1525 else:
1526 1526 return difffn(opts, None)
1527 1527
1528 1528 def difflabel(func, *args, **kw):
1529 1529 '''yields 2-tuples of (output, label) based on the output of func()'''
1530 1530 prefixes = [('diff', 'diff.diffline'),
1531 1531 ('copy', 'diff.extended'),
1532 1532 ('rename', 'diff.extended'),
1533 1533 ('old', 'diff.extended'),
1534 1534 ('new', 'diff.extended'),
1535 1535 ('deleted', 'diff.extended'),
1536 1536 ('---', 'diff.file_a'),
1537 1537 ('+++', 'diff.file_b'),
1538 1538 ('@@', 'diff.hunk'),
1539 1539 ('-', 'diff.deleted'),
1540 1540 ('+', 'diff.inserted')]
1541 1541
1542 1542 for chunk in func(*args, **kw):
1543 1543 lines = chunk.split('\n')
1544 1544 for i, line in enumerate(lines):
1545 1545 if i != 0:
1546 1546 yield ('\n', '')
1547 1547 stripline = line
1548 1548 if line and line[0] in '+-':
1549 1549 # highlight trailing whitespace, but only in changed lines
1550 1550 stripline = line.rstrip()
1551 1551 for prefix, label in prefixes:
1552 1552 if stripline.startswith(prefix):
1553 1553 yield (stripline, label)
1554 1554 break
1555 1555 else:
1556 1556 yield (line, '')
1557 1557 if line != stripline:
1558 1558 yield (line[len(stripline):], 'diff.trailingwhitespace')
1559 1559
1560 1560 def diffui(*args, **kw):
1561 1561 '''like diff(), but yields 2-tuples of (output, label) for ui.write()'''
1562 1562 return difflabel(diff, *args, **kw)
1563 1563
1564 1564
1565 1565 def _addmodehdr(header, omode, nmode):
1566 1566 if omode != nmode:
1567 1567 header.append('old mode %s\n' % omode)
1568 1568 header.append('new mode %s\n' % nmode)
1569 1569
1570 1570 def trydiff(repo, revs, ctx1, ctx2, modified, added, removed,
1571 1571 copy, getfilectx, opts, losedatafn, prefix):
1572 1572
1573 1573 def join(f):
1574 1574 return os.path.join(prefix, f)
1575 1575
1576 1576 date1 = util.datestr(ctx1.date())
1577 1577 man1 = ctx1.manifest()
1578 1578
1579 1579 gone = set()
1580 1580 gitmode = {'l': '120000', 'x': '100755', '': '100644'}
1581 1581
1582 1582 copyto = dict([(v, k) for k, v in copy.items()])
1583 1583
1584 1584 if opts.git:
1585 1585 revs = None
1586 1586
1587 1587 for f in sorted(modified + added + removed):
1588 1588 to = None
1589 1589 tn = None
1590 1590 dodiff = True
1591 1591 header = []
1592 1592 if f in man1:
1593 1593 to = getfilectx(f, ctx1).data()
1594 1594 if f not in removed:
1595 1595 tn = getfilectx(f, ctx2).data()
1596 1596 a, b = f, f
1597 1597 if opts.git or losedatafn:
1598 1598 if f in added:
1599 1599 mode = gitmode[ctx2.flags(f)]
1600 1600 if f in copy or f in copyto:
1601 1601 if opts.git:
1602 1602 if f in copy:
1603 1603 a = copy[f]
1604 1604 else:
1605 1605 a = copyto[f]
1606 1606 omode = gitmode[man1.flags(a)]
1607 1607 _addmodehdr(header, omode, mode)
1608 1608 if a in removed and a not in gone:
1609 1609 op = 'rename'
1610 1610 gone.add(a)
1611 1611 else:
1612 1612 op = 'copy'
1613 1613 header.append('%s from %s\n' % (op, join(a)))
1614 1614 header.append('%s to %s\n' % (op, join(f)))
1615 1615 to = getfilectx(a, ctx1).data()
1616 1616 else:
1617 1617 losedatafn(f)
1618 1618 else:
1619 1619 if opts.git:
1620 1620 header.append('new file mode %s\n' % mode)
1621 1621 elif ctx2.flags(f):
1622 1622 losedatafn(f)
1623 1623 # In theory, if tn was copied or renamed we should check
1624 1624 # if the source is binary too but the copy record already
1625 1625 # forces git mode.
1626 1626 if util.binary(tn):
1627 1627 if opts.git:
1628 1628 dodiff = 'binary'
1629 1629 else:
1630 1630 losedatafn(f)
1631 1631 if not opts.git and not tn:
1632 1632 # regular diffs cannot represent new empty file
1633 1633 losedatafn(f)
1634 1634 elif f in removed:
1635 1635 if opts.git:
1636 1636 # have we already reported a copy above?
1637 1637 if ((f in copy and copy[f] in added
1638 1638 and copyto[copy[f]] == f) or
1639 1639 (f in copyto and copyto[f] in added
1640 1640 and copy[copyto[f]] == f)):
1641 1641 dodiff = False
1642 1642 else:
1643 1643 header.append('deleted file mode %s\n' %
1644 1644 gitmode[man1.flags(f)])
1645 1645 elif not to or util.binary(to):
1646 1646 # regular diffs cannot represent empty file deletion
1647 1647 losedatafn(f)
1648 1648 else:
1649 1649 oflag = man1.flags(f)
1650 1650 nflag = ctx2.flags(f)
1651 1651 binary = util.binary(to) or util.binary(tn)
1652 1652 if opts.git:
1653 1653 _addmodehdr(header, gitmode[oflag], gitmode[nflag])
1654 1654 if binary:
1655 1655 dodiff = 'binary'
1656 1656 elif binary or nflag != oflag:
1657 1657 losedatafn(f)
1658 1658 if opts.git:
1659 1659 header.insert(0, mdiff.diffline(revs, join(a), join(b), opts))
1660 1660
1661 1661 if dodiff:
1662 1662 if dodiff == 'binary':
1663 1663 text = b85diff(to, tn)
1664 1664 else:
1665 1665 text = mdiff.unidiff(to, date1,
1666 1666 # ctx2 date may be dynamic
1667 1667 tn, util.datestr(ctx2.date()),
1668 1668 join(a), join(b), revs, opts=opts)
1669 1669 if header and (text or len(header) > 1):
1670 1670 yield ''.join(header)
1671 1671 if text:
1672 1672 yield text
1673 1673
1674 1674 def diffstatsum(stats):
1675 1675 maxfile, addtotal, removetotal, binary = 0, 0, 0, False
1676 1676 for f, a, r, b in stats:
1677 1677 maxfile = max(maxfile, encoding.colwidth(f))
1678 1678 addtotal += a
1679 1679 removetotal += r
1680 1680 binary = binary or b
1681 1681
1682 1682 return maxfile, addtotal, removetotal, binary
1683 1683
1684 1684 def diffstatdata(lines):
1685 1685 diffre = re.compile('^diff .*-r [a-z0-9]+\s(.*)$')
1686 1686
1687 1687 results = []
1688 1688 filename, adds, removes = None, 0, 0
1689 1689
1690 1690 def addresult():
1691 1691 if filename:
1692 1692 isbinary = adds == 0 and removes == 0
1693 1693 results.append((filename, adds, removes, isbinary))
1694 1694
1695 1695 for line in lines:
1696 1696 if line.startswith('diff'):
1697 1697 addresult()
1698 1698 # set numbers to 0 anyway when starting new file
1699 1699 adds, removes = 0, 0
1700 1700 if line.startswith('diff --git'):
1701 1701 filename = gitre.search(line).group(1)
1702 1702 elif line.startswith('diff -r'):
1703 1703 # format: "diff -r ... -r ... filename"
1704 1704 filename = diffre.search(line).group(1)
1705 1705 elif line.startswith('+') and not line.startswith('+++'):
1706 1706 adds += 1
1707 1707 elif line.startswith('-') and not line.startswith('---'):
1708 1708 removes += 1
1709 1709 addresult()
1710 1710 return results
1711 1711
1712 1712 def diffstat(lines, width=80, git=False):
1713 1713 output = []
1714 1714 stats = diffstatdata(lines)
1715 1715 maxname, totaladds, totalremoves, hasbinary = diffstatsum(stats)
1716 1716 maxtotal = totaladds + totalremoves
1717 1717
1718 1718 countwidth = len(str(maxtotal))
1719 1719 if hasbinary and countwidth < 3:
1720 1720 countwidth = 3
1721 1721 graphwidth = width - countwidth - maxname - 6
1722 1722 if graphwidth < 10:
1723 1723 graphwidth = 10
1724 1724
1725 1725 def scale(i):
1726 1726 if maxtotal <= graphwidth:
1727 1727 return i
1728 1728 # If diffstat runs out of room it doesn't print anything,
1729 1729 # which isn't very useful, so always print at least one + or -
1730 1730 # if there were at least some changes.
1731 1731 return max(i * graphwidth // maxtotal, int(bool(i)))
1732 1732
1733 1733 for filename, adds, removes, isbinary in stats:
1734 1734 if git and isbinary:
1735 1735 count = 'Bin'
1736 1736 else:
1737 1737 count = adds + removes
1738 1738 pluses = '+' * scale(adds)
1739 1739 minuses = '-' * scale(removes)
1740 1740 output.append(' %s%s | %*s %s%s\n' %
1741 1741 (filename, ' ' * (maxname - encoding.colwidth(filename)),
1742 1742 countwidth, count, pluses, minuses))
1743 1743
1744 1744 if stats:
1745 1745 output.append(_(' %d files changed, %d insertions(+), %d deletions(-)\n')
1746 1746 % (len(stats), totaladds, totalremoves))
1747 1747
1748 1748 return ''.join(output)
1749 1749
1750 1750 def diffstatui(*args, **kw):
1751 1751 '''like diffstat(), but yields 2-tuples of (output, label) for
1752 1752 ui.write()
1753 1753 '''
1754 1754
1755 1755 for line in diffstat(*args, **kw).splitlines():
1756 1756 if line and line[-1] in '+-':
1757 1757 name, graph = line.rsplit(' ', 1)
1758 1758 yield (name + ' ', '')
1759 1759 m = re.search(r'\++', graph)
1760 1760 if m:
1761 1761 yield (m.group(0), 'diffstat.inserted')
1762 1762 m = re.search(r'-+', graph)
1763 1763 if m:
1764 1764 yield (m.group(0), 'diffstat.deleted')
1765 1765 else:
1766 1766 yield (line, '')
1767 1767 yield ('\n', '')
@@ -1,693 +1,693 b''
1 1 # scmutil.py - Mercurial core utility functions
2 2 #
3 3 # Copyright Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 from i18n import _
9 9 import util, error, osutil, revset, similar
10 10 import match as matchmod
11 11 import os, errno, stat, sys, glob
12 12
13 13 def checkfilename(f):
14 14 '''Check that the filename f is an acceptable filename for a tracked file'''
15 15 if '\r' in f or '\n' in f:
16 16 raise util.Abort(_("'\\n' and '\\r' disallowed in filenames: %r") % f)
17 17
18 18 def checkportable(ui, f):
19 19 '''Check if filename f is portable and warn or abort depending on config'''
20 20 checkfilename(f)
21 21 abort, warn = checkportabilityalert(ui)
22 22 if abort or warn:
23 23 msg = util.checkwinfilename(f)
24 24 if msg:
25 25 msg = "%s: %r" % (msg, f)
26 26 if abort:
27 27 raise util.Abort(msg)
28 28 ui.warn(_("warning: %s\n") % msg)
29 29
30 30 def checkportabilityalert(ui):
31 31 '''check if the user's config requests nothing, a warning, or abort for
32 32 non-portable filenames'''
33 33 val = ui.config('ui', 'portablefilenames', 'warn')
34 34 lval = val.lower()
35 35 bval = util.parsebool(val)
36 36 abort = os.name == 'nt' or lval == 'abort'
37 37 warn = bval or lval == 'warn'
38 38 if bval is None and not (warn or abort or lval == 'ignore'):
39 39 raise error.ConfigError(
40 40 _("ui.portablefilenames value is invalid ('%s')") % val)
41 41 return abort, warn
42 42
43 43 class casecollisionauditor(object):
44 44 def __init__(self, ui, abort, existingiter):
45 45 self._ui = ui
46 46 self._abort = abort
47 47 self._map = {}
48 48 for f in existingiter:
49 49 self._map[f.lower()] = f
50 50
51 51 def __call__(self, f):
52 52 fl = f.lower()
53 53 map = self._map
54 54 if fl in map and map[fl] != f:
55 55 msg = _('possible case-folding collision for %s') % f
56 56 if self._abort:
57 57 raise util.Abort(msg)
58 58 self._ui.warn(_("warning: %s\n") % msg)
59 59 map[fl] = f
60 60
61 61 class pathauditor(object):
62 62 '''ensure that a filesystem path contains no banned components.
63 63 the following properties of a path are checked:
64 64
65 65 - ends with a directory separator
66 66 - under top-level .hg
67 67 - starts at the root of a windows drive
68 68 - contains ".."
69 69 - traverses a symlink (e.g. a/symlink_here/b)
70 70 - inside a nested repository (a callback can be used to approve
71 71 some nested repositories, e.g., subrepositories)
72 72 '''
73 73
74 74 def __init__(self, root, callback=None):
75 75 self.audited = set()
76 76 self.auditeddir = set()
77 77 self.root = root
78 78 self.callback = callback
79 79
80 80 def __call__(self, path):
81 81 '''Check the relative path.
82 82 path may contain a pattern (e.g. foodir/**.txt)'''
83 83
84 84 if path in self.audited:
85 85 return
86 86 # AIX ignores "/" at end of path, others raise EISDIR.
87 87 if util.endswithsep(path):
88 88 raise util.Abort(_("path ends in directory separator: %s") % path)
89 89 normpath = os.path.normcase(path)
90 90 parts = util.splitpath(normpath)
91 91 if (os.path.splitdrive(path)[0]
92 92 or parts[0].lower() in ('.hg', '.hg.', '')
93 93 or os.pardir in parts):
94 94 raise util.Abort(_("path contains illegal component: %s") % path)
95 95 if '.hg' in path.lower():
96 96 lparts = [p.lower() for p in parts]
97 97 for p in '.hg', '.hg.':
98 98 if p in lparts[1:]:
99 99 pos = lparts.index(p)
100 100 base = os.path.join(*parts[:pos])
101 101 raise util.Abort(_('path %r is inside nested repo %r')
102 102 % (path, base))
103 103
104 104 parts.pop()
105 105 prefixes = []
106 106 while parts:
107 107 prefix = os.sep.join(parts)
108 108 if prefix in self.auditeddir:
109 109 break
110 110 curpath = os.path.join(self.root, prefix)
111 111 try:
112 112 st = os.lstat(curpath)
113 113 except OSError, err:
114 114 # EINVAL can be raised as invalid path syntax under win32.
115 115 # They must be ignored for patterns can be checked too.
116 116 if err.errno not in (errno.ENOENT, errno.ENOTDIR, errno.EINVAL):
117 117 raise
118 118 else:
119 119 if stat.S_ISLNK(st.st_mode):
120 120 raise util.Abort(
121 121 _('path %r traverses symbolic link %r')
122 122 % (path, prefix))
123 123 elif (stat.S_ISDIR(st.st_mode) and
124 124 os.path.isdir(os.path.join(curpath, '.hg'))):
125 125 if not self.callback or not self.callback(curpath):
126 126 raise util.Abort(_('path %r is inside nested repo %r') %
127 127 (path, prefix))
128 128 prefixes.append(prefix)
129 129 parts.pop()
130 130
131 131 self.audited.add(path)
132 132 # only add prefixes to the cache after checking everything: we don't
133 133 # want to add "foo/bar/baz" before checking if there's a "foo/.hg"
134 134 self.auditeddir.update(prefixes)
135 135
136 136 class abstractopener(object):
137 137 """Abstract base class; cannot be instantiated"""
138 138
139 139 def __init__(self, *args, **kwargs):
140 140 '''Prevent instantiation; don't call this from subclasses.'''
141 141 raise NotImplementedError('attempted instantiating ' + str(type(self)))
142 142
143 143 def read(self, path):
144 144 fp = self(path, 'rb')
145 145 try:
146 146 return fp.read()
147 147 finally:
148 148 fp.close()
149 149
150 150 def write(self, path, data):
151 151 fp = self(path, 'wb')
152 152 try:
153 153 return fp.write(data)
154 154 finally:
155 155 fp.close()
156 156
157 157 def append(self, path, data):
158 158 fp = self(path, 'ab')
159 159 try:
160 160 return fp.write(data)
161 161 finally:
162 162 fp.close()
163 163
164 164 class opener(abstractopener):
165 165 '''Open files relative to a base directory
166 166
167 167 This class is used to hide the details of COW semantics and
168 168 remote file access from higher level code.
169 169 '''
170 170 def __init__(self, base, audit=True):
171 171 self.base = base
172 172 if audit:
173 173 self.auditor = pathauditor(base)
174 174 else:
175 175 self.auditor = util.always
176 176 self.createmode = None
177 177 self._trustnlink = None
178 178
179 179 @util.propertycache
180 180 def _cansymlink(self):
181 181 return util.checklink(self.base)
182 182
183 183 def _fixfilemode(self, name):
184 184 if self.createmode is None:
185 185 return
186 186 os.chmod(name, self.createmode & 0666)
187 187
188 188 def __call__(self, path, mode="r", text=False, atomictemp=False):
189 189 r = util.checkosfilename(path)
190 190 if r:
191 191 raise util.Abort("%s: %r" % (r, path))
192 192 self.auditor(path)
193 193 f = os.path.join(self.base, path)
194 194
195 195 if not text and "b" not in mode:
196 196 mode += "b" # for that other OS
197 197
198 198 nlink = -1
199 199 dirname, basename = os.path.split(f)
200 200 # If basename is empty, then the path is malformed because it points
201 201 # to a directory. Let the posixfile() call below raise IOError.
202 202 if basename and mode not in ('r', 'rb'):
203 203 if atomictemp:
204 204 if not os.path.isdir(dirname):
205 205 util.makedirs(dirname, self.createmode)
206 206 return util.atomictempfile(f, mode, self.createmode)
207 207 try:
208 208 if 'w' in mode:
209 209 util.unlink(f)
210 210 nlink = 0
211 211 else:
212 212 # nlinks() may behave differently for files on Windows
213 213 # shares if the file is open.
214 214 fd = util.posixfile(f)
215 215 nlink = util.nlinks(f)
216 216 if nlink < 1:
217 217 nlink = 2 # force mktempcopy (issue1922)
218 218 fd.close()
219 219 except (OSError, IOError), e:
220 220 if e.errno != errno.ENOENT:
221 221 raise
222 222 nlink = 0
223 223 if not os.path.isdir(dirname):
224 224 util.makedirs(dirname, self.createmode)
225 225 if nlink > 0:
226 226 if self._trustnlink is None:
227 227 self._trustnlink = nlink > 1 or util.checknlink(f)
228 228 if nlink > 1 or not self._trustnlink:
229 229 util.rename(util.mktempcopy(f), f)
230 230 fp = util.posixfile(f, mode)
231 231 if nlink == 0:
232 232 self._fixfilemode(f)
233 233 return fp
234 234
235 235 def symlink(self, src, dst):
236 236 self.auditor(dst)
237 237 linkname = os.path.join(self.base, dst)
238 238 try:
239 239 os.unlink(linkname)
240 240 except OSError:
241 241 pass
242 242
243 243 dirname = os.path.dirname(linkname)
244 244 if not os.path.exists(dirname):
245 245 util.makedirs(dirname, self.createmode)
246 246
247 247 if self._cansymlink:
248 248 try:
249 249 os.symlink(src, linkname)
250 250 except OSError, err:
251 251 raise OSError(err.errno, _('could not symlink to %r: %s') %
252 252 (src, err.strerror), linkname)
253 253 else:
254 254 f = self(dst, "w")
255 255 f.write(src)
256 256 f.close()
257 257 self._fixfilemode(dst)
258 258
259 259 def audit(self, path):
260 260 self.auditor(path)
261 261
262 262 class filteropener(abstractopener):
263 263 '''Wrapper opener for filtering filenames with a function.'''
264 264
265 265 def __init__(self, opener, filter):
266 266 self._filter = filter
267 267 self._orig = opener
268 268
269 269 def __call__(self, path, *args, **kwargs):
270 270 return self._orig(self._filter(path), *args, **kwargs)
271 271
272 272 def canonpath(root, cwd, myname, auditor=None):
273 273 '''return the canonical path of myname, given cwd and root'''
274 274 if util.endswithsep(root):
275 275 rootsep = root
276 276 else:
277 277 rootsep = root + os.sep
278 278 name = myname
279 279 if not os.path.isabs(name):
280 280 name = os.path.join(root, cwd, name)
281 281 name = os.path.normpath(name)
282 282 if auditor is None:
283 283 auditor = pathauditor(root)
284 284 if name != rootsep and name.startswith(rootsep):
285 285 name = name[len(rootsep):]
286 286 auditor(name)
287 287 return util.pconvert(name)
288 288 elif name == root:
289 289 return ''
290 290 else:
291 291 # Determine whether `name' is in the hierarchy at or beneath `root',
292 292 # by iterating name=dirname(name) until that causes no change (can't
293 293 # check name == '/', because that doesn't work on windows). For each
294 294 # `name', compare dev/inode numbers. If they match, the list `rel'
295 295 # holds the reversed list of components making up the relative file
296 296 # name we want.
297 297 root_st = os.stat(root)
298 298 rel = []
299 299 while True:
300 300 try:
301 301 name_st = os.stat(name)
302 302 except OSError:
303 303 break
304 304 if util.samestat(name_st, root_st):
305 305 if not rel:
306 306 # name was actually the same as root (maybe a symlink)
307 307 return ''
308 308 rel.reverse()
309 309 name = os.path.join(*rel)
310 310 auditor(name)
311 311 return util.pconvert(name)
312 312 dirname, basename = os.path.split(name)
313 313 rel.append(basename)
314 314 if dirname == name:
315 315 break
316 316 name = dirname
317 317
318 318 raise util.Abort('%s not under root' % myname)
319 319
320 320 def walkrepos(path, followsym=False, seen_dirs=None, recurse=False):
321 321 '''yield every hg repository under path, recursively.'''
322 322 def errhandler(err):
323 323 if err.filename == path:
324 324 raise err
325 325 if followsym and hasattr(os.path, 'samestat'):
326 326 def adddir(dirlst, dirname):
327 327 match = False
328 328 samestat = os.path.samestat
329 329 dirstat = os.stat(dirname)
330 330 for lstdirstat in dirlst:
331 331 if samestat(dirstat, lstdirstat):
332 332 match = True
333 333 break
334 334 if not match:
335 335 dirlst.append(dirstat)
336 336 return not match
337 337 else:
338 338 followsym = False
339 339
340 340 if (seen_dirs is None) and followsym:
341 341 seen_dirs = []
342 342 adddir(seen_dirs, path)
343 343 for root, dirs, files in os.walk(path, topdown=True, onerror=errhandler):
344 344 dirs.sort()
345 345 if '.hg' in dirs:
346 346 yield root # found a repository
347 347 qroot = os.path.join(root, '.hg', 'patches')
348 348 if os.path.isdir(os.path.join(qroot, '.hg')):
349 349 yield qroot # we have a patch queue repo here
350 350 if recurse:
351 351 # avoid recursing inside the .hg directory
352 352 dirs.remove('.hg')
353 353 else:
354 354 dirs[:] = [] # don't descend further
355 355 elif followsym:
356 356 newdirs = []
357 357 for d in dirs:
358 358 fname = os.path.join(root, d)
359 359 if adddir(seen_dirs, fname):
360 360 if os.path.islink(fname):
361 361 for hgname in walkrepos(fname, True, seen_dirs):
362 362 yield hgname
363 363 else:
364 364 newdirs.append(d)
365 365 dirs[:] = newdirs
366 366
367 367 def osrcpath():
368 368 '''return default os-specific hgrc search path'''
369 369 path = systemrcpath()
370 370 path.extend(userrcpath())
371 371 path = [os.path.normpath(f) for f in path]
372 372 return path
373 373
374 374 _rcpath = None
375 375
376 376 def rcpath():
377 377 '''return hgrc search path. if env var HGRCPATH is set, use it.
378 378 for each item in path, if directory, use files ending in .rc,
379 379 else use item.
380 380 make HGRCPATH empty to only look in .hg/hgrc of current repo.
381 381 if no HGRCPATH, use default os-specific path.'''
382 382 global _rcpath
383 383 if _rcpath is None:
384 384 if 'HGRCPATH' in os.environ:
385 385 _rcpath = []
386 386 for p in os.environ['HGRCPATH'].split(os.pathsep):
387 387 if not p:
388 388 continue
389 389 p = util.expandpath(p)
390 390 if os.path.isdir(p):
391 391 for f, kind in osutil.listdir(p):
392 392 if f.endswith('.rc'):
393 393 _rcpath.append(os.path.join(p, f))
394 394 else:
395 395 _rcpath.append(p)
396 396 else:
397 397 _rcpath = osrcpath()
398 398 return _rcpath
399 399
400 400 if os.name != 'nt':
401 401
402 402 def rcfiles(path):
403 403 rcs = [os.path.join(path, 'hgrc')]
404 404 rcdir = os.path.join(path, 'hgrc.d')
405 405 try:
406 406 rcs.extend([os.path.join(rcdir, f)
407 407 for f, kind in osutil.listdir(rcdir)
408 408 if f.endswith(".rc")])
409 409 except OSError:
410 410 pass
411 411 return rcs
412 412
413 413 def systemrcpath():
414 414 path = []
415 415 # old mod_python does not set sys.argv
416 416 if len(getattr(sys, 'argv', [])) > 0:
417 417 path.extend(rcfiles(os.path.dirname(sys.argv[0]) +
418 418 '/../etc/mercurial'))
419 419 path.extend(rcfiles('/etc/mercurial'))
420 420 return path
421 421
422 422 def userrcpath():
423 423 return [os.path.expanduser('~/.hgrc')]
424 424
425 425 else:
426 426
427 427 _HKEY_LOCAL_MACHINE = 0x80000002L
428 428
429 429 def systemrcpath():
430 430 '''return default os-specific hgrc search path'''
431 431 rcpath = []
432 432 filename = util.executablepath()
433 433 # Use mercurial.ini found in directory with hg.exe
434 434 progrc = os.path.join(os.path.dirname(filename), 'mercurial.ini')
435 435 if os.path.isfile(progrc):
436 436 rcpath.append(progrc)
437 437 return rcpath
438 438 # Use hgrc.d found in directory with hg.exe
439 439 progrcd = os.path.join(os.path.dirname(filename), 'hgrc.d')
440 440 if os.path.isdir(progrcd):
441 441 for f, kind in osutil.listdir(progrcd):
442 442 if f.endswith('.rc'):
443 443 rcpath.append(os.path.join(progrcd, f))
444 444 return rcpath
445 445 # else look for a system rcpath in the registry
446 446 value = util.lookupreg('SOFTWARE\\Mercurial', None,
447 447 _HKEY_LOCAL_MACHINE)
448 448 if not isinstance(value, str) or not value:
449 449 return rcpath
450 450 value = value.replace('/', os.sep)
451 451 for p in value.split(os.pathsep):
452 452 if p.lower().endswith('mercurial.ini'):
453 453 rcpath.append(p)
454 454 elif os.path.isdir(p):
455 455 for f, kind in osutil.listdir(p):
456 456 if f.endswith('.rc'):
457 457 rcpath.append(os.path.join(p, f))
458 458 return rcpath
459 459
460 460 def userrcpath():
461 461 '''return os-specific hgrc search path to the user dir'''
462 462 home = os.path.expanduser('~')
463 463 path = [os.path.join(home, 'mercurial.ini'),
464 464 os.path.join(home, '.hgrc')]
465 465 userprofile = os.environ.get('USERPROFILE')
466 466 if userprofile:
467 467 path.append(os.path.join(userprofile, 'mercurial.ini'))
468 468 path.append(os.path.join(userprofile, '.hgrc'))
469 469 return path
470 470
471 471 def revsingle(repo, revspec, default='.'):
472 472 if not revspec:
473 473 return repo[default]
474 474
475 475 l = revrange(repo, [revspec])
476 476 if len(l) < 1:
477 477 raise util.Abort(_('empty revision set'))
478 478 return repo[l[-1]]
479 479
480 480 def revpair(repo, revs):
481 481 if not revs:
482 482 return repo.dirstate.p1(), None
483 483
484 484 l = revrange(repo, revs)
485 485
486 486 if len(l) == 0:
487 487 return repo.dirstate.p1(), None
488 488
489 489 if len(l) == 1:
490 490 return repo.lookup(l[0]), None
491 491
492 492 return repo.lookup(l[0]), repo.lookup(l[-1])
493 493
494 494 _revrangesep = ':'
495 495
496 496 def revrange(repo, revs):
497 497 """Yield revision as strings from a list of revision specifications."""
498 498
499 499 def revfix(repo, val, defval):
500 500 if not val and val != 0 and defval is not None:
501 501 return defval
502 502 return repo.changelog.rev(repo.lookup(val))
503 503
504 504 seen, l = set(), []
505 505 for spec in revs:
506 506 # attempt to parse old-style ranges first to deal with
507 507 # things like old-tag which contain query metacharacters
508 508 try:
509 509 if isinstance(spec, int):
510 510 seen.add(spec)
511 511 l.append(spec)
512 512 continue
513 513
514 514 if _revrangesep in spec:
515 515 start, end = spec.split(_revrangesep, 1)
516 516 start = revfix(repo, start, 0)
517 517 end = revfix(repo, end, len(repo) - 1)
518 518 step = start > end and -1 or 1
519 519 for rev in xrange(start, end + step, step):
520 520 if rev in seen:
521 521 continue
522 522 seen.add(rev)
523 523 l.append(rev)
524 524 continue
525 525 elif spec and spec in repo: # single unquoted rev
526 526 rev = revfix(repo, spec, None)
527 527 if rev in seen:
528 528 continue
529 529 seen.add(rev)
530 530 l.append(rev)
531 531 continue
532 532 except error.RepoLookupError:
533 533 pass
534 534
535 535 # fall through to new-style queries if old-style fails
536 536 m = revset.match(repo.ui, spec)
537 537 for r in m(repo, range(len(repo))):
538 538 if r not in seen:
539 539 l.append(r)
540 540 seen.update(l)
541 541
542 542 return l
543 543
544 544 def expandpats(pats):
545 545 if not util.expandglobs:
546 546 return list(pats)
547 547 ret = []
548 548 for p in pats:
549 549 kind, name = matchmod._patsplit(p, None)
550 550 if kind is None:
551 551 try:
552 552 globbed = glob.glob(name)
553 553 except re.error:
554 554 globbed = [name]
555 555 if globbed:
556 556 ret.extend(globbed)
557 557 continue
558 558 ret.append(p)
559 559 return ret
560 560
561 561 def match(repo, pats=[], opts={}, globbed=False, default='relpath'):
562 562 if pats == ("",):
563 563 pats = []
564 564 if not globbed and default == 'relpath':
565 565 pats = expandpats(pats or [])
566 566 m = matchmod.match(repo.root, repo.getcwd(), pats,
567 567 opts.get('include'), opts.get('exclude'), default,
568 568 auditor=repo.auditor)
569 569 def badfn(f, msg):
570 570 repo.ui.warn("%s: %s\n" % (m.rel(f), msg))
571 571 m.bad = badfn
572 572 return m
573 573
574 574 def matchall(repo):
575 575 return matchmod.always(repo.root, repo.getcwd())
576 576
577 577 def matchfiles(repo, files):
578 578 return matchmod.exact(repo.root, repo.getcwd(), files)
579 579
580 580 def addremove(repo, pats=[], opts={}, dry_run=None, similarity=None):
581 581 if dry_run is None:
582 582 dry_run = opts.get('dry_run')
583 583 if similarity is None:
584 584 similarity = float(opts.get('similarity') or 0)
585 585 # we'd use status here, except handling of symlinks and ignore is tricky
586 586 added, unknown, deleted, removed = [], [], [], []
587 587 audit_path = pathauditor(repo.root)
588 588 m = match(repo, pats, opts)
589 589 for abs in repo.walk(m):
590 590 target = repo.wjoin(abs)
591 591 good = True
592 592 try:
593 593 audit_path(abs)
594 594 except (OSError, util.Abort):
595 595 good = False
596 596 rel = m.rel(abs)
597 597 exact = m.exact(abs)
598 598 if good and abs not in repo.dirstate:
599 599 unknown.append(abs)
600 600 if repo.ui.verbose or not exact:
601 601 repo.ui.status(_('adding %s\n') % ((pats and rel) or abs))
602 602 elif repo.dirstate[abs] != 'r' and (not good or not os.path.lexists(target)
603 603 or (os.path.isdir(target) and not os.path.islink(target))):
604 604 deleted.append(abs)
605 605 if repo.ui.verbose or not exact:
606 606 repo.ui.status(_('removing %s\n') % ((pats and rel) or abs))
607 607 # for finding renames
608 608 elif repo.dirstate[abs] == 'r':
609 609 removed.append(abs)
610 610 elif repo.dirstate[abs] == 'a':
611 611 added.append(abs)
612 612 copies = {}
613 613 if similarity > 0:
614 614 for old, new, score in similar.findrenames(repo,
615 615 added + unknown, removed + deleted, similarity):
616 616 if repo.ui.verbose or not m.exact(old) or not m.exact(new):
617 617 repo.ui.status(_('recording removal of %s as rename to %s '
618 618 '(%d%% similar)\n') %
619 619 (m.rel(old), m.rel(new), score * 100))
620 620 copies[new] = old
621 621
622 622 if not dry_run:
623 623 wctx = repo[None]
624 624 wlock = repo.wlock()
625 625 try:
626 wctx.remove(deleted)
626 wctx.forget(deleted)
627 627 wctx.add(unknown)
628 628 for new, old in copies.iteritems():
629 629 wctx.copy(old, new)
630 630 finally:
631 631 wlock.release()
632 632
633 633 def updatedir(ui, repo, patches, similarity=0):
634 634 '''Update dirstate after patch application according to metadata'''
635 635 if not patches:
636 636 return []
637 637 copies = []
638 638 removes = set()
639 639 cfiles = patches.keys()
640 640 cwd = repo.getcwd()
641 641 if cwd:
642 642 cfiles = [util.pathto(repo.root, cwd, f) for f in patches.keys()]
643 643 for f in patches:
644 644 gp = patches[f]
645 645 if not gp:
646 646 continue
647 647 if gp.op == 'RENAME':
648 648 copies.append((gp.oldpath, gp.path))
649 649 removes.add(gp.oldpath)
650 650 elif gp.op == 'COPY':
651 651 copies.append((gp.oldpath, gp.path))
652 652 elif gp.op == 'DELETE':
653 653 removes.add(gp.path)
654 654
655 655 wctx = repo[None]
656 656 for src, dst in copies:
657 657 dirstatecopy(ui, repo, wctx, src, dst, cwd=cwd)
658 658 if (not similarity) and removes:
659 659 wctx.remove(sorted(removes), True)
660 660
661 661 for f in patches:
662 662 gp = patches[f]
663 663 if gp and gp.mode:
664 664 islink, isexec = gp.mode
665 665 dst = repo.wjoin(gp.path)
666 666 # patch won't create empty files
667 667 if gp.op == 'ADD' and not os.path.lexists(dst):
668 668 flags = (isexec and 'x' or '') + (islink and 'l' or '')
669 669 repo.wwrite(gp.path, '', flags)
670 670 util.setflags(dst, islink, isexec)
671 671 addremove(repo, cfiles, similarity=similarity)
672 672 files = patches.keys()
673 673 files.extend([r for r in removes if r not in files])
674 674 return sorted(files)
675 675
676 676 def dirstatecopy(ui, repo, wctx, src, dst, dryrun=False, cwd=None):
677 677 """Update the dirstate to reflect the intent of copying src to dst. For
678 678 different reasons it might not end with dst being marked as copied from src.
679 679 """
680 680 origsrc = repo.dirstate.copied(src) or src
681 681 if dst == origsrc: # copying back a copy?
682 682 if repo.dirstate[dst] not in 'mn' and not dryrun:
683 683 repo.dirstate.normallookup(dst)
684 684 else:
685 685 if repo.dirstate[origsrc] == 'a' and origsrc == src:
686 686 if not ui.quiet:
687 687 ui.warn(_("%s has not been committed yet, so no copy "
688 688 "data will be stored for %s.\n")
689 689 % (repo.pathto(origsrc, cwd), repo.pathto(dst, cwd)))
690 690 if repo.dirstate[dst] in '?r' and not dryrun:
691 691 wctx.add([dst])
692 692 elif not dryrun:
693 693 wctx.copy(origsrc, dst)
General Comments 0
You need to be logged in to leave comments. Login now