##// END OF EJS Templates
commands: refactor diff --stat and qdiff --stat...
Yuya Nishihara -
r11050:5d35f7d9 default
parent child Browse files
Show More
@@ -1,2821 +1,2805 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
42 42 from mercurial.i18n import _
43 43 from mercurial.node import bin, hex, short, nullid, nullrev
44 44 from mercurial.lock import release
45 45 from mercurial import commands, cmdutil, hg, patch, util
46 46 from mercurial import repair, extensions, url, error
47 47 import os, sys, re, errno
48 48
49 49 commands.norepo += " qclone"
50 50
51 51 # Patch names looks like unix-file names.
52 52 # They must be joinable with queue directory and result in the patch path.
53 53 normname = util.normpath
54 54
55 55 class statusentry(object):
56 56 def __init__(self, node, name):
57 57 self.node, self.name = node, name
58 58
59 59 def __str__(self):
60 60 return hex(self.node) + ':' + self.name
61 61
62 62 class patchheader(object):
63 63 def __init__(self, pf, plainmode=False):
64 64 def eatdiff(lines):
65 65 while lines:
66 66 l = lines[-1]
67 67 if (l.startswith("diff -") or
68 68 l.startswith("Index:") or
69 69 l.startswith("===========")):
70 70 del lines[-1]
71 71 else:
72 72 break
73 73 def eatempty(lines):
74 74 while lines:
75 75 if not lines[-1].strip():
76 76 del lines[-1]
77 77 else:
78 78 break
79 79
80 80 message = []
81 81 comments = []
82 82 user = None
83 83 date = None
84 84 parent = None
85 85 format = None
86 86 subject = None
87 87 diffstart = 0
88 88
89 89 for line in file(pf):
90 90 line = line.rstrip()
91 91 if (line.startswith('diff --git')
92 92 or (diffstart and line.startswith('+++ '))):
93 93 diffstart = 2
94 94 break
95 95 diffstart = 0 # reset
96 96 if line.startswith("--- "):
97 97 diffstart = 1
98 98 continue
99 99 elif format == "hgpatch":
100 100 # parse values when importing the result of an hg export
101 101 if line.startswith("# User "):
102 102 user = line[7:]
103 103 elif line.startswith("# Date "):
104 104 date = line[7:]
105 105 elif line.startswith("# Parent "):
106 106 parent = line[9:]
107 107 elif not line.startswith("# ") and line:
108 108 message.append(line)
109 109 format = None
110 110 elif line == '# HG changeset patch':
111 111 message = []
112 112 format = "hgpatch"
113 113 elif (format != "tagdone" and (line.startswith("Subject: ") or
114 114 line.startswith("subject: "))):
115 115 subject = line[9:]
116 116 format = "tag"
117 117 elif (format != "tagdone" and (line.startswith("From: ") or
118 118 line.startswith("from: "))):
119 119 user = line[6:]
120 120 format = "tag"
121 121 elif (format != "tagdone" and (line.startswith("Date: ") or
122 122 line.startswith("date: "))):
123 123 date = line[6:]
124 124 format = "tag"
125 125 elif format == "tag" and line == "":
126 126 # when looking for tags (subject: from: etc) they
127 127 # end once you find a blank line in the source
128 128 format = "tagdone"
129 129 elif message or line:
130 130 message.append(line)
131 131 comments.append(line)
132 132
133 133 eatdiff(message)
134 134 eatdiff(comments)
135 135 eatempty(message)
136 136 eatempty(comments)
137 137
138 138 # make sure message isn't empty
139 139 if format and format.startswith("tag") and subject:
140 140 message.insert(0, "")
141 141 message.insert(0, subject)
142 142
143 143 self.message = message
144 144 self.comments = comments
145 145 self.user = user
146 146 self.date = date
147 147 self.parent = parent
148 148 self.haspatch = diffstart > 1
149 149 self.plainmode = plainmode
150 150
151 151 def setuser(self, user):
152 152 if not self.updateheader(['From: ', '# User '], user):
153 153 try:
154 154 patchheaderat = self.comments.index('# HG changeset patch')
155 155 self.comments.insert(patchheaderat + 1, '# User ' + user)
156 156 except ValueError:
157 157 if self.plainmode or self._hasheader(['Date: ']):
158 158 self.comments = ['From: ' + user] + self.comments
159 159 else:
160 160 tmp = ['# HG changeset patch', '# User ' + user, '']
161 161 self.comments = tmp + self.comments
162 162 self.user = user
163 163
164 164 def setdate(self, date):
165 165 if not self.updateheader(['Date: ', '# Date '], date):
166 166 try:
167 167 patchheaderat = self.comments.index('# HG changeset patch')
168 168 self.comments.insert(patchheaderat + 1, '# Date ' + date)
169 169 except ValueError:
170 170 if self.plainmode or self._hasheader(['From: ']):
171 171 self.comments = ['Date: ' + date] + self.comments
172 172 else:
173 173 tmp = ['# HG changeset patch', '# Date ' + date, '']
174 174 self.comments = tmp + self.comments
175 175 self.date = date
176 176
177 177 def setparent(self, parent):
178 178 if not self.updateheader(['# Parent '], parent):
179 179 try:
180 180 patchheaderat = self.comments.index('# HG changeset patch')
181 181 self.comments.insert(patchheaderat + 1, '# Parent ' + parent)
182 182 except ValueError:
183 183 pass
184 184 self.parent = parent
185 185
186 186 def setmessage(self, message):
187 187 if self.comments:
188 188 self._delmsg()
189 189 self.message = [message]
190 190 self.comments += self.message
191 191
192 192 def updateheader(self, prefixes, new):
193 193 '''Update all references to a field in the patch header.
194 194 Return whether the field is present.'''
195 195 res = False
196 196 for prefix in prefixes:
197 197 for i in xrange(len(self.comments)):
198 198 if self.comments[i].startswith(prefix):
199 199 self.comments[i] = prefix + new
200 200 res = True
201 201 break
202 202 return res
203 203
204 204 def _hasheader(self, prefixes):
205 205 '''Check if a header starts with any of the given prefixes.'''
206 206 for prefix in prefixes:
207 207 for comment in self.comments:
208 208 if comment.startswith(prefix):
209 209 return True
210 210 return False
211 211
212 212 def __str__(self):
213 213 if not self.comments:
214 214 return ''
215 215 return '\n'.join(self.comments) + '\n\n'
216 216
217 217 def _delmsg(self):
218 218 '''Remove existing message, keeping the rest of the comments fields.
219 219 If comments contains 'subject: ', message will prepend
220 220 the field and a blank line.'''
221 221 if self.message:
222 222 subj = 'subject: ' + self.message[0].lower()
223 223 for i in xrange(len(self.comments)):
224 224 if subj == self.comments[i].lower():
225 225 del self.comments[i]
226 226 self.message = self.message[2:]
227 227 break
228 228 ci = 0
229 229 for mi in self.message:
230 230 while mi != self.comments[ci]:
231 231 ci += 1
232 232 del self.comments[ci]
233 233
234 234 class queue(object):
235 235 def __init__(self, ui, path, patchdir=None):
236 236 self.basepath = path
237 237 self.path = patchdir or os.path.join(path, "patches")
238 238 self.opener = util.opener(self.path)
239 239 self.ui = ui
240 240 self.applied_dirty = 0
241 241 self.series_dirty = 0
242 242 self.series_path = "series"
243 243 self.status_path = "status"
244 244 self.guards_path = "guards"
245 245 self.active_guards = None
246 246 self.guards_dirty = False
247 247 # Handle mq.git as a bool with extended values
248 248 try:
249 249 gitmode = ui.configbool('mq', 'git', None)
250 250 if gitmode is None:
251 251 raise error.ConfigError()
252 252 self.gitmode = gitmode and 'yes' or 'no'
253 253 except error.ConfigError:
254 254 self.gitmode = ui.config('mq', 'git', 'auto').lower()
255 255 self.plainmode = ui.configbool('mq', 'plain', False)
256 256
257 257 @util.propertycache
258 258 def applied(self):
259 259 if os.path.exists(self.join(self.status_path)):
260 260 def parse(l):
261 261 n, name = l.split(':', 1)
262 262 return statusentry(bin(n), name)
263 263 lines = self.opener(self.status_path).read().splitlines()
264 264 return [parse(l) for l in lines]
265 265 return []
266 266
267 267 @util.propertycache
268 268 def full_series(self):
269 269 if os.path.exists(self.join(self.series_path)):
270 270 return self.opener(self.series_path).read().splitlines()
271 271 return []
272 272
273 273 @util.propertycache
274 274 def series(self):
275 275 self.parse_series()
276 276 return self.series
277 277
278 278 @util.propertycache
279 279 def series_guards(self):
280 280 self.parse_series()
281 281 return self.series_guards
282 282
283 283 def invalidate(self):
284 284 for a in 'applied full_series series series_guards'.split():
285 285 if a in self.__dict__:
286 286 delattr(self, a)
287 287 self.applied_dirty = 0
288 288 self.series_dirty = 0
289 289 self.guards_dirty = False
290 290 self.active_guards = None
291 291
292 292 def diffopts(self, opts={}, patchfn=None):
293 293 diffopts = patch.diffopts(self.ui, opts)
294 294 if self.gitmode == 'auto':
295 295 diffopts.upgrade = True
296 296 elif self.gitmode == 'keep':
297 297 pass
298 298 elif self.gitmode in ('yes', 'no'):
299 299 diffopts.git = self.gitmode == 'yes'
300 300 else:
301 301 raise util.Abort(_('mq.git option can be auto/keep/yes/no'
302 302 ' got %s') % self.gitmode)
303 303 if patchfn:
304 304 diffopts = self.patchopts(diffopts, patchfn)
305 305 return diffopts
306 306
307 307 def patchopts(self, diffopts, *patches):
308 308 """Return a copy of input diff options with git set to true if
309 309 referenced patch is a git patch and should be preserved as such.
310 310 """
311 311 diffopts = diffopts.copy()
312 312 if not diffopts.git and self.gitmode == 'keep':
313 313 for patchfn in patches:
314 314 patchf = self.opener(patchfn, 'r')
315 315 # if the patch was a git patch, refresh it as a git patch
316 316 for line in patchf:
317 317 if line.startswith('diff --git'):
318 318 diffopts.git = True
319 319 break
320 320 patchf.close()
321 321 return diffopts
322 322
323 323 def join(self, *p):
324 324 return os.path.join(self.path, *p)
325 325
326 326 def find_series(self, patch):
327 327 def matchpatch(l):
328 328 l = l.split('#', 1)[0]
329 329 return l.strip() == patch
330 330 for index, l in enumerate(self.full_series):
331 331 if matchpatch(l):
332 332 return index
333 333 return None
334 334
335 335 guard_re = re.compile(r'\s?#([-+][^-+# \t\r\n\f][^# \t\r\n\f]*)')
336 336
337 337 def parse_series(self):
338 338 self.series = []
339 339 self.series_guards = []
340 340 for l in self.full_series:
341 341 h = l.find('#')
342 342 if h == -1:
343 343 patch = l
344 344 comment = ''
345 345 elif h == 0:
346 346 continue
347 347 else:
348 348 patch = l[:h]
349 349 comment = l[h:]
350 350 patch = patch.strip()
351 351 if patch:
352 352 if patch in self.series:
353 353 raise util.Abort(_('%s appears more than once in %s') %
354 354 (patch, self.join(self.series_path)))
355 355 self.series.append(patch)
356 356 self.series_guards.append(self.guard_re.findall(comment))
357 357
358 358 def check_guard(self, guard):
359 359 if not guard:
360 360 return _('guard cannot be an empty string')
361 361 bad_chars = '# \t\r\n\f'
362 362 first = guard[0]
363 363 if first in '-+':
364 364 return (_('guard %r starts with invalid character: %r') %
365 365 (guard, first))
366 366 for c in bad_chars:
367 367 if c in guard:
368 368 return _('invalid character in guard %r: %r') % (guard, c)
369 369
370 370 def set_active(self, guards):
371 371 for guard in guards:
372 372 bad = self.check_guard(guard)
373 373 if bad:
374 374 raise util.Abort(bad)
375 375 guards = sorted(set(guards))
376 376 self.ui.debug('active guards: %s\n' % ' '.join(guards))
377 377 self.active_guards = guards
378 378 self.guards_dirty = True
379 379
380 380 def active(self):
381 381 if self.active_guards is None:
382 382 self.active_guards = []
383 383 try:
384 384 guards = self.opener(self.guards_path).read().split()
385 385 except IOError, err:
386 386 if err.errno != errno.ENOENT:
387 387 raise
388 388 guards = []
389 389 for i, guard in enumerate(guards):
390 390 bad = self.check_guard(guard)
391 391 if bad:
392 392 self.ui.warn('%s:%d: %s\n' %
393 393 (self.join(self.guards_path), i + 1, bad))
394 394 else:
395 395 self.active_guards.append(guard)
396 396 return self.active_guards
397 397
398 398 def set_guards(self, idx, guards):
399 399 for g in guards:
400 400 if len(g) < 2:
401 401 raise util.Abort(_('guard %r too short') % g)
402 402 if g[0] not in '-+':
403 403 raise util.Abort(_('guard %r starts with invalid char') % g)
404 404 bad = self.check_guard(g[1:])
405 405 if bad:
406 406 raise util.Abort(bad)
407 407 drop = self.guard_re.sub('', self.full_series[idx])
408 408 self.full_series[idx] = drop + ''.join([' #' + g for g in guards])
409 409 self.parse_series()
410 410 self.series_dirty = True
411 411
412 412 def pushable(self, idx):
413 413 if isinstance(idx, str):
414 414 idx = self.series.index(idx)
415 415 patchguards = self.series_guards[idx]
416 416 if not patchguards:
417 417 return True, None
418 418 guards = self.active()
419 419 exactneg = [g for g in patchguards if g[0] == '-' and g[1:] in guards]
420 420 if exactneg:
421 421 return False, exactneg[0]
422 422 pos = [g for g in patchguards if g[0] == '+']
423 423 exactpos = [g for g in pos if g[1:] in guards]
424 424 if pos:
425 425 if exactpos:
426 426 return True, exactpos[0]
427 427 return False, pos
428 428 return True, ''
429 429
430 430 def explain_pushable(self, idx, all_patches=False):
431 431 write = all_patches and self.ui.write or self.ui.warn
432 432 if all_patches or self.ui.verbose:
433 433 if isinstance(idx, str):
434 434 idx = self.series.index(idx)
435 435 pushable, why = self.pushable(idx)
436 436 if all_patches and pushable:
437 437 if why is None:
438 438 write(_('allowing %s - no guards in effect\n') %
439 439 self.series[idx])
440 440 else:
441 441 if not why:
442 442 write(_('allowing %s - no matching negative guards\n') %
443 443 self.series[idx])
444 444 else:
445 445 write(_('allowing %s - guarded by %r\n') %
446 446 (self.series[idx], why))
447 447 if not pushable:
448 448 if why:
449 449 write(_('skipping %s - guarded by %r\n') %
450 450 (self.series[idx], why))
451 451 else:
452 452 write(_('skipping %s - no matching guards\n') %
453 453 self.series[idx])
454 454
455 455 def save_dirty(self):
456 456 def write_list(items, path):
457 457 fp = self.opener(path, 'w')
458 458 for i in items:
459 459 fp.write("%s\n" % i)
460 460 fp.close()
461 461 if self.applied_dirty:
462 462 write_list(map(str, self.applied), self.status_path)
463 463 if self.series_dirty:
464 464 write_list(self.full_series, self.series_path)
465 465 if self.guards_dirty:
466 466 write_list(self.active_guards, self.guards_path)
467 467
468 468 def removeundo(self, repo):
469 469 undo = repo.sjoin('undo')
470 470 if not os.path.exists(undo):
471 471 return
472 472 try:
473 473 os.unlink(undo)
474 474 except OSError, inst:
475 475 self.ui.warn(_('error removing undo: %s\n') % str(inst))
476 476
477 477 def printdiff(self, repo, diffopts, node1, node2=None, files=None,
478 478 fp=None, changes=None, opts={}):
479 479 stat = opts.get('stat')
480
481 480 m = cmdutil.match(repo, files, opts)
482 if fp is None:
483 write = repo.ui.write
484 else:
485 def write(s, **kw):
486 fp.write(s)
487 if stat:
488 diffopts.context = 0
489 width = self.ui.interactive() and util.termwidth() or 80
490 chunks = patch.diff(repo, node1, node2, m, changes, diffopts)
491 for chunk, label in patch.diffstatui(util.iterlines(chunks),
492 width=width,
493 git=diffopts.git):
494 write(chunk, label=label)
495 else:
496 for chunk, label in patch.diffui(repo, node1, node2, m, changes,
497 diffopts):
498 write(chunk, label=label)
481 cmdutil.diffordiffstat(self.ui, repo, diffopts, node1, node2, m,
482 changes, stat, fp)
499 483
500 484 def mergeone(self, repo, mergeq, head, patch, rev, diffopts):
501 485 # first try just applying the patch
502 486 (err, n) = self.apply(repo, [patch], update_status=False,
503 487 strict=True, merge=rev)
504 488
505 489 if err == 0:
506 490 return (err, n)
507 491
508 492 if n is None:
509 493 raise util.Abort(_("apply failed for patch %s") % patch)
510 494
511 495 self.ui.warn(_("patch didn't work out, merging %s\n") % patch)
512 496
513 497 # apply failed, strip away that rev and merge.
514 498 hg.clean(repo, head)
515 499 self.strip(repo, n, update=False, backup='strip')
516 500
517 501 ctx = repo[rev]
518 502 ret = hg.merge(repo, rev)
519 503 if ret:
520 504 raise util.Abort(_("update returned %d") % ret)
521 505 n = repo.commit(ctx.description(), ctx.user(), force=True)
522 506 if n is None:
523 507 raise util.Abort(_("repo commit failed"))
524 508 try:
525 509 ph = patchheader(mergeq.join(patch), self.plainmode)
526 510 except:
527 511 raise util.Abort(_("unable to read %s") % patch)
528 512
529 513 diffopts = self.patchopts(diffopts, patch)
530 514 patchf = self.opener(patch, "w")
531 515 comments = str(ph)
532 516 if comments:
533 517 patchf.write(comments)
534 518 self.printdiff(repo, diffopts, head, n, fp=patchf)
535 519 patchf.close()
536 520 self.removeundo(repo)
537 521 return (0, n)
538 522
539 523 def qparents(self, repo, rev=None):
540 524 if rev is None:
541 525 (p1, p2) = repo.dirstate.parents()
542 526 if p2 == nullid:
543 527 return p1
544 528 if not self.applied:
545 529 return None
546 530 return self.applied[-1].node
547 531 p1, p2 = repo.changelog.parents(rev)
548 532 if p2 != nullid and p2 in [x.node for x in self.applied]:
549 533 return p2
550 534 return p1
551 535
552 536 def mergepatch(self, repo, mergeq, series, diffopts):
553 537 if not self.applied:
554 538 # each of the patches merged in will have two parents. This
555 539 # can confuse the qrefresh, qdiff, and strip code because it
556 540 # needs to know which parent is actually in the patch queue.
557 541 # so, we insert a merge marker with only one parent. This way
558 542 # the first patch in the queue is never a merge patch
559 543 #
560 544 pname = ".hg.patches.merge.marker"
561 545 n = repo.commit('[mq]: merge marker', force=True)
562 546 self.removeundo(repo)
563 547 self.applied.append(statusentry(n, pname))
564 548 self.applied_dirty = 1
565 549
566 550 head = self.qparents(repo)
567 551
568 552 for patch in series:
569 553 patch = mergeq.lookup(patch, strict=True)
570 554 if not patch:
571 555 self.ui.warn(_("patch %s does not exist\n") % patch)
572 556 return (1, None)
573 557 pushable, reason = self.pushable(patch)
574 558 if not pushable:
575 559 self.explain_pushable(patch, all_patches=True)
576 560 continue
577 561 info = mergeq.isapplied(patch)
578 562 if not info:
579 563 self.ui.warn(_("patch %s is not applied\n") % patch)
580 564 return (1, None)
581 565 rev = info[1]
582 566 err, head = self.mergeone(repo, mergeq, head, patch, rev, diffopts)
583 567 if head:
584 568 self.applied.append(statusentry(head, patch))
585 569 self.applied_dirty = 1
586 570 if err:
587 571 return (err, head)
588 572 self.save_dirty()
589 573 return (0, head)
590 574
591 575 def patch(self, repo, patchfile):
592 576 '''Apply patchfile to the working directory.
593 577 patchfile: name of patch file'''
594 578 files = {}
595 579 try:
596 580 fuzz = patch.patch(patchfile, self.ui, strip=1, cwd=repo.root,
597 581 files=files, eolmode=None)
598 582 except Exception, inst:
599 583 self.ui.note(str(inst) + '\n')
600 584 if not self.ui.verbose:
601 585 self.ui.warn(_("patch failed, unable to continue (try -v)\n"))
602 586 return (False, files, False)
603 587
604 588 return (True, files, fuzz)
605 589
606 590 def apply(self, repo, series, list=False, update_status=True,
607 591 strict=False, patchdir=None, merge=None, all_files=None):
608 592 wlock = lock = tr = None
609 593 try:
610 594 wlock = repo.wlock()
611 595 lock = repo.lock()
612 596 tr = repo.transaction("qpush")
613 597 try:
614 598 ret = self._apply(repo, series, list, update_status,
615 599 strict, patchdir, merge, all_files=all_files)
616 600 tr.close()
617 601 self.save_dirty()
618 602 return ret
619 603 except:
620 604 try:
621 605 tr.abort()
622 606 finally:
623 607 repo.invalidate()
624 608 repo.dirstate.invalidate()
625 609 raise
626 610 finally:
627 611 del tr
628 612 release(lock, wlock)
629 613 self.removeundo(repo)
630 614
631 615 def _apply(self, repo, series, list=False, update_status=True,
632 616 strict=False, patchdir=None, merge=None, all_files=None):
633 617 '''returns (error, hash)
634 618 error = 1 for unable to read, 2 for patch failed, 3 for patch fuzz'''
635 619 # TODO unify with commands.py
636 620 if not patchdir:
637 621 patchdir = self.path
638 622 err = 0
639 623 n = None
640 624 for patchname in series:
641 625 pushable, reason = self.pushable(patchname)
642 626 if not pushable:
643 627 self.explain_pushable(patchname, all_patches=True)
644 628 continue
645 629 self.ui.status(_("applying %s\n") % patchname)
646 630 pf = os.path.join(patchdir, patchname)
647 631
648 632 try:
649 633 ph = patchheader(self.join(patchname), self.plainmode)
650 634 except:
651 635 self.ui.warn(_("unable to read %s\n") % patchname)
652 636 err = 1
653 637 break
654 638
655 639 message = ph.message
656 640 if not message:
657 641 message = "imported patch %s\n" % patchname
658 642 else:
659 643 if list:
660 644 message.append("\nimported patch %s" % patchname)
661 645 message = '\n'.join(message)
662 646
663 647 if ph.haspatch:
664 648 (patcherr, files, fuzz) = self.patch(repo, pf)
665 649 if all_files is not None:
666 650 all_files.update(files)
667 651 patcherr = not patcherr
668 652 else:
669 653 self.ui.warn(_("patch %s is empty\n") % patchname)
670 654 patcherr, files, fuzz = 0, [], 0
671 655
672 656 if merge and files:
673 657 # Mark as removed/merged and update dirstate parent info
674 658 removed = []
675 659 merged = []
676 660 for f in files:
677 661 if os.path.exists(repo.wjoin(f)):
678 662 merged.append(f)
679 663 else:
680 664 removed.append(f)
681 665 for f in removed:
682 666 repo.dirstate.remove(f)
683 667 for f in merged:
684 668 repo.dirstate.merge(f)
685 669 p1, p2 = repo.dirstate.parents()
686 670 repo.dirstate.setparents(p1, merge)
687 671
688 672 files = patch.updatedir(self.ui, repo, files)
689 673 match = cmdutil.matchfiles(repo, files or [])
690 674 n = repo.commit(message, ph.user, ph.date, match=match, force=True)
691 675
692 676 if n is None:
693 677 raise util.Abort(_("repo commit failed"))
694 678
695 679 if update_status:
696 680 self.applied.append(statusentry(n, patchname))
697 681
698 682 if patcherr:
699 683 self.ui.warn(_("patch failed, rejects left in working dir\n"))
700 684 err = 2
701 685 break
702 686
703 687 if fuzz and strict:
704 688 self.ui.warn(_("fuzz found when applying patch, stopping\n"))
705 689 err = 3
706 690 break
707 691 return (err, n)
708 692
709 693 def _cleanup(self, patches, numrevs, keep=False):
710 694 if not keep:
711 695 r = self.qrepo()
712 696 if r:
713 697 r.remove(patches, True)
714 698 else:
715 699 for p in patches:
716 700 os.unlink(self.join(p))
717 701
718 702 if numrevs:
719 703 del self.applied[:numrevs]
720 704 self.applied_dirty = 1
721 705
722 706 for i in sorted([self.find_series(p) for p in patches], reverse=True):
723 707 del self.full_series[i]
724 708 self.parse_series()
725 709 self.series_dirty = 1
726 710
727 711 def _revpatches(self, repo, revs):
728 712 firstrev = repo[self.applied[0].node].rev()
729 713 patches = []
730 714 for i, rev in enumerate(revs):
731 715
732 716 if rev < firstrev:
733 717 raise util.Abort(_('revision %d is not managed') % rev)
734 718
735 719 ctx = repo[rev]
736 720 base = self.applied[i].node
737 721 if ctx.node() != base:
738 722 msg = _('cannot delete revision %d above applied patches')
739 723 raise util.Abort(msg % rev)
740 724
741 725 patch = self.applied[i].name
742 726 for fmt in ('[mq]: %s', 'imported patch %s'):
743 727 if ctx.description() == fmt % patch:
744 728 msg = _('patch %s finalized without changeset message\n')
745 729 repo.ui.status(msg % patch)
746 730 break
747 731
748 732 patches.append(patch)
749 733 return patches
750 734
751 735 def finish(self, repo, revs):
752 736 patches = self._revpatches(repo, sorted(revs))
753 737 self._cleanup(patches, len(patches))
754 738
755 739 def delete(self, repo, patches, opts):
756 740 if not patches and not opts.get('rev'):
757 741 raise util.Abort(_('qdelete requires at least one revision or '
758 742 'patch name'))
759 743
760 744 realpatches = []
761 745 for patch in patches:
762 746 patch = self.lookup(patch, strict=True)
763 747 info = self.isapplied(patch)
764 748 if info:
765 749 raise util.Abort(_("cannot delete applied patch %s") % patch)
766 750 if patch not in self.series:
767 751 raise util.Abort(_("patch %s not in series file") % patch)
768 752 realpatches.append(patch)
769 753
770 754 numrevs = 0
771 755 if opts.get('rev'):
772 756 if not self.applied:
773 757 raise util.Abort(_('no patches applied'))
774 758 revs = cmdutil.revrange(repo, opts['rev'])
775 759 if len(revs) > 1 and revs[0] > revs[1]:
776 760 revs.reverse()
777 761 revpatches = self._revpatches(repo, revs)
778 762 realpatches += revpatches
779 763 numrevs = len(revpatches)
780 764
781 765 self._cleanup(realpatches, numrevs, opts.get('keep'))
782 766
783 767 def check_toppatch(self, repo):
784 768 if self.applied:
785 769 top = self.applied[-1].node
786 770 patch = self.applied[-1].name
787 771 pp = repo.dirstate.parents()
788 772 if top not in pp:
789 773 raise util.Abort(_("working directory revision is not qtip"))
790 774 return top, patch
791 775 return None, None
792 776
793 777 def check_localchanges(self, repo, force=False, refresh=True):
794 778 m, a, r, d = repo.status()[:4]
795 779 if (m or a or r or d) and not force:
796 780 if refresh:
797 781 raise util.Abort(_("local changes found, refresh first"))
798 782 else:
799 783 raise util.Abort(_("local changes found"))
800 784 return m, a, r, d
801 785
802 786 _reserved = ('series', 'status', 'guards')
803 787 def check_reserved_name(self, name):
804 788 if (name in self._reserved or name.startswith('.hg')
805 789 or name.startswith('.mq') or '#' in name or ':' in name):
806 790 raise util.Abort(_('"%s" cannot be used as the name of a patch')
807 791 % name)
808 792
809 793 def new(self, repo, patchfn, *pats, **opts):
810 794 """options:
811 795 msg: a string or a no-argument function returning a string
812 796 """
813 797 msg = opts.get('msg')
814 798 user = opts.get('user')
815 799 date = opts.get('date')
816 800 if date:
817 801 date = util.parsedate(date)
818 802 diffopts = self.diffopts({'git': opts.get('git')})
819 803 self.check_reserved_name(patchfn)
820 804 if os.path.exists(self.join(patchfn)):
821 805 raise util.Abort(_('patch "%s" already exists') % patchfn)
822 806 if opts.get('include') or opts.get('exclude') or pats:
823 807 match = cmdutil.match(repo, pats, opts)
824 808 # detect missing files in pats
825 809 def badfn(f, msg):
826 810 raise util.Abort('%s: %s' % (f, msg))
827 811 match.bad = badfn
828 812 m, a, r, d = repo.status(match=match)[:4]
829 813 else:
830 814 m, a, r, d = self.check_localchanges(repo, force=True)
831 815 match = cmdutil.matchfiles(repo, m + a + r)
832 816 if len(repo[None].parents()) > 1:
833 817 raise util.Abort(_('cannot manage merge changesets'))
834 818 commitfiles = m + a + r
835 819 self.check_toppatch(repo)
836 820 insert = self.full_series_end()
837 821 wlock = repo.wlock()
838 822 try:
839 823 # if patch file write fails, abort early
840 824 p = self.opener(patchfn, "w")
841 825 try:
842 826 if self.plainmode:
843 827 if user:
844 828 p.write("From: " + user + "\n")
845 829 if not date:
846 830 p.write("\n")
847 831 if date:
848 832 p.write("Date: %d %d\n\n" % date)
849 833 else:
850 834 p.write("# HG changeset patch\n")
851 835 p.write("# Parent "
852 836 + hex(repo[None].parents()[0].node()) + "\n")
853 837 if user:
854 838 p.write("# User " + user + "\n")
855 839 if date:
856 840 p.write("# Date %s %s\n\n" % date)
857 841 if hasattr(msg, '__call__'):
858 842 msg = msg()
859 843 commitmsg = msg and msg or ("[mq]: %s" % patchfn)
860 844 n = repo.commit(commitmsg, user, date, match=match, force=True)
861 845 if n is None:
862 846 raise util.Abort(_("repo commit failed"))
863 847 try:
864 848 self.full_series[insert:insert] = [patchfn]
865 849 self.applied.append(statusentry(n, patchfn))
866 850 self.parse_series()
867 851 self.series_dirty = 1
868 852 self.applied_dirty = 1
869 853 if msg:
870 854 msg = msg + "\n\n"
871 855 p.write(msg)
872 856 if commitfiles:
873 857 parent = self.qparents(repo, n)
874 858 chunks = patch.diff(repo, node1=parent, node2=n,
875 859 match=match, opts=diffopts)
876 860 for chunk in chunks:
877 861 p.write(chunk)
878 862 p.close()
879 863 wlock.release()
880 864 wlock = None
881 865 r = self.qrepo()
882 866 if r:
883 867 r.add([patchfn])
884 868 except:
885 869 repo.rollback()
886 870 raise
887 871 except Exception:
888 872 patchpath = self.join(patchfn)
889 873 try:
890 874 os.unlink(patchpath)
891 875 except:
892 876 self.ui.warn(_('error unlinking %s\n') % patchpath)
893 877 raise
894 878 self.removeundo(repo)
895 879 finally:
896 880 release(wlock)
897 881
898 882 def strip(self, repo, rev, update=True, backup="all", force=None):
899 883 wlock = lock = None
900 884 try:
901 885 wlock = repo.wlock()
902 886 lock = repo.lock()
903 887
904 888 if update:
905 889 self.check_localchanges(repo, force=force, refresh=False)
906 890 urev = self.qparents(repo, rev)
907 891 hg.clean(repo, urev)
908 892 repo.dirstate.write()
909 893
910 894 self.removeundo(repo)
911 895 repair.strip(self.ui, repo, rev, backup)
912 896 # strip may have unbundled a set of backed up revisions after
913 897 # the actual strip
914 898 self.removeundo(repo)
915 899 finally:
916 900 release(lock, wlock)
917 901
918 902 def isapplied(self, patch):
919 903 """returns (index, rev, patch)"""
920 904 for i, a in enumerate(self.applied):
921 905 if a.name == patch:
922 906 return (i, a.node, a.name)
923 907 return None
924 908
925 909 # if the exact patch name does not exist, we try a few
926 910 # variations. If strict is passed, we try only #1
927 911 #
928 912 # 1) a number to indicate an offset in the series file
929 913 # 2) a unique substring of the patch name was given
930 914 # 3) patchname[-+]num to indicate an offset in the series file
931 915 def lookup(self, patch, strict=False):
932 916 patch = patch and str(patch)
933 917
934 918 def partial_name(s):
935 919 if s in self.series:
936 920 return s
937 921 matches = [x for x in self.series if s in x]
938 922 if len(matches) > 1:
939 923 self.ui.warn(_('patch name "%s" is ambiguous:\n') % s)
940 924 for m in matches:
941 925 self.ui.warn(' %s\n' % m)
942 926 return None
943 927 if matches:
944 928 return matches[0]
945 929 if self.series and self.applied:
946 930 if s == 'qtip':
947 931 return self.series[self.series_end(True)-1]
948 932 if s == 'qbase':
949 933 return self.series[0]
950 934 return None
951 935
952 936 if patch is None:
953 937 return None
954 938 if patch in self.series:
955 939 return patch
956 940
957 941 if not os.path.isfile(self.join(patch)):
958 942 try:
959 943 sno = int(patch)
960 944 except (ValueError, OverflowError):
961 945 pass
962 946 else:
963 947 if -len(self.series) <= sno < len(self.series):
964 948 return self.series[sno]
965 949
966 950 if not strict:
967 951 res = partial_name(patch)
968 952 if res:
969 953 return res
970 954 minus = patch.rfind('-')
971 955 if minus >= 0:
972 956 res = partial_name(patch[:minus])
973 957 if res:
974 958 i = self.series.index(res)
975 959 try:
976 960 off = int(patch[minus + 1:] or 1)
977 961 except (ValueError, OverflowError):
978 962 pass
979 963 else:
980 964 if i - off >= 0:
981 965 return self.series[i - off]
982 966 plus = patch.rfind('+')
983 967 if plus >= 0:
984 968 res = partial_name(patch[:plus])
985 969 if res:
986 970 i = self.series.index(res)
987 971 try:
988 972 off = int(patch[plus + 1:] or 1)
989 973 except (ValueError, OverflowError):
990 974 pass
991 975 else:
992 976 if i + off < len(self.series):
993 977 return self.series[i + off]
994 978 raise util.Abort(_("patch %s not in series") % patch)
995 979
996 980 def push(self, repo, patch=None, force=False, list=False,
997 981 mergeq=None, all=False):
998 982 diffopts = self.diffopts()
999 983 wlock = repo.wlock()
1000 984 try:
1001 985 heads = []
1002 986 for b, ls in repo.branchmap().iteritems():
1003 987 heads += ls
1004 988 if not heads:
1005 989 heads = [nullid]
1006 990 if repo.dirstate.parents()[0] not in heads:
1007 991 self.ui.status(_("(working directory not at a head)\n"))
1008 992
1009 993 if not self.series:
1010 994 self.ui.warn(_('no patches in series\n'))
1011 995 return 0
1012 996
1013 997 patch = self.lookup(patch)
1014 998 # Suppose our series file is: A B C and the current 'top'
1015 999 # patch is B. qpush C should be performed (moving forward)
1016 1000 # qpush B is a NOP (no change) qpush A is an error (can't
1017 1001 # go backwards with qpush)
1018 1002 if patch:
1019 1003 info = self.isapplied(patch)
1020 1004 if info:
1021 1005 if info[0] < len(self.applied) - 1:
1022 1006 raise util.Abort(
1023 1007 _("cannot push to a previous patch: %s") % patch)
1024 1008 self.ui.warn(
1025 1009 _('qpush: %s is already at the top\n') % patch)
1026 1010 return
1027 1011 pushable, reason = self.pushable(patch)
1028 1012 if not pushable:
1029 1013 if reason:
1030 1014 reason = _('guarded by %r') % reason
1031 1015 else:
1032 1016 reason = _('no matching guards')
1033 1017 self.ui.warn(_("cannot push '%s' - %s\n") % (patch, reason))
1034 1018 return 1
1035 1019 elif all:
1036 1020 patch = self.series[-1]
1037 1021 if self.isapplied(patch):
1038 1022 self.ui.warn(_('all patches are currently applied\n'))
1039 1023 return 0
1040 1024
1041 1025 # Following the above example, starting at 'top' of B:
1042 1026 # qpush should be performed (pushes C), but a subsequent
1043 1027 # qpush without an argument is an error (nothing to
1044 1028 # apply). This allows a loop of "...while hg qpush..." to
1045 1029 # work as it detects an error when done
1046 1030 start = self.series_end()
1047 1031 if start == len(self.series):
1048 1032 self.ui.warn(_('patch series already fully applied\n'))
1049 1033 return 1
1050 1034 if not force:
1051 1035 self.check_localchanges(repo)
1052 1036
1053 1037 self.applied_dirty = 1
1054 1038 if start > 0:
1055 1039 self.check_toppatch(repo)
1056 1040 if not patch:
1057 1041 patch = self.series[start]
1058 1042 end = start + 1
1059 1043 else:
1060 1044 end = self.series.index(patch, start) + 1
1061 1045
1062 1046 s = self.series[start:end]
1063 1047 all_files = set()
1064 1048 try:
1065 1049 if mergeq:
1066 1050 ret = self.mergepatch(repo, mergeq, s, diffopts)
1067 1051 else:
1068 1052 ret = self.apply(repo, s, list, all_files=all_files)
1069 1053 except:
1070 1054 self.ui.warn(_('cleaning up working directory...'))
1071 1055 node = repo.dirstate.parents()[0]
1072 1056 hg.revert(repo, node, None)
1073 1057 # only remove unknown files that we know we touched or
1074 1058 # created while patching
1075 1059 for f in all_files:
1076 1060 if f not in repo.dirstate:
1077 1061 try:
1078 1062 util.unlink(repo.wjoin(f))
1079 1063 except OSError, inst:
1080 1064 if inst.errno != errno.ENOENT:
1081 1065 raise
1082 1066 self.ui.warn(_('done\n'))
1083 1067 raise
1084 1068
1085 1069 if not self.applied:
1086 1070 return ret[0]
1087 1071 top = self.applied[-1].name
1088 1072 if ret[0] and ret[0] > 1:
1089 1073 msg = _("errors during apply, please fix and refresh %s\n")
1090 1074 self.ui.write(msg % top)
1091 1075 else:
1092 1076 self.ui.write(_("now at: %s\n") % top)
1093 1077 return ret[0]
1094 1078
1095 1079 finally:
1096 1080 wlock.release()
1097 1081
1098 1082 def pop(self, repo, patch=None, force=False, update=True, all=False):
1099 1083 wlock = repo.wlock()
1100 1084 try:
1101 1085 if patch:
1102 1086 # index, rev, patch
1103 1087 info = self.isapplied(patch)
1104 1088 if not info:
1105 1089 patch = self.lookup(patch)
1106 1090 info = self.isapplied(patch)
1107 1091 if not info:
1108 1092 raise util.Abort(_("patch %s is not applied") % patch)
1109 1093
1110 1094 if not self.applied:
1111 1095 # Allow qpop -a to work repeatedly,
1112 1096 # but not qpop without an argument
1113 1097 self.ui.warn(_("no patches applied\n"))
1114 1098 return not all
1115 1099
1116 1100 if all:
1117 1101 start = 0
1118 1102 elif patch:
1119 1103 start = info[0] + 1
1120 1104 else:
1121 1105 start = len(self.applied) - 1
1122 1106
1123 1107 if start >= len(self.applied):
1124 1108 self.ui.warn(_("qpop: %s is already at the top\n") % patch)
1125 1109 return
1126 1110
1127 1111 if not update:
1128 1112 parents = repo.dirstate.parents()
1129 1113 rr = [x.node for x in self.applied]
1130 1114 for p in parents:
1131 1115 if p in rr:
1132 1116 self.ui.warn(_("qpop: forcing dirstate update\n"))
1133 1117 update = True
1134 1118 else:
1135 1119 parents = [p.node() for p in repo[None].parents()]
1136 1120 needupdate = False
1137 1121 for entry in self.applied[start:]:
1138 1122 if entry.node in parents:
1139 1123 needupdate = True
1140 1124 break
1141 1125 update = needupdate
1142 1126
1143 1127 if not force and update:
1144 1128 self.check_localchanges(repo)
1145 1129
1146 1130 self.applied_dirty = 1
1147 1131 end = len(self.applied)
1148 1132 rev = self.applied[start].node
1149 1133 if update:
1150 1134 top = self.check_toppatch(repo)[0]
1151 1135
1152 1136 try:
1153 1137 heads = repo.changelog.heads(rev)
1154 1138 except error.LookupError:
1155 1139 node = short(rev)
1156 1140 raise util.Abort(_('trying to pop unknown node %s') % node)
1157 1141
1158 1142 if heads != [self.applied[-1].node]:
1159 1143 raise util.Abort(_("popping would remove a revision not "
1160 1144 "managed by this patch queue"))
1161 1145
1162 1146 # we know there are no local changes, so we can make a simplified
1163 1147 # form of hg.update.
1164 1148 if update:
1165 1149 qp = self.qparents(repo, rev)
1166 1150 ctx = repo[qp]
1167 1151 m, a, r, d = repo.status(qp, top)[:4]
1168 1152 if d:
1169 1153 raise util.Abort(_("deletions found between repo revs"))
1170 1154 for f in a:
1171 1155 try:
1172 1156 util.unlink(repo.wjoin(f))
1173 1157 except OSError, e:
1174 1158 if e.errno != errno.ENOENT:
1175 1159 raise
1176 1160 repo.dirstate.forget(f)
1177 1161 for f in m + r:
1178 1162 fctx = ctx[f]
1179 1163 repo.wwrite(f, fctx.data(), fctx.flags())
1180 1164 repo.dirstate.normal(f)
1181 1165 repo.dirstate.setparents(qp, nullid)
1182 1166 for patch in reversed(self.applied[start:end]):
1183 1167 self.ui.status(_("popping %s\n") % patch.name)
1184 1168 del self.applied[start:end]
1185 1169 self.strip(repo, rev, update=False, backup='strip')
1186 1170 if self.applied:
1187 1171 self.ui.write(_("now at: %s\n") % self.applied[-1].name)
1188 1172 else:
1189 1173 self.ui.write(_("patch queue now empty\n"))
1190 1174 finally:
1191 1175 wlock.release()
1192 1176
1193 1177 def diff(self, repo, pats, opts):
1194 1178 top, patch = self.check_toppatch(repo)
1195 1179 if not top:
1196 1180 self.ui.write(_("no patches applied\n"))
1197 1181 return
1198 1182 qp = self.qparents(repo, top)
1199 1183 if opts.get('reverse'):
1200 1184 node1, node2 = None, qp
1201 1185 else:
1202 1186 node1, node2 = qp, None
1203 1187 diffopts = self.diffopts(opts, patch)
1204 1188 self.printdiff(repo, diffopts, node1, node2, files=pats, opts=opts)
1205 1189
1206 1190 def refresh(self, repo, pats=None, **opts):
1207 1191 if not self.applied:
1208 1192 self.ui.write(_("no patches applied\n"))
1209 1193 return 1
1210 1194 msg = opts.get('msg', '').rstrip()
1211 1195 newuser = opts.get('user')
1212 1196 newdate = opts.get('date')
1213 1197 if newdate:
1214 1198 newdate = '%d %d' % util.parsedate(newdate)
1215 1199 wlock = repo.wlock()
1216 1200
1217 1201 try:
1218 1202 self.check_toppatch(repo)
1219 1203 (top, patchfn) = (self.applied[-1].node, self.applied[-1].name)
1220 1204 if repo.changelog.heads(top) != [top]:
1221 1205 raise util.Abort(_("cannot refresh a revision with children"))
1222 1206
1223 1207 cparents = repo.changelog.parents(top)
1224 1208 patchparent = self.qparents(repo, top)
1225 1209 ph = patchheader(self.join(patchfn), self.plainmode)
1226 1210 diffopts = self.diffopts({'git': opts.get('git')}, patchfn)
1227 1211 if msg:
1228 1212 ph.setmessage(msg)
1229 1213 if newuser:
1230 1214 ph.setuser(newuser)
1231 1215 if newdate:
1232 1216 ph.setdate(newdate)
1233 1217 ph.setparent(hex(patchparent))
1234 1218
1235 1219 # only commit new patch when write is complete
1236 1220 patchf = self.opener(patchfn, 'w', atomictemp=True)
1237 1221
1238 1222 comments = str(ph)
1239 1223 if comments:
1240 1224 patchf.write(comments)
1241 1225
1242 1226 # update the dirstate in place, strip off the qtip commit
1243 1227 # and then commit.
1244 1228 #
1245 1229 # this should really read:
1246 1230 # mm, dd, aa, aa2 = repo.status(tip, patchparent)[:4]
1247 1231 # but we do it backwards to take advantage of manifest/chlog
1248 1232 # caching against the next repo.status call
1249 1233 mm, aa, dd, aa2 = repo.status(patchparent, top)[:4]
1250 1234 changes = repo.changelog.read(top)
1251 1235 man = repo.manifest.read(changes[0])
1252 1236 aaa = aa[:]
1253 1237 matchfn = cmdutil.match(repo, pats, opts)
1254 1238 # in short mode, we only diff the files included in the
1255 1239 # patch already plus specified files
1256 1240 if opts.get('short'):
1257 1241 # if amending a patch, we start with existing
1258 1242 # files plus specified files - unfiltered
1259 1243 match = cmdutil.matchfiles(repo, mm + aa + dd + matchfn.files())
1260 1244 # filter with inc/exl options
1261 1245 matchfn = cmdutil.match(repo, opts=opts)
1262 1246 else:
1263 1247 match = cmdutil.matchall(repo)
1264 1248 m, a, r, d = repo.status(match=match)[:4]
1265 1249
1266 1250 # we might end up with files that were added between
1267 1251 # qtip and the dirstate parent, but then changed in the
1268 1252 # local dirstate. in this case, we want them to only
1269 1253 # show up in the added section
1270 1254 for x in m:
1271 1255 if x not in aa:
1272 1256 mm.append(x)
1273 1257 # we might end up with files added by the local dirstate that
1274 1258 # were deleted by the patch. In this case, they should only
1275 1259 # show up in the changed section.
1276 1260 for x in a:
1277 1261 if x in dd:
1278 1262 del dd[dd.index(x)]
1279 1263 mm.append(x)
1280 1264 else:
1281 1265 aa.append(x)
1282 1266 # make sure any files deleted in the local dirstate
1283 1267 # are not in the add or change column of the patch
1284 1268 forget = []
1285 1269 for x in d + r:
1286 1270 if x in aa:
1287 1271 del aa[aa.index(x)]
1288 1272 forget.append(x)
1289 1273 continue
1290 1274 elif x in mm:
1291 1275 del mm[mm.index(x)]
1292 1276 dd.append(x)
1293 1277
1294 1278 m = list(set(mm))
1295 1279 r = list(set(dd))
1296 1280 a = list(set(aa))
1297 1281 c = [filter(matchfn, l) for l in (m, a, r)]
1298 1282 match = cmdutil.matchfiles(repo, set(c[0] + c[1] + c[2]))
1299 1283 chunks = patch.diff(repo, patchparent, match=match,
1300 1284 changes=c, opts=diffopts)
1301 1285 for chunk in chunks:
1302 1286 patchf.write(chunk)
1303 1287
1304 1288 try:
1305 1289 if diffopts.git or diffopts.upgrade:
1306 1290 copies = {}
1307 1291 for dst in a:
1308 1292 src = repo.dirstate.copied(dst)
1309 1293 # during qfold, the source file for copies may
1310 1294 # be removed. Treat this as a simple add.
1311 1295 if src is not None and src in repo.dirstate:
1312 1296 copies.setdefault(src, []).append(dst)
1313 1297 repo.dirstate.add(dst)
1314 1298 # remember the copies between patchparent and qtip
1315 1299 for dst in aaa:
1316 1300 f = repo.file(dst)
1317 1301 src = f.renamed(man[dst])
1318 1302 if src:
1319 1303 copies.setdefault(src[0], []).extend(
1320 1304 copies.get(dst, []))
1321 1305 if dst in a:
1322 1306 copies[src[0]].append(dst)
1323 1307 # we can't copy a file created by the patch itself
1324 1308 if dst in copies:
1325 1309 del copies[dst]
1326 1310 for src, dsts in copies.iteritems():
1327 1311 for dst in dsts:
1328 1312 repo.dirstate.copy(src, dst)
1329 1313 else:
1330 1314 for dst in a:
1331 1315 repo.dirstate.add(dst)
1332 1316 # Drop useless copy information
1333 1317 for f in list(repo.dirstate.copies()):
1334 1318 repo.dirstate.copy(None, f)
1335 1319 for f in r:
1336 1320 repo.dirstate.remove(f)
1337 1321 # if the patch excludes a modified file, mark that
1338 1322 # file with mtime=0 so status can see it.
1339 1323 mm = []
1340 1324 for i in xrange(len(m)-1, -1, -1):
1341 1325 if not matchfn(m[i]):
1342 1326 mm.append(m[i])
1343 1327 del m[i]
1344 1328 for f in m:
1345 1329 repo.dirstate.normal(f)
1346 1330 for f in mm:
1347 1331 repo.dirstate.normallookup(f)
1348 1332 for f in forget:
1349 1333 repo.dirstate.forget(f)
1350 1334
1351 1335 if not msg:
1352 1336 if not ph.message:
1353 1337 message = "[mq]: %s\n" % patchfn
1354 1338 else:
1355 1339 message = "\n".join(ph.message)
1356 1340 else:
1357 1341 message = msg
1358 1342
1359 1343 user = ph.user or changes[1]
1360 1344
1361 1345 # assumes strip can roll itself back if interrupted
1362 1346 repo.dirstate.setparents(*cparents)
1363 1347 self.applied.pop()
1364 1348 self.applied_dirty = 1
1365 1349 self.strip(repo, top, update=False,
1366 1350 backup='strip')
1367 1351 except:
1368 1352 repo.dirstate.invalidate()
1369 1353 raise
1370 1354
1371 1355 try:
1372 1356 # might be nice to attempt to roll back strip after this
1373 1357 patchf.rename()
1374 1358 n = repo.commit(message, user, ph.date, match=match,
1375 1359 force=True)
1376 1360 self.applied.append(statusentry(n, patchfn))
1377 1361 except:
1378 1362 ctx = repo[cparents[0]]
1379 1363 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1380 1364 self.save_dirty()
1381 1365 self.ui.warn(_('refresh interrupted while patch was popped! '
1382 1366 '(revert --all, qpush to recover)\n'))
1383 1367 raise
1384 1368 finally:
1385 1369 wlock.release()
1386 1370 self.removeundo(repo)
1387 1371
1388 1372 def init(self, repo, create=False):
1389 1373 if not create and os.path.isdir(self.path):
1390 1374 raise util.Abort(_("patch queue directory already exists"))
1391 1375 try:
1392 1376 os.mkdir(self.path)
1393 1377 except OSError, inst:
1394 1378 if inst.errno != errno.EEXIST or not create:
1395 1379 raise
1396 1380 if create:
1397 1381 return self.qrepo(create=True)
1398 1382
1399 1383 def unapplied(self, repo, patch=None):
1400 1384 if patch and patch not in self.series:
1401 1385 raise util.Abort(_("patch %s is not in series file") % patch)
1402 1386 if not patch:
1403 1387 start = self.series_end()
1404 1388 else:
1405 1389 start = self.series.index(patch) + 1
1406 1390 unapplied = []
1407 1391 for i in xrange(start, len(self.series)):
1408 1392 pushable, reason = self.pushable(i)
1409 1393 if pushable:
1410 1394 unapplied.append((i, self.series[i]))
1411 1395 self.explain_pushable(i)
1412 1396 return unapplied
1413 1397
1414 1398 def qseries(self, repo, missing=None, start=0, length=None, status=None,
1415 1399 summary=False):
1416 1400 def displayname(pfx, patchname, state):
1417 1401 if pfx:
1418 1402 self.ui.write(pfx)
1419 1403 if summary:
1420 1404 ph = patchheader(self.join(patchname), self.plainmode)
1421 1405 msg = ph.message and ph.message[0] or ''
1422 1406 if not self.ui.plain():
1423 1407 width = util.termwidth() - len(pfx) - len(patchname) - 2
1424 1408 if width > 0:
1425 1409 msg = util.ellipsis(msg, width)
1426 1410 else:
1427 1411 msg = ''
1428 1412 self.ui.write(patchname, label='qseries.' + state)
1429 1413 self.ui.write(': ')
1430 1414 self.ui.write(msg, label='qseries.message.' + state)
1431 1415 else:
1432 1416 self.ui.write(patchname, label='qseries.' + state)
1433 1417 self.ui.write('\n')
1434 1418
1435 1419 applied = set([p.name for p in self.applied])
1436 1420 if length is None:
1437 1421 length = len(self.series) - start
1438 1422 if not missing:
1439 1423 if self.ui.verbose:
1440 1424 idxwidth = len(str(start + length - 1))
1441 1425 for i in xrange(start, start + length):
1442 1426 patch = self.series[i]
1443 1427 if patch in applied:
1444 1428 char, state = 'A', 'applied'
1445 1429 elif self.pushable(i)[0]:
1446 1430 char, state = 'U', 'unapplied'
1447 1431 else:
1448 1432 char, state = 'G', 'guarded'
1449 1433 pfx = ''
1450 1434 if self.ui.verbose:
1451 1435 pfx = '%*d %s ' % (idxwidth, i, char)
1452 1436 elif status and status != char:
1453 1437 continue
1454 1438 displayname(pfx, patch, state)
1455 1439 else:
1456 1440 msng_list = []
1457 1441 for root, dirs, files in os.walk(self.path):
1458 1442 d = root[len(self.path) + 1:]
1459 1443 for f in files:
1460 1444 fl = os.path.join(d, f)
1461 1445 if (fl not in self.series and
1462 1446 fl not in (self.status_path, self.series_path,
1463 1447 self.guards_path)
1464 1448 and not fl.startswith('.')):
1465 1449 msng_list.append(fl)
1466 1450 for x in sorted(msng_list):
1467 1451 pfx = self.ui.verbose and ('D ') or ''
1468 1452 displayname(pfx, x, 'missing')
1469 1453
1470 1454 def issaveline(self, l):
1471 1455 if l.name == '.hg.patches.save.line':
1472 1456 return True
1473 1457
1474 1458 def qrepo(self, create=False):
1475 1459 if create or os.path.isdir(self.join(".hg")):
1476 1460 return hg.repository(self.ui, path=self.path, create=create)
1477 1461
1478 1462 def restore(self, repo, rev, delete=None, qupdate=None):
1479 1463 desc = repo[rev].description().strip()
1480 1464 lines = desc.splitlines()
1481 1465 i = 0
1482 1466 datastart = None
1483 1467 series = []
1484 1468 applied = []
1485 1469 qpp = None
1486 1470 for i, line in enumerate(lines):
1487 1471 if line == 'Patch Data:':
1488 1472 datastart = i + 1
1489 1473 elif line.startswith('Dirstate:'):
1490 1474 l = line.rstrip()
1491 1475 l = l[10:].split(' ')
1492 1476 qpp = [bin(x) for x in l]
1493 1477 elif datastart != None:
1494 1478 l = line.rstrip()
1495 1479 n, name = l.split(':', 1)
1496 1480 if n:
1497 1481 applied.append(statusentry(bin(n), name))
1498 1482 else:
1499 1483 series.append(l)
1500 1484 if datastart is None:
1501 1485 self.ui.warn(_("No saved patch data found\n"))
1502 1486 return 1
1503 1487 self.ui.warn(_("restoring status: %s\n") % lines[0])
1504 1488 self.full_series = series
1505 1489 self.applied = applied
1506 1490 self.parse_series()
1507 1491 self.series_dirty = 1
1508 1492 self.applied_dirty = 1
1509 1493 heads = repo.changelog.heads()
1510 1494 if delete:
1511 1495 if rev not in heads:
1512 1496 self.ui.warn(_("save entry has children, leaving it alone\n"))
1513 1497 else:
1514 1498 self.ui.warn(_("removing save entry %s\n") % short(rev))
1515 1499 pp = repo.dirstate.parents()
1516 1500 if rev in pp:
1517 1501 update = True
1518 1502 else:
1519 1503 update = False
1520 1504 self.strip(repo, rev, update=update, backup='strip')
1521 1505 if qpp:
1522 1506 self.ui.warn(_("saved queue repository parents: %s %s\n") %
1523 1507 (short(qpp[0]), short(qpp[1])))
1524 1508 if qupdate:
1525 1509 self.ui.status(_("queue directory updating\n"))
1526 1510 r = self.qrepo()
1527 1511 if not r:
1528 1512 self.ui.warn(_("Unable to load queue repository\n"))
1529 1513 return 1
1530 1514 hg.clean(r, qpp[0])
1531 1515
1532 1516 def save(self, repo, msg=None):
1533 1517 if not self.applied:
1534 1518 self.ui.warn(_("save: no patches applied, exiting\n"))
1535 1519 return 1
1536 1520 if self.issaveline(self.applied[-1]):
1537 1521 self.ui.warn(_("status is already saved\n"))
1538 1522 return 1
1539 1523
1540 1524 if not msg:
1541 1525 msg = _("hg patches saved state")
1542 1526 else:
1543 1527 msg = "hg patches: " + msg.rstrip('\r\n')
1544 1528 r = self.qrepo()
1545 1529 if r:
1546 1530 pp = r.dirstate.parents()
1547 1531 msg += "\nDirstate: %s %s" % (hex(pp[0]), hex(pp[1]))
1548 1532 msg += "\n\nPatch Data:\n"
1549 1533 msg += ''.join('%s\n' % x for x in self.applied)
1550 1534 msg += ''.join(':%s\n' % x for x in self.full_series)
1551 1535 n = repo.commit(msg, force=True)
1552 1536 if not n:
1553 1537 self.ui.warn(_("repo commit failed\n"))
1554 1538 return 1
1555 1539 self.applied.append(statusentry(n, '.hg.patches.save.line'))
1556 1540 self.applied_dirty = 1
1557 1541 self.removeundo(repo)
1558 1542
1559 1543 def full_series_end(self):
1560 1544 if self.applied:
1561 1545 p = self.applied[-1].name
1562 1546 end = self.find_series(p)
1563 1547 if end is None:
1564 1548 return len(self.full_series)
1565 1549 return end + 1
1566 1550 return 0
1567 1551
1568 1552 def series_end(self, all_patches=False):
1569 1553 """If all_patches is False, return the index of the next pushable patch
1570 1554 in the series, or the series length. If all_patches is True, return the
1571 1555 index of the first patch past the last applied one.
1572 1556 """
1573 1557 end = 0
1574 1558 def next(start):
1575 1559 if all_patches or start >= len(self.series):
1576 1560 return start
1577 1561 for i in xrange(start, len(self.series)):
1578 1562 p, reason = self.pushable(i)
1579 1563 if p:
1580 1564 break
1581 1565 self.explain_pushable(i)
1582 1566 return i
1583 1567 if self.applied:
1584 1568 p = self.applied[-1].name
1585 1569 try:
1586 1570 end = self.series.index(p)
1587 1571 except ValueError:
1588 1572 return 0
1589 1573 return next(end + 1)
1590 1574 return next(end)
1591 1575
1592 1576 def appliedname(self, index):
1593 1577 pname = self.applied[index].name
1594 1578 if not self.ui.verbose:
1595 1579 p = pname
1596 1580 else:
1597 1581 p = str(self.series.index(pname)) + " " + pname
1598 1582 return p
1599 1583
1600 1584 def qimport(self, repo, files, patchname=None, rev=None, existing=None,
1601 1585 force=None, git=False):
1602 1586 def checkseries(patchname):
1603 1587 if patchname in self.series:
1604 1588 raise util.Abort(_('patch %s is already in the series file')
1605 1589 % patchname)
1606 1590 def checkfile(patchname):
1607 1591 if not force and os.path.exists(self.join(patchname)):
1608 1592 raise util.Abort(_('patch "%s" already exists')
1609 1593 % patchname)
1610 1594
1611 1595 if rev:
1612 1596 if files:
1613 1597 raise util.Abort(_('option "-r" not valid when importing '
1614 1598 'files'))
1615 1599 rev = cmdutil.revrange(repo, rev)
1616 1600 rev.sort(reverse=True)
1617 1601 if (len(files) > 1 or len(rev) > 1) and patchname:
1618 1602 raise util.Abort(_('option "-n" not valid when importing multiple '
1619 1603 'patches'))
1620 1604 added = []
1621 1605 if rev:
1622 1606 # If mq patches are applied, we can only import revisions
1623 1607 # that form a linear path to qbase.
1624 1608 # Otherwise, they should form a linear path to a head.
1625 1609 heads = repo.changelog.heads(repo.changelog.node(rev[-1]))
1626 1610 if len(heads) > 1:
1627 1611 raise util.Abort(_('revision %d is the root of more than one '
1628 1612 'branch') % rev[-1])
1629 1613 if self.applied:
1630 1614 base = repo.changelog.node(rev[0])
1631 1615 if base in [n.node for n in self.applied]:
1632 1616 raise util.Abort(_('revision %d is already managed')
1633 1617 % rev[0])
1634 1618 if heads != [self.applied[-1].node]:
1635 1619 raise util.Abort(_('revision %d is not the parent of '
1636 1620 'the queue') % rev[0])
1637 1621 base = repo.changelog.rev(self.applied[0].node)
1638 1622 lastparent = repo.changelog.parentrevs(base)[0]
1639 1623 else:
1640 1624 if heads != [repo.changelog.node(rev[0])]:
1641 1625 raise util.Abort(_('revision %d has unmanaged children')
1642 1626 % rev[0])
1643 1627 lastparent = None
1644 1628
1645 1629 diffopts = self.diffopts({'git': git})
1646 1630 for r in rev:
1647 1631 p1, p2 = repo.changelog.parentrevs(r)
1648 1632 n = repo.changelog.node(r)
1649 1633 if p2 != nullrev:
1650 1634 raise util.Abort(_('cannot import merge revision %d') % r)
1651 1635 if lastparent and lastparent != r:
1652 1636 raise util.Abort(_('revision %d is not the parent of %d')
1653 1637 % (r, lastparent))
1654 1638 lastparent = p1
1655 1639
1656 1640 if not patchname:
1657 1641 patchname = normname('%d.diff' % r)
1658 1642 self.check_reserved_name(patchname)
1659 1643 checkseries(patchname)
1660 1644 checkfile(patchname)
1661 1645 self.full_series.insert(0, patchname)
1662 1646
1663 1647 patchf = self.opener(patchname, "w")
1664 1648 cmdutil.export(repo, [n], fp=patchf, opts=diffopts)
1665 1649 patchf.close()
1666 1650
1667 1651 se = statusentry(n, patchname)
1668 1652 self.applied.insert(0, se)
1669 1653
1670 1654 added.append(patchname)
1671 1655 patchname = None
1672 1656 self.parse_series()
1673 1657 self.applied_dirty = 1
1674 1658
1675 1659 for i, filename in enumerate(files):
1676 1660 if existing:
1677 1661 if filename == '-':
1678 1662 raise util.Abort(_('-e is incompatible with import from -'))
1679 1663 if not patchname:
1680 1664 patchname = normname(filename)
1681 1665 self.check_reserved_name(patchname)
1682 1666 if not os.path.isfile(self.join(patchname)):
1683 1667 raise util.Abort(_("patch %s does not exist") % patchname)
1684 1668 else:
1685 1669 try:
1686 1670 if filename == '-':
1687 1671 if not patchname:
1688 1672 raise util.Abort(
1689 1673 _('need --name to import a patch from -'))
1690 1674 text = sys.stdin.read()
1691 1675 else:
1692 1676 text = url.open(self.ui, filename).read()
1693 1677 except (OSError, IOError):
1694 1678 raise util.Abort(_("unable to read %s") % filename)
1695 1679 if not patchname:
1696 1680 patchname = normname(os.path.basename(filename))
1697 1681 self.check_reserved_name(patchname)
1698 1682 checkfile(patchname)
1699 1683 patchf = self.opener(patchname, "w")
1700 1684 patchf.write(text)
1701 1685 if not force:
1702 1686 checkseries(patchname)
1703 1687 if patchname not in self.series:
1704 1688 index = self.full_series_end() + i
1705 1689 self.full_series[index:index] = [patchname]
1706 1690 self.parse_series()
1707 1691 self.ui.warn(_("adding %s to series file\n") % patchname)
1708 1692 added.append(patchname)
1709 1693 patchname = None
1710 1694 self.series_dirty = 1
1711 1695 qrepo = self.qrepo()
1712 1696 if qrepo:
1713 1697 qrepo.add(added)
1714 1698
1715 1699 def delete(ui, repo, *patches, **opts):
1716 1700 """remove patches from queue
1717 1701
1718 1702 The patches must not be applied, and at least one patch is required. With
1719 1703 -k/--keep, the patch files are preserved in the patch directory.
1720 1704
1721 1705 To stop managing a patch and move it into permanent history,
1722 1706 use the qfinish command."""
1723 1707 q = repo.mq
1724 1708 q.delete(repo, patches, opts)
1725 1709 q.save_dirty()
1726 1710 return 0
1727 1711
1728 1712 def applied(ui, repo, patch=None, **opts):
1729 1713 """print the patches already applied"""
1730 1714
1731 1715 q = repo.mq
1732 1716 l = len(q.applied)
1733 1717
1734 1718 if patch:
1735 1719 if patch not in q.series:
1736 1720 raise util.Abort(_("patch %s is not in series file") % patch)
1737 1721 end = q.series.index(patch) + 1
1738 1722 else:
1739 1723 end = q.series_end(True)
1740 1724
1741 1725 if opts.get('last') and not end:
1742 1726 ui.write(_("no patches applied\n"))
1743 1727 return 1
1744 1728 elif opts.get('last') and end == 1:
1745 1729 ui.write(_("only one patch applied\n"))
1746 1730 return 1
1747 1731 elif opts.get('last'):
1748 1732 start = end - 2
1749 1733 end = 1
1750 1734 else:
1751 1735 start = 0
1752 1736
1753 1737 return q.qseries(repo, length=end, start=start, status='A',
1754 1738 summary=opts.get('summary'))
1755 1739
1756 1740 def unapplied(ui, repo, patch=None, **opts):
1757 1741 """print the patches not yet applied"""
1758 1742
1759 1743 q = repo.mq
1760 1744 if patch:
1761 1745 if patch not in q.series:
1762 1746 raise util.Abort(_("patch %s is not in series file") % patch)
1763 1747 start = q.series.index(patch) + 1
1764 1748 else:
1765 1749 start = q.series_end(True)
1766 1750
1767 1751 if start == len(q.series) and opts.get('first'):
1768 1752 ui.write(_("all patches applied\n"))
1769 1753 return 1
1770 1754
1771 1755 length = opts.get('first') and 1 or None
1772 1756 return q.qseries(repo, start=start, length=length, status='U',
1773 1757 summary=opts.get('summary'))
1774 1758
1775 1759 def qimport(ui, repo, *filename, **opts):
1776 1760 """import a patch
1777 1761
1778 1762 The patch is inserted into the series after the last applied
1779 1763 patch. If no patches have been applied, qimport prepends the patch
1780 1764 to the series.
1781 1765
1782 1766 The patch will have the same name as its source file unless you
1783 1767 give it a new one with -n/--name.
1784 1768
1785 1769 You can register an existing patch inside the patch directory with
1786 1770 the -e/--existing flag.
1787 1771
1788 1772 With -f/--force, an existing patch of the same name will be
1789 1773 overwritten.
1790 1774
1791 1775 An existing changeset may be placed under mq control with -r/--rev
1792 1776 (e.g. qimport --rev tip -n patch will place tip under mq control).
1793 1777 With -g/--git, patches imported with --rev will use the git diff
1794 1778 format. See the diffs help topic for information on why this is
1795 1779 important for preserving rename/copy information and permission
1796 1780 changes.
1797 1781
1798 1782 To import a patch from standard input, pass - as the patch file.
1799 1783 When importing from standard input, a patch name must be specified
1800 1784 using the --name flag.
1801 1785 """
1802 1786 q = repo.mq
1803 1787 q.qimport(repo, filename, patchname=opts['name'],
1804 1788 existing=opts['existing'], force=opts['force'], rev=opts['rev'],
1805 1789 git=opts['git'])
1806 1790 q.save_dirty()
1807 1791
1808 1792 if opts.get('push') and not opts.get('rev'):
1809 1793 return q.push(repo, None)
1810 1794 return 0
1811 1795
1812 1796 def qinit(ui, repo, create):
1813 1797 """initialize a new queue repository
1814 1798
1815 1799 This command also creates a series file for ordering patches, and
1816 1800 an mq-specific .hgignore file in the queue repository, to exclude
1817 1801 the status and guards files (these contain mostly transient state)."""
1818 1802 q = repo.mq
1819 1803 r = q.init(repo, create)
1820 1804 q.save_dirty()
1821 1805 if r:
1822 1806 if not os.path.exists(r.wjoin('.hgignore')):
1823 1807 fp = r.wopener('.hgignore', 'w')
1824 1808 fp.write('^\\.hg\n')
1825 1809 fp.write('^\\.mq\n')
1826 1810 fp.write('syntax: glob\n')
1827 1811 fp.write('status\n')
1828 1812 fp.write('guards\n')
1829 1813 fp.close()
1830 1814 if not os.path.exists(r.wjoin('series')):
1831 1815 r.wopener('series', 'w').close()
1832 1816 r.add(['.hgignore', 'series'])
1833 1817 commands.add(ui, r)
1834 1818 return 0
1835 1819
1836 1820 def init(ui, repo, **opts):
1837 1821 """init a new queue repository (DEPRECATED)
1838 1822
1839 1823 The queue repository is unversioned by default. If
1840 1824 -c/--create-repo is specified, qinit will create a separate nested
1841 1825 repository for patches (qinit -c may also be run later to convert
1842 1826 an unversioned patch repository into a versioned one). You can use
1843 1827 qcommit to commit changes to this queue repository.
1844 1828
1845 1829 This command is deprecated. Without -c, it's implied by other relevant
1846 1830 commands. With -c, use hg init --mq instead."""
1847 1831 return qinit(ui, repo, create=opts['create_repo'])
1848 1832
1849 1833 def clone(ui, source, dest=None, **opts):
1850 1834 '''clone main and patch repository at same time
1851 1835
1852 1836 If source is local, destination will have no patches applied. If
1853 1837 source is remote, this command can not check if patches are
1854 1838 applied in source, so cannot guarantee that patches are not
1855 1839 applied in destination. If you clone remote repository, be sure
1856 1840 before that it has no patches applied.
1857 1841
1858 1842 Source patch repository is looked for in <src>/.hg/patches by
1859 1843 default. Use -p <url> to change.
1860 1844
1861 1845 The patch directory must be a nested Mercurial repository, as
1862 1846 would be created by init --mq.
1863 1847 '''
1864 1848 def patchdir(repo):
1865 1849 url = repo.url()
1866 1850 if url.endswith('/'):
1867 1851 url = url[:-1]
1868 1852 return url + '/.hg/patches'
1869 1853 if dest is None:
1870 1854 dest = hg.defaultdest(source)
1871 1855 sr = hg.repository(cmdutil.remoteui(ui, opts), ui.expandpath(source))
1872 1856 if opts['patches']:
1873 1857 patchespath = ui.expandpath(opts['patches'])
1874 1858 else:
1875 1859 patchespath = patchdir(sr)
1876 1860 try:
1877 1861 hg.repository(ui, patchespath)
1878 1862 except error.RepoError:
1879 1863 raise util.Abort(_('versioned patch repository not found'
1880 1864 ' (see init --mq)'))
1881 1865 qbase, destrev = None, None
1882 1866 if sr.local():
1883 1867 if sr.mq.applied:
1884 1868 qbase = sr.mq.applied[0].node
1885 1869 if not hg.islocal(dest):
1886 1870 heads = set(sr.heads())
1887 1871 destrev = list(heads.difference(sr.heads(qbase)))
1888 1872 destrev.append(sr.changelog.parents(qbase)[0])
1889 1873 elif sr.capable('lookup'):
1890 1874 try:
1891 1875 qbase = sr.lookup('qbase')
1892 1876 except error.RepoError:
1893 1877 pass
1894 1878 ui.note(_('cloning main repository\n'))
1895 1879 sr, dr = hg.clone(ui, sr.url(), dest,
1896 1880 pull=opts['pull'],
1897 1881 rev=destrev,
1898 1882 update=False,
1899 1883 stream=opts['uncompressed'])
1900 1884 ui.note(_('cloning patch repository\n'))
1901 1885 hg.clone(ui, opts['patches'] or patchdir(sr), patchdir(dr),
1902 1886 pull=opts['pull'], update=not opts['noupdate'],
1903 1887 stream=opts['uncompressed'])
1904 1888 if dr.local():
1905 1889 if qbase:
1906 1890 ui.note(_('stripping applied patches from destination '
1907 1891 'repository\n'))
1908 1892 dr.mq.strip(dr, qbase, update=False, backup=None)
1909 1893 if not opts['noupdate']:
1910 1894 ui.note(_('updating destination repository\n'))
1911 1895 hg.update(dr, dr.changelog.tip())
1912 1896
1913 1897 def commit(ui, repo, *pats, **opts):
1914 1898 """commit changes in the queue repository (DEPRECATED)
1915 1899
1916 1900 This command is deprecated; use hg commit --mq instead."""
1917 1901 q = repo.mq
1918 1902 r = q.qrepo()
1919 1903 if not r:
1920 1904 raise util.Abort('no queue repository')
1921 1905 commands.commit(r.ui, r, *pats, **opts)
1922 1906
1923 1907 def series(ui, repo, **opts):
1924 1908 """print the entire series file"""
1925 1909 repo.mq.qseries(repo, missing=opts['missing'], summary=opts['summary'])
1926 1910 return 0
1927 1911
1928 1912 def top(ui, repo, **opts):
1929 1913 """print the name of the current patch"""
1930 1914 q = repo.mq
1931 1915 t = q.applied and q.series_end(True) or 0
1932 1916 if t:
1933 1917 return q.qseries(repo, start=t - 1, length=1, status='A',
1934 1918 summary=opts.get('summary'))
1935 1919 else:
1936 1920 ui.write(_("no patches applied\n"))
1937 1921 return 1
1938 1922
1939 1923 def next(ui, repo, **opts):
1940 1924 """print the name of the next patch"""
1941 1925 q = repo.mq
1942 1926 end = q.series_end()
1943 1927 if end == len(q.series):
1944 1928 ui.write(_("all patches applied\n"))
1945 1929 return 1
1946 1930 return q.qseries(repo, start=end, length=1, summary=opts.get('summary'))
1947 1931
1948 1932 def prev(ui, repo, **opts):
1949 1933 """print the name of the previous patch"""
1950 1934 q = repo.mq
1951 1935 l = len(q.applied)
1952 1936 if l == 1:
1953 1937 ui.write(_("only one patch applied\n"))
1954 1938 return 1
1955 1939 if not l:
1956 1940 ui.write(_("no patches applied\n"))
1957 1941 return 1
1958 1942 return q.qseries(repo, start=l - 2, length=1, status='A',
1959 1943 summary=opts.get('summary'))
1960 1944
1961 1945 def setupheaderopts(ui, opts):
1962 1946 if not opts.get('user') and opts.get('currentuser'):
1963 1947 opts['user'] = ui.username()
1964 1948 if not opts.get('date') and opts.get('currentdate'):
1965 1949 opts['date'] = "%d %d" % util.makedate()
1966 1950
1967 1951 def new(ui, repo, patch, *args, **opts):
1968 1952 """create a new patch
1969 1953
1970 1954 qnew creates a new patch on top of the currently-applied patch (if
1971 1955 any). The patch will be initialized with any outstanding changes
1972 1956 in the working directory. You may also use -I/--include,
1973 1957 -X/--exclude, and/or a list of files after the patch name to add
1974 1958 only changes to matching files to the new patch, leaving the rest
1975 1959 as uncommitted modifications.
1976 1960
1977 1961 -u/--user and -d/--date can be used to set the (given) user and
1978 1962 date, respectively. -U/--currentuser and -D/--currentdate set user
1979 1963 to current user and date to current date.
1980 1964
1981 1965 -e/--edit, -m/--message or -l/--logfile set the patch header as
1982 1966 well as the commit message. If none is specified, the header is
1983 1967 empty and the commit message is '[mq]: PATCH'.
1984 1968
1985 1969 Use the -g/--git option to keep the patch in the git extended diff
1986 1970 format. Read the diffs help topic for more information on why this
1987 1971 is important for preserving permission changes and copy/rename
1988 1972 information.
1989 1973 """
1990 1974 msg = cmdutil.logmessage(opts)
1991 1975 def getmsg():
1992 1976 return ui.edit(msg, ui.username())
1993 1977 q = repo.mq
1994 1978 opts['msg'] = msg
1995 1979 if opts.get('edit'):
1996 1980 opts['msg'] = getmsg
1997 1981 else:
1998 1982 opts['msg'] = msg
1999 1983 setupheaderopts(ui, opts)
2000 1984 q.new(repo, patch, *args, **opts)
2001 1985 q.save_dirty()
2002 1986 return 0
2003 1987
2004 1988 def refresh(ui, repo, *pats, **opts):
2005 1989 """update the current patch
2006 1990
2007 1991 If any file patterns are provided, the refreshed patch will
2008 1992 contain only the modifications that match those patterns; the
2009 1993 remaining modifications will remain in the working directory.
2010 1994
2011 1995 If -s/--short is specified, files currently included in the patch
2012 1996 will be refreshed just like matched files and remain in the patch.
2013 1997
2014 1998 hg add/remove/copy/rename work as usual, though you might want to
2015 1999 use git-style patches (-g/--git or [diff] git=1) to track copies
2016 2000 and renames. See the diffs help topic for more information on the
2017 2001 git diff format.
2018 2002 """
2019 2003 q = repo.mq
2020 2004 message = cmdutil.logmessage(opts)
2021 2005 if opts['edit']:
2022 2006 if not q.applied:
2023 2007 ui.write(_("no patches applied\n"))
2024 2008 return 1
2025 2009 if message:
2026 2010 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
2027 2011 patch = q.applied[-1].name
2028 2012 ph = patchheader(q.join(patch), q.plainmode)
2029 2013 message = ui.edit('\n'.join(ph.message), ph.user or ui.username())
2030 2014 setupheaderopts(ui, opts)
2031 2015 ret = q.refresh(repo, pats, msg=message, **opts)
2032 2016 q.save_dirty()
2033 2017 return ret
2034 2018
2035 2019 def diff(ui, repo, *pats, **opts):
2036 2020 """diff of the current patch and subsequent modifications
2037 2021
2038 2022 Shows a diff which includes the current patch as well as any
2039 2023 changes which have been made in the working directory since the
2040 2024 last refresh (thus showing what the current patch would become
2041 2025 after a qrefresh).
2042 2026
2043 2027 Use :hg:`diff` if you only want to see the changes made since the
2044 2028 last qrefresh, or :hg:`export qtip` if you want to see changes
2045 2029 made by the current patch without including changes made since the
2046 2030 qrefresh.
2047 2031 """
2048 2032 repo.mq.diff(repo, pats, opts)
2049 2033 return 0
2050 2034
2051 2035 def fold(ui, repo, *files, **opts):
2052 2036 """fold the named patches into the current patch
2053 2037
2054 2038 Patches must not yet be applied. Each patch will be successively
2055 2039 applied to the current patch in the order given. If all the
2056 2040 patches apply successfully, the current patch will be refreshed
2057 2041 with the new cumulative patch, and the folded patches will be
2058 2042 deleted. With -k/--keep, the folded patch files will not be
2059 2043 removed afterwards.
2060 2044
2061 2045 The header for each folded patch will be concatenated with the
2062 2046 current patch header, separated by a line of '* * *'."""
2063 2047
2064 2048 q = repo.mq
2065 2049
2066 2050 if not files:
2067 2051 raise util.Abort(_('qfold requires at least one patch name'))
2068 2052 if not q.check_toppatch(repo)[0]:
2069 2053 raise util.Abort(_('No patches applied'))
2070 2054 q.check_localchanges(repo)
2071 2055
2072 2056 message = cmdutil.logmessage(opts)
2073 2057 if opts['edit']:
2074 2058 if message:
2075 2059 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
2076 2060
2077 2061 parent = q.lookup('qtip')
2078 2062 patches = []
2079 2063 messages = []
2080 2064 for f in files:
2081 2065 p = q.lookup(f)
2082 2066 if p in patches or p == parent:
2083 2067 ui.warn(_('Skipping already folded patch %s') % p)
2084 2068 if q.isapplied(p):
2085 2069 raise util.Abort(_('qfold cannot fold already applied patch %s') % p)
2086 2070 patches.append(p)
2087 2071
2088 2072 for p in patches:
2089 2073 if not message:
2090 2074 ph = patchheader(q.join(p), q.plainmode)
2091 2075 if ph.message:
2092 2076 messages.append(ph.message)
2093 2077 pf = q.join(p)
2094 2078 (patchsuccess, files, fuzz) = q.patch(repo, pf)
2095 2079 if not patchsuccess:
2096 2080 raise util.Abort(_('Error folding patch %s') % p)
2097 2081 patch.updatedir(ui, repo, files)
2098 2082
2099 2083 if not message:
2100 2084 ph = patchheader(q.join(parent), q.plainmode)
2101 2085 message, user = ph.message, ph.user
2102 2086 for msg in messages:
2103 2087 message.append('* * *')
2104 2088 message.extend(msg)
2105 2089 message = '\n'.join(message)
2106 2090
2107 2091 if opts['edit']:
2108 2092 message = ui.edit(message, user or ui.username())
2109 2093
2110 2094 diffopts = q.patchopts(q.diffopts(), *patches)
2111 2095 q.refresh(repo, msg=message, git=diffopts.git)
2112 2096 q.delete(repo, patches, opts)
2113 2097 q.save_dirty()
2114 2098
2115 2099 def goto(ui, repo, patch, **opts):
2116 2100 '''push or pop patches until named patch is at top of stack'''
2117 2101 q = repo.mq
2118 2102 patch = q.lookup(patch)
2119 2103 if q.isapplied(patch):
2120 2104 ret = q.pop(repo, patch, force=opts['force'])
2121 2105 else:
2122 2106 ret = q.push(repo, patch, force=opts['force'])
2123 2107 q.save_dirty()
2124 2108 return ret
2125 2109
2126 2110 def guard(ui, repo, *args, **opts):
2127 2111 '''set or print guards for a patch
2128 2112
2129 2113 Guards control whether a patch can be pushed. A patch with no
2130 2114 guards is always pushed. A patch with a positive guard ("+foo") is
2131 2115 pushed only if the qselect command has activated it. A patch with
2132 2116 a negative guard ("-foo") is never pushed if the qselect command
2133 2117 has activated it.
2134 2118
2135 2119 With no arguments, print the currently active guards.
2136 2120 With arguments, set guards for the named patch.
2137 2121 NOTE: Specifying negative guards now requires '--'.
2138 2122
2139 2123 To set guards on another patch::
2140 2124
2141 2125 hg qguard other.patch -- +2.6.17 -stable
2142 2126 '''
2143 2127 def status(idx):
2144 2128 guards = q.series_guards[idx] or ['unguarded']
2145 2129 ui.write('%s: ' % ui.label(q.series[idx], 'qguard.patch'))
2146 2130 for i, guard in enumerate(guards):
2147 2131 if guard.startswith('+'):
2148 2132 ui.write(guard, label='qguard.positive')
2149 2133 elif guard.startswith('-'):
2150 2134 ui.write(guard, label='qguard.negative')
2151 2135 else:
2152 2136 ui.write(guard, label='qguard.unguarded')
2153 2137 if i != len(guards) - 1:
2154 2138 ui.write(' ')
2155 2139 ui.write('\n')
2156 2140 q = repo.mq
2157 2141 patch = None
2158 2142 args = list(args)
2159 2143 if opts['list']:
2160 2144 if args or opts['none']:
2161 2145 raise util.Abort(_('cannot mix -l/--list with options or arguments'))
2162 2146 for i in xrange(len(q.series)):
2163 2147 status(i)
2164 2148 return
2165 2149 if not args or args[0][0:1] in '-+':
2166 2150 if not q.applied:
2167 2151 raise util.Abort(_('no patches applied'))
2168 2152 patch = q.applied[-1].name
2169 2153 if patch is None and args[0][0:1] not in '-+':
2170 2154 patch = args.pop(0)
2171 2155 if patch is None:
2172 2156 raise util.Abort(_('no patch to work with'))
2173 2157 if args or opts['none']:
2174 2158 idx = q.find_series(patch)
2175 2159 if idx is None:
2176 2160 raise util.Abort(_('no patch named %s') % patch)
2177 2161 q.set_guards(idx, args)
2178 2162 q.save_dirty()
2179 2163 else:
2180 2164 status(q.series.index(q.lookup(patch)))
2181 2165
2182 2166 def header(ui, repo, patch=None):
2183 2167 """print the header of the topmost or specified patch"""
2184 2168 q = repo.mq
2185 2169
2186 2170 if patch:
2187 2171 patch = q.lookup(patch)
2188 2172 else:
2189 2173 if not q.applied:
2190 2174 ui.write(_('no patches applied\n'))
2191 2175 return 1
2192 2176 patch = q.lookup('qtip')
2193 2177 ph = patchheader(q.join(patch), q.plainmode)
2194 2178
2195 2179 ui.write('\n'.join(ph.message) + '\n')
2196 2180
2197 2181 def lastsavename(path):
2198 2182 (directory, base) = os.path.split(path)
2199 2183 names = os.listdir(directory)
2200 2184 namere = re.compile("%s.([0-9]+)" % base)
2201 2185 maxindex = None
2202 2186 maxname = None
2203 2187 for f in names:
2204 2188 m = namere.match(f)
2205 2189 if m:
2206 2190 index = int(m.group(1))
2207 2191 if maxindex is None or index > maxindex:
2208 2192 maxindex = index
2209 2193 maxname = f
2210 2194 if maxname:
2211 2195 return (os.path.join(directory, maxname), maxindex)
2212 2196 return (None, None)
2213 2197
2214 2198 def savename(path):
2215 2199 (last, index) = lastsavename(path)
2216 2200 if last is None:
2217 2201 index = 0
2218 2202 newpath = path + ".%d" % (index + 1)
2219 2203 return newpath
2220 2204
2221 2205 def push(ui, repo, patch=None, **opts):
2222 2206 """push the next patch onto the stack
2223 2207
2224 2208 When -f/--force is applied, all local changes in patched files
2225 2209 will be lost.
2226 2210 """
2227 2211 q = repo.mq
2228 2212 mergeq = None
2229 2213
2230 2214 if opts['merge']:
2231 2215 if opts['name']:
2232 2216 newpath = repo.join(opts['name'])
2233 2217 else:
2234 2218 newpath, i = lastsavename(q.path)
2235 2219 if not newpath:
2236 2220 ui.warn(_("no saved queues found, please use -n\n"))
2237 2221 return 1
2238 2222 mergeq = queue(ui, repo.join(""), newpath)
2239 2223 ui.warn(_("merging with queue at: %s\n") % mergeq.path)
2240 2224 ret = q.push(repo, patch, force=opts['force'], list=opts['list'],
2241 2225 mergeq=mergeq, all=opts.get('all'))
2242 2226 return ret
2243 2227
2244 2228 def pop(ui, repo, patch=None, **opts):
2245 2229 """pop the current patch off the stack
2246 2230
2247 2231 By default, pops off the top of the patch stack. If given a patch
2248 2232 name, keeps popping off patches until the named patch is at the
2249 2233 top of the stack.
2250 2234 """
2251 2235 localupdate = True
2252 2236 if opts['name']:
2253 2237 q = queue(ui, repo.join(""), repo.join(opts['name']))
2254 2238 ui.warn(_('using patch queue: %s\n') % q.path)
2255 2239 localupdate = False
2256 2240 else:
2257 2241 q = repo.mq
2258 2242 ret = q.pop(repo, patch, force=opts['force'], update=localupdate,
2259 2243 all=opts['all'])
2260 2244 q.save_dirty()
2261 2245 return ret
2262 2246
2263 2247 def rename(ui, repo, patch, name=None, **opts):
2264 2248 """rename a patch
2265 2249
2266 2250 With one argument, renames the current patch to PATCH1.
2267 2251 With two arguments, renames PATCH1 to PATCH2."""
2268 2252
2269 2253 q = repo.mq
2270 2254
2271 2255 if not name:
2272 2256 name = patch
2273 2257 patch = None
2274 2258
2275 2259 if patch:
2276 2260 patch = q.lookup(patch)
2277 2261 else:
2278 2262 if not q.applied:
2279 2263 ui.write(_('no patches applied\n'))
2280 2264 return
2281 2265 patch = q.lookup('qtip')
2282 2266 absdest = q.join(name)
2283 2267 if os.path.isdir(absdest):
2284 2268 name = normname(os.path.join(name, os.path.basename(patch)))
2285 2269 absdest = q.join(name)
2286 2270 if os.path.exists(absdest):
2287 2271 raise util.Abort(_('%s already exists') % absdest)
2288 2272
2289 2273 if name in q.series:
2290 2274 raise util.Abort(
2291 2275 _('A patch named %s already exists in the series file') % name)
2292 2276
2293 2277 ui.note(_('renaming %s to %s\n') % (patch, name))
2294 2278 i = q.find_series(patch)
2295 2279 guards = q.guard_re.findall(q.full_series[i])
2296 2280 q.full_series[i] = name + ''.join([' #' + g for g in guards])
2297 2281 q.parse_series()
2298 2282 q.series_dirty = 1
2299 2283
2300 2284 info = q.isapplied(patch)
2301 2285 if info:
2302 2286 q.applied[info[0]] = statusentry(info[1], name)
2303 2287 q.applied_dirty = 1
2304 2288
2305 2289 util.rename(q.join(patch), absdest)
2306 2290 r = q.qrepo()
2307 2291 if r:
2308 2292 wlock = r.wlock()
2309 2293 try:
2310 2294 if r.dirstate[patch] == 'a':
2311 2295 r.dirstate.forget(patch)
2312 2296 r.dirstate.add(name)
2313 2297 else:
2314 2298 if r.dirstate[name] == 'r':
2315 2299 r.undelete([name])
2316 2300 r.copy(patch, name)
2317 2301 r.remove([patch], False)
2318 2302 finally:
2319 2303 wlock.release()
2320 2304
2321 2305 q.save_dirty()
2322 2306
2323 2307 def restore(ui, repo, rev, **opts):
2324 2308 """restore the queue state saved by a revision (DEPRECATED)
2325 2309
2326 2310 This command is deprecated, use rebase --mq instead."""
2327 2311 rev = repo.lookup(rev)
2328 2312 q = repo.mq
2329 2313 q.restore(repo, rev, delete=opts['delete'],
2330 2314 qupdate=opts['update'])
2331 2315 q.save_dirty()
2332 2316 return 0
2333 2317
2334 2318 def save(ui, repo, **opts):
2335 2319 """save current queue state (DEPRECATED)
2336 2320
2337 2321 This command is deprecated, use rebase --mq instead."""
2338 2322 q = repo.mq
2339 2323 message = cmdutil.logmessage(opts)
2340 2324 ret = q.save(repo, msg=message)
2341 2325 if ret:
2342 2326 return ret
2343 2327 q.save_dirty()
2344 2328 if opts['copy']:
2345 2329 path = q.path
2346 2330 if opts['name']:
2347 2331 newpath = os.path.join(q.basepath, opts['name'])
2348 2332 if os.path.exists(newpath):
2349 2333 if not os.path.isdir(newpath):
2350 2334 raise util.Abort(_('destination %s exists and is not '
2351 2335 'a directory') % newpath)
2352 2336 if not opts['force']:
2353 2337 raise util.Abort(_('destination %s exists, '
2354 2338 'use -f to force') % newpath)
2355 2339 else:
2356 2340 newpath = savename(path)
2357 2341 ui.warn(_("copy %s to %s\n") % (path, newpath))
2358 2342 util.copyfiles(path, newpath)
2359 2343 if opts['empty']:
2360 2344 try:
2361 2345 os.unlink(q.join(q.status_path))
2362 2346 except:
2363 2347 pass
2364 2348 return 0
2365 2349
2366 2350 def strip(ui, repo, rev, **opts):
2367 2351 """strip a revision and all its descendants from the repository
2368 2352
2369 2353 If one of the working directory's parent revisions is stripped, the
2370 2354 working directory will be updated to the parent of the stripped
2371 2355 revision.
2372 2356 """
2373 2357 backup = 'all'
2374 2358 if opts['backup']:
2375 2359 backup = 'strip'
2376 2360 elif opts['nobackup']:
2377 2361 backup = 'none'
2378 2362
2379 2363 rev = repo.lookup(rev)
2380 2364 p = repo.dirstate.parents()
2381 2365 cl = repo.changelog
2382 2366 update = True
2383 2367 if p[0] == nullid:
2384 2368 update = False
2385 2369 elif p[1] == nullid and rev != cl.ancestor(p[0], rev):
2386 2370 update = False
2387 2371 elif rev not in (cl.ancestor(p[0], rev), cl.ancestor(p[1], rev)):
2388 2372 update = False
2389 2373
2390 2374 repo.mq.strip(repo, rev, backup=backup, update=update, force=opts['force'])
2391 2375 return 0
2392 2376
2393 2377 def select(ui, repo, *args, **opts):
2394 2378 '''set or print guarded patches to push
2395 2379
2396 2380 Use the qguard command to set or print guards on patch, then use
2397 2381 qselect to tell mq which guards to use. A patch will be pushed if
2398 2382 it has no guards or any positive guards match the currently
2399 2383 selected guard, but will not be pushed if any negative guards
2400 2384 match the current guard. For example::
2401 2385
2402 2386 qguard foo.patch -stable (negative guard)
2403 2387 qguard bar.patch +stable (positive guard)
2404 2388 qselect stable
2405 2389
2406 2390 This activates the "stable" guard. mq will skip foo.patch (because
2407 2391 it has a negative match) but push bar.patch (because it has a
2408 2392 positive match).
2409 2393
2410 2394 With no arguments, prints the currently active guards.
2411 2395 With one argument, sets the active guard.
2412 2396
2413 2397 Use -n/--none to deactivate guards (no other arguments needed).
2414 2398 When no guards are active, patches with positive guards are
2415 2399 skipped and patches with negative guards are pushed.
2416 2400
2417 2401 qselect can change the guards on applied patches. It does not pop
2418 2402 guarded patches by default. Use --pop to pop back to the last
2419 2403 applied patch that is not guarded. Use --reapply (which implies
2420 2404 --pop) to push back to the current patch afterwards, but skip
2421 2405 guarded patches.
2422 2406
2423 2407 Use -s/--series to print a list of all guards in the series file
2424 2408 (no other arguments needed). Use -v for more information.'''
2425 2409
2426 2410 q = repo.mq
2427 2411 guards = q.active()
2428 2412 if args or opts['none']:
2429 2413 old_unapplied = q.unapplied(repo)
2430 2414 old_guarded = [i for i in xrange(len(q.applied)) if
2431 2415 not q.pushable(i)[0]]
2432 2416 q.set_active(args)
2433 2417 q.save_dirty()
2434 2418 if not args:
2435 2419 ui.status(_('guards deactivated\n'))
2436 2420 if not opts['pop'] and not opts['reapply']:
2437 2421 unapplied = q.unapplied(repo)
2438 2422 guarded = [i for i in xrange(len(q.applied))
2439 2423 if not q.pushable(i)[0]]
2440 2424 if len(unapplied) != len(old_unapplied):
2441 2425 ui.status(_('number of unguarded, unapplied patches has '
2442 2426 'changed from %d to %d\n') %
2443 2427 (len(old_unapplied), len(unapplied)))
2444 2428 if len(guarded) != len(old_guarded):
2445 2429 ui.status(_('number of guarded, applied patches has changed '
2446 2430 'from %d to %d\n') %
2447 2431 (len(old_guarded), len(guarded)))
2448 2432 elif opts['series']:
2449 2433 guards = {}
2450 2434 noguards = 0
2451 2435 for gs in q.series_guards:
2452 2436 if not gs:
2453 2437 noguards += 1
2454 2438 for g in gs:
2455 2439 guards.setdefault(g, 0)
2456 2440 guards[g] += 1
2457 2441 if ui.verbose:
2458 2442 guards['NONE'] = noguards
2459 2443 guards = guards.items()
2460 2444 guards.sort(key=lambda x: x[0][1:])
2461 2445 if guards:
2462 2446 ui.note(_('guards in series file:\n'))
2463 2447 for guard, count in guards:
2464 2448 ui.note('%2d ' % count)
2465 2449 ui.write(guard, '\n')
2466 2450 else:
2467 2451 ui.note(_('no guards in series file\n'))
2468 2452 else:
2469 2453 if guards:
2470 2454 ui.note(_('active guards:\n'))
2471 2455 for g in guards:
2472 2456 ui.write(g, '\n')
2473 2457 else:
2474 2458 ui.write(_('no active guards\n'))
2475 2459 reapply = opts['reapply'] and q.applied and q.appliedname(-1)
2476 2460 popped = False
2477 2461 if opts['pop'] or opts['reapply']:
2478 2462 for i in xrange(len(q.applied)):
2479 2463 pushable, reason = q.pushable(i)
2480 2464 if not pushable:
2481 2465 ui.status(_('popping guarded patches\n'))
2482 2466 popped = True
2483 2467 if i == 0:
2484 2468 q.pop(repo, all=True)
2485 2469 else:
2486 2470 q.pop(repo, i - 1)
2487 2471 break
2488 2472 if popped:
2489 2473 try:
2490 2474 if reapply:
2491 2475 ui.status(_('reapplying unguarded patches\n'))
2492 2476 q.push(repo, reapply)
2493 2477 finally:
2494 2478 q.save_dirty()
2495 2479
2496 2480 def finish(ui, repo, *revrange, **opts):
2497 2481 """move applied patches into repository history
2498 2482
2499 2483 Finishes the specified revisions (corresponding to applied
2500 2484 patches) by moving them out of mq control into regular repository
2501 2485 history.
2502 2486
2503 2487 Accepts a revision range or the -a/--applied option. If --applied
2504 2488 is specified, all applied mq revisions are removed from mq
2505 2489 control. Otherwise, the given revisions must be at the base of the
2506 2490 stack of applied patches.
2507 2491
2508 2492 This can be especially useful if your changes have been applied to
2509 2493 an upstream repository, or if you are about to push your changes
2510 2494 to upstream.
2511 2495 """
2512 2496 if not opts['applied'] and not revrange:
2513 2497 raise util.Abort(_('no revisions specified'))
2514 2498 elif opts['applied']:
2515 2499 revrange = ('qbase:qtip',) + revrange
2516 2500
2517 2501 q = repo.mq
2518 2502 if not q.applied:
2519 2503 ui.status(_('no patches applied\n'))
2520 2504 return 0
2521 2505
2522 2506 revs = cmdutil.revrange(repo, revrange)
2523 2507 q.finish(repo, revs)
2524 2508 q.save_dirty()
2525 2509 return 0
2526 2510
2527 2511 def reposetup(ui, repo):
2528 2512 class mqrepo(repo.__class__):
2529 2513 @util.propertycache
2530 2514 def mq(self):
2531 2515 return queue(self.ui, self.join(""))
2532 2516
2533 2517 def abort_if_wdir_patched(self, errmsg, force=False):
2534 2518 if self.mq.applied and not force:
2535 2519 parent = self.dirstate.parents()[0]
2536 2520 if parent in [s.node for s in self.mq.applied]:
2537 2521 raise util.Abort(errmsg)
2538 2522
2539 2523 def commit(self, text="", user=None, date=None, match=None,
2540 2524 force=False, editor=False, extra={}):
2541 2525 self.abort_if_wdir_patched(
2542 2526 _('cannot commit over an applied mq patch'),
2543 2527 force)
2544 2528
2545 2529 return super(mqrepo, self).commit(text, user, date, match, force,
2546 2530 editor, extra)
2547 2531
2548 2532 def push(self, remote, force=False, revs=None):
2549 2533 if self.mq.applied and not force and not revs:
2550 2534 raise util.Abort(_('source has mq patches applied'))
2551 2535 return super(mqrepo, self).push(remote, force, revs)
2552 2536
2553 2537 def _findtags(self):
2554 2538 '''augment tags from base class with patch tags'''
2555 2539 result = super(mqrepo, self)._findtags()
2556 2540
2557 2541 q = self.mq
2558 2542 if not q.applied:
2559 2543 return result
2560 2544
2561 2545 mqtags = [(patch.node, patch.name) for patch in q.applied]
2562 2546
2563 2547 if mqtags[-1][0] not in self.changelog.nodemap:
2564 2548 self.ui.warn(_('mq status file refers to unknown node %s\n')
2565 2549 % short(mqtags[-1][0]))
2566 2550 return result
2567 2551
2568 2552 mqtags.append((mqtags[-1][0], 'qtip'))
2569 2553 mqtags.append((mqtags[0][0], 'qbase'))
2570 2554 mqtags.append((self.changelog.parents(mqtags[0][0])[0], 'qparent'))
2571 2555 tags = result[0]
2572 2556 for patch in mqtags:
2573 2557 if patch[1] in tags:
2574 2558 self.ui.warn(_('Tag %s overrides mq patch of the same name\n')
2575 2559 % patch[1])
2576 2560 else:
2577 2561 tags[patch[1]] = patch[0]
2578 2562
2579 2563 return result
2580 2564
2581 2565 def _branchtags(self, partial, lrev):
2582 2566 q = self.mq
2583 2567 if not q.applied:
2584 2568 return super(mqrepo, self)._branchtags(partial, lrev)
2585 2569
2586 2570 cl = self.changelog
2587 2571 qbasenode = q.applied[0].node
2588 2572 if qbasenode not in cl.nodemap:
2589 2573 self.ui.warn(_('mq status file refers to unknown node %s\n')
2590 2574 % short(qbasenode))
2591 2575 return super(mqrepo, self)._branchtags(partial, lrev)
2592 2576
2593 2577 qbase = cl.rev(qbasenode)
2594 2578 start = lrev + 1
2595 2579 if start < qbase:
2596 2580 # update the cache (excluding the patches) and save it
2597 2581 ctxgen = (self[r] for r in xrange(lrev + 1, qbase))
2598 2582 self._updatebranchcache(partial, ctxgen)
2599 2583 self._writebranchcache(partial, cl.node(qbase - 1), qbase - 1)
2600 2584 start = qbase
2601 2585 # if start = qbase, the cache is as updated as it should be.
2602 2586 # if start > qbase, the cache includes (part of) the patches.
2603 2587 # we might as well use it, but we won't save it.
2604 2588
2605 2589 # update the cache up to the tip
2606 2590 ctxgen = (self[r] for r in xrange(start, len(cl)))
2607 2591 self._updatebranchcache(partial, ctxgen)
2608 2592
2609 2593 return partial
2610 2594
2611 2595 if repo.local():
2612 2596 repo.__class__ = mqrepo
2613 2597
2614 2598 def mqimport(orig, ui, repo, *args, **kwargs):
2615 2599 if (hasattr(repo, 'abort_if_wdir_patched')
2616 2600 and not kwargs.get('no_commit', False)):
2617 2601 repo.abort_if_wdir_patched(_('cannot import over an applied patch'),
2618 2602 kwargs.get('force'))
2619 2603 return orig(ui, repo, *args, **kwargs)
2620 2604
2621 2605 def mqinit(orig, ui, *args, **kwargs):
2622 2606 mq = kwargs.pop('mq', None)
2623 2607
2624 2608 if not mq:
2625 2609 return orig(ui, *args, **kwargs)
2626 2610
2627 2611 if args:
2628 2612 repopath = args[0]
2629 2613 if not hg.islocal(repopath):
2630 2614 raise util.Abort(_('only a local queue repository '
2631 2615 'may be initialized'))
2632 2616 else:
2633 2617 repopath = cmdutil.findrepo(os.getcwd())
2634 2618 if not repopath:
2635 2619 raise util.Abort(_('There is no Mercurial repository here '
2636 2620 '(.hg not found)'))
2637 2621 repo = hg.repository(ui, repopath)
2638 2622 return qinit(ui, repo, True)
2639 2623
2640 2624 def mqcommand(orig, ui, repo, *args, **kwargs):
2641 2625 """Add --mq option to operate on patch repository instead of main"""
2642 2626
2643 2627 # some commands do not like getting unknown options
2644 2628 mq = kwargs.pop('mq', None)
2645 2629
2646 2630 if not mq:
2647 2631 return orig(ui, repo, *args, **kwargs)
2648 2632
2649 2633 q = repo.mq
2650 2634 r = q.qrepo()
2651 2635 if not r:
2652 2636 raise util.Abort('no queue repository')
2653 2637 return orig(r.ui, r, *args, **kwargs)
2654 2638
2655 2639 def uisetup(ui):
2656 2640 mqopt = [('', 'mq', None, _("operate on patch repository"))]
2657 2641
2658 2642 extensions.wrapcommand(commands.table, 'import', mqimport)
2659 2643
2660 2644 entry = extensions.wrapcommand(commands.table, 'init', mqinit)
2661 2645 entry[1].extend(mqopt)
2662 2646
2663 2647 norepo = commands.norepo.split(" ")
2664 2648 for cmd in commands.table.keys():
2665 2649 cmd = cmdutil.parsealiases(cmd)[0]
2666 2650 if cmd in norepo:
2667 2651 continue
2668 2652 entry = extensions.wrapcommand(commands.table, cmd, mqcommand)
2669 2653 entry[1].extend(mqopt)
2670 2654
2671 2655 seriesopts = [('s', 'summary', None, _('print first line of patch header'))]
2672 2656
2673 2657 cmdtable = {
2674 2658 "qapplied":
2675 2659 (applied,
2676 2660 [('1', 'last', None, _('show only the last patch'))] + seriesopts,
2677 2661 _('hg qapplied [-1] [-s] [PATCH]')),
2678 2662 "qclone":
2679 2663 (clone,
2680 2664 [('', 'pull', None, _('use pull protocol to copy metadata')),
2681 2665 ('U', 'noupdate', None, _('do not update the new working directories')),
2682 2666 ('', 'uncompressed', None,
2683 2667 _('use uncompressed transfer (fast over LAN)')),
2684 2668 ('p', 'patches', '', _('location of source patch repository')),
2685 2669 ] + commands.remoteopts,
2686 2670 _('hg qclone [OPTION]... SOURCE [DEST]')),
2687 2671 "qcommit|qci":
2688 2672 (commit,
2689 2673 commands.table["^commit|ci"][1],
2690 2674 _('hg qcommit [OPTION]... [FILE]...')),
2691 2675 "^qdiff":
2692 2676 (diff,
2693 2677 commands.diffopts + commands.diffopts2 + commands.walkopts,
2694 2678 _('hg qdiff [OPTION]... [FILE]...')),
2695 2679 "qdelete|qremove|qrm":
2696 2680 (delete,
2697 2681 [('k', 'keep', None, _('keep patch file')),
2698 2682 ('r', 'rev', [], _('stop managing a revision (DEPRECATED)'))],
2699 2683 _('hg qdelete [-k] [-r REV]... [PATCH]...')),
2700 2684 'qfold':
2701 2685 (fold,
2702 2686 [('e', 'edit', None, _('edit patch header')),
2703 2687 ('k', 'keep', None, _('keep folded patch files')),
2704 2688 ] + commands.commitopts,
2705 2689 _('hg qfold [-e] [-k] [-m TEXT] [-l FILE] PATCH...')),
2706 2690 'qgoto':
2707 2691 (goto,
2708 2692 [('f', 'force', None, _('overwrite any local changes'))],
2709 2693 _('hg qgoto [OPTION]... PATCH')),
2710 2694 'qguard':
2711 2695 (guard,
2712 2696 [('l', 'list', None, _('list all patches and guards')),
2713 2697 ('n', 'none', None, _('drop all guards'))],
2714 2698 _('hg qguard [-l] [-n] [PATCH] [-- [+GUARD]... [-GUARD]...]')),
2715 2699 'qheader': (header, [], _('hg qheader [PATCH]')),
2716 2700 "qimport":
2717 2701 (qimport,
2718 2702 [('e', 'existing', None, _('import file in patch directory')),
2719 2703 ('n', 'name', '', _('name of patch file')),
2720 2704 ('f', 'force', None, _('overwrite existing files')),
2721 2705 ('r', 'rev', [], _('place existing revisions under mq control')),
2722 2706 ('g', 'git', None, _('use git extended diff format')),
2723 2707 ('P', 'push', None, _('qpush after importing'))],
2724 2708 _('hg qimport [-e] [-n NAME] [-f] [-g] [-P] [-r REV]... FILE...')),
2725 2709 "^qinit":
2726 2710 (init,
2727 2711 [('c', 'create-repo', None, _('create queue repository'))],
2728 2712 _('hg qinit [-c]')),
2729 2713 "^qnew":
2730 2714 (new,
2731 2715 [('e', 'edit', None, _('edit commit message')),
2732 2716 ('f', 'force', None, _('import uncommitted changes (DEPRECATED)')),
2733 2717 ('g', 'git', None, _('use git extended diff format')),
2734 2718 ('U', 'currentuser', None, _('add "From: <current user>" to patch')),
2735 2719 ('u', 'user', '', _('add "From: <given user>" to patch')),
2736 2720 ('D', 'currentdate', None, _('add "Date: <current date>" to patch')),
2737 2721 ('d', 'date', '', _('add "Date: <given date>" to patch'))
2738 2722 ] + commands.walkopts + commands.commitopts,
2739 2723 _('hg qnew [-e] [-m TEXT] [-l FILE] PATCH [FILE]...')),
2740 2724 "qnext": (next, [] + seriesopts, _('hg qnext [-s]')),
2741 2725 "qprev": (prev, [] + seriesopts, _('hg qprev [-s]')),
2742 2726 "^qpop":
2743 2727 (pop,
2744 2728 [('a', 'all', None, _('pop all patches')),
2745 2729 ('n', 'name', '', _('queue name to pop (DEPRECATED)')),
2746 2730 ('f', 'force', None, _('forget any local changes to patched files'))],
2747 2731 _('hg qpop [-a] [-n NAME] [-f] [PATCH | INDEX]')),
2748 2732 "^qpush":
2749 2733 (push,
2750 2734 [('f', 'force', None, _('apply if the patch has rejects')),
2751 2735 ('l', 'list', None, _('list patch name in commit text')),
2752 2736 ('a', 'all', None, _('apply all patches')),
2753 2737 ('m', 'merge', None, _('merge from another queue (DEPRECATED)')),
2754 2738 ('n', 'name', '', _('merge queue name (DEPRECATED)'))],
2755 2739 _('hg qpush [-f] [-l] [-a] [-m] [-n NAME] [PATCH | INDEX]')),
2756 2740 "^qrefresh":
2757 2741 (refresh,
2758 2742 [('e', 'edit', None, _('edit commit message')),
2759 2743 ('g', 'git', None, _('use git extended diff format')),
2760 2744 ('s', 'short', None,
2761 2745 _('refresh only files already in the patch and specified files')),
2762 2746 ('U', 'currentuser', None,
2763 2747 _('add/update author field in patch with current user')),
2764 2748 ('u', 'user', '',
2765 2749 _('add/update author field in patch with given user')),
2766 2750 ('D', 'currentdate', None,
2767 2751 _('add/update date field in patch with current date')),
2768 2752 ('d', 'date', '',
2769 2753 _('add/update date field in patch with given date'))
2770 2754 ] + commands.walkopts + commands.commitopts,
2771 2755 _('hg qrefresh [-I] [-X] [-e] [-m TEXT] [-l FILE] [-s] [FILE]...')),
2772 2756 'qrename|qmv':
2773 2757 (rename, [], _('hg qrename PATCH1 [PATCH2]')),
2774 2758 "qrestore":
2775 2759 (restore,
2776 2760 [('d', 'delete', None, _('delete save entry')),
2777 2761 ('u', 'update', None, _('update queue working directory'))],
2778 2762 _('hg qrestore [-d] [-u] REV')),
2779 2763 "qsave":
2780 2764 (save,
2781 2765 [('c', 'copy', None, _('copy patch directory')),
2782 2766 ('n', 'name', '', _('copy directory name')),
2783 2767 ('e', 'empty', None, _('clear queue status file')),
2784 2768 ('f', 'force', None, _('force copy'))] + commands.commitopts,
2785 2769 _('hg qsave [-m TEXT] [-l FILE] [-c] [-n NAME] [-e] [-f]')),
2786 2770 "qselect":
2787 2771 (select,
2788 2772 [('n', 'none', None, _('disable all guards')),
2789 2773 ('s', 'series', None, _('list all guards in series file')),
2790 2774 ('', 'pop', None, _('pop to before first guarded applied patch')),
2791 2775 ('', 'reapply', None, _('pop, then reapply patches'))],
2792 2776 _('hg qselect [OPTION]... [GUARD]...')),
2793 2777 "qseries":
2794 2778 (series,
2795 2779 [('m', 'missing', None, _('print patches not in series')),
2796 2780 ] + seriesopts,
2797 2781 _('hg qseries [-ms]')),
2798 2782 "strip":
2799 2783 (strip,
2800 2784 [('f', 'force', None, _('force removal with local changes')),
2801 2785 ('b', 'backup', None, _('bundle unrelated changesets')),
2802 2786 ('n', 'nobackup', None, _('no backups'))],
2803 2787 _('hg strip [-f] [-b] [-n] REV')),
2804 2788 "qtop": (top, [] + seriesopts, _('hg qtop [-s]')),
2805 2789 "qunapplied":
2806 2790 (unapplied,
2807 2791 [('1', 'first', None, _('show only the first patch'))] + seriesopts,
2808 2792 _('hg qunapplied [-1] [-s] [PATCH]')),
2809 2793 "qfinish":
2810 2794 (finish,
2811 2795 [('a', 'applied', None, _('finish all applied changesets'))],
2812 2796 _('hg qfinish [-a] [REV]...')),
2813 2797 }
2814 2798
2815 2799 colortable = {'qguard.negative': 'red',
2816 2800 'qguard.positive': 'yellow',
2817 2801 'qguard.unguarded': 'green',
2818 2802 'qseries.applied': 'blue bold underline',
2819 2803 'qseries.guarded': 'black bold',
2820 2804 'qseries.missing': 'red bold',
2821 2805 'qseries.unapplied': 'black bold'}
@@ -1,1261 +1,1285 b''
1 1 # cmdutil.py - help for command processing in 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, nullid, nullrev, short
9 9 from i18n import _
10 10 import os, sys, errno, re, glob, tempfile
11 11 import mdiff, bdiff, util, templater, patch, error, encoding, templatekw
12 12 import match as _match
13 13
14 14 revrangesep = ':'
15 15
16 16 def parsealiases(cmd):
17 17 return cmd.lstrip("^").split("|")
18 18
19 19 def findpossible(cmd, table, strict=False):
20 20 """
21 21 Return cmd -> (aliases, command table entry)
22 22 for each matching command.
23 23 Return debug commands (or their aliases) only if no normal command matches.
24 24 """
25 25 choice = {}
26 26 debugchoice = {}
27 27 for e in table.keys():
28 28 aliases = parsealiases(e)
29 29 found = None
30 30 if cmd in aliases:
31 31 found = cmd
32 32 elif not strict:
33 33 for a in aliases:
34 34 if a.startswith(cmd):
35 35 found = a
36 36 break
37 37 if found is not None:
38 38 if aliases[0].startswith("debug") or found.startswith("debug"):
39 39 debugchoice[found] = (aliases, table[e])
40 40 else:
41 41 choice[found] = (aliases, table[e])
42 42
43 43 if not choice and debugchoice:
44 44 choice = debugchoice
45 45
46 46 return choice
47 47
48 48 def findcmd(cmd, table, strict=True):
49 49 """Return (aliases, command table entry) for command string."""
50 50 choice = findpossible(cmd, table, strict)
51 51
52 52 if cmd in choice:
53 53 return choice[cmd]
54 54
55 55 if len(choice) > 1:
56 56 clist = choice.keys()
57 57 clist.sort()
58 58 raise error.AmbiguousCommand(cmd, clist)
59 59
60 60 if choice:
61 61 return choice.values()[0]
62 62
63 63 raise error.UnknownCommand(cmd)
64 64
65 65 def findrepo(p):
66 66 while not os.path.isdir(os.path.join(p, ".hg")):
67 67 oldp, p = p, os.path.dirname(p)
68 68 if p == oldp:
69 69 return None
70 70
71 71 return p
72 72
73 73 def bail_if_changed(repo):
74 74 if repo.dirstate.parents()[1] != nullid:
75 75 raise util.Abort(_('outstanding uncommitted merge'))
76 76 modified, added, removed, deleted = repo.status()[:4]
77 77 if modified or added or removed or deleted:
78 78 raise util.Abort(_("outstanding uncommitted changes"))
79 79
80 80 def logmessage(opts):
81 81 """ get the log message according to -m and -l option """
82 82 message = opts.get('message')
83 83 logfile = opts.get('logfile')
84 84
85 85 if message and logfile:
86 86 raise util.Abort(_('options --message and --logfile are mutually '
87 87 'exclusive'))
88 88 if not message and logfile:
89 89 try:
90 90 if logfile == '-':
91 91 message = sys.stdin.read()
92 92 else:
93 93 message = open(logfile).read()
94 94 except IOError, inst:
95 95 raise util.Abort(_("can't read commit message '%s': %s") %
96 96 (logfile, inst.strerror))
97 97 return message
98 98
99 99 def loglimit(opts):
100 100 """get the log limit according to option -l/--limit"""
101 101 limit = opts.get('limit')
102 102 if limit:
103 103 try:
104 104 limit = int(limit)
105 105 except ValueError:
106 106 raise util.Abort(_('limit must be a positive integer'))
107 107 if limit <= 0:
108 108 raise util.Abort(_('limit must be positive'))
109 109 else:
110 110 limit = None
111 111 return limit
112 112
113 113 def remoteui(src, opts):
114 114 'build a remote ui from ui or repo and opts'
115 115 if hasattr(src, 'baseui'): # looks like a repository
116 116 dst = src.baseui.copy() # drop repo-specific config
117 117 src = src.ui # copy target options from repo
118 118 else: # assume it's a global ui object
119 119 dst = src.copy() # keep all global options
120 120
121 121 # copy ssh-specific options
122 122 for o in 'ssh', 'remotecmd':
123 123 v = opts.get(o) or src.config('ui', o)
124 124 if v:
125 125 dst.setconfig("ui", o, v)
126 126
127 127 # copy bundle-specific options
128 128 r = src.config('bundle', 'mainreporoot')
129 129 if r:
130 130 dst.setconfig('bundle', 'mainreporoot', r)
131 131
132 132 # copy auth and http_proxy section settings
133 133 for sect in ('auth', 'http_proxy'):
134 134 for key, val in src.configitems(sect):
135 135 dst.setconfig(sect, key, val)
136 136
137 137 return dst
138 138
139 139 def revpair(repo, revs):
140 140 '''return pair of nodes, given list of revisions. second item can
141 141 be None, meaning use working dir.'''
142 142
143 143 def revfix(repo, val, defval):
144 144 if not val and val != 0 and defval is not None:
145 145 val = defval
146 146 return repo.lookup(val)
147 147
148 148 if not revs:
149 149 return repo.dirstate.parents()[0], None
150 150 end = None
151 151 if len(revs) == 1:
152 152 if revrangesep in revs[0]:
153 153 start, end = revs[0].split(revrangesep, 1)
154 154 start = revfix(repo, start, 0)
155 155 end = revfix(repo, end, len(repo) - 1)
156 156 else:
157 157 start = revfix(repo, revs[0], None)
158 158 elif len(revs) == 2:
159 159 if revrangesep in revs[0] or revrangesep in revs[1]:
160 160 raise util.Abort(_('too many revisions specified'))
161 161 start = revfix(repo, revs[0], None)
162 162 end = revfix(repo, revs[1], None)
163 163 else:
164 164 raise util.Abort(_('too many revisions specified'))
165 165 return start, end
166 166
167 167 def revrange(repo, revs):
168 168 """Yield revision as strings from a list of revision specifications."""
169 169
170 170 def revfix(repo, val, defval):
171 171 if not val and val != 0 and defval is not None:
172 172 return defval
173 173 return repo.changelog.rev(repo.lookup(val))
174 174
175 175 seen, l = set(), []
176 176 for spec in revs:
177 177 if revrangesep in spec:
178 178 start, end = spec.split(revrangesep, 1)
179 179 start = revfix(repo, start, 0)
180 180 end = revfix(repo, end, len(repo) - 1)
181 181 step = start > end and -1 or 1
182 182 for rev in xrange(start, end + step, step):
183 183 if rev in seen:
184 184 continue
185 185 seen.add(rev)
186 186 l.append(rev)
187 187 else:
188 188 rev = revfix(repo, spec, None)
189 189 if rev in seen:
190 190 continue
191 191 seen.add(rev)
192 192 l.append(rev)
193 193
194 194 return l
195 195
196 196 def make_filename(repo, pat, node,
197 197 total=None, seqno=None, revwidth=None, pathname=None):
198 198 node_expander = {
199 199 'H': lambda: hex(node),
200 200 'R': lambda: str(repo.changelog.rev(node)),
201 201 'h': lambda: short(node),
202 202 }
203 203 expander = {
204 204 '%': lambda: '%',
205 205 'b': lambda: os.path.basename(repo.root),
206 206 }
207 207
208 208 try:
209 209 if node:
210 210 expander.update(node_expander)
211 211 if node:
212 212 expander['r'] = (lambda:
213 213 str(repo.changelog.rev(node)).zfill(revwidth or 0))
214 214 if total is not None:
215 215 expander['N'] = lambda: str(total)
216 216 if seqno is not None:
217 217 expander['n'] = lambda: str(seqno)
218 218 if total is not None and seqno is not None:
219 219 expander['n'] = lambda: str(seqno).zfill(len(str(total)))
220 220 if pathname is not None:
221 221 expander['s'] = lambda: os.path.basename(pathname)
222 222 expander['d'] = lambda: os.path.dirname(pathname) or '.'
223 223 expander['p'] = lambda: pathname
224 224
225 225 newname = []
226 226 patlen = len(pat)
227 227 i = 0
228 228 while i < patlen:
229 229 c = pat[i]
230 230 if c == '%':
231 231 i += 1
232 232 c = pat[i]
233 233 c = expander[c]()
234 234 newname.append(c)
235 235 i += 1
236 236 return ''.join(newname)
237 237 except KeyError, inst:
238 238 raise util.Abort(_("invalid format spec '%%%s' in output filename") %
239 239 inst.args[0])
240 240
241 241 def make_file(repo, pat, node=None,
242 242 total=None, seqno=None, revwidth=None, mode='wb', pathname=None):
243 243
244 244 writable = 'w' in mode or 'a' in mode
245 245
246 246 if not pat or pat == '-':
247 247 return writable and sys.stdout or sys.stdin
248 248 if hasattr(pat, 'write') and writable:
249 249 return pat
250 250 if hasattr(pat, 'read') and 'r' in mode:
251 251 return pat
252 252 return open(make_filename(repo, pat, node, total, seqno, revwidth,
253 253 pathname),
254 254 mode)
255 255
256 256 def expandpats(pats):
257 257 if not util.expandglobs:
258 258 return list(pats)
259 259 ret = []
260 260 for p in pats:
261 261 kind, name = _match._patsplit(p, None)
262 262 if kind is None:
263 263 try:
264 264 globbed = glob.glob(name)
265 265 except re.error:
266 266 globbed = [name]
267 267 if globbed:
268 268 ret.extend(globbed)
269 269 continue
270 270 ret.append(p)
271 271 return ret
272 272
273 273 def match(repo, pats=[], opts={}, globbed=False, default='relpath'):
274 274 if not globbed and default == 'relpath':
275 275 pats = expandpats(pats or [])
276 276 m = _match.match(repo.root, repo.getcwd(), pats,
277 277 opts.get('include'), opts.get('exclude'), default)
278 278 def badfn(f, msg):
279 279 repo.ui.warn("%s: %s\n" % (m.rel(f), msg))
280 280 m.bad = badfn
281 281 return m
282 282
283 283 def matchall(repo):
284 284 return _match.always(repo.root, repo.getcwd())
285 285
286 286 def matchfiles(repo, files):
287 287 return _match.exact(repo.root, repo.getcwd(), files)
288 288
289 289 def findrenames(repo, added, removed, threshold):
290 290 '''find renamed files -- yields (before, after, score) tuples'''
291 291 copies = {}
292 292 ctx = repo['.']
293 293 for i, r in enumerate(removed):
294 294 repo.ui.progress(_('searching'), i, total=len(removed))
295 295 if r not in ctx:
296 296 continue
297 297 fctx = ctx.filectx(r)
298 298
299 299 # lazily load text
300 300 @util.cachefunc
301 301 def data():
302 302 orig = fctx.data()
303 303 return orig, mdiff.splitnewlines(orig)
304 304
305 305 def score(text):
306 306 if not len(text):
307 307 return 0.0
308 308 if not fctx.cmp(text):
309 309 return 1.0
310 310 if threshold == 1.0:
311 311 return 0.0
312 312 orig, lines = data()
313 313 # bdiff.blocks() returns blocks of matching lines
314 314 # count the number of bytes in each
315 315 equal = 0
316 316 matches = bdiff.blocks(text, orig)
317 317 for x1, x2, y1, y2 in matches:
318 318 for line in lines[y1:y2]:
319 319 equal += len(line)
320 320
321 321 lengths = len(text) + len(orig)
322 322 return equal * 2.0 / lengths
323 323
324 324 for a in added:
325 325 bestscore = copies.get(a, (None, threshold))[1]
326 326 myscore = score(repo.wread(a))
327 327 if myscore >= bestscore:
328 328 copies[a] = (r, myscore)
329 329 repo.ui.progress(_('searching'), None)
330 330
331 331 for dest, v in copies.iteritems():
332 332 source, score = v
333 333 yield source, dest, score
334 334
335 335 def addremove(repo, pats=[], opts={}, dry_run=None, similarity=None):
336 336 if dry_run is None:
337 337 dry_run = opts.get('dry_run')
338 338 if similarity is None:
339 339 similarity = float(opts.get('similarity') or 0)
340 340 # we'd use status here, except handling of symlinks and ignore is tricky
341 341 added, unknown, deleted, removed = [], [], [], []
342 342 audit_path = util.path_auditor(repo.root)
343 343 m = match(repo, pats, opts)
344 344 for abs in repo.walk(m):
345 345 target = repo.wjoin(abs)
346 346 good = True
347 347 try:
348 348 audit_path(abs)
349 349 except:
350 350 good = False
351 351 rel = m.rel(abs)
352 352 exact = m.exact(abs)
353 353 if good and abs not in repo.dirstate:
354 354 unknown.append(abs)
355 355 if repo.ui.verbose or not exact:
356 356 repo.ui.status(_('adding %s\n') % ((pats and rel) or abs))
357 357 elif repo.dirstate[abs] != 'r' and (not good or not util.lexists(target)
358 358 or (os.path.isdir(target) and not os.path.islink(target))):
359 359 deleted.append(abs)
360 360 if repo.ui.verbose or not exact:
361 361 repo.ui.status(_('removing %s\n') % ((pats and rel) or abs))
362 362 # for finding renames
363 363 elif repo.dirstate[abs] == 'r':
364 364 removed.append(abs)
365 365 elif repo.dirstate[abs] == 'a':
366 366 added.append(abs)
367 367 copies = {}
368 368 if similarity > 0:
369 369 for old, new, score in findrenames(repo, added + unknown,
370 370 removed + deleted, similarity):
371 371 if repo.ui.verbose or not m.exact(old) or not m.exact(new):
372 372 repo.ui.status(_('recording removal of %s as rename to %s '
373 373 '(%d%% similar)\n') %
374 374 (m.rel(old), m.rel(new), score * 100))
375 375 copies[new] = old
376 376
377 377 if not dry_run:
378 378 wlock = repo.wlock()
379 379 try:
380 380 repo.remove(deleted)
381 381 repo.add(unknown)
382 382 for new, old in copies.iteritems():
383 383 repo.copy(old, new)
384 384 finally:
385 385 wlock.release()
386 386
387 387 def copy(ui, repo, pats, opts, rename=False):
388 388 # called with the repo lock held
389 389 #
390 390 # hgsep => pathname that uses "/" to separate directories
391 391 # ossep => pathname that uses os.sep to separate directories
392 392 cwd = repo.getcwd()
393 393 targets = {}
394 394 after = opts.get("after")
395 395 dryrun = opts.get("dry_run")
396 396
397 397 def walkpat(pat):
398 398 srcs = []
399 399 m = match(repo, [pat], opts, globbed=True)
400 400 for abs in repo.walk(m):
401 401 state = repo.dirstate[abs]
402 402 rel = m.rel(abs)
403 403 exact = m.exact(abs)
404 404 if state in '?r':
405 405 if exact and state == '?':
406 406 ui.warn(_('%s: not copying - file is not managed\n') % rel)
407 407 if exact and state == 'r':
408 408 ui.warn(_('%s: not copying - file has been marked for'
409 409 ' remove\n') % rel)
410 410 continue
411 411 # abs: hgsep
412 412 # rel: ossep
413 413 srcs.append((abs, rel, exact))
414 414 return srcs
415 415
416 416 # abssrc: hgsep
417 417 # relsrc: ossep
418 418 # otarget: ossep
419 419 def copyfile(abssrc, relsrc, otarget, exact):
420 420 abstarget = util.canonpath(repo.root, cwd, otarget)
421 421 reltarget = repo.pathto(abstarget, cwd)
422 422 target = repo.wjoin(abstarget)
423 423 src = repo.wjoin(abssrc)
424 424 state = repo.dirstate[abstarget]
425 425
426 426 # check for collisions
427 427 prevsrc = targets.get(abstarget)
428 428 if prevsrc is not None:
429 429 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
430 430 (reltarget, repo.pathto(abssrc, cwd),
431 431 repo.pathto(prevsrc, cwd)))
432 432 return
433 433
434 434 # check for overwrites
435 435 exists = os.path.exists(target)
436 436 if not after and exists or after and state in 'mn':
437 437 if not opts['force']:
438 438 ui.warn(_('%s: not overwriting - file exists\n') %
439 439 reltarget)
440 440 return
441 441
442 442 if after:
443 443 if not exists:
444 444 return
445 445 elif not dryrun:
446 446 try:
447 447 if exists:
448 448 os.unlink(target)
449 449 targetdir = os.path.dirname(target) or '.'
450 450 if not os.path.isdir(targetdir):
451 451 os.makedirs(targetdir)
452 452 util.copyfile(src, target)
453 453 except IOError, inst:
454 454 if inst.errno == errno.ENOENT:
455 455 ui.warn(_('%s: deleted in working copy\n') % relsrc)
456 456 else:
457 457 ui.warn(_('%s: cannot copy - %s\n') %
458 458 (relsrc, inst.strerror))
459 459 return True # report a failure
460 460
461 461 if ui.verbose or not exact:
462 462 if rename:
463 463 ui.status(_('moving %s to %s\n') % (relsrc, reltarget))
464 464 else:
465 465 ui.status(_('copying %s to %s\n') % (relsrc, reltarget))
466 466
467 467 targets[abstarget] = abssrc
468 468
469 469 # fix up dirstate
470 470 origsrc = repo.dirstate.copied(abssrc) or abssrc
471 471 if abstarget == origsrc: # copying back a copy?
472 472 if state not in 'mn' and not dryrun:
473 473 repo.dirstate.normallookup(abstarget)
474 474 else:
475 475 if repo.dirstate[origsrc] == 'a' and origsrc == abssrc:
476 476 if not ui.quiet:
477 477 ui.warn(_("%s has not been committed yet, so no copy "
478 478 "data will be stored for %s.\n")
479 479 % (repo.pathto(origsrc, cwd), reltarget))
480 480 if repo.dirstate[abstarget] in '?r' and not dryrun:
481 481 repo.add([abstarget])
482 482 elif not dryrun:
483 483 repo.copy(origsrc, abstarget)
484 484
485 485 if rename and not dryrun:
486 486 repo.remove([abssrc], not after)
487 487
488 488 # pat: ossep
489 489 # dest ossep
490 490 # srcs: list of (hgsep, hgsep, ossep, bool)
491 491 # return: function that takes hgsep and returns ossep
492 492 def targetpathfn(pat, dest, srcs):
493 493 if os.path.isdir(pat):
494 494 abspfx = util.canonpath(repo.root, cwd, pat)
495 495 abspfx = util.localpath(abspfx)
496 496 if destdirexists:
497 497 striplen = len(os.path.split(abspfx)[0])
498 498 else:
499 499 striplen = len(abspfx)
500 500 if striplen:
501 501 striplen += len(os.sep)
502 502 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
503 503 elif destdirexists:
504 504 res = lambda p: os.path.join(dest,
505 505 os.path.basename(util.localpath(p)))
506 506 else:
507 507 res = lambda p: dest
508 508 return res
509 509
510 510 # pat: ossep
511 511 # dest ossep
512 512 # srcs: list of (hgsep, hgsep, ossep, bool)
513 513 # return: function that takes hgsep and returns ossep
514 514 def targetpathafterfn(pat, dest, srcs):
515 515 if _match.patkind(pat):
516 516 # a mercurial pattern
517 517 res = lambda p: os.path.join(dest,
518 518 os.path.basename(util.localpath(p)))
519 519 else:
520 520 abspfx = util.canonpath(repo.root, cwd, pat)
521 521 if len(abspfx) < len(srcs[0][0]):
522 522 # A directory. Either the target path contains the last
523 523 # component of the source path or it does not.
524 524 def evalpath(striplen):
525 525 score = 0
526 526 for s in srcs:
527 527 t = os.path.join(dest, util.localpath(s[0])[striplen:])
528 528 if os.path.exists(t):
529 529 score += 1
530 530 return score
531 531
532 532 abspfx = util.localpath(abspfx)
533 533 striplen = len(abspfx)
534 534 if striplen:
535 535 striplen += len(os.sep)
536 536 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
537 537 score = evalpath(striplen)
538 538 striplen1 = len(os.path.split(abspfx)[0])
539 539 if striplen1:
540 540 striplen1 += len(os.sep)
541 541 if evalpath(striplen1) > score:
542 542 striplen = striplen1
543 543 res = lambda p: os.path.join(dest,
544 544 util.localpath(p)[striplen:])
545 545 else:
546 546 # a file
547 547 if destdirexists:
548 548 res = lambda p: os.path.join(dest,
549 549 os.path.basename(util.localpath(p)))
550 550 else:
551 551 res = lambda p: dest
552 552 return res
553 553
554 554
555 555 pats = expandpats(pats)
556 556 if not pats:
557 557 raise util.Abort(_('no source or destination specified'))
558 558 if len(pats) == 1:
559 559 raise util.Abort(_('no destination specified'))
560 560 dest = pats.pop()
561 561 destdirexists = os.path.isdir(dest) and not os.path.islink(dest)
562 562 if not destdirexists:
563 563 if len(pats) > 1 or _match.patkind(pats[0]):
564 564 raise util.Abort(_('with multiple sources, destination must be an '
565 565 'existing directory'))
566 566 if util.endswithsep(dest):
567 567 raise util.Abort(_('destination %s is not a directory') % dest)
568 568
569 569 tfn = targetpathfn
570 570 if after:
571 571 tfn = targetpathafterfn
572 572 copylist = []
573 573 for pat in pats:
574 574 srcs = walkpat(pat)
575 575 if not srcs:
576 576 continue
577 577 copylist.append((tfn(pat, dest, srcs), srcs))
578 578 if not copylist:
579 579 raise util.Abort(_('no files to copy'))
580 580
581 581 errors = 0
582 582 for targetpath, srcs in copylist:
583 583 for abssrc, relsrc, exact in srcs:
584 584 if copyfile(abssrc, relsrc, targetpath(abssrc), exact):
585 585 errors += 1
586 586
587 587 if errors:
588 588 ui.warn(_('(consider using --after)\n'))
589 589
590 590 return errors
591 591
592 592 def service(opts, parentfn=None, initfn=None, runfn=None, logfile=None,
593 593 runargs=None, appendpid=False):
594 594 '''Run a command as a service.'''
595 595
596 596 if opts['daemon'] and not opts['daemon_pipefds']:
597 597 # Signal child process startup with file removal
598 598 lockfd, lockpath = tempfile.mkstemp(prefix='hg-service-')
599 599 os.close(lockfd)
600 600 try:
601 601 if not runargs:
602 602 runargs = util.hgcmd() + sys.argv[1:]
603 603 runargs.append('--daemon-pipefds=%s' % lockpath)
604 604 # Don't pass --cwd to the child process, because we've already
605 605 # changed directory.
606 606 for i in xrange(1, len(runargs)):
607 607 if runargs[i].startswith('--cwd='):
608 608 del runargs[i]
609 609 break
610 610 elif runargs[i].startswith('--cwd'):
611 611 del runargs[i:i + 2]
612 612 break
613 613 def condfn():
614 614 return not os.path.exists(lockpath)
615 615 pid = util.rundetached(runargs, condfn)
616 616 if pid < 0:
617 617 raise util.Abort(_('child process failed to start'))
618 618 finally:
619 619 try:
620 620 os.unlink(lockpath)
621 621 except OSError, e:
622 622 if e.errno != errno.ENOENT:
623 623 raise
624 624 if parentfn:
625 625 return parentfn(pid)
626 626 else:
627 627 return
628 628
629 629 if initfn:
630 630 initfn()
631 631
632 632 if opts['pid_file']:
633 633 mode = appendpid and 'a' or 'w'
634 634 fp = open(opts['pid_file'], mode)
635 635 fp.write(str(os.getpid()) + '\n')
636 636 fp.close()
637 637
638 638 if opts['daemon_pipefds']:
639 639 lockpath = opts['daemon_pipefds']
640 640 try:
641 641 os.setsid()
642 642 except AttributeError:
643 643 pass
644 644 os.unlink(lockpath)
645 645 util.hidewindow()
646 646 sys.stdout.flush()
647 647 sys.stderr.flush()
648 648
649 649 nullfd = os.open(util.nulldev, os.O_RDWR)
650 650 logfilefd = nullfd
651 651 if logfile:
652 652 logfilefd = os.open(logfile, os.O_RDWR | os.O_CREAT | os.O_APPEND)
653 653 os.dup2(nullfd, 0)
654 654 os.dup2(logfilefd, 1)
655 655 os.dup2(logfilefd, 2)
656 656 if nullfd not in (0, 1, 2):
657 657 os.close(nullfd)
658 658 if logfile and logfilefd not in (0, 1, 2):
659 659 os.close(logfilefd)
660 660
661 661 if runfn:
662 662 return runfn()
663 663
664 664 def export(repo, revs, template='hg-%h.patch', fp=None, switch_parent=False,
665 665 opts=None):
666 666 '''export changesets as hg patches.'''
667 667
668 668 total = len(revs)
669 669 revwidth = max([len(str(rev)) for rev in revs])
670 670
671 671 def single(rev, seqno, fp):
672 672 ctx = repo[rev]
673 673 node = ctx.node()
674 674 parents = [p.node() for p in ctx.parents() if p]
675 675 branch = ctx.branch()
676 676 if switch_parent:
677 677 parents.reverse()
678 678 prev = (parents and parents[0]) or nullid
679 679
680 680 if not fp:
681 681 fp = make_file(repo, template, node, total=total, seqno=seqno,
682 682 revwidth=revwidth, mode='ab')
683 683 if fp != sys.stdout and hasattr(fp, 'name'):
684 684 repo.ui.note("%s\n" % fp.name)
685 685
686 686 fp.write("# HG changeset patch\n")
687 687 fp.write("# User %s\n" % ctx.user())
688 688 fp.write("# Date %d %d\n" % ctx.date())
689 689 if branch and (branch != 'default'):
690 690 fp.write("# Branch %s\n" % branch)
691 691 fp.write("# Node ID %s\n" % hex(node))
692 692 fp.write("# Parent %s\n" % hex(prev))
693 693 if len(parents) > 1:
694 694 fp.write("# Parent %s\n" % hex(parents[1]))
695 695 fp.write(ctx.description().rstrip())
696 696 fp.write("\n\n")
697 697
698 698 for chunk in patch.diff(repo, prev, node, opts=opts):
699 699 fp.write(chunk)
700 700
701 701 for seqno, rev in enumerate(revs):
702 702 single(rev, seqno + 1, fp)
703 703
704 def diffordiffstat(ui, repo, diffopts, node1, node2, match,
705 changes=None, stat=False, fp=None):
706 '''show diff or diffstat.'''
707 if fp is None:
708 write = ui.write
709 else:
710 def write(s, **kw):
711 fp.write(s)
712
713 if stat:
714 diffopts.context = 0
715 width = 80
716 if not ui.plain():
717 width = util.termwidth()
718 chunks = patch.diff(repo, node1, node2, match, changes, diffopts)
719 for chunk, label in patch.diffstatui(util.iterlines(chunks),
720 width=width,
721 git=diffopts.git):
722 write(chunk, label=label)
723 else:
724 for chunk, label in patch.diffui(repo, node1, node2, match,
725 changes, diffopts):
726 write(chunk, label=label)
727
704 728 class changeset_printer(object):
705 729 '''show changeset information when templating not requested.'''
706 730
707 731 def __init__(self, ui, repo, patch, diffopts, buffered):
708 732 self.ui = ui
709 733 self.repo = repo
710 734 self.buffered = buffered
711 735 self.patch = patch
712 736 self.diffopts = diffopts
713 737 self.header = {}
714 738 self.hunk = {}
715 739 self.lastheader = None
716 740 self.footer = None
717 741
718 742 def flush(self, rev):
719 743 if rev in self.header:
720 744 h = self.header[rev]
721 745 if h != self.lastheader:
722 746 self.lastheader = h
723 747 self.ui.write(h)
724 748 del self.header[rev]
725 749 if rev in self.hunk:
726 750 self.ui.write(self.hunk[rev])
727 751 del self.hunk[rev]
728 752 return 1
729 753 return 0
730 754
731 755 def close(self):
732 756 if self.footer:
733 757 self.ui.write(self.footer)
734 758
735 759 def show(self, ctx, copies=None, **props):
736 760 if self.buffered:
737 761 self.ui.pushbuffer()
738 762 self._show(ctx, copies, props)
739 763 self.hunk[ctx.rev()] = self.ui.popbuffer(labeled=True)
740 764 else:
741 765 self._show(ctx, copies, props)
742 766
743 767 def _show(self, ctx, copies, props):
744 768 '''show a single changeset or file revision'''
745 769 changenode = ctx.node()
746 770 rev = ctx.rev()
747 771
748 772 if self.ui.quiet:
749 773 self.ui.write("%d:%s\n" % (rev, short(changenode)),
750 774 label='log.node')
751 775 return
752 776
753 777 log = self.repo.changelog
754 778 date = util.datestr(ctx.date())
755 779
756 780 hexfunc = self.ui.debugflag and hex or short
757 781
758 782 parents = [(p, hexfunc(log.node(p)))
759 783 for p in self._meaningful_parentrevs(log, rev)]
760 784
761 785 self.ui.write(_("changeset: %d:%s\n") % (rev, hexfunc(changenode)),
762 786 label='log.changeset')
763 787
764 788 branch = ctx.branch()
765 789 # don't show the default branch name
766 790 if branch != 'default':
767 791 branch = encoding.tolocal(branch)
768 792 self.ui.write(_("branch: %s\n") % branch,
769 793 label='log.branch')
770 794 for tag in self.repo.nodetags(changenode):
771 795 self.ui.write(_("tag: %s\n") % tag,
772 796 label='log.tag')
773 797 for parent in parents:
774 798 self.ui.write(_("parent: %d:%s\n") % parent,
775 799 label='log.parent')
776 800
777 801 if self.ui.debugflag:
778 802 mnode = ctx.manifestnode()
779 803 self.ui.write(_("manifest: %d:%s\n") %
780 804 (self.repo.manifest.rev(mnode), hex(mnode)),
781 805 label='ui.debug log.manifest')
782 806 self.ui.write(_("user: %s\n") % ctx.user(),
783 807 label='log.user')
784 808 self.ui.write(_("date: %s\n") % date,
785 809 label='log.date')
786 810
787 811 if self.ui.debugflag:
788 812 files = self.repo.status(log.parents(changenode)[0], changenode)[:3]
789 813 for key, value in zip([_("files:"), _("files+:"), _("files-:")],
790 814 files):
791 815 if value:
792 816 self.ui.write("%-12s %s\n" % (key, " ".join(value)),
793 817 label='ui.debug log.files')
794 818 elif ctx.files() and self.ui.verbose:
795 819 self.ui.write(_("files: %s\n") % " ".join(ctx.files()),
796 820 label='ui.note log.files')
797 821 if copies and self.ui.verbose:
798 822 copies = ['%s (%s)' % c for c in copies]
799 823 self.ui.write(_("copies: %s\n") % ' '.join(copies),
800 824 label='ui.note log.copies')
801 825
802 826 extra = ctx.extra()
803 827 if extra and self.ui.debugflag:
804 828 for key, value in sorted(extra.items()):
805 829 self.ui.write(_("extra: %s=%s\n")
806 830 % (key, value.encode('string_escape')),
807 831 label='ui.debug log.extra')
808 832
809 833 description = ctx.description().strip()
810 834 if description:
811 835 if self.ui.verbose:
812 836 self.ui.write(_("description:\n"),
813 837 label='ui.note log.description')
814 838 self.ui.write(description,
815 839 label='ui.note log.description')
816 840 self.ui.write("\n\n")
817 841 else:
818 842 self.ui.write(_("summary: %s\n") %
819 843 description.splitlines()[0],
820 844 label='log.summary')
821 845 self.ui.write("\n")
822 846
823 847 self.showpatch(changenode)
824 848
825 849 def showpatch(self, node):
826 850 if self.patch:
827 851 prev = self.repo.changelog.parents(node)[0]
828 852 chunks = patch.diffui(self.repo, prev, node, match=self.patch,
829 853 opts=patch.diffopts(self.ui, self.diffopts))
830 854 for chunk, label in chunks:
831 855 self.ui.write(chunk, label=label)
832 856 self.ui.write("\n")
833 857
834 858 def _meaningful_parentrevs(self, log, rev):
835 859 """Return list of meaningful (or all if debug) parentrevs for rev.
836 860
837 861 For merges (two non-nullrev revisions) both parents are meaningful.
838 862 Otherwise the first parent revision is considered meaningful if it
839 863 is not the preceding revision.
840 864 """
841 865 parents = log.parentrevs(rev)
842 866 if not self.ui.debugflag and parents[1] == nullrev:
843 867 if parents[0] >= rev - 1:
844 868 parents = []
845 869 else:
846 870 parents = [parents[0]]
847 871 return parents
848 872
849 873
850 874 class changeset_templater(changeset_printer):
851 875 '''format changeset information.'''
852 876
853 877 def __init__(self, ui, repo, patch, diffopts, mapfile, buffered):
854 878 changeset_printer.__init__(self, ui, repo, patch, diffopts, buffered)
855 879 formatnode = ui.debugflag and (lambda x: x) or (lambda x: x[:12])
856 880 defaulttempl = {
857 881 'parent': '{rev}:{node|formatnode} ',
858 882 'manifest': '{rev}:{node|formatnode}',
859 883 'file_copy': '{name} ({source})',
860 884 'extra': '{key}={value|stringescape}'
861 885 }
862 886 # filecopy is preserved for compatibility reasons
863 887 defaulttempl['filecopy'] = defaulttempl['file_copy']
864 888 self.t = templater.templater(mapfile, {'formatnode': formatnode},
865 889 cache=defaulttempl)
866 890 self.cache = {}
867 891
868 892 def use_template(self, t):
869 893 '''set template string to use'''
870 894 self.t.cache['changeset'] = t
871 895
872 896 def _meaningful_parentrevs(self, ctx):
873 897 """Return list of meaningful (or all if debug) parentrevs for rev.
874 898 """
875 899 parents = ctx.parents()
876 900 if len(parents) > 1:
877 901 return parents
878 902 if self.ui.debugflag:
879 903 return [parents[0], self.repo['null']]
880 904 if parents[0].rev() >= ctx.rev() - 1:
881 905 return []
882 906 return parents
883 907
884 908 def _show(self, ctx, copies, props):
885 909 '''show a single changeset or file revision'''
886 910
887 911 showlist = templatekw.showlist
888 912
889 913 # showparents() behaviour depends on ui trace level which
890 914 # causes unexpected behaviours at templating level and makes
891 915 # it harder to extract it in a standalone function. Its
892 916 # behaviour cannot be changed so leave it here for now.
893 917 def showparents(**args):
894 918 ctx = args['ctx']
895 919 parents = [[('rev', p.rev()), ('node', p.hex())]
896 920 for p in self._meaningful_parentrevs(ctx)]
897 921 return showlist('parent', parents, **args)
898 922
899 923 props = props.copy()
900 924 props.update(templatekw.keywords)
901 925 props['parents'] = showparents
902 926 props['templ'] = self.t
903 927 props['ctx'] = ctx
904 928 props['repo'] = self.repo
905 929 props['revcache'] = {'copies': copies}
906 930 props['cache'] = self.cache
907 931
908 932 # find correct templates for current mode
909 933
910 934 tmplmodes = [
911 935 (True, None),
912 936 (self.ui.verbose, 'verbose'),
913 937 (self.ui.quiet, 'quiet'),
914 938 (self.ui.debugflag, 'debug'),
915 939 ]
916 940
917 941 types = {'header': '', 'footer':'', 'changeset': 'changeset'}
918 942 for mode, postfix in tmplmodes:
919 943 for type in types:
920 944 cur = postfix and ('%s_%s' % (type, postfix)) or type
921 945 if mode and cur in self.t:
922 946 types[type] = cur
923 947
924 948 try:
925 949
926 950 # write header
927 951 if types['header']:
928 952 h = templater.stringify(self.t(types['header'], **props))
929 953 if self.buffered:
930 954 self.header[ctx.rev()] = h
931 955 else:
932 956 self.ui.write(h)
933 957
934 958 # write changeset metadata, then patch if requested
935 959 key = types['changeset']
936 960 self.ui.write(templater.stringify(self.t(key, **props)))
937 961 self.showpatch(ctx.node())
938 962
939 963 if types['footer']:
940 964 if not self.footer:
941 965 self.footer = templater.stringify(self.t(types['footer'],
942 966 **props))
943 967
944 968 except KeyError, inst:
945 969 msg = _("%s: no key named '%s'")
946 970 raise util.Abort(msg % (self.t.mapfile, inst.args[0]))
947 971 except SyntaxError, inst:
948 972 raise util.Abort('%s: %s' % (self.t.mapfile, inst.args[0]))
949 973
950 974 def show_changeset(ui, repo, opts, buffered=False, matchfn=False):
951 975 """show one changeset using template or regular display.
952 976
953 977 Display format will be the first non-empty hit of:
954 978 1. option 'template'
955 979 2. option 'style'
956 980 3. [ui] setting 'logtemplate'
957 981 4. [ui] setting 'style'
958 982 If all of these values are either the unset or the empty string,
959 983 regular display via changeset_printer() is done.
960 984 """
961 985 # options
962 986 patch = False
963 987 if opts.get('patch'):
964 988 patch = matchfn or matchall(repo)
965 989
966 990 tmpl = opts.get('template')
967 991 style = None
968 992 if tmpl:
969 993 tmpl = templater.parsestring(tmpl, quoted=False)
970 994 else:
971 995 style = opts.get('style')
972 996
973 997 # ui settings
974 998 if not (tmpl or style):
975 999 tmpl = ui.config('ui', 'logtemplate')
976 1000 if tmpl:
977 1001 tmpl = templater.parsestring(tmpl)
978 1002 else:
979 1003 style = util.expandpath(ui.config('ui', 'style', ''))
980 1004
981 1005 if not (tmpl or style):
982 1006 return changeset_printer(ui, repo, patch, opts, buffered)
983 1007
984 1008 mapfile = None
985 1009 if style and not tmpl:
986 1010 mapfile = style
987 1011 if not os.path.split(mapfile)[0]:
988 1012 mapname = (templater.templatepath('map-cmdline.' + mapfile)
989 1013 or templater.templatepath(mapfile))
990 1014 if mapname:
991 1015 mapfile = mapname
992 1016
993 1017 try:
994 1018 t = changeset_templater(ui, repo, patch, opts, mapfile, buffered)
995 1019 except SyntaxError, inst:
996 1020 raise util.Abort(inst.args[0])
997 1021 if tmpl:
998 1022 t.use_template(tmpl)
999 1023 return t
1000 1024
1001 1025 def finddate(ui, repo, date):
1002 1026 """Find the tipmost changeset that matches the given date spec"""
1003 1027
1004 1028 df = util.matchdate(date)
1005 1029 m = matchall(repo)
1006 1030 results = {}
1007 1031
1008 1032 def prep(ctx, fns):
1009 1033 d = ctx.date()
1010 1034 if df(d[0]):
1011 1035 results[ctx.rev()] = d
1012 1036
1013 1037 for ctx in walkchangerevs(repo, m, {'rev': None}, prep):
1014 1038 rev = ctx.rev()
1015 1039 if rev in results:
1016 1040 ui.status(_("Found revision %s from %s\n") %
1017 1041 (rev, util.datestr(results[rev])))
1018 1042 return str(rev)
1019 1043
1020 1044 raise util.Abort(_("revision matching date not found"))
1021 1045
1022 1046 def walkchangerevs(repo, match, opts, prepare):
1023 1047 '''Iterate over files and the revs in which they changed.
1024 1048
1025 1049 Callers most commonly need to iterate backwards over the history
1026 1050 in which they are interested. Doing so has awful (quadratic-looking)
1027 1051 performance, so we use iterators in a "windowed" way.
1028 1052
1029 1053 We walk a window of revisions in the desired order. Within the
1030 1054 window, we first walk forwards to gather data, then in the desired
1031 1055 order (usually backwards) to display it.
1032 1056
1033 1057 This function returns an iterator yielding contexts. Before
1034 1058 yielding each context, the iterator will first call the prepare
1035 1059 function on each context in the window in forward order.'''
1036 1060
1037 1061 def increasing_windows(start, end, windowsize=8, sizelimit=512):
1038 1062 if start < end:
1039 1063 while start < end:
1040 1064 yield start, min(windowsize, end - start)
1041 1065 start += windowsize
1042 1066 if windowsize < sizelimit:
1043 1067 windowsize *= 2
1044 1068 else:
1045 1069 while start > end:
1046 1070 yield start, min(windowsize, start - end - 1)
1047 1071 start -= windowsize
1048 1072 if windowsize < sizelimit:
1049 1073 windowsize *= 2
1050 1074
1051 1075 follow = opts.get('follow') or opts.get('follow_first')
1052 1076
1053 1077 if not len(repo):
1054 1078 return []
1055 1079
1056 1080 if follow:
1057 1081 defrange = '%s:0' % repo['.'].rev()
1058 1082 else:
1059 1083 defrange = '-1:0'
1060 1084 revs = revrange(repo, opts['rev'] or [defrange])
1061 1085 wanted = set()
1062 1086 slowpath = match.anypats() or (match.files() and opts.get('removed'))
1063 1087 fncache = {}
1064 1088 change = util.cachefunc(repo.changectx)
1065 1089
1066 1090 if not slowpath and not match.files():
1067 1091 # No files, no patterns. Display all revs.
1068 1092 wanted = set(revs)
1069 1093 copies = []
1070 1094
1071 1095 if not slowpath:
1072 1096 # Only files, no patterns. Check the history of each file.
1073 1097 def filerevgen(filelog, node):
1074 1098 cl_count = len(repo)
1075 1099 if node is None:
1076 1100 last = len(filelog) - 1
1077 1101 else:
1078 1102 last = filelog.rev(node)
1079 1103 for i, window in increasing_windows(last, nullrev):
1080 1104 revs = []
1081 1105 for j in xrange(i - window, i + 1):
1082 1106 n = filelog.node(j)
1083 1107 revs.append((filelog.linkrev(j),
1084 1108 follow and filelog.renamed(n)))
1085 1109 for rev in reversed(revs):
1086 1110 # only yield rev for which we have the changelog, it can
1087 1111 # happen while doing "hg log" during a pull or commit
1088 1112 if rev[0] < cl_count:
1089 1113 yield rev
1090 1114 def iterfiles():
1091 1115 for filename in match.files():
1092 1116 yield filename, None
1093 1117 for filename_node in copies:
1094 1118 yield filename_node
1095 1119 minrev, maxrev = min(revs), max(revs)
1096 1120 for file_, node in iterfiles():
1097 1121 filelog = repo.file(file_)
1098 1122 if not len(filelog):
1099 1123 if node is None:
1100 1124 # A zero count may be a directory or deleted file, so
1101 1125 # try to find matching entries on the slow path.
1102 1126 if follow:
1103 1127 raise util.Abort(
1104 1128 _('cannot follow nonexistent file: "%s"') % file_)
1105 1129 slowpath = True
1106 1130 break
1107 1131 else:
1108 1132 continue
1109 1133 for rev, copied in filerevgen(filelog, node):
1110 1134 if rev <= maxrev:
1111 1135 if rev < minrev:
1112 1136 break
1113 1137 fncache.setdefault(rev, [])
1114 1138 fncache[rev].append(file_)
1115 1139 wanted.add(rev)
1116 1140 if copied:
1117 1141 copies.append(copied)
1118 1142 if slowpath:
1119 1143 if follow:
1120 1144 raise util.Abort(_('can only follow copies/renames for explicit '
1121 1145 'filenames'))
1122 1146
1123 1147 # The slow path checks files modified in every changeset.
1124 1148 def changerevgen():
1125 1149 for i, window in increasing_windows(len(repo) - 1, nullrev):
1126 1150 for j in xrange(i - window, i + 1):
1127 1151 yield change(j)
1128 1152
1129 1153 for ctx in changerevgen():
1130 1154 matches = filter(match, ctx.files())
1131 1155 if matches:
1132 1156 fncache[ctx.rev()] = matches
1133 1157 wanted.add(ctx.rev())
1134 1158
1135 1159 class followfilter(object):
1136 1160 def __init__(self, onlyfirst=False):
1137 1161 self.startrev = nullrev
1138 1162 self.roots = set()
1139 1163 self.onlyfirst = onlyfirst
1140 1164
1141 1165 def match(self, rev):
1142 1166 def realparents(rev):
1143 1167 if self.onlyfirst:
1144 1168 return repo.changelog.parentrevs(rev)[0:1]
1145 1169 else:
1146 1170 return filter(lambda x: x != nullrev,
1147 1171 repo.changelog.parentrevs(rev))
1148 1172
1149 1173 if self.startrev == nullrev:
1150 1174 self.startrev = rev
1151 1175 return True
1152 1176
1153 1177 if rev > self.startrev:
1154 1178 # forward: all descendants
1155 1179 if not self.roots:
1156 1180 self.roots.add(self.startrev)
1157 1181 for parent in realparents(rev):
1158 1182 if parent in self.roots:
1159 1183 self.roots.add(rev)
1160 1184 return True
1161 1185 else:
1162 1186 # backwards: all parents
1163 1187 if not self.roots:
1164 1188 self.roots.update(realparents(self.startrev))
1165 1189 if rev in self.roots:
1166 1190 self.roots.remove(rev)
1167 1191 self.roots.update(realparents(rev))
1168 1192 return True
1169 1193
1170 1194 return False
1171 1195
1172 1196 # it might be worthwhile to do this in the iterator if the rev range
1173 1197 # is descending and the prune args are all within that range
1174 1198 for rev in opts.get('prune', ()):
1175 1199 rev = repo.changelog.rev(repo.lookup(rev))
1176 1200 ff = followfilter()
1177 1201 stop = min(revs[0], revs[-1])
1178 1202 for x in xrange(rev, stop - 1, -1):
1179 1203 if ff.match(x):
1180 1204 wanted.discard(x)
1181 1205
1182 1206 def iterate():
1183 1207 if follow and not match.files():
1184 1208 ff = followfilter(onlyfirst=opts.get('follow_first'))
1185 1209 def want(rev):
1186 1210 return ff.match(rev) and rev in wanted
1187 1211 else:
1188 1212 def want(rev):
1189 1213 return rev in wanted
1190 1214
1191 1215 for i, window in increasing_windows(0, len(revs)):
1192 1216 change = util.cachefunc(repo.changectx)
1193 1217 nrevs = [rev for rev in revs[i:i + window] if want(rev)]
1194 1218 for rev in sorted(nrevs):
1195 1219 fns = fncache.get(rev)
1196 1220 ctx = change(rev)
1197 1221 if not fns:
1198 1222 def fns_generator():
1199 1223 for f in ctx.files():
1200 1224 if match(f):
1201 1225 yield f
1202 1226 fns = fns_generator()
1203 1227 prepare(ctx, fns)
1204 1228 for rev in nrevs:
1205 1229 yield change(rev)
1206 1230 return iterate()
1207 1231
1208 1232 def commit(ui, repo, commitfunc, pats, opts):
1209 1233 '''commit the specified files or all outstanding changes'''
1210 1234 date = opts.get('date')
1211 1235 if date:
1212 1236 opts['date'] = util.parsedate(date)
1213 1237 message = logmessage(opts)
1214 1238
1215 1239 # extract addremove carefully -- this function can be called from a command
1216 1240 # that doesn't support addremove
1217 1241 if opts.get('addremove'):
1218 1242 addremove(repo, pats, opts)
1219 1243
1220 1244 return commitfunc(ui, repo, message, match(repo, pats, opts), opts)
1221 1245
1222 1246 def commiteditor(repo, ctx, subs):
1223 1247 if ctx.description():
1224 1248 return ctx.description()
1225 1249 return commitforceeditor(repo, ctx, subs)
1226 1250
1227 1251 def commitforceeditor(repo, ctx, subs):
1228 1252 edittext = []
1229 1253 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
1230 1254 if ctx.description():
1231 1255 edittext.append(ctx.description())
1232 1256 edittext.append("")
1233 1257 edittext.append("") # Empty line between message and comments.
1234 1258 edittext.append(_("HG: Enter commit message."
1235 1259 " Lines beginning with 'HG:' are removed."))
1236 1260 edittext.append(_("HG: Leave message empty to abort commit."))
1237 1261 edittext.append("HG: --")
1238 1262 edittext.append(_("HG: user: %s") % ctx.user())
1239 1263 if ctx.p2():
1240 1264 edittext.append(_("HG: branch merge"))
1241 1265 if ctx.branch():
1242 1266 edittext.append(_("HG: branch '%s'")
1243 1267 % encoding.tolocal(ctx.branch()))
1244 1268 edittext.extend([_("HG: subrepo %s") % s for s in subs])
1245 1269 edittext.extend([_("HG: added %s") % f for f in added])
1246 1270 edittext.extend([_("HG: changed %s") % f for f in modified])
1247 1271 edittext.extend([_("HG: removed %s") % f for f in removed])
1248 1272 if not added and not modified and not removed:
1249 1273 edittext.append(_("HG: no files changed"))
1250 1274 edittext.append("")
1251 1275 # run editor in the repository root
1252 1276 olddir = os.getcwd()
1253 1277 os.chdir(repo.root)
1254 1278 text = repo.ui.edit("\n".join(edittext), ctx.user())
1255 1279 text = re.sub("(?m)^HG:.*\n", "", text)
1256 1280 os.chdir(olddir)
1257 1281
1258 1282 if not text.strip():
1259 1283 raise util.Abort(_("empty commit message"))
1260 1284
1261 1285 return text
@@ -1,3934 +1,3920 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, 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, util, revlog, bundlerepo, extensions, copies, error
13 13 import patch, help, mdiff, url, encoding, templatekw
14 14 import archival, changegroup, cmdutil, sshserver, hbisect, hgweb, hgweb.server
15 15 import merge as mergemod
16 16 import minirst
17 17
18 18 # Commands start here, listed alphabetically
19 19
20 20 def add(ui, repo, *pats, **opts):
21 21 """add the specified files on the next commit
22 22
23 23 Schedule files to be version controlled and added to the
24 24 repository.
25 25
26 26 The files will be added to the repository at the next commit. To
27 27 undo an add before that, see hg forget.
28 28
29 29 If no names are given, add all files to the repository.
30 30
31 31 .. container:: verbose
32 32
33 33 An example showing how new (unknown) files are added
34 34 automatically by :hg:`add`::
35 35
36 36 $ ls
37 37 foo.c
38 38 $ hg status
39 39 ? foo.c
40 40 $ hg add
41 41 adding foo.c
42 42 $ hg status
43 43 A foo.c
44 44 """
45 45
46 46 bad = []
47 47 names = []
48 48 m = cmdutil.match(repo, pats, opts)
49 49 oldbad = m.bad
50 50 m.bad = lambda x, y: bad.append(x) or oldbad(x, y)
51 51
52 52 for f in repo.walk(m):
53 53 exact = m.exact(f)
54 54 if exact or f not in repo.dirstate:
55 55 names.append(f)
56 56 if ui.verbose or not exact:
57 57 ui.status(_('adding %s\n') % m.rel(f))
58 58 if not opts.get('dry_run'):
59 59 bad += [f for f in repo.add(names) if f in m.files()]
60 60 return bad and 1 or 0
61 61
62 62 def addremove(ui, repo, *pats, **opts):
63 63 """add all new files, delete all missing files
64 64
65 65 Add all new files and remove all missing files from the
66 66 repository.
67 67
68 68 New files are ignored if they match any of the patterns in
69 69 .hgignore. As with add, these changes take effect at the next
70 70 commit.
71 71
72 72 Use the -s/--similarity option to detect renamed files. With a
73 73 parameter greater than 0, this compares every removed file with
74 74 every added file and records those similar enough as renames. This
75 75 option takes a percentage between 0 (disabled) and 100 (files must
76 76 be identical) as its parameter. Detecting renamed files this way
77 77 can be expensive.
78 78 """
79 79 try:
80 80 sim = float(opts.get('similarity') or 0)
81 81 except ValueError:
82 82 raise util.Abort(_('similarity must be a number'))
83 83 if sim < 0 or sim > 100:
84 84 raise util.Abort(_('similarity must be between 0 and 100'))
85 85 return cmdutil.addremove(repo, pats, opts, similarity=sim / 100.0)
86 86
87 87 def annotate(ui, repo, *pats, **opts):
88 88 """show changeset information by line for each file
89 89
90 90 List changes in files, showing the revision id responsible for
91 91 each line
92 92
93 93 This command is useful for discovering when a change was made and
94 94 by whom.
95 95
96 96 Without the -a/--text option, annotate will avoid processing files
97 97 it detects as binary. With -a, annotate will annotate the file
98 98 anyway, although the results will probably be neither useful
99 99 nor desirable.
100 100 """
101 101 if opts.get('follow'):
102 102 # --follow is deprecated and now just an alias for -f/--file
103 103 # to mimic the behavior of Mercurial before version 1.5
104 104 opts['file'] = 1
105 105
106 106 datefunc = ui.quiet and util.shortdate or util.datestr
107 107 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
108 108
109 109 if not pats:
110 110 raise util.Abort(_('at least one filename or pattern is required'))
111 111
112 112 opmap = [('user', lambda x: ui.shortuser(x[0].user())),
113 113 ('number', lambda x: str(x[0].rev())),
114 114 ('changeset', lambda x: short(x[0].node())),
115 115 ('date', getdate),
116 116 ('file', lambda x: x[0].path()),
117 117 ]
118 118
119 119 if (not opts.get('user') and not opts.get('changeset')
120 120 and not opts.get('date') and not opts.get('file')):
121 121 opts['number'] = 1
122 122
123 123 linenumber = opts.get('line_number') is not None
124 124 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
125 125 raise util.Abort(_('at least one of -n/-c is required for -l'))
126 126
127 127 funcmap = [func for op, func in opmap if opts.get(op)]
128 128 if linenumber:
129 129 lastfunc = funcmap[-1]
130 130 funcmap[-1] = lambda x: "%s:%s" % (lastfunc(x), x[1])
131 131
132 132 ctx = repo[opts.get('rev')]
133 133 m = cmdutil.match(repo, pats, opts)
134 134 follow = not opts.get('no_follow')
135 135 for abs in ctx.walk(m):
136 136 fctx = ctx[abs]
137 137 if not opts.get('text') and util.binary(fctx.data()):
138 138 ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
139 139 continue
140 140
141 141 lines = fctx.annotate(follow=follow, linenumber=linenumber)
142 142 pieces = []
143 143
144 144 for f in funcmap:
145 145 l = [f(n) for n, dummy in lines]
146 146 if l:
147 147 ml = max(map(len, l))
148 148 pieces.append(["%*s" % (ml, x) for x in l])
149 149
150 150 if pieces:
151 151 for p, l in zip(zip(*pieces), lines):
152 152 ui.write("%s: %s" % (" ".join(p), l[1]))
153 153
154 154 def archive(ui, repo, dest, **opts):
155 155 '''create an unversioned archive of a repository revision
156 156
157 157 By default, the revision used is the parent of the working
158 158 directory; use -r/--rev to specify a different revision.
159 159
160 160 The archive type is automatically detected based on file
161 161 extension (or override using -t/--type).
162 162
163 163 Valid types are:
164 164
165 165 :``files``: a directory full of files (default)
166 166 :``tar``: tar archive, uncompressed
167 167 :``tbz2``: tar archive, compressed using bzip2
168 168 :``tgz``: tar archive, compressed using gzip
169 169 :``uzip``: zip archive, uncompressed
170 170 :``zip``: zip archive, compressed using deflate
171 171
172 172 The exact name of the destination archive or directory is given
173 173 using a format string; see :hg:`help export` for details.
174 174
175 175 Each member added to an archive file has a directory prefix
176 176 prepended. Use -p/--prefix to specify a format string for the
177 177 prefix. The default is the basename of the archive, with suffixes
178 178 removed.
179 179 '''
180 180
181 181 ctx = repo[opts.get('rev')]
182 182 if not ctx:
183 183 raise util.Abort(_('no working directory: please specify a revision'))
184 184 node = ctx.node()
185 185 dest = cmdutil.make_filename(repo, dest, node)
186 186 if os.path.realpath(dest) == repo.root:
187 187 raise util.Abort(_('repository root cannot be destination'))
188 188
189 189 def guess_type():
190 190 exttypes = {
191 191 'tar': ['.tar'],
192 192 'tbz2': ['.tbz2', '.tar.bz2'],
193 193 'tgz': ['.tgz', '.tar.gz'],
194 194 'zip': ['.zip'],
195 195 }
196 196
197 197 for type, extensions in exttypes.items():
198 198 if util.any(dest.endswith(ext) for ext in extensions):
199 199 return type
200 200 return None
201 201
202 202 kind = opts.get('type') or guess_type() or 'files'
203 203 prefix = opts.get('prefix')
204 204
205 205 if dest == '-':
206 206 if kind == 'files':
207 207 raise util.Abort(_('cannot archive plain files to stdout'))
208 208 dest = sys.stdout
209 209 if not prefix:
210 210 prefix = os.path.basename(repo.root) + '-%h'
211 211
212 212 prefix = cmdutil.make_filename(repo, prefix, node)
213 213 matchfn = cmdutil.match(repo, [], opts)
214 214 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
215 215 matchfn, prefix)
216 216
217 217 def backout(ui, repo, node=None, rev=None, **opts):
218 218 '''reverse effect of earlier changeset
219 219
220 220 Commit the backed out changes as a new changeset. The new
221 221 changeset is a child of the backed out changeset.
222 222
223 223 If you backout a changeset other than the tip, a new head is
224 224 created. This head will be the new tip and you should merge this
225 225 backout changeset with another head.
226 226
227 227 The --merge option remembers the parent of the working directory
228 228 before starting the backout, then merges the new head with that
229 229 changeset afterwards. This saves you from doing the merge by hand.
230 230 The result of this merge is not committed, as with a normal merge.
231 231
232 232 See :hg:`help dates` for a list of formats valid for -d/--date.
233 233 '''
234 234 if rev and node:
235 235 raise util.Abort(_("please specify just one revision"))
236 236
237 237 if not rev:
238 238 rev = node
239 239
240 240 if not rev:
241 241 raise util.Abort(_("please specify a revision to backout"))
242 242
243 243 date = opts.get('date')
244 244 if date:
245 245 opts['date'] = util.parsedate(date)
246 246
247 247 cmdutil.bail_if_changed(repo)
248 248 node = repo.lookup(rev)
249 249
250 250 op1, op2 = repo.dirstate.parents()
251 251 a = repo.changelog.ancestor(op1, node)
252 252 if a != node:
253 253 raise util.Abort(_('cannot backout change on a different branch'))
254 254
255 255 p1, p2 = repo.changelog.parents(node)
256 256 if p1 == nullid:
257 257 raise util.Abort(_('cannot backout a change with no parents'))
258 258 if p2 != nullid:
259 259 if not opts.get('parent'):
260 260 raise util.Abort(_('cannot backout a merge changeset without '
261 261 '--parent'))
262 262 p = repo.lookup(opts['parent'])
263 263 if p not in (p1, p2):
264 264 raise util.Abort(_('%s is not a parent of %s') %
265 265 (short(p), short(node)))
266 266 parent = p
267 267 else:
268 268 if opts.get('parent'):
269 269 raise util.Abort(_('cannot use --parent on non-merge changeset'))
270 270 parent = p1
271 271
272 272 # the backout should appear on the same branch
273 273 branch = repo.dirstate.branch()
274 274 hg.clean(repo, node, show_stats=False)
275 275 repo.dirstate.setbranch(branch)
276 276 revert_opts = opts.copy()
277 277 revert_opts['date'] = None
278 278 revert_opts['all'] = True
279 279 revert_opts['rev'] = hex(parent)
280 280 revert_opts['no_backup'] = None
281 281 revert(ui, repo, **revert_opts)
282 282 commit_opts = opts.copy()
283 283 commit_opts['addremove'] = False
284 284 if not commit_opts['message'] and not commit_opts['logfile']:
285 285 # we don't translate commit messages
286 286 commit_opts['message'] = "Backed out changeset %s" % short(node)
287 287 commit_opts['force_editor'] = True
288 288 commit(ui, repo, **commit_opts)
289 289 def nice(node):
290 290 return '%d:%s' % (repo.changelog.rev(node), short(node))
291 291 ui.status(_('changeset %s backs out changeset %s\n') %
292 292 (nice(repo.changelog.tip()), nice(node)))
293 293 if op1 != node:
294 294 hg.clean(repo, op1, show_stats=False)
295 295 if opts.get('merge'):
296 296 ui.status(_('merging with changeset %s\n')
297 297 % nice(repo.changelog.tip()))
298 298 hg.merge(repo, hex(repo.changelog.tip()))
299 299 else:
300 300 ui.status(_('the backout changeset is a new head - '
301 301 'do not forget to merge\n'))
302 302 ui.status(_('(use "backout --merge" '
303 303 'if you want to auto-merge)\n'))
304 304
305 305 def bisect(ui, repo, rev=None, extra=None, command=None,
306 306 reset=None, good=None, bad=None, skip=None, noupdate=None):
307 307 """subdivision search of changesets
308 308
309 309 This command helps to find changesets which introduce problems. To
310 310 use, mark the earliest changeset you know exhibits the problem as
311 311 bad, then mark the latest changeset which is free from the problem
312 312 as good. Bisect will update your working directory to a revision
313 313 for testing (unless the -U/--noupdate option is specified). Once
314 314 you have performed tests, mark the working directory as good or
315 315 bad, and bisect will either update to another candidate changeset
316 316 or announce that it has found the bad revision.
317 317
318 318 As a shortcut, you can also use the revision argument to mark a
319 319 revision as good or bad without checking it out first.
320 320
321 321 If you supply a command, it will be used for automatic bisection.
322 322 Its exit status will be used to mark revisions as good or bad:
323 323 status 0 means good, 125 means to skip the revision, 127
324 324 (command not found) will abort the bisection, and any other
325 325 non-zero exit status means the revision is bad.
326 326 """
327 327 def print_result(nodes, good):
328 328 displayer = cmdutil.show_changeset(ui, repo, {})
329 329 if len(nodes) == 1:
330 330 # narrowed it down to a single revision
331 331 if good:
332 332 ui.write(_("The first good revision is:\n"))
333 333 else:
334 334 ui.write(_("The first bad revision is:\n"))
335 335 displayer.show(repo[nodes[0]])
336 336 else:
337 337 # multiple possible revisions
338 338 if good:
339 339 ui.write(_("Due to skipped revisions, the first "
340 340 "good revision could be any of:\n"))
341 341 else:
342 342 ui.write(_("Due to skipped revisions, the first "
343 343 "bad revision could be any of:\n"))
344 344 for n in nodes:
345 345 displayer.show(repo[n])
346 346 displayer.close()
347 347
348 348 def check_state(state, interactive=True):
349 349 if not state['good'] or not state['bad']:
350 350 if (good or bad or skip or reset) and interactive:
351 351 return
352 352 if not state['good']:
353 353 raise util.Abort(_('cannot bisect (no known good revisions)'))
354 354 else:
355 355 raise util.Abort(_('cannot bisect (no known bad revisions)'))
356 356 return True
357 357
358 358 # backward compatibility
359 359 if rev in "good bad reset init".split():
360 360 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
361 361 cmd, rev, extra = rev, extra, None
362 362 if cmd == "good":
363 363 good = True
364 364 elif cmd == "bad":
365 365 bad = True
366 366 else:
367 367 reset = True
368 368 elif extra or good + bad + skip + reset + bool(command) > 1:
369 369 raise util.Abort(_('incompatible arguments'))
370 370
371 371 if reset:
372 372 p = repo.join("bisect.state")
373 373 if os.path.exists(p):
374 374 os.unlink(p)
375 375 return
376 376
377 377 state = hbisect.load_state(repo)
378 378
379 379 if command:
380 380 changesets = 1
381 381 try:
382 382 while changesets:
383 383 # update state
384 384 status = util.system(command)
385 385 if status == 125:
386 386 transition = "skip"
387 387 elif status == 0:
388 388 transition = "good"
389 389 # status < 0 means process was killed
390 390 elif status == 127:
391 391 raise util.Abort(_("failed to execute %s") % command)
392 392 elif status < 0:
393 393 raise util.Abort(_("%s killed") % command)
394 394 else:
395 395 transition = "bad"
396 396 ctx = repo[rev or '.']
397 397 state[transition].append(ctx.node())
398 398 ui.status(_('Changeset %d:%s: %s\n') % (ctx, ctx, transition))
399 399 check_state(state, interactive=False)
400 400 # bisect
401 401 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
402 402 # update to next check
403 403 cmdutil.bail_if_changed(repo)
404 404 hg.clean(repo, nodes[0], show_stats=False)
405 405 finally:
406 406 hbisect.save_state(repo, state)
407 407 return print_result(nodes, good)
408 408
409 409 # update state
410 410 node = repo.lookup(rev or '.')
411 411 if good or bad or skip:
412 412 if good:
413 413 state['good'].append(node)
414 414 elif bad:
415 415 state['bad'].append(node)
416 416 elif skip:
417 417 state['skip'].append(node)
418 418 hbisect.save_state(repo, state)
419 419
420 420 if not check_state(state):
421 421 return
422 422
423 423 # actually bisect
424 424 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
425 425 if changesets == 0:
426 426 print_result(nodes, good)
427 427 else:
428 428 assert len(nodes) == 1 # only a single node can be tested next
429 429 node = nodes[0]
430 430 # compute the approximate number of remaining tests
431 431 tests, size = 0, 2
432 432 while size <= changesets:
433 433 tests, size = tests + 1, size * 2
434 434 rev = repo.changelog.rev(node)
435 435 ui.write(_("Testing changeset %d:%s "
436 436 "(%d changesets remaining, ~%d tests)\n")
437 437 % (rev, short(node), changesets, tests))
438 438 if not noupdate:
439 439 cmdutil.bail_if_changed(repo)
440 440 return hg.clean(repo, node)
441 441
442 442 def branch(ui, repo, label=None, **opts):
443 443 """set or show the current branch name
444 444
445 445 With no argument, show the current branch name. With one argument,
446 446 set the working directory branch name (the branch will not exist
447 447 in the repository until the next commit). Standard practice
448 448 recommends that primary development take place on the 'default'
449 449 branch.
450 450
451 451 Unless -f/--force is specified, branch will not let you set a
452 452 branch name that already exists, even if it's inactive.
453 453
454 454 Use -C/--clean to reset the working directory branch to that of
455 455 the parent of the working directory, negating a previous branch
456 456 change.
457 457
458 458 Use the command :hg:`update` to switch to an existing branch. Use
459 459 :hg:`commit --close-branch` to mark this branch as closed.
460 460 """
461 461
462 462 if opts.get('clean'):
463 463 label = repo[None].parents()[0].branch()
464 464 repo.dirstate.setbranch(label)
465 465 ui.status(_('reset working directory to branch %s\n') % label)
466 466 elif label:
467 467 utflabel = encoding.fromlocal(label)
468 468 if not opts.get('force') and utflabel in repo.branchtags():
469 469 if label not in [p.branch() for p in repo.parents()]:
470 470 raise util.Abort(_('a branch of the same name already exists'
471 471 " (use 'hg update' to switch to it)"))
472 472 repo.dirstate.setbranch(utflabel)
473 473 ui.status(_('marked working directory as branch %s\n') % label)
474 474 else:
475 475 ui.write("%s\n" % encoding.tolocal(repo.dirstate.branch()))
476 476
477 477 def branches(ui, repo, active=False, closed=False):
478 478 """list repository named branches
479 479
480 480 List the repository's named branches, indicating which ones are
481 481 inactive. If -c/--closed is specified, also list branches which have
482 482 been marked closed (see hg commit --close-branch).
483 483
484 484 If -a/--active is specified, only show active branches. A branch
485 485 is considered active if it contains repository heads.
486 486
487 487 Use the command :hg:`update` to switch to an existing branch.
488 488 """
489 489
490 490 hexfunc = ui.debugflag and hex or short
491 491 activebranches = [repo[n].branch() for n in repo.heads()]
492 492 def testactive(tag, node):
493 493 realhead = tag in activebranches
494 494 open = node in repo.branchheads(tag, closed=False)
495 495 return realhead and open
496 496 branches = sorted([(testactive(tag, node), repo.changelog.rev(node), tag)
497 497 for tag, node in repo.branchtags().items()],
498 498 reverse=True)
499 499
500 500 for isactive, node, tag in branches:
501 501 if (not active) or isactive:
502 502 encodedtag = encoding.tolocal(tag)
503 503 if ui.quiet:
504 504 ui.write("%s\n" % encodedtag)
505 505 else:
506 506 hn = repo.lookup(node)
507 507 if isactive:
508 508 notice = ''
509 509 elif hn not in repo.branchheads(tag, closed=False):
510 510 if not closed:
511 511 continue
512 512 notice = _(' (closed)')
513 513 else:
514 514 notice = _(' (inactive)')
515 515 rev = str(node).rjust(31 - encoding.colwidth(encodedtag))
516 516 data = encodedtag, rev, hexfunc(hn), notice
517 517 ui.write("%s %s:%s%s\n" % data)
518 518
519 519 def bundle(ui, repo, fname, dest=None, **opts):
520 520 """create a changegroup file
521 521
522 522 Generate a compressed changegroup file collecting changesets not
523 523 known to be in another repository.
524 524
525 525 If you omit the destination repository, then hg assumes the
526 526 destination will have all the nodes you specify with --base
527 527 parameters. To create a bundle containing all changesets, use
528 528 -a/--all (or --base null).
529 529
530 530 You can change compression method with the -t/--type option.
531 531 The available compression methods are: none, bzip2, and
532 532 gzip (by default, bundles are compressed using bzip2).
533 533
534 534 The bundle file can then be transferred using conventional means
535 535 and applied to another repository with the unbundle or pull
536 536 command. This is useful when direct push and pull are not
537 537 available or when exporting an entire repository is undesirable.
538 538
539 539 Applying bundles preserves all changeset contents including
540 540 permissions, copy/rename information, and revision history.
541 541 """
542 542 revs = opts.get('rev') or None
543 543 if revs:
544 544 revs = [repo.lookup(rev) for rev in revs]
545 545 if opts.get('all'):
546 546 base = ['null']
547 547 else:
548 548 base = opts.get('base')
549 549 if base:
550 550 if dest:
551 551 raise util.Abort(_("--base is incompatible with specifying "
552 552 "a destination"))
553 553 base = [repo.lookup(rev) for rev in base]
554 554 # create the right base
555 555 # XXX: nodesbetween / changegroup* should be "fixed" instead
556 556 o = []
557 557 has = set((nullid,))
558 558 for n in base:
559 559 has.update(repo.changelog.reachable(n))
560 560 if revs:
561 561 visit = list(revs)
562 562 has.difference_update(revs)
563 563 else:
564 564 visit = repo.changelog.heads()
565 565 seen = {}
566 566 while visit:
567 567 n = visit.pop(0)
568 568 parents = [p for p in repo.changelog.parents(n) if p not in has]
569 569 if len(parents) == 0:
570 570 if n not in has:
571 571 o.append(n)
572 572 else:
573 573 for p in parents:
574 574 if p not in seen:
575 575 seen[p] = 1
576 576 visit.append(p)
577 577 else:
578 578 dest = ui.expandpath(dest or 'default-push', dest or 'default')
579 579 dest, branches = hg.parseurl(dest, opts.get('branch'))
580 580 other = hg.repository(cmdutil.remoteui(repo, opts), dest)
581 581 revs, checkout = hg.addbranchrevs(repo, other, branches, revs)
582 582 o = repo.findoutgoing(other, force=opts.get('force'))
583 583
584 584 if not o:
585 585 ui.status(_("no changes found\n"))
586 586 return
587 587
588 588 if revs:
589 589 cg = repo.changegroupsubset(o, revs, 'bundle')
590 590 else:
591 591 cg = repo.changegroup(o, 'bundle')
592 592
593 593 bundletype = opts.get('type', 'bzip2').lower()
594 594 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
595 595 bundletype = btypes.get(bundletype)
596 596 if bundletype not in changegroup.bundletypes:
597 597 raise util.Abort(_('unknown bundle type specified with --type'))
598 598
599 599 changegroup.writebundle(cg, fname, bundletype)
600 600
601 601 def cat(ui, repo, file1, *pats, **opts):
602 602 """output the current or given revision of files
603 603
604 604 Print the specified files as they were at the given revision. If
605 605 no revision is given, the parent of the working directory is used,
606 606 or tip if no revision is checked out.
607 607
608 608 Output may be to a file, in which case the name of the file is
609 609 given using a format string. The formatting rules are the same as
610 610 for the export command, with the following additions:
611 611
612 612 :``%s``: basename of file being printed
613 613 :``%d``: dirname of file being printed, or '.' if in repository root
614 614 :``%p``: root-relative path name of file being printed
615 615 """
616 616 ctx = repo[opts.get('rev')]
617 617 err = 1
618 618 m = cmdutil.match(repo, (file1,) + pats, opts)
619 619 for abs in ctx.walk(m):
620 620 fp = cmdutil.make_file(repo, opts.get('output'), ctx.node(), pathname=abs)
621 621 data = ctx[abs].data()
622 622 if opts.get('decode'):
623 623 data = repo.wwritedata(abs, data)
624 624 fp.write(data)
625 625 err = 0
626 626 return err
627 627
628 628 def clone(ui, source, dest=None, **opts):
629 629 """make a copy of an existing repository
630 630
631 631 Create a copy of an existing repository in a new directory.
632 632
633 633 If no destination directory name is specified, it defaults to the
634 634 basename of the source.
635 635
636 636 The location of the source is added to the new repository's
637 637 .hg/hgrc file, as the default to be used for future pulls.
638 638
639 639 See :hg:`help urls` for valid source format details.
640 640
641 641 It is possible to specify an ``ssh://`` URL as the destination, but no
642 642 .hg/hgrc and working directory will be created on the remote side.
643 643 Please see :hg:`help urls` for important details about ``ssh://`` URLs.
644 644
645 645 A set of changesets (tags, or branch names) to pull may be specified
646 646 by listing each changeset (tag, or branch name) with -r/--rev.
647 647 If -r/--rev is used, the cloned repository will contain only a subset
648 648 of the changesets of the source repository. Only the set of changesets
649 649 defined by all -r/--rev options (including all their ancestors)
650 650 will be pulled into the destination repository.
651 651 No subsequent changesets (including subsequent tags) will be present
652 652 in the destination.
653 653
654 654 Using -r/--rev (or 'clone src#rev dest') implies --pull, even for
655 655 local source repositories.
656 656
657 657 For efficiency, hardlinks are used for cloning whenever the source
658 658 and destination are on the same filesystem (note this applies only
659 659 to the repository data, not to the working directory). Some
660 660 filesystems, such as AFS, implement hardlinking incorrectly, but
661 661 do not report errors. In these cases, use the --pull option to
662 662 avoid hardlinking.
663 663
664 664 In some cases, you can clone repositories and the working directory
665 665 using full hardlinks with ::
666 666
667 667 $ cp -al REPO REPOCLONE
668 668
669 669 This is the fastest way to clone, but it is not always safe. The
670 670 operation is not atomic (making sure REPO is not modified during
671 671 the operation is up to you) and you have to make sure your editor
672 672 breaks hardlinks (Emacs and most Linux Kernel tools do so). Also,
673 673 this is not compatible with certain extensions that place their
674 674 metadata under the .hg directory, such as mq.
675 675
676 676 Mercurial will update the working directory to the first applicable
677 677 revision from this list:
678 678
679 679 a) null if -U or the source repository has no changesets
680 680 b) if -u . and the source repository is local, the first parent of
681 681 the source repository's working directory
682 682 c) the changeset specified with -u (if a branch name, this means the
683 683 latest head of that branch)
684 684 d) the changeset specified with -r
685 685 e) the tipmost head specified with -b
686 686 f) the tipmost head specified with the url#branch source syntax
687 687 g) the tipmost head of the default branch
688 688 h) tip
689 689 """
690 690 if opts.get('noupdate') and opts.get('updaterev'):
691 691 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
692 692
693 693 hg.clone(cmdutil.remoteui(ui, opts), source, dest,
694 694 pull=opts.get('pull'),
695 695 stream=opts.get('uncompressed'),
696 696 rev=opts.get('rev'),
697 697 update=opts.get('updaterev') or not opts.get('noupdate'),
698 698 branch=opts.get('branch'))
699 699
700 700 def commit(ui, repo, *pats, **opts):
701 701 """commit the specified files or all outstanding changes
702 702
703 703 Commit changes to the given files into the repository. Unlike a
704 704 centralized RCS, this operation is a local operation. See hg push
705 705 for a way to actively distribute your changes.
706 706
707 707 If a list of files is omitted, all changes reported by :hg:`status`
708 708 will be committed.
709 709
710 710 If you are committing the result of a merge, do not provide any
711 711 filenames or -I/-X filters.
712 712
713 713 If no commit message is specified, the configured editor is
714 714 started to prompt you for a message.
715 715
716 716 See :hg:`help dates` for a list of formats valid for -d/--date.
717 717 """
718 718 extra = {}
719 719 if opts.get('close_branch'):
720 720 extra['close'] = 1
721 721 e = cmdutil.commiteditor
722 722 if opts.get('force_editor'):
723 723 e = cmdutil.commitforceeditor
724 724
725 725 def commitfunc(ui, repo, message, match, opts):
726 726 return repo.commit(message, opts.get('user'), opts.get('date'), match,
727 727 editor=e, extra=extra)
728 728
729 729 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
730 730 if not node:
731 731 ui.status(_("nothing changed\n"))
732 732 return
733 733 cl = repo.changelog
734 734 rev = cl.rev(node)
735 735 parents = cl.parentrevs(rev)
736 736 if rev - 1 in parents:
737 737 # one of the parents was the old tip
738 738 pass
739 739 elif (parents == (nullrev, nullrev) or
740 740 len(cl.heads(cl.node(parents[0]))) > 1 and
741 741 (parents[1] == nullrev or len(cl.heads(cl.node(parents[1]))) > 1)):
742 742 ui.status(_('created new head\n'))
743 743
744 744 if ui.debugflag:
745 745 ui.write(_('committed changeset %d:%s\n') % (rev, hex(node)))
746 746 elif ui.verbose:
747 747 ui.write(_('committed changeset %d:%s\n') % (rev, short(node)))
748 748
749 749 def copy(ui, repo, *pats, **opts):
750 750 """mark files as copied for the next commit
751 751
752 752 Mark dest as having copies of source files. If dest is a
753 753 directory, copies are put in that directory. If dest is a file,
754 754 the source must be a single file.
755 755
756 756 By default, this command copies the contents of files as they
757 757 exist in the working directory. If invoked with -A/--after, the
758 758 operation is recorded, but no copying is performed.
759 759
760 760 This command takes effect with the next commit. To undo a copy
761 761 before that, see hg revert.
762 762 """
763 763 wlock = repo.wlock(False)
764 764 try:
765 765 return cmdutil.copy(ui, repo, pats, opts)
766 766 finally:
767 767 wlock.release()
768 768
769 769 def debugancestor(ui, repo, *args):
770 770 """find the ancestor revision of two revisions in a given index"""
771 771 if len(args) == 3:
772 772 index, rev1, rev2 = args
773 773 r = revlog.revlog(util.opener(os.getcwd(), audit=False), index)
774 774 lookup = r.lookup
775 775 elif len(args) == 2:
776 776 if not repo:
777 777 raise util.Abort(_("There is no Mercurial repository here "
778 778 "(.hg not found)"))
779 779 rev1, rev2 = args
780 780 r = repo.changelog
781 781 lookup = repo.lookup
782 782 else:
783 783 raise util.Abort(_('either two or three arguments required'))
784 784 a = r.ancestor(lookup(rev1), lookup(rev2))
785 785 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
786 786
787 787 def debugcommands(ui, cmd='', *args):
788 788 for cmd, vals in sorted(table.iteritems()):
789 789 cmd = cmd.split('|')[0].strip('^')
790 790 opts = ', '.join([i[1] for i in vals[1]])
791 791 ui.write('%s: %s\n' % (cmd, opts))
792 792
793 793 def debugcomplete(ui, cmd='', **opts):
794 794 """returns the completion list associated with the given command"""
795 795
796 796 if opts.get('options'):
797 797 options = []
798 798 otables = [globalopts]
799 799 if cmd:
800 800 aliases, entry = cmdutil.findcmd(cmd, table, False)
801 801 otables.append(entry[1])
802 802 for t in otables:
803 803 for o in t:
804 804 if "(DEPRECATED)" in o[3]:
805 805 continue
806 806 if o[0]:
807 807 options.append('-%s' % o[0])
808 808 options.append('--%s' % o[1])
809 809 ui.write("%s\n" % "\n".join(options))
810 810 return
811 811
812 812 cmdlist = cmdutil.findpossible(cmd, table)
813 813 if ui.verbose:
814 814 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
815 815 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
816 816
817 817 def debugfsinfo(ui, path = "."):
818 818 open('.debugfsinfo', 'w').write('')
819 819 ui.write('exec: %s\n' % (util.checkexec(path) and 'yes' or 'no'))
820 820 ui.write('symlink: %s\n' % (util.checklink(path) and 'yes' or 'no'))
821 821 ui.write('case-sensitive: %s\n' % (util.checkcase('.debugfsinfo')
822 822 and 'yes' or 'no'))
823 823 os.unlink('.debugfsinfo')
824 824
825 825 def debugrebuildstate(ui, repo, rev="tip"):
826 826 """rebuild the dirstate as it would look like for the given revision"""
827 827 ctx = repo[rev]
828 828 wlock = repo.wlock()
829 829 try:
830 830 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
831 831 finally:
832 832 wlock.release()
833 833
834 834 def debugcheckstate(ui, repo):
835 835 """validate the correctness of the current dirstate"""
836 836 parent1, parent2 = repo.dirstate.parents()
837 837 m1 = repo[parent1].manifest()
838 838 m2 = repo[parent2].manifest()
839 839 errors = 0
840 840 for f in repo.dirstate:
841 841 state = repo.dirstate[f]
842 842 if state in "nr" and f not in m1:
843 843 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
844 844 errors += 1
845 845 if state in "a" and f in m1:
846 846 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
847 847 errors += 1
848 848 if state in "m" and f not in m1 and f not in m2:
849 849 ui.warn(_("%s in state %s, but not in either manifest\n") %
850 850 (f, state))
851 851 errors += 1
852 852 for f in m1:
853 853 state = repo.dirstate[f]
854 854 if state not in "nrm":
855 855 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
856 856 errors += 1
857 857 if errors:
858 858 error = _(".hg/dirstate inconsistent with current parent's manifest")
859 859 raise util.Abort(error)
860 860
861 861 def showconfig(ui, repo, *values, **opts):
862 862 """show combined config settings from all hgrc files
863 863
864 864 With no arguments, print names and values of all config items.
865 865
866 866 With one argument of the form section.name, print just the value
867 867 of that config item.
868 868
869 869 With multiple arguments, print names and values of all config
870 870 items with matching section names.
871 871
872 872 With --debug, the source (filename and line number) is printed
873 873 for each config item.
874 874 """
875 875
876 876 for f in util.rcpath():
877 877 ui.debug(_('read config from: %s\n') % f)
878 878 untrusted = bool(opts.get('untrusted'))
879 879 if values:
880 880 if len([v for v in values if '.' in v]) > 1:
881 881 raise util.Abort(_('only one config item permitted'))
882 882 for section, name, value in ui.walkconfig(untrusted=untrusted):
883 883 sectname = section + '.' + name
884 884 if values:
885 885 for v in values:
886 886 if v == section:
887 887 ui.debug('%s: ' %
888 888 ui.configsource(section, name, untrusted))
889 889 ui.write('%s=%s\n' % (sectname, value))
890 890 elif v == sectname:
891 891 ui.debug('%s: ' %
892 892 ui.configsource(section, name, untrusted))
893 893 ui.write(value, '\n')
894 894 else:
895 895 ui.debug('%s: ' %
896 896 ui.configsource(section, name, untrusted))
897 897 ui.write('%s=%s\n' % (sectname, value))
898 898
899 899 def debugsetparents(ui, repo, rev1, rev2=None):
900 900 """manually set the parents of the current working directory
901 901
902 902 This is useful for writing repository conversion tools, but should
903 903 be used with care.
904 904 """
905 905
906 906 if not rev2:
907 907 rev2 = hex(nullid)
908 908
909 909 wlock = repo.wlock()
910 910 try:
911 911 repo.dirstate.setparents(repo.lookup(rev1), repo.lookup(rev2))
912 912 finally:
913 913 wlock.release()
914 914
915 915 def debugstate(ui, repo, nodates=None):
916 916 """show the contents of the current dirstate"""
917 917 timestr = ""
918 918 showdate = not nodates
919 919 for file_, ent in sorted(repo.dirstate._map.iteritems()):
920 920 if showdate:
921 921 if ent[3] == -1:
922 922 # Pad or slice to locale representation
923 923 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
924 924 time.localtime(0)))
925 925 timestr = 'unset'
926 926 timestr = (timestr[:locale_len] +
927 927 ' ' * (locale_len - len(timestr)))
928 928 else:
929 929 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
930 930 time.localtime(ent[3]))
931 931 if ent[1] & 020000:
932 932 mode = 'lnk'
933 933 else:
934 934 mode = '%3o' % (ent[1] & 0777)
935 935 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
936 936 for f in repo.dirstate.copies():
937 937 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
938 938
939 939 def debugsub(ui, repo, rev=None):
940 940 if rev == '':
941 941 rev = None
942 942 for k, v in sorted(repo[rev].substate.items()):
943 943 ui.write('path %s\n' % k)
944 944 ui.write(' source %s\n' % v[0])
945 945 ui.write(' revision %s\n' % v[1])
946 946
947 947 def debugdata(ui, file_, rev):
948 948 """dump the contents of a data file revision"""
949 949 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_[:-2] + ".i")
950 950 try:
951 951 ui.write(r.revision(r.lookup(rev)))
952 952 except KeyError:
953 953 raise util.Abort(_('invalid revision identifier %s') % rev)
954 954
955 955 def debugdate(ui, date, range=None, **opts):
956 956 """parse and display a date"""
957 957 if opts["extended"]:
958 958 d = util.parsedate(date, util.extendeddateformats)
959 959 else:
960 960 d = util.parsedate(date)
961 961 ui.write("internal: %s %s\n" % d)
962 962 ui.write("standard: %s\n" % util.datestr(d))
963 963 if range:
964 964 m = util.matchdate(range)
965 965 ui.write("match: %s\n" % m(d[0]))
966 966
967 967 def debugindex(ui, file_):
968 968 """dump the contents of an index file"""
969 969 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_)
970 970 ui.write(" rev offset length base linkrev"
971 971 " nodeid p1 p2\n")
972 972 for i in r:
973 973 node = r.node(i)
974 974 try:
975 975 pp = r.parents(node)
976 976 except:
977 977 pp = [nullid, nullid]
978 978 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
979 979 i, r.start(i), r.length(i), r.base(i), r.linkrev(i),
980 980 short(node), short(pp[0]), short(pp[1])))
981 981
982 982 def debugindexdot(ui, file_):
983 983 """dump an index DAG as a graphviz dot file"""
984 984 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_)
985 985 ui.write("digraph G {\n")
986 986 for i in r:
987 987 node = r.node(i)
988 988 pp = r.parents(node)
989 989 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
990 990 if pp[1] != nullid:
991 991 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
992 992 ui.write("}\n")
993 993
994 994 def debuginstall(ui):
995 995 '''test Mercurial installation'''
996 996
997 997 def writetemp(contents):
998 998 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
999 999 f = os.fdopen(fd, "wb")
1000 1000 f.write(contents)
1001 1001 f.close()
1002 1002 return name
1003 1003
1004 1004 problems = 0
1005 1005
1006 1006 # encoding
1007 1007 ui.status(_("Checking encoding (%s)...\n") % encoding.encoding)
1008 1008 try:
1009 1009 encoding.fromlocal("test")
1010 1010 except util.Abort, inst:
1011 1011 ui.write(" %s\n" % inst)
1012 1012 ui.write(_(" (check that your locale is properly set)\n"))
1013 1013 problems += 1
1014 1014
1015 1015 # compiled modules
1016 1016 ui.status(_("Checking extensions...\n"))
1017 1017 try:
1018 1018 import bdiff, mpatch, base85
1019 1019 except Exception, inst:
1020 1020 ui.write(" %s\n" % inst)
1021 1021 ui.write(_(" One or more extensions could not be found"))
1022 1022 ui.write(_(" (check that you compiled the extensions)\n"))
1023 1023 problems += 1
1024 1024
1025 1025 # templates
1026 1026 ui.status(_("Checking templates...\n"))
1027 1027 try:
1028 1028 import templater
1029 1029 templater.templater(templater.templatepath("map-cmdline.default"))
1030 1030 except Exception, inst:
1031 1031 ui.write(" %s\n" % inst)
1032 1032 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
1033 1033 problems += 1
1034 1034
1035 1035 # patch
1036 1036 ui.status(_("Checking patch...\n"))
1037 1037 patchproblems = 0
1038 1038 a = "1\n2\n3\n4\n"
1039 1039 b = "1\n2\n3\ninsert\n4\n"
1040 1040 fa = writetemp(a)
1041 1041 d = mdiff.unidiff(a, None, b, None, os.path.basename(fa),
1042 1042 os.path.basename(fa))
1043 1043 fd = writetemp(d)
1044 1044
1045 1045 files = {}
1046 1046 try:
1047 1047 patch.patch(fd, ui, cwd=os.path.dirname(fa), files=files)
1048 1048 except util.Abort, e:
1049 1049 ui.write(_(" patch call failed:\n"))
1050 1050 ui.write(" " + str(e) + "\n")
1051 1051 patchproblems += 1
1052 1052 else:
1053 1053 if list(files) != [os.path.basename(fa)]:
1054 1054 ui.write(_(" unexpected patch output!\n"))
1055 1055 patchproblems += 1
1056 1056 a = open(fa).read()
1057 1057 if a != b:
1058 1058 ui.write(_(" patch test failed!\n"))
1059 1059 patchproblems += 1
1060 1060
1061 1061 if patchproblems:
1062 1062 if ui.config('ui', 'patch'):
1063 1063 ui.write(_(" (Current patch tool may be incompatible with patch,"
1064 1064 " or misconfigured. Please check your .hgrc file)\n"))
1065 1065 else:
1066 1066 ui.write(_(" Internal patcher failure, please report this error"
1067 1067 " to http://mercurial.selenic.com/bts/\n"))
1068 1068 problems += patchproblems
1069 1069
1070 1070 os.unlink(fa)
1071 1071 os.unlink(fd)
1072 1072
1073 1073 # editor
1074 1074 ui.status(_("Checking commit editor...\n"))
1075 1075 editor = ui.geteditor()
1076 1076 cmdpath = util.find_exe(editor) or util.find_exe(editor.split()[0])
1077 1077 if not cmdpath:
1078 1078 if editor == 'vi':
1079 1079 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
1080 1080 ui.write(_(" (specify a commit editor in your .hgrc file)\n"))
1081 1081 else:
1082 1082 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
1083 1083 ui.write(_(" (specify a commit editor in your .hgrc file)\n"))
1084 1084 problems += 1
1085 1085
1086 1086 # check username
1087 1087 ui.status(_("Checking username...\n"))
1088 1088 try:
1089 1089 user = ui.username()
1090 1090 except util.Abort, e:
1091 1091 ui.write(" %s\n" % e)
1092 1092 ui.write(_(" (specify a username in your .hgrc file)\n"))
1093 1093 problems += 1
1094 1094
1095 1095 if not problems:
1096 1096 ui.status(_("No problems detected\n"))
1097 1097 else:
1098 1098 ui.write(_("%s problems detected,"
1099 1099 " please check your install!\n") % problems)
1100 1100
1101 1101 return problems
1102 1102
1103 1103 def debugrename(ui, repo, file1, *pats, **opts):
1104 1104 """dump rename information"""
1105 1105
1106 1106 ctx = repo[opts.get('rev')]
1107 1107 m = cmdutil.match(repo, (file1,) + pats, opts)
1108 1108 for abs in ctx.walk(m):
1109 1109 fctx = ctx[abs]
1110 1110 o = fctx.filelog().renamed(fctx.filenode())
1111 1111 rel = m.rel(abs)
1112 1112 if o:
1113 1113 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
1114 1114 else:
1115 1115 ui.write(_("%s not renamed\n") % rel)
1116 1116
1117 1117 def debugwalk(ui, repo, *pats, **opts):
1118 1118 """show how files match on given patterns"""
1119 1119 m = cmdutil.match(repo, pats, opts)
1120 1120 items = list(repo.walk(m))
1121 1121 if not items:
1122 1122 return
1123 1123 fmt = 'f %%-%ds %%-%ds %%s' % (
1124 1124 max([len(abs) for abs in items]),
1125 1125 max([len(m.rel(abs)) for abs in items]))
1126 1126 for abs in items:
1127 1127 line = fmt % (abs, m.rel(abs), m.exact(abs) and 'exact' or '')
1128 1128 ui.write("%s\n" % line.rstrip())
1129 1129
1130 1130 def diff(ui, repo, *pats, **opts):
1131 1131 """diff repository (or selected files)
1132 1132
1133 1133 Show differences between revisions for the specified files.
1134 1134
1135 1135 Differences between files are shown using the unified diff format.
1136 1136
1137 1137 NOTE: diff may generate unexpected results for merges, as it will
1138 1138 default to comparing against the working directory's first parent
1139 1139 changeset if no revisions are specified.
1140 1140
1141 1141 When two revision arguments are given, then changes are shown
1142 1142 between those revisions. If only one revision is specified then
1143 1143 that revision is compared to the working directory, and, when no
1144 1144 revisions are specified, the working directory files are compared
1145 1145 to its parent.
1146 1146
1147 1147 Alternatively you can specify -c/--change with a revision to see
1148 1148 the changes in that changeset relative to its first parent.
1149 1149
1150 1150 Without the -a/--text option, diff will avoid generating diffs of
1151 1151 files it detects as binary. With -a, diff will generate a diff
1152 1152 anyway, probably with undesirable results.
1153 1153
1154 1154 Use the -g/--git option to generate diffs in the git extended diff
1155 1155 format. For more information, read :hg:`help diffs`.
1156 1156 """
1157 1157
1158 1158 revs = opts.get('rev')
1159 1159 change = opts.get('change')
1160 1160 stat = opts.get('stat')
1161 1161 reverse = opts.get('reverse')
1162 1162
1163 1163 if revs and change:
1164 1164 msg = _('cannot specify --rev and --change at the same time')
1165 1165 raise util.Abort(msg)
1166 1166 elif change:
1167 1167 node2 = repo.lookup(change)
1168 1168 node1 = repo[node2].parents()[0].node()
1169 1169 else:
1170 1170 node1, node2 = cmdutil.revpair(repo, revs)
1171 1171
1172 1172 if reverse:
1173 1173 node1, node2 = node2, node1
1174 1174
1175 if stat:
1176 opts['unified'] = '0'
1177 1175 diffopts = patch.diffopts(ui, opts)
1178
1179 1176 m = cmdutil.match(repo, pats, opts)
1180 if stat:
1181 it = patch.diff(repo, node1, node2, match=m, opts=diffopts)
1182 width = 80
1183 if not ui.plain():
1184 width = util.termwidth()
1185 for chunk, label in patch.diffstatui(util.iterlines(it), width=width,
1186 git=diffopts.git):
1187 ui.write(chunk, label=label)
1188 else:
1189 it = patch.diffui(repo, node1, node2, match=m, opts=diffopts)
1190 for chunk, label in it:
1191 ui.write(chunk, label=label)
1177 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat)
1192 1178
1193 1179 def export(ui, repo, *changesets, **opts):
1194 1180 """dump the header and diffs for one or more changesets
1195 1181
1196 1182 Print the changeset header and diffs for one or more revisions.
1197 1183
1198 1184 The information shown in the changeset header is: author, date,
1199 1185 branch name (if non-default), changeset hash, parent(s) and commit
1200 1186 comment.
1201 1187
1202 1188 NOTE: export may generate unexpected diff output for merge
1203 1189 changesets, as it will compare the merge changeset against its
1204 1190 first parent only.
1205 1191
1206 1192 Output may be to a file, in which case the name of the file is
1207 1193 given using a format string. The formatting rules are as follows:
1208 1194
1209 1195 :``%%``: literal "%" character
1210 1196 :``%H``: changeset hash (40 bytes of hexadecimal)
1211 1197 :``%N``: number of patches being generated
1212 1198 :``%R``: changeset revision number
1213 1199 :``%b``: basename of the exporting repository
1214 1200 :``%h``: short-form changeset hash (12 bytes of hexadecimal)
1215 1201 :``%n``: zero-padded sequence number, starting at 1
1216 1202 :``%r``: zero-padded changeset revision number
1217 1203
1218 1204 Without the -a/--text option, export will avoid generating diffs
1219 1205 of files it detects as binary. With -a, export will generate a
1220 1206 diff anyway, probably with undesirable results.
1221 1207
1222 1208 Use the -g/--git option to generate diffs in the git extended diff
1223 1209 format. See :hg:`help diffs` for more information.
1224 1210
1225 1211 With the --switch-parent option, the diff will be against the
1226 1212 second parent. It can be useful to review a merge.
1227 1213 """
1228 1214 changesets += tuple(opts.get('rev', []))
1229 1215 if not changesets:
1230 1216 raise util.Abort(_("export requires at least one changeset"))
1231 1217 revs = cmdutil.revrange(repo, changesets)
1232 1218 if len(revs) > 1:
1233 1219 ui.note(_('exporting patches:\n'))
1234 1220 else:
1235 1221 ui.note(_('exporting patch:\n'))
1236 1222 cmdutil.export(repo, revs, template=opts.get('output'),
1237 1223 switch_parent=opts.get('switch_parent'),
1238 1224 opts=patch.diffopts(ui, opts))
1239 1225
1240 1226 def forget(ui, repo, *pats, **opts):
1241 1227 """forget the specified files on the next commit
1242 1228
1243 1229 Mark the specified files so they will no longer be tracked
1244 1230 after the next commit.
1245 1231
1246 1232 This only removes files from the current branch, not from the
1247 1233 entire project history, and it does not delete them from the
1248 1234 working directory.
1249 1235
1250 1236 To undo a forget before the next commit, see hg add.
1251 1237 """
1252 1238
1253 1239 if not pats:
1254 1240 raise util.Abort(_('no files specified'))
1255 1241
1256 1242 m = cmdutil.match(repo, pats, opts)
1257 1243 s = repo.status(match=m, clean=True)
1258 1244 forget = sorted(s[0] + s[1] + s[3] + s[6])
1259 1245
1260 1246 for f in m.files():
1261 1247 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
1262 1248 ui.warn(_('not removing %s: file is already untracked\n')
1263 1249 % m.rel(f))
1264 1250
1265 1251 for f in forget:
1266 1252 if ui.verbose or not m.exact(f):
1267 1253 ui.status(_('removing %s\n') % m.rel(f))
1268 1254
1269 1255 repo.remove(forget, unlink=False)
1270 1256
1271 1257 def grep(ui, repo, pattern, *pats, **opts):
1272 1258 """search for a pattern in specified files and revisions
1273 1259
1274 1260 Search revisions of files for a regular expression.
1275 1261
1276 1262 This command behaves differently than Unix grep. It only accepts
1277 1263 Python/Perl regexps. It searches repository history, not the
1278 1264 working directory. It always prints the revision number in which a
1279 1265 match appears.
1280 1266
1281 1267 By default, grep only prints output for the first revision of a
1282 1268 file in which it finds a match. To get it to print every revision
1283 1269 that contains a change in match status ("-" for a match that
1284 1270 becomes a non-match, or "+" for a non-match that becomes a match),
1285 1271 use the --all flag.
1286 1272 """
1287 1273 reflags = 0
1288 1274 if opts.get('ignore_case'):
1289 1275 reflags |= re.I
1290 1276 try:
1291 1277 regexp = re.compile(pattern, reflags)
1292 1278 except Exception, inst:
1293 1279 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
1294 1280 return None
1295 1281 sep, eol = ':', '\n'
1296 1282 if opts.get('print0'):
1297 1283 sep = eol = '\0'
1298 1284
1299 1285 getfile = util.lrucachefunc(repo.file)
1300 1286
1301 1287 def matchlines(body):
1302 1288 begin = 0
1303 1289 linenum = 0
1304 1290 while True:
1305 1291 match = regexp.search(body, begin)
1306 1292 if not match:
1307 1293 break
1308 1294 mstart, mend = match.span()
1309 1295 linenum += body.count('\n', begin, mstart) + 1
1310 1296 lstart = body.rfind('\n', begin, mstart) + 1 or begin
1311 1297 begin = body.find('\n', mend) + 1 or len(body)
1312 1298 lend = begin - 1
1313 1299 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
1314 1300
1315 1301 class linestate(object):
1316 1302 def __init__(self, line, linenum, colstart, colend):
1317 1303 self.line = line
1318 1304 self.linenum = linenum
1319 1305 self.colstart = colstart
1320 1306 self.colend = colend
1321 1307
1322 1308 def __hash__(self):
1323 1309 return hash((self.linenum, self.line))
1324 1310
1325 1311 def __eq__(self, other):
1326 1312 return self.line == other.line
1327 1313
1328 1314 matches = {}
1329 1315 copies = {}
1330 1316 def grepbody(fn, rev, body):
1331 1317 matches[rev].setdefault(fn, [])
1332 1318 m = matches[rev][fn]
1333 1319 for lnum, cstart, cend, line in matchlines(body):
1334 1320 s = linestate(line, lnum, cstart, cend)
1335 1321 m.append(s)
1336 1322
1337 1323 def difflinestates(a, b):
1338 1324 sm = difflib.SequenceMatcher(None, a, b)
1339 1325 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
1340 1326 if tag == 'insert':
1341 1327 for i in xrange(blo, bhi):
1342 1328 yield ('+', b[i])
1343 1329 elif tag == 'delete':
1344 1330 for i in xrange(alo, ahi):
1345 1331 yield ('-', a[i])
1346 1332 elif tag == 'replace':
1347 1333 for i in xrange(alo, ahi):
1348 1334 yield ('-', a[i])
1349 1335 for i in xrange(blo, bhi):
1350 1336 yield ('+', b[i])
1351 1337
1352 1338 def display(fn, ctx, pstates, states):
1353 1339 rev = ctx.rev()
1354 1340 datefunc = ui.quiet and util.shortdate or util.datestr
1355 1341 found = False
1356 1342 filerevmatches = {}
1357 1343 if opts.get('all'):
1358 1344 iter = difflinestates(pstates, states)
1359 1345 else:
1360 1346 iter = [('', l) for l in states]
1361 1347 for change, l in iter:
1362 1348 cols = [fn, str(rev)]
1363 1349 before, match, after = None, None, None
1364 1350 if opts.get('line_number'):
1365 1351 cols.append(str(l.linenum))
1366 1352 if opts.get('all'):
1367 1353 cols.append(change)
1368 1354 if opts.get('user'):
1369 1355 cols.append(ui.shortuser(ctx.user()))
1370 1356 if opts.get('date'):
1371 1357 cols.append(datefunc(ctx.date()))
1372 1358 if opts.get('files_with_matches'):
1373 1359 c = (fn, rev)
1374 1360 if c in filerevmatches:
1375 1361 continue
1376 1362 filerevmatches[c] = 1
1377 1363 else:
1378 1364 before = l.line[:l.colstart]
1379 1365 match = l.line[l.colstart:l.colend]
1380 1366 after = l.line[l.colend:]
1381 1367 ui.write(sep.join(cols))
1382 1368 if before is not None:
1383 1369 ui.write(sep + before)
1384 1370 ui.write(match, label='grep.match')
1385 1371 ui.write(after)
1386 1372 ui.write(eol)
1387 1373 found = True
1388 1374 return found
1389 1375
1390 1376 skip = {}
1391 1377 revfiles = {}
1392 1378 matchfn = cmdutil.match(repo, pats, opts)
1393 1379 found = False
1394 1380 follow = opts.get('follow')
1395 1381
1396 1382 def prep(ctx, fns):
1397 1383 rev = ctx.rev()
1398 1384 pctx = ctx.parents()[0]
1399 1385 parent = pctx.rev()
1400 1386 matches.setdefault(rev, {})
1401 1387 matches.setdefault(parent, {})
1402 1388 files = revfiles.setdefault(rev, [])
1403 1389 for fn in fns:
1404 1390 flog = getfile(fn)
1405 1391 try:
1406 1392 fnode = ctx.filenode(fn)
1407 1393 except error.LookupError:
1408 1394 continue
1409 1395
1410 1396 copied = flog.renamed(fnode)
1411 1397 copy = follow and copied and copied[0]
1412 1398 if copy:
1413 1399 copies.setdefault(rev, {})[fn] = copy
1414 1400 if fn in skip:
1415 1401 if copy:
1416 1402 skip[copy] = True
1417 1403 continue
1418 1404 files.append(fn)
1419 1405
1420 1406 if fn not in matches[rev]:
1421 1407 grepbody(fn, rev, flog.read(fnode))
1422 1408
1423 1409 pfn = copy or fn
1424 1410 if pfn not in matches[parent]:
1425 1411 try:
1426 1412 fnode = pctx.filenode(pfn)
1427 1413 grepbody(pfn, parent, flog.read(fnode))
1428 1414 except error.LookupError:
1429 1415 pass
1430 1416
1431 1417 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
1432 1418 rev = ctx.rev()
1433 1419 parent = ctx.parents()[0].rev()
1434 1420 for fn in sorted(revfiles.get(rev, [])):
1435 1421 states = matches[rev][fn]
1436 1422 copy = copies.get(rev, {}).get(fn)
1437 1423 if fn in skip:
1438 1424 if copy:
1439 1425 skip[copy] = True
1440 1426 continue
1441 1427 pstates = matches.get(parent, {}).get(copy or fn, [])
1442 1428 if pstates or states:
1443 1429 r = display(fn, ctx, pstates, states)
1444 1430 found = found or r
1445 1431 if r and not opts.get('all'):
1446 1432 skip[fn] = True
1447 1433 if copy:
1448 1434 skip[copy] = True
1449 1435 del matches[rev]
1450 1436 del revfiles[rev]
1451 1437
1452 1438 def heads(ui, repo, *branchrevs, **opts):
1453 1439 """show current repository heads or show branch heads
1454 1440
1455 1441 With no arguments, show all repository branch heads.
1456 1442
1457 1443 Repository "heads" are changesets with no child changesets. They are
1458 1444 where development generally takes place and are the usual targets
1459 1445 for update and merge operations. Branch heads are changesets that have
1460 1446 no child changeset on the same branch.
1461 1447
1462 1448 If one or more REVs are given, only branch heads on the branches
1463 1449 associated with the specified changesets are shown.
1464 1450
1465 1451 If -c/--closed is specified, also show branch heads marked closed
1466 1452 (see hg commit --close-branch).
1467 1453
1468 1454 If STARTREV is specified, only those heads that are descendants of
1469 1455 STARTREV will be displayed.
1470 1456
1471 1457 If -t/--topo is specified, named branch mechanics will be ignored and only
1472 1458 changesets without children will be shown.
1473 1459 """
1474 1460
1475 1461 if opts.get('rev'):
1476 1462 start = repo.lookup(opts['rev'])
1477 1463 else:
1478 1464 start = None
1479 1465
1480 1466 if opts.get('topo'):
1481 1467 heads = [repo[h] for h in repo.heads(start)]
1482 1468 else:
1483 1469 heads = []
1484 1470 for b, ls in repo.branchmap().iteritems():
1485 1471 if start is None:
1486 1472 heads += [repo[h] for h in ls]
1487 1473 continue
1488 1474 startrev = repo.changelog.rev(start)
1489 1475 descendants = set(repo.changelog.descendants(startrev))
1490 1476 descendants.add(startrev)
1491 1477 rev = repo.changelog.rev
1492 1478 heads += [repo[h] for h in ls if rev(h) in descendants]
1493 1479
1494 1480 if branchrevs:
1495 1481 decode, encode = encoding.fromlocal, encoding.tolocal
1496 1482 branches = set(repo[decode(br)].branch() for br in branchrevs)
1497 1483 heads = [h for h in heads if h.branch() in branches]
1498 1484
1499 1485 if not opts.get('closed'):
1500 1486 heads = [h for h in heads if not h.extra().get('close')]
1501 1487
1502 1488 if opts.get('active') and branchrevs:
1503 1489 dagheads = repo.heads(start)
1504 1490 heads = [h for h in heads if h.node() in dagheads]
1505 1491
1506 1492 if branchrevs:
1507 1493 haveheads = set(h.branch() for h in heads)
1508 1494 if branches - haveheads:
1509 1495 headless = ', '.join(encode(b) for b in branches - haveheads)
1510 1496 msg = _('no open branch heads found on branches %s')
1511 1497 if opts.get('rev'):
1512 1498 msg += _(' (started at %s)' % opts['rev'])
1513 1499 ui.warn((msg + '\n') % headless)
1514 1500
1515 1501 if not heads:
1516 1502 return 1
1517 1503
1518 1504 heads = sorted(heads, key=lambda x: -x.rev())
1519 1505 displayer = cmdutil.show_changeset(ui, repo, opts)
1520 1506 for ctx in heads:
1521 1507 displayer.show(ctx)
1522 1508 displayer.close()
1523 1509
1524 1510 def help_(ui, name=None, with_version=False, unknowncmd=False):
1525 1511 """show help for a given topic or a help overview
1526 1512
1527 1513 With no arguments, print a list of commands with short help messages.
1528 1514
1529 1515 Given a topic, extension, or command name, print help for that
1530 1516 topic."""
1531 1517 option_lists = []
1532 1518 textwidth = util.termwidth() - 2
1533 1519
1534 1520 def addglobalopts(aliases):
1535 1521 if ui.verbose:
1536 1522 option_lists.append((_("global options:"), globalopts))
1537 1523 if name == 'shortlist':
1538 1524 option_lists.append((_('use "hg help" for the full list '
1539 1525 'of commands'), ()))
1540 1526 else:
1541 1527 if name == 'shortlist':
1542 1528 msg = _('use "hg help" for the full list of commands '
1543 1529 'or "hg -v" for details')
1544 1530 elif aliases:
1545 1531 msg = _('use "hg -v help%s" to show aliases and '
1546 1532 'global options') % (name and " " + name or "")
1547 1533 else:
1548 1534 msg = _('use "hg -v help %s" to show global options') % name
1549 1535 option_lists.append((msg, ()))
1550 1536
1551 1537 def helpcmd(name):
1552 1538 if with_version:
1553 1539 version_(ui)
1554 1540 ui.write('\n')
1555 1541
1556 1542 try:
1557 1543 aliases, entry = cmdutil.findcmd(name, table, strict=unknowncmd)
1558 1544 except error.AmbiguousCommand, inst:
1559 1545 # py3k fix: except vars can't be used outside the scope of the
1560 1546 # except block, nor can be used inside a lambda. python issue4617
1561 1547 prefix = inst.args[0]
1562 1548 select = lambda c: c.lstrip('^').startswith(prefix)
1563 1549 helplist(_('list of commands:\n\n'), select)
1564 1550 return
1565 1551
1566 1552 # check if it's an invalid alias and display its error if it is
1567 1553 if getattr(entry[0], 'badalias', False):
1568 1554 if not unknowncmd:
1569 1555 entry[0](ui)
1570 1556 return
1571 1557
1572 1558 # synopsis
1573 1559 if len(entry) > 2:
1574 1560 if entry[2].startswith('hg'):
1575 1561 ui.write("%s\n" % entry[2])
1576 1562 else:
1577 1563 ui.write('hg %s %s\n' % (aliases[0], entry[2]))
1578 1564 else:
1579 1565 ui.write('hg %s\n' % aliases[0])
1580 1566
1581 1567 # aliases
1582 1568 if not ui.quiet and len(aliases) > 1:
1583 1569 ui.write(_("\naliases: %s\n") % ', '.join(aliases[1:]))
1584 1570
1585 1571 # description
1586 1572 doc = gettext(entry[0].__doc__)
1587 1573 if not doc:
1588 1574 doc = _("(no help text available)")
1589 1575 if hasattr(entry[0], 'definition'): # aliased command
1590 1576 doc = _('alias for: hg %s\n\n%s') % (entry[0].definition, doc)
1591 1577 if ui.quiet:
1592 1578 doc = doc.splitlines()[0]
1593 1579 keep = ui.verbose and ['verbose'] or []
1594 1580 formatted, pruned = minirst.format(doc, textwidth, keep=keep)
1595 1581 ui.write("\n%s\n" % formatted)
1596 1582 if pruned:
1597 1583 ui.write(_('\nuse "hg -v help %s" to show verbose help\n') % name)
1598 1584
1599 1585 if not ui.quiet:
1600 1586 # options
1601 1587 if entry[1]:
1602 1588 option_lists.append((_("options:\n"), entry[1]))
1603 1589
1604 1590 addglobalopts(False)
1605 1591
1606 1592 def helplist(header, select=None):
1607 1593 h = {}
1608 1594 cmds = {}
1609 1595 for c, e in table.iteritems():
1610 1596 f = c.split("|", 1)[0]
1611 1597 if select and not select(f):
1612 1598 continue
1613 1599 if (not select and name != 'shortlist' and
1614 1600 e[0].__module__ != __name__):
1615 1601 continue
1616 1602 if name == "shortlist" and not f.startswith("^"):
1617 1603 continue
1618 1604 f = f.lstrip("^")
1619 1605 if not ui.debugflag and f.startswith("debug"):
1620 1606 continue
1621 1607 doc = e[0].__doc__
1622 1608 if doc and 'DEPRECATED' in doc and not ui.verbose:
1623 1609 continue
1624 1610 doc = gettext(doc)
1625 1611 if not doc:
1626 1612 doc = _("(no help text available)")
1627 1613 h[f] = doc.splitlines()[0].rstrip()
1628 1614 cmds[f] = c.lstrip("^")
1629 1615
1630 1616 if not h:
1631 1617 ui.status(_('no commands defined\n'))
1632 1618 return
1633 1619
1634 1620 ui.status(header)
1635 1621 fns = sorted(h)
1636 1622 m = max(map(len, fns))
1637 1623 for f in fns:
1638 1624 if ui.verbose:
1639 1625 commands = cmds[f].replace("|",", ")
1640 1626 ui.write(" %s:\n %s\n"%(commands, h[f]))
1641 1627 else:
1642 1628 ui.write(' %-*s %s\n' % (m, f, util.wrap(h[f], m + 4)))
1643 1629
1644 1630 if not ui.quiet:
1645 1631 addglobalopts(True)
1646 1632
1647 1633 def helptopic(name):
1648 1634 for names, header, doc in help.helptable:
1649 1635 if name in names:
1650 1636 break
1651 1637 else:
1652 1638 raise error.UnknownCommand(name)
1653 1639
1654 1640 # description
1655 1641 if not doc:
1656 1642 doc = _("(no help text available)")
1657 1643 if hasattr(doc, '__call__'):
1658 1644 doc = doc()
1659 1645
1660 1646 ui.write("%s\n\n" % header)
1661 1647 ui.write("%s\n" % minirst.format(doc, textwidth, indent=4))
1662 1648
1663 1649 def helpext(name):
1664 1650 try:
1665 1651 mod = extensions.find(name)
1666 1652 doc = gettext(mod.__doc__) or _('no help text available')
1667 1653 except KeyError:
1668 1654 mod = None
1669 1655 doc = extensions.disabledext(name)
1670 1656 if not doc:
1671 1657 raise error.UnknownCommand(name)
1672 1658
1673 1659 if '\n' not in doc:
1674 1660 head, tail = doc, ""
1675 1661 else:
1676 1662 head, tail = doc.split('\n', 1)
1677 1663 ui.write(_('%s extension - %s\n\n') % (name.split('.')[-1], head))
1678 1664 if tail:
1679 1665 ui.write(minirst.format(tail, textwidth))
1680 1666 ui.status('\n\n')
1681 1667
1682 1668 if mod:
1683 1669 try:
1684 1670 ct = mod.cmdtable
1685 1671 except AttributeError:
1686 1672 ct = {}
1687 1673 modcmds = set([c.split('|', 1)[0] for c in ct])
1688 1674 helplist(_('list of commands:\n\n'), modcmds.__contains__)
1689 1675 else:
1690 1676 ui.write(_('use "hg help extensions" for information on enabling '
1691 1677 'extensions\n'))
1692 1678
1693 1679 def helpextcmd(name):
1694 1680 cmd, ext, mod = extensions.disabledcmd(name, ui.config('ui', 'strict'))
1695 1681 doc = gettext(mod.__doc__).splitlines()[0]
1696 1682
1697 1683 msg = help.listexts(_("'%s' is provided by the following "
1698 1684 "extension:") % cmd, {ext: doc}, len(ext),
1699 1685 indent=4)
1700 1686 ui.write(minirst.format(msg, textwidth))
1701 1687 ui.write('\n\n')
1702 1688 ui.write(_('use "hg help extensions" for information on enabling '
1703 1689 'extensions\n'))
1704 1690
1705 1691 if name and name != 'shortlist':
1706 1692 i = None
1707 1693 if unknowncmd:
1708 1694 queries = (helpextcmd,)
1709 1695 else:
1710 1696 queries = (helptopic, helpcmd, helpext, helpextcmd)
1711 1697 for f in queries:
1712 1698 try:
1713 1699 f(name)
1714 1700 i = None
1715 1701 break
1716 1702 except error.UnknownCommand, inst:
1717 1703 i = inst
1718 1704 if i:
1719 1705 raise i
1720 1706
1721 1707 else:
1722 1708 # program name
1723 1709 if ui.verbose or with_version:
1724 1710 version_(ui)
1725 1711 else:
1726 1712 ui.status(_("Mercurial Distributed SCM\n"))
1727 1713 ui.status('\n')
1728 1714
1729 1715 # list of commands
1730 1716 if name == "shortlist":
1731 1717 header = _('basic commands:\n\n')
1732 1718 else:
1733 1719 header = _('list of commands:\n\n')
1734 1720
1735 1721 helplist(header)
1736 1722 if name != 'shortlist':
1737 1723 exts, maxlength = extensions.enabled()
1738 1724 text = help.listexts(_('enabled extensions:'), exts, maxlength)
1739 1725 if text:
1740 1726 ui.write("\n%s\n" % minirst.format(text, textwidth))
1741 1727
1742 1728 # list all option lists
1743 1729 opt_output = []
1744 1730 for title, options in option_lists:
1745 1731 opt_output.append(("\n%s" % title, None))
1746 1732 for shortopt, longopt, default, desc in options:
1747 1733 if _("DEPRECATED") in desc and not ui.verbose:
1748 1734 continue
1749 1735 opt_output.append(("%2s%s" % (shortopt and "-%s" % shortopt,
1750 1736 longopt and " --%s" % longopt),
1751 1737 "%s%s" % (desc,
1752 1738 default
1753 1739 and _(" (default: %s)") % default
1754 1740 or "")))
1755 1741
1756 1742 if not name:
1757 1743 ui.write(_("\nadditional help topics:\n\n"))
1758 1744 topics = []
1759 1745 for names, header, doc in help.helptable:
1760 1746 topics.append((sorted(names, key=len, reverse=True)[0], header))
1761 1747 topics_len = max([len(s[0]) for s in topics])
1762 1748 for t, desc in topics:
1763 1749 ui.write(" %-*s %s\n" % (topics_len, t, desc))
1764 1750
1765 1751 if opt_output:
1766 1752 opts_len = max([len(line[0]) for line in opt_output if line[1]] or [0])
1767 1753 for first, second in opt_output:
1768 1754 if second:
1769 1755 second = util.wrap(second, opts_len + 3)
1770 1756 ui.write(" %-*s %s\n" % (opts_len, first, second))
1771 1757 else:
1772 1758 ui.write("%s\n" % first)
1773 1759
1774 1760 def identify(ui, repo, source=None,
1775 1761 rev=None, num=None, id=None, branch=None, tags=None):
1776 1762 """identify the working copy or specified revision
1777 1763
1778 1764 With no revision, print a summary of the current state of the
1779 1765 repository.
1780 1766
1781 1767 Specifying a path to a repository root or Mercurial bundle will
1782 1768 cause lookup to operate on that repository/bundle.
1783 1769
1784 1770 This summary identifies the repository state using one or two
1785 1771 parent hash identifiers, followed by a "+" if there are
1786 1772 uncommitted changes in the working directory, a list of tags for
1787 1773 this revision and a branch name for non-default branches.
1788 1774 """
1789 1775
1790 1776 if not repo and not source:
1791 1777 raise util.Abort(_("There is no Mercurial repository here "
1792 1778 "(.hg not found)"))
1793 1779
1794 1780 hexfunc = ui.debugflag and hex or short
1795 1781 default = not (num or id or branch or tags)
1796 1782 output = []
1797 1783
1798 1784 revs = []
1799 1785 if source:
1800 1786 source, branches = hg.parseurl(ui.expandpath(source))
1801 1787 repo = hg.repository(ui, source)
1802 1788 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
1803 1789
1804 1790 if not repo.local():
1805 1791 if not rev and revs:
1806 1792 rev = revs[0]
1807 1793 if not rev:
1808 1794 rev = "tip"
1809 1795 if num or branch or tags:
1810 1796 raise util.Abort(
1811 1797 "can't query remote revision number, branch, or tags")
1812 1798 output = [hexfunc(repo.lookup(rev))]
1813 1799 elif not rev:
1814 1800 ctx = repo[None]
1815 1801 parents = ctx.parents()
1816 1802 changed = False
1817 1803 if default or id or num:
1818 1804 changed = util.any(repo.status())
1819 1805 if default or id:
1820 1806 output = ["%s%s" % ('+'.join([hexfunc(p.node()) for p in parents]),
1821 1807 (changed) and "+" or "")]
1822 1808 if num:
1823 1809 output.append("%s%s" % ('+'.join([str(p.rev()) for p in parents]),
1824 1810 (changed) and "+" or ""))
1825 1811 else:
1826 1812 ctx = repo[rev]
1827 1813 if default or id:
1828 1814 output = [hexfunc(ctx.node())]
1829 1815 if num:
1830 1816 output.append(str(ctx.rev()))
1831 1817
1832 1818 if repo.local() and default and not ui.quiet:
1833 1819 b = encoding.tolocal(ctx.branch())
1834 1820 if b != 'default':
1835 1821 output.append("(%s)" % b)
1836 1822
1837 1823 # multiple tags for a single parent separated by '/'
1838 1824 t = "/".join(ctx.tags())
1839 1825 if t:
1840 1826 output.append(t)
1841 1827
1842 1828 if branch:
1843 1829 output.append(encoding.tolocal(ctx.branch()))
1844 1830
1845 1831 if tags:
1846 1832 output.extend(ctx.tags())
1847 1833
1848 1834 ui.write("%s\n" % ' '.join(output))
1849 1835
1850 1836 def import_(ui, repo, patch1, *patches, **opts):
1851 1837 """import an ordered set of patches
1852 1838
1853 1839 Import a list of patches and commit them individually (unless
1854 1840 --no-commit is specified).
1855 1841
1856 1842 If there are outstanding changes in the working directory, import
1857 1843 will abort unless given the -f/--force flag.
1858 1844
1859 1845 You can import a patch straight from a mail message. Even patches
1860 1846 as attachments work (to use the body part, it must have type
1861 1847 text/plain or text/x-patch). From and Subject headers of email
1862 1848 message are used as default committer and commit message. All
1863 1849 text/plain body parts before first diff are added to commit
1864 1850 message.
1865 1851
1866 1852 If the imported patch was generated by hg export, user and
1867 1853 description from patch override values from message headers and
1868 1854 body. Values given on command line with -m/--message and -u/--user
1869 1855 override these.
1870 1856
1871 1857 If --exact is specified, import will set the working directory to
1872 1858 the parent of each patch before applying it, and will abort if the
1873 1859 resulting changeset has a different ID than the one recorded in
1874 1860 the patch. This may happen due to character set problems or other
1875 1861 deficiencies in the text patch format.
1876 1862
1877 1863 With -s/--similarity, hg will attempt to discover renames and
1878 1864 copies in the patch in the same way as 'addremove'.
1879 1865
1880 1866 To read a patch from standard input, use "-" as the patch name. If
1881 1867 a URL is specified, the patch will be downloaded from it.
1882 1868 See :hg:`help dates` for a list of formats valid for -d/--date.
1883 1869 """
1884 1870 patches = (patch1,) + patches
1885 1871
1886 1872 date = opts.get('date')
1887 1873 if date:
1888 1874 opts['date'] = util.parsedate(date)
1889 1875
1890 1876 try:
1891 1877 sim = float(opts.get('similarity') or 0)
1892 1878 except ValueError:
1893 1879 raise util.Abort(_('similarity must be a number'))
1894 1880 if sim < 0 or sim > 100:
1895 1881 raise util.Abort(_('similarity must be between 0 and 100'))
1896 1882
1897 1883 if opts.get('exact') or not opts.get('force'):
1898 1884 cmdutil.bail_if_changed(repo)
1899 1885
1900 1886 d = opts["base"]
1901 1887 strip = opts["strip"]
1902 1888 wlock = lock = None
1903 1889
1904 1890 def tryone(ui, hunk):
1905 1891 tmpname, message, user, date, branch, nodeid, p1, p2 = \
1906 1892 patch.extract(ui, hunk)
1907 1893
1908 1894 if not tmpname:
1909 1895 return None
1910 1896 commitid = _('to working directory')
1911 1897
1912 1898 try:
1913 1899 cmdline_message = cmdutil.logmessage(opts)
1914 1900 if cmdline_message:
1915 1901 # pickup the cmdline msg
1916 1902 message = cmdline_message
1917 1903 elif message:
1918 1904 # pickup the patch msg
1919 1905 message = message.strip()
1920 1906 else:
1921 1907 # launch the editor
1922 1908 message = None
1923 1909 ui.debug('message:\n%s\n' % message)
1924 1910
1925 1911 wp = repo.parents()
1926 1912 if opts.get('exact'):
1927 1913 if not nodeid or not p1:
1928 1914 raise util.Abort(_('not a Mercurial patch'))
1929 1915 p1 = repo.lookup(p1)
1930 1916 p2 = repo.lookup(p2 or hex(nullid))
1931 1917
1932 1918 if p1 != wp[0].node():
1933 1919 hg.clean(repo, p1)
1934 1920 repo.dirstate.setparents(p1, p2)
1935 1921 elif p2:
1936 1922 try:
1937 1923 p1 = repo.lookup(p1)
1938 1924 p2 = repo.lookup(p2)
1939 1925 if p1 == wp[0].node():
1940 1926 repo.dirstate.setparents(p1, p2)
1941 1927 except error.RepoError:
1942 1928 pass
1943 1929 if opts.get('exact') or opts.get('import_branch'):
1944 1930 repo.dirstate.setbranch(branch or 'default')
1945 1931
1946 1932 files = {}
1947 1933 try:
1948 1934 patch.patch(tmpname, ui, strip=strip, cwd=repo.root,
1949 1935 files=files, eolmode=None)
1950 1936 finally:
1951 1937 files = patch.updatedir(ui, repo, files,
1952 1938 similarity=sim / 100.0)
1953 1939 if not opts.get('no_commit'):
1954 1940 if opts.get('exact'):
1955 1941 m = None
1956 1942 else:
1957 1943 m = cmdutil.matchfiles(repo, files or [])
1958 1944 n = repo.commit(message, opts.get('user') or user,
1959 1945 opts.get('date') or date, match=m,
1960 1946 editor=cmdutil.commiteditor)
1961 1947 if opts.get('exact'):
1962 1948 if hex(n) != nodeid:
1963 1949 repo.rollback()
1964 1950 raise util.Abort(_('patch is damaged'
1965 1951 ' or loses information'))
1966 1952 # Force a dirstate write so that the next transaction
1967 1953 # backups an up-do-date file.
1968 1954 repo.dirstate.write()
1969 1955 if n:
1970 1956 commitid = short(n)
1971 1957
1972 1958 return commitid
1973 1959 finally:
1974 1960 os.unlink(tmpname)
1975 1961
1976 1962 try:
1977 1963 wlock = repo.wlock()
1978 1964 lock = repo.lock()
1979 1965 lastcommit = None
1980 1966 for p in patches:
1981 1967 pf = os.path.join(d, p)
1982 1968
1983 1969 if pf == '-':
1984 1970 ui.status(_("applying patch from stdin\n"))
1985 1971 pf = sys.stdin
1986 1972 else:
1987 1973 ui.status(_("applying %s\n") % p)
1988 1974 pf = url.open(ui, pf)
1989 1975
1990 1976 haspatch = False
1991 1977 for hunk in patch.split(pf):
1992 1978 commitid = tryone(ui, hunk)
1993 1979 if commitid:
1994 1980 haspatch = True
1995 1981 if lastcommit:
1996 1982 ui.status(_('applied %s\n') % lastcommit)
1997 1983 lastcommit = commitid
1998 1984
1999 1985 if not haspatch:
2000 1986 raise util.Abort(_('no diffs found'))
2001 1987
2002 1988 finally:
2003 1989 release(lock, wlock)
2004 1990
2005 1991 def incoming(ui, repo, source="default", **opts):
2006 1992 """show new changesets found in source
2007 1993
2008 1994 Show new changesets found in the specified path/URL or the default
2009 1995 pull location. These are the changesets that would have been pulled
2010 1996 if a pull at the time you issued this command.
2011 1997
2012 1998 For remote repository, using --bundle avoids downloading the
2013 1999 changesets twice if the incoming is followed by a pull.
2014 2000
2015 2001 See pull for valid source format details.
2016 2002 """
2017 2003 limit = cmdutil.loglimit(opts)
2018 2004 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
2019 2005 other = hg.repository(cmdutil.remoteui(repo, opts), source)
2020 2006 ui.status(_('comparing with %s\n') % url.hidepassword(source))
2021 2007 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
2022 2008 if revs:
2023 2009 revs = [other.lookup(rev) for rev in revs]
2024 2010 common, incoming, rheads = repo.findcommonincoming(other, heads=revs,
2025 2011 force=opts["force"])
2026 2012 if not incoming:
2027 2013 try:
2028 2014 os.unlink(opts["bundle"])
2029 2015 except:
2030 2016 pass
2031 2017 ui.status(_("no changes found\n"))
2032 2018 return 1
2033 2019
2034 2020 cleanup = None
2035 2021 try:
2036 2022 fname = opts["bundle"]
2037 2023 if fname or not other.local():
2038 2024 # create a bundle (uncompressed if other repo is not local)
2039 2025
2040 2026 if revs is None and other.capable('changegroupsubset'):
2041 2027 revs = rheads
2042 2028
2043 2029 if revs is None:
2044 2030 cg = other.changegroup(incoming, "incoming")
2045 2031 else:
2046 2032 cg = other.changegroupsubset(incoming, revs, 'incoming')
2047 2033 bundletype = other.local() and "HG10BZ" or "HG10UN"
2048 2034 fname = cleanup = changegroup.writebundle(cg, fname, bundletype)
2049 2035 # keep written bundle?
2050 2036 if opts["bundle"]:
2051 2037 cleanup = None
2052 2038 if not other.local():
2053 2039 # use the created uncompressed bundlerepo
2054 2040 other = bundlerepo.bundlerepository(ui, repo.root, fname)
2055 2041
2056 2042 o = other.changelog.nodesbetween(incoming, revs)[0]
2057 2043 if opts.get('newest_first'):
2058 2044 o.reverse()
2059 2045 displayer = cmdutil.show_changeset(ui, other, opts)
2060 2046 count = 0
2061 2047 for n in o:
2062 2048 if limit is not None and count >= limit:
2063 2049 break
2064 2050 parents = [p for p in other.changelog.parents(n) if p != nullid]
2065 2051 if opts.get('no_merges') and len(parents) == 2:
2066 2052 continue
2067 2053 count += 1
2068 2054 displayer.show(other[n])
2069 2055 displayer.close()
2070 2056 finally:
2071 2057 if hasattr(other, 'close'):
2072 2058 other.close()
2073 2059 if cleanup:
2074 2060 os.unlink(cleanup)
2075 2061
2076 2062 def init(ui, dest=".", **opts):
2077 2063 """create a new repository in the given directory
2078 2064
2079 2065 Initialize a new repository in the given directory. If the given
2080 2066 directory does not exist, it will be created.
2081 2067
2082 2068 If no directory is given, the current directory is used.
2083 2069
2084 2070 It is possible to specify an ``ssh://`` URL as the destination.
2085 2071 See :hg:`help urls` for more information.
2086 2072 """
2087 2073 hg.repository(cmdutil.remoteui(ui, opts), dest, create=1)
2088 2074
2089 2075 def locate(ui, repo, *pats, **opts):
2090 2076 """locate files matching specific patterns
2091 2077
2092 2078 Print files under Mercurial control in the working directory whose
2093 2079 names match the given patterns.
2094 2080
2095 2081 By default, this command searches all directories in the working
2096 2082 directory. To search just the current directory and its
2097 2083 subdirectories, use "--include .".
2098 2084
2099 2085 If no patterns are given to match, this command prints the names
2100 2086 of all files under Mercurial control in the working directory.
2101 2087
2102 2088 If you want to feed the output of this command into the "xargs"
2103 2089 command, use the -0 option to both this command and "xargs". This
2104 2090 will avoid the problem of "xargs" treating single filenames that
2105 2091 contain whitespace as multiple filenames.
2106 2092 """
2107 2093 end = opts.get('print0') and '\0' or '\n'
2108 2094 rev = opts.get('rev') or None
2109 2095
2110 2096 ret = 1
2111 2097 m = cmdutil.match(repo, pats, opts, default='relglob')
2112 2098 m.bad = lambda x, y: False
2113 2099 for abs in repo[rev].walk(m):
2114 2100 if not rev and abs not in repo.dirstate:
2115 2101 continue
2116 2102 if opts.get('fullpath'):
2117 2103 ui.write(repo.wjoin(abs), end)
2118 2104 else:
2119 2105 ui.write(((pats and m.rel(abs)) or abs), end)
2120 2106 ret = 0
2121 2107
2122 2108 return ret
2123 2109
2124 2110 def log(ui, repo, *pats, **opts):
2125 2111 """show revision history of entire repository or files
2126 2112
2127 2113 Print the revision history of the specified files or the entire
2128 2114 project.
2129 2115
2130 2116 File history is shown without following rename or copy history of
2131 2117 files. Use -f/--follow with a filename to follow history across
2132 2118 renames and copies. --follow without a filename will only show
2133 2119 ancestors or descendants of the starting revision. --follow-first
2134 2120 only follows the first parent of merge revisions.
2135 2121
2136 2122 If no revision range is specified, the default is tip:0 unless
2137 2123 --follow is set, in which case the working directory parent is
2138 2124 used as the starting revision.
2139 2125
2140 2126 See :hg:`help dates` for a list of formats valid for -d/--date.
2141 2127
2142 2128 By default this command prints revision number and changeset id,
2143 2129 tags, non-trivial parents, user, date and time, and a summary for
2144 2130 each commit. When the -v/--verbose switch is used, the list of
2145 2131 changed files and full commit message are shown.
2146 2132
2147 2133 NOTE: log -p/--patch may generate unexpected diff output for merge
2148 2134 changesets, as it will only compare the merge changeset against
2149 2135 its first parent. Also, only files different from BOTH parents
2150 2136 will appear in files:.
2151 2137 """
2152 2138
2153 2139 matchfn = cmdutil.match(repo, pats, opts)
2154 2140 limit = cmdutil.loglimit(opts)
2155 2141 count = 0
2156 2142
2157 2143 endrev = None
2158 2144 if opts.get('copies') and opts.get('rev'):
2159 2145 endrev = max(cmdutil.revrange(repo, opts.get('rev'))) + 1
2160 2146
2161 2147 df = False
2162 2148 if opts["date"]:
2163 2149 df = util.matchdate(opts["date"])
2164 2150
2165 2151 branches = opts.get('branch', []) + opts.get('only_branch', [])
2166 2152 opts['branch'] = [repo.lookupbranch(b) for b in branches]
2167 2153
2168 2154 displayer = cmdutil.show_changeset(ui, repo, opts, True, matchfn)
2169 2155 def prep(ctx, fns):
2170 2156 rev = ctx.rev()
2171 2157 parents = [p for p in repo.changelog.parentrevs(rev)
2172 2158 if p != nullrev]
2173 2159 if opts.get('no_merges') and len(parents) == 2:
2174 2160 return
2175 2161 if opts.get('only_merges') and len(parents) != 2:
2176 2162 return
2177 2163 if opts.get('branch') and ctx.branch() not in opts['branch']:
2178 2164 return
2179 2165 if df and not df(ctx.date()[0]):
2180 2166 return
2181 2167 if opts['user'] and not [k for k in opts['user'] if k in ctx.user()]:
2182 2168 return
2183 2169 if opts.get('keyword'):
2184 2170 for k in [kw.lower() for kw in opts['keyword']]:
2185 2171 if (k in ctx.user().lower() or
2186 2172 k in ctx.description().lower() or
2187 2173 k in " ".join(ctx.files()).lower()):
2188 2174 break
2189 2175 else:
2190 2176 return
2191 2177
2192 2178 copies = None
2193 2179 if opts.get('copies') and rev:
2194 2180 copies = []
2195 2181 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
2196 2182 for fn in ctx.files():
2197 2183 rename = getrenamed(fn, rev)
2198 2184 if rename:
2199 2185 copies.append((fn, rename[0]))
2200 2186
2201 2187 displayer.show(ctx, copies=copies)
2202 2188
2203 2189 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
2204 2190 if count == limit:
2205 2191 break
2206 2192 if displayer.flush(ctx.rev()):
2207 2193 count += 1
2208 2194 displayer.close()
2209 2195
2210 2196 def manifest(ui, repo, node=None, rev=None):
2211 2197 """output the current or given revision of the project manifest
2212 2198
2213 2199 Print a list of version controlled files for the given revision.
2214 2200 If no revision is given, the first parent of the working directory
2215 2201 is used, or the null revision if no revision is checked out.
2216 2202
2217 2203 With -v, print file permissions, symlink and executable bits.
2218 2204 With --debug, print file revision hashes.
2219 2205 """
2220 2206
2221 2207 if rev and node:
2222 2208 raise util.Abort(_("please specify just one revision"))
2223 2209
2224 2210 if not node:
2225 2211 node = rev
2226 2212
2227 2213 decor = {'l':'644 @ ', 'x':'755 * ', '':'644 '}
2228 2214 ctx = repo[node]
2229 2215 for f in ctx:
2230 2216 if ui.debugflag:
2231 2217 ui.write("%40s " % hex(ctx.manifest()[f]))
2232 2218 if ui.verbose:
2233 2219 ui.write(decor[ctx.flags(f)])
2234 2220 ui.write("%s\n" % f)
2235 2221
2236 2222 def merge(ui, repo, node=None, **opts):
2237 2223 """merge working directory with another revision
2238 2224
2239 2225 The current working directory is updated with all changes made in
2240 2226 the requested revision since the last common predecessor revision.
2241 2227
2242 2228 Files that changed between either parent are marked as changed for
2243 2229 the next commit and a commit must be performed before any further
2244 2230 updates to the repository are allowed. The next commit will have
2245 2231 two parents.
2246 2232
2247 2233 If no revision is specified, the working directory's parent is a
2248 2234 head revision, and the current branch contains exactly one other
2249 2235 head, the other head is merged with by default. Otherwise, an
2250 2236 explicit revision with which to merge with must be provided.
2251 2237 """
2252 2238
2253 2239 if opts.get('rev') and node:
2254 2240 raise util.Abort(_("please specify just one revision"))
2255 2241 if not node:
2256 2242 node = opts.get('rev')
2257 2243
2258 2244 if not node:
2259 2245 branch = repo.changectx(None).branch()
2260 2246 bheads = repo.branchheads(branch)
2261 2247 if len(bheads) > 2:
2262 2248 ui.warn(_("abort: branch '%s' has %d heads - "
2263 2249 "please merge with an explicit rev\n")
2264 2250 % (branch, len(bheads)))
2265 2251 ui.status(_("(run 'hg heads .' to see heads)\n"))
2266 2252 return False
2267 2253
2268 2254 parent = repo.dirstate.parents()[0]
2269 2255 if len(bheads) == 1:
2270 2256 if len(repo.heads()) > 1:
2271 2257 ui.warn(_("abort: branch '%s' has one head - "
2272 2258 "please merge with an explicit rev\n" % branch))
2273 2259 ui.status(_("(run 'hg heads' to see all heads)\n"))
2274 2260 return False
2275 2261 msg = _('there is nothing to merge')
2276 2262 if parent != repo.lookup(repo[None].branch()):
2277 2263 msg = _('%s - use "hg update" instead') % msg
2278 2264 raise util.Abort(msg)
2279 2265
2280 2266 if parent not in bheads:
2281 2267 raise util.Abort(_('working dir not at a head rev - '
2282 2268 'use "hg update" or merge with an explicit rev'))
2283 2269 node = parent == bheads[0] and bheads[-1] or bheads[0]
2284 2270
2285 2271 if opts.get('preview'):
2286 2272 # find nodes that are ancestors of p2 but not of p1
2287 2273 p1 = repo.lookup('.')
2288 2274 p2 = repo.lookup(node)
2289 2275 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
2290 2276
2291 2277 displayer = cmdutil.show_changeset(ui, repo, opts)
2292 2278 for node in nodes:
2293 2279 displayer.show(repo[node])
2294 2280 displayer.close()
2295 2281 return 0
2296 2282
2297 2283 return hg.merge(repo, node, force=opts.get('force'))
2298 2284
2299 2285 def outgoing(ui, repo, dest=None, **opts):
2300 2286 """show changesets not found in the destination
2301 2287
2302 2288 Show changesets not found in the specified destination repository
2303 2289 or the default push location. These are the changesets that would
2304 2290 be pushed if a push was requested.
2305 2291
2306 2292 See pull for details of valid destination formats.
2307 2293 """
2308 2294 limit = cmdutil.loglimit(opts)
2309 2295 dest = ui.expandpath(dest or 'default-push', dest or 'default')
2310 2296 dest, branches = hg.parseurl(dest, opts.get('branch'))
2311 2297 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
2312 2298 if revs:
2313 2299 revs = [repo.lookup(rev) for rev in revs]
2314 2300
2315 2301 other = hg.repository(cmdutil.remoteui(repo, opts), dest)
2316 2302 ui.status(_('comparing with %s\n') % url.hidepassword(dest))
2317 2303 o = repo.findoutgoing(other, force=opts.get('force'))
2318 2304 if not o:
2319 2305 ui.status(_("no changes found\n"))
2320 2306 return 1
2321 2307 o = repo.changelog.nodesbetween(o, revs)[0]
2322 2308 if opts.get('newest_first'):
2323 2309 o.reverse()
2324 2310 displayer = cmdutil.show_changeset(ui, repo, opts)
2325 2311 count = 0
2326 2312 for n in o:
2327 2313 if limit is not None and count >= limit:
2328 2314 break
2329 2315 parents = [p for p in repo.changelog.parents(n) if p != nullid]
2330 2316 if opts.get('no_merges') and len(parents) == 2:
2331 2317 continue
2332 2318 count += 1
2333 2319 displayer.show(repo[n])
2334 2320 displayer.close()
2335 2321
2336 2322 def parents(ui, repo, file_=None, **opts):
2337 2323 """show the parents of the working directory or revision
2338 2324
2339 2325 Print the working directory's parent revisions. If a revision is
2340 2326 given via -r/--rev, the parent of that revision will be printed.
2341 2327 If a file argument is given, the revision in which the file was
2342 2328 last changed (before the working directory revision or the
2343 2329 argument to --rev if given) is printed.
2344 2330 """
2345 2331 rev = opts.get('rev')
2346 2332 if rev:
2347 2333 ctx = repo[rev]
2348 2334 else:
2349 2335 ctx = repo[None]
2350 2336
2351 2337 if file_:
2352 2338 m = cmdutil.match(repo, (file_,), opts)
2353 2339 if m.anypats() or len(m.files()) != 1:
2354 2340 raise util.Abort(_('can only specify an explicit filename'))
2355 2341 file_ = m.files()[0]
2356 2342 filenodes = []
2357 2343 for cp in ctx.parents():
2358 2344 if not cp:
2359 2345 continue
2360 2346 try:
2361 2347 filenodes.append(cp.filenode(file_))
2362 2348 except error.LookupError:
2363 2349 pass
2364 2350 if not filenodes:
2365 2351 raise util.Abort(_("'%s' not found in manifest!") % file_)
2366 2352 fl = repo.file(file_)
2367 2353 p = [repo.lookup(fl.linkrev(fl.rev(fn))) for fn in filenodes]
2368 2354 else:
2369 2355 p = [cp.node() for cp in ctx.parents()]
2370 2356
2371 2357 displayer = cmdutil.show_changeset(ui, repo, opts)
2372 2358 for n in p:
2373 2359 if n != nullid:
2374 2360 displayer.show(repo[n])
2375 2361 displayer.close()
2376 2362
2377 2363 def paths(ui, repo, search=None):
2378 2364 """show aliases for remote repositories
2379 2365
2380 2366 Show definition of symbolic path name NAME. If no name is given,
2381 2367 show definition of all available names.
2382 2368
2383 2369 Path names are defined in the [paths] section of
2384 2370 ``/etc/mercurial/hgrc`` and ``$HOME/.hgrc``. If run inside a
2385 2371 repository, ``.hg/hgrc`` is used, too.
2386 2372
2387 2373 The path names ``default`` and ``default-push`` have a special
2388 2374 meaning. When performing a push or pull operation, they are used
2389 2375 as fallbacks if no location is specified on the command-line.
2390 2376 When ``default-push`` is set, it will be used for push and
2391 2377 ``default`` will be used for pull; otherwise ``default`` is used
2392 2378 as the fallback for both. When cloning a repository, the clone
2393 2379 source is written as ``default`` in ``.hg/hgrc``. Note that
2394 2380 ``default`` and ``default-push`` apply to all inbound (e.g.
2395 2381 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
2396 2382 :hg:`bundle`) operations.
2397 2383
2398 2384 See :hg:`help urls` for more information.
2399 2385 """
2400 2386 if search:
2401 2387 for name, path in ui.configitems("paths"):
2402 2388 if name == search:
2403 2389 ui.write("%s\n" % url.hidepassword(path))
2404 2390 return
2405 2391 ui.warn(_("not found!\n"))
2406 2392 return 1
2407 2393 else:
2408 2394 for name, path in ui.configitems("paths"):
2409 2395 ui.write("%s = %s\n" % (name, url.hidepassword(path)))
2410 2396
2411 2397 def postincoming(ui, repo, modheads, optupdate, checkout):
2412 2398 if modheads == 0:
2413 2399 return
2414 2400 if optupdate:
2415 2401 if (modheads <= 1 or len(repo.branchheads()) == 1) or checkout:
2416 2402 return hg.update(repo, checkout)
2417 2403 else:
2418 2404 ui.status(_("not updating, since new heads added\n"))
2419 2405 if modheads > 1:
2420 2406 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
2421 2407 else:
2422 2408 ui.status(_("(run 'hg update' to get a working copy)\n"))
2423 2409
2424 2410 def pull(ui, repo, source="default", **opts):
2425 2411 """pull changes from the specified source
2426 2412
2427 2413 Pull changes from a remote repository to a local one.
2428 2414
2429 2415 This finds all changes from the repository at the specified path
2430 2416 or URL and adds them to a local repository (the current one unless
2431 2417 -R is specified). By default, this does not update the copy of the
2432 2418 project in the working directory.
2433 2419
2434 2420 Use hg incoming if you want to see what would have been added by a
2435 2421 pull at the time you issued this command. If you then decide to
2436 2422 added those changes to the repository, you should use pull -r X
2437 2423 where X is the last changeset listed by hg incoming.
2438 2424
2439 2425 If SOURCE is omitted, the 'default' path will be used.
2440 2426 See :hg:`help urls` for more information.
2441 2427 """
2442 2428 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
2443 2429 other = hg.repository(cmdutil.remoteui(repo, opts), source)
2444 2430 ui.status(_('pulling from %s\n') % url.hidepassword(source))
2445 2431 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
2446 2432 if revs:
2447 2433 try:
2448 2434 revs = [other.lookup(rev) for rev in revs]
2449 2435 except error.CapabilityError:
2450 2436 err = _("Other repository doesn't support revision lookup, "
2451 2437 "so a rev cannot be specified.")
2452 2438 raise util.Abort(err)
2453 2439
2454 2440 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
2455 2441 if checkout:
2456 2442 checkout = str(repo.changelog.rev(other.lookup(checkout)))
2457 2443 return postincoming(ui, repo, modheads, opts.get('update'), checkout)
2458 2444
2459 2445 def push(ui, repo, dest=None, **opts):
2460 2446 """push changes to the specified destination
2461 2447
2462 2448 Push changes from the local repository to the specified destination.
2463 2449
2464 2450 This is the symmetrical operation for pull. It moves changes from
2465 2451 the current repository to a different one. If the destination is
2466 2452 local this is identical to a pull in that directory from the
2467 2453 current one.
2468 2454
2469 2455 By default, push will refuse to run if it detects the result would
2470 2456 increase the number of remote heads. This generally indicates the
2471 2457 user forgot to pull and merge before pushing.
2472 2458
2473 2459 If -r/--rev is used, the named revision and all its ancestors will
2474 2460 be pushed to the remote repository.
2475 2461
2476 2462 Please see :hg:`help urls` for important details about ``ssh://``
2477 2463 URLs. If DESTINATION is omitted, a default path will be used.
2478 2464 """
2479 2465 dest = ui.expandpath(dest or 'default-push', dest or 'default')
2480 2466 dest, branches = hg.parseurl(dest, opts.get('branch'))
2481 2467 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
2482 2468 other = hg.repository(cmdutil.remoteui(repo, opts), dest)
2483 2469 ui.status(_('pushing to %s\n') % url.hidepassword(dest))
2484 2470 if revs:
2485 2471 revs = [repo.lookup(rev) for rev in revs]
2486 2472
2487 2473 # push subrepos depth-first for coherent ordering
2488 2474 c = repo['']
2489 2475 subs = c.substate # only repos that are committed
2490 2476 for s in sorted(subs):
2491 2477 c.sub(s).push(opts.get('force'))
2492 2478
2493 2479 r = repo.push(other, opts.get('force'), revs=revs)
2494 2480 return r == 0
2495 2481
2496 2482 def recover(ui, repo):
2497 2483 """roll back an interrupted transaction
2498 2484
2499 2485 Recover from an interrupted commit or pull.
2500 2486
2501 2487 This command tries to fix the repository status after an
2502 2488 interrupted operation. It should only be necessary when Mercurial
2503 2489 suggests it.
2504 2490 """
2505 2491 if repo.recover():
2506 2492 return hg.verify(repo)
2507 2493 return 1
2508 2494
2509 2495 def remove(ui, repo, *pats, **opts):
2510 2496 """remove the specified files on the next commit
2511 2497
2512 2498 Schedule the indicated files for removal from the repository.
2513 2499
2514 2500 This only removes files from the current branch, not from the
2515 2501 entire project history. -A/--after can be used to remove only
2516 2502 files that have already been deleted, -f/--force can be used to
2517 2503 force deletion, and -Af can be used to remove files from the next
2518 2504 revision without deleting them from the working directory.
2519 2505
2520 2506 The following table details the behavior of remove for different
2521 2507 file states (columns) and option combinations (rows). The file
2522 2508 states are Added [A], Clean [C], Modified [M] and Missing [!] (as
2523 2509 reported by hg status). The actions are Warn, Remove (from branch)
2524 2510 and Delete (from disk)::
2525 2511
2526 2512 A C M !
2527 2513 none W RD W R
2528 2514 -f R RD RD R
2529 2515 -A W W W R
2530 2516 -Af R R R R
2531 2517
2532 2518 This command schedules the files to be removed at the next commit.
2533 2519 To undo a remove before that, see hg revert.
2534 2520 """
2535 2521
2536 2522 after, force = opts.get('after'), opts.get('force')
2537 2523 if not pats and not after:
2538 2524 raise util.Abort(_('no files specified'))
2539 2525
2540 2526 m = cmdutil.match(repo, pats, opts)
2541 2527 s = repo.status(match=m, clean=True)
2542 2528 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
2543 2529
2544 2530 for f in m.files():
2545 2531 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
2546 2532 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
2547 2533
2548 2534 def warn(files, reason):
2549 2535 for f in files:
2550 2536 ui.warn(_('not removing %s: file %s (use -f to force removal)\n')
2551 2537 % (m.rel(f), reason))
2552 2538
2553 2539 if force:
2554 2540 remove, forget = modified + deleted + clean, added
2555 2541 elif after:
2556 2542 remove, forget = deleted, []
2557 2543 warn(modified + added + clean, _('still exists'))
2558 2544 else:
2559 2545 remove, forget = deleted + clean, []
2560 2546 warn(modified, _('is modified'))
2561 2547 warn(added, _('has been marked for add'))
2562 2548
2563 2549 for f in sorted(remove + forget):
2564 2550 if ui.verbose or not m.exact(f):
2565 2551 ui.status(_('removing %s\n') % m.rel(f))
2566 2552
2567 2553 repo.forget(forget)
2568 2554 repo.remove(remove, unlink=not after)
2569 2555
2570 2556 def rename(ui, repo, *pats, **opts):
2571 2557 """rename files; equivalent of copy + remove
2572 2558
2573 2559 Mark dest as copies of sources; mark sources for deletion. If dest
2574 2560 is a directory, copies are put in that directory. If dest is a
2575 2561 file, there can only be one source.
2576 2562
2577 2563 By default, this command copies the contents of files as they
2578 2564 exist in the working directory. If invoked with -A/--after, the
2579 2565 operation is recorded, but no copying is performed.
2580 2566
2581 2567 This command takes effect at the next commit. To undo a rename
2582 2568 before that, see hg revert.
2583 2569 """
2584 2570 wlock = repo.wlock(False)
2585 2571 try:
2586 2572 return cmdutil.copy(ui, repo, pats, opts, rename=True)
2587 2573 finally:
2588 2574 wlock.release()
2589 2575
2590 2576 def resolve(ui, repo, *pats, **opts):
2591 2577 """various operations to help finish a merge
2592 2578
2593 2579 This command includes several actions that are often useful while
2594 2580 performing a merge, after running ``merge`` but before running
2595 2581 ``commit``. (It is only meaningful if your working directory has
2596 2582 two parents.) It is most relevant for merges with unresolved
2597 2583 conflicts, which are typically a result of non-interactive merging with
2598 2584 ``internal:merge`` or a command-line merge tool like ``diff3``.
2599 2585
2600 2586 The available actions are:
2601 2587
2602 2588 1) list files that were merged with conflicts (U, for unresolved)
2603 2589 and without conflicts (R, for resolved): ``hg resolve -l``
2604 2590 (this is like ``status`` for merges)
2605 2591 2) record that you have resolved conflicts in certain files:
2606 2592 ``hg resolve -m [file ...]`` (default: mark all unresolved files)
2607 2593 3) forget that you have resolved conflicts in certain files:
2608 2594 ``hg resolve -u [file ...]`` (default: unmark all resolved files)
2609 2595 4) discard your current attempt(s) at resolving conflicts and
2610 2596 restart the merge from scratch: ``hg resolve file...``
2611 2597 (or ``-a`` for all unresolved files)
2612 2598
2613 2599 Note that Mercurial will not let you commit files with unresolved merge
2614 2600 conflicts. You must use ``hg resolve -m ...`` before you can commit
2615 2601 after a conflicting merge.
2616 2602 """
2617 2603
2618 2604 all, mark, unmark, show, nostatus = \
2619 2605 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
2620 2606
2621 2607 if (show and (mark or unmark)) or (mark and unmark):
2622 2608 raise util.Abort(_("too many options specified"))
2623 2609 if pats and all:
2624 2610 raise util.Abort(_("can't specify --all and patterns"))
2625 2611 if not (all or pats or show or mark or unmark):
2626 2612 raise util.Abort(_('no files or directories specified; '
2627 2613 'use --all to remerge all files'))
2628 2614
2629 2615 ms = mergemod.mergestate(repo)
2630 2616 m = cmdutil.match(repo, pats, opts)
2631 2617
2632 2618 for f in ms:
2633 2619 if m(f):
2634 2620 if show:
2635 2621 if nostatus:
2636 2622 ui.write("%s\n" % f)
2637 2623 else:
2638 2624 ui.write("%s %s\n" % (ms[f].upper(), f),
2639 2625 label='resolve.' +
2640 2626 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
2641 2627 elif mark:
2642 2628 ms.mark(f, "r")
2643 2629 elif unmark:
2644 2630 ms.mark(f, "u")
2645 2631 else:
2646 2632 wctx = repo[None]
2647 2633 mctx = wctx.parents()[-1]
2648 2634
2649 2635 # backup pre-resolve (merge uses .orig for its own purposes)
2650 2636 a = repo.wjoin(f)
2651 2637 util.copyfile(a, a + ".resolve")
2652 2638
2653 2639 # resolve file
2654 2640 ms.resolve(f, wctx, mctx)
2655 2641
2656 2642 # replace filemerge's .orig file with our resolve file
2657 2643 util.rename(a + ".resolve", a + ".orig")
2658 2644
2659 2645 def revert(ui, repo, *pats, **opts):
2660 2646 """restore individual files or directories to an earlier state
2661 2647
2662 2648 (Use update -r to check out earlier revisions, revert does not
2663 2649 change the working directory parents.)
2664 2650
2665 2651 With no revision specified, revert the named files or directories
2666 2652 to the contents they had in the parent of the working directory.
2667 2653 This restores the contents of the affected files to an unmodified
2668 2654 state and unschedules adds, removes, copies, and renames. If the
2669 2655 working directory has two parents, you must explicitly specify a
2670 2656 revision.
2671 2657
2672 2658 Using the -r/--rev option, revert the given files or directories
2673 2659 to their contents as of a specific revision. This can be helpful
2674 2660 to "roll back" some or all of an earlier change. See :hg:`help
2675 2661 dates` for a list of formats valid for -d/--date.
2676 2662
2677 2663 Revert modifies the working directory. It does not commit any
2678 2664 changes, or change the parent of the working directory. If you
2679 2665 revert to a revision other than the parent of the working
2680 2666 directory, the reverted files will thus appear modified
2681 2667 afterwards.
2682 2668
2683 2669 If a file has been deleted, it is restored. If the executable mode
2684 2670 of a file was changed, it is reset.
2685 2671
2686 2672 If names are given, all files matching the names are reverted.
2687 2673 If no arguments are given, no files are reverted.
2688 2674
2689 2675 Modified files are saved with a .orig suffix before reverting.
2690 2676 To disable these backups, use --no-backup.
2691 2677 """
2692 2678
2693 2679 if opts["date"]:
2694 2680 if opts["rev"]:
2695 2681 raise util.Abort(_("you can't specify a revision and a date"))
2696 2682 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
2697 2683
2698 2684 if not pats and not opts.get('all'):
2699 2685 raise util.Abort(_('no files or directories specified; '
2700 2686 'use --all to revert the whole repo'))
2701 2687
2702 2688 parent, p2 = repo.dirstate.parents()
2703 2689 if not opts.get('rev') and p2 != nullid:
2704 2690 raise util.Abort(_('uncommitted merge - please provide a '
2705 2691 'specific revision'))
2706 2692 ctx = repo[opts.get('rev')]
2707 2693 node = ctx.node()
2708 2694 mf = ctx.manifest()
2709 2695 if node == parent:
2710 2696 pmf = mf
2711 2697 else:
2712 2698 pmf = None
2713 2699
2714 2700 # need all matching names in dirstate and manifest of target rev,
2715 2701 # so have to walk both. do not print errors if files exist in one
2716 2702 # but not other.
2717 2703
2718 2704 names = {}
2719 2705
2720 2706 wlock = repo.wlock()
2721 2707 try:
2722 2708 # walk dirstate.
2723 2709
2724 2710 m = cmdutil.match(repo, pats, opts)
2725 2711 m.bad = lambda x, y: False
2726 2712 for abs in repo.walk(m):
2727 2713 names[abs] = m.rel(abs), m.exact(abs)
2728 2714
2729 2715 # walk target manifest.
2730 2716
2731 2717 def badfn(path, msg):
2732 2718 if path in names:
2733 2719 return
2734 2720 path_ = path + '/'
2735 2721 for f in names:
2736 2722 if f.startswith(path_):
2737 2723 return
2738 2724 ui.warn("%s: %s\n" % (m.rel(path), msg))
2739 2725
2740 2726 m = cmdutil.match(repo, pats, opts)
2741 2727 m.bad = badfn
2742 2728 for abs in repo[node].walk(m):
2743 2729 if abs not in names:
2744 2730 names[abs] = m.rel(abs), m.exact(abs)
2745 2731
2746 2732 m = cmdutil.matchfiles(repo, names)
2747 2733 changes = repo.status(match=m)[:4]
2748 2734 modified, added, removed, deleted = map(set, changes)
2749 2735
2750 2736 # if f is a rename, also revert the source
2751 2737 cwd = repo.getcwd()
2752 2738 for f in added:
2753 2739 src = repo.dirstate.copied(f)
2754 2740 if src and src not in names and repo.dirstate[src] == 'r':
2755 2741 removed.add(src)
2756 2742 names[src] = (repo.pathto(src, cwd), True)
2757 2743
2758 2744 def removeforget(abs):
2759 2745 if repo.dirstate[abs] == 'a':
2760 2746 return _('forgetting %s\n')
2761 2747 return _('removing %s\n')
2762 2748
2763 2749 revert = ([], _('reverting %s\n'))
2764 2750 add = ([], _('adding %s\n'))
2765 2751 remove = ([], removeforget)
2766 2752 undelete = ([], _('undeleting %s\n'))
2767 2753
2768 2754 disptable = (
2769 2755 # dispatch table:
2770 2756 # file state
2771 2757 # action if in target manifest
2772 2758 # action if not in target manifest
2773 2759 # make backup if in target manifest
2774 2760 # make backup if not in target manifest
2775 2761 (modified, revert, remove, True, True),
2776 2762 (added, revert, remove, True, False),
2777 2763 (removed, undelete, None, False, False),
2778 2764 (deleted, revert, remove, False, False),
2779 2765 )
2780 2766
2781 2767 for abs, (rel, exact) in sorted(names.items()):
2782 2768 mfentry = mf.get(abs)
2783 2769 target = repo.wjoin(abs)
2784 2770 def handle(xlist, dobackup):
2785 2771 xlist[0].append(abs)
2786 2772 if dobackup and not opts.get('no_backup') and util.lexists(target):
2787 2773 bakname = "%s.orig" % rel
2788 2774 ui.note(_('saving current version of %s as %s\n') %
2789 2775 (rel, bakname))
2790 2776 if not opts.get('dry_run'):
2791 2777 util.copyfile(target, bakname)
2792 2778 if ui.verbose or not exact:
2793 2779 msg = xlist[1]
2794 2780 if not isinstance(msg, basestring):
2795 2781 msg = msg(abs)
2796 2782 ui.status(msg % rel)
2797 2783 for table, hitlist, misslist, backuphit, backupmiss in disptable:
2798 2784 if abs not in table:
2799 2785 continue
2800 2786 # file has changed in dirstate
2801 2787 if mfentry:
2802 2788 handle(hitlist, backuphit)
2803 2789 elif misslist is not None:
2804 2790 handle(misslist, backupmiss)
2805 2791 break
2806 2792 else:
2807 2793 if abs not in repo.dirstate:
2808 2794 if mfentry:
2809 2795 handle(add, True)
2810 2796 elif exact:
2811 2797 ui.warn(_('file not managed: %s\n') % rel)
2812 2798 continue
2813 2799 # file has not changed in dirstate
2814 2800 if node == parent:
2815 2801 if exact:
2816 2802 ui.warn(_('no changes needed to %s\n') % rel)
2817 2803 continue
2818 2804 if pmf is None:
2819 2805 # only need parent manifest in this unlikely case,
2820 2806 # so do not read by default
2821 2807 pmf = repo[parent].manifest()
2822 2808 if abs in pmf:
2823 2809 if mfentry:
2824 2810 # if version of file is same in parent and target
2825 2811 # manifests, do nothing
2826 2812 if (pmf[abs] != mfentry or
2827 2813 pmf.flags(abs) != mf.flags(abs)):
2828 2814 handle(revert, False)
2829 2815 else:
2830 2816 handle(remove, False)
2831 2817
2832 2818 if not opts.get('dry_run'):
2833 2819 def checkout(f):
2834 2820 fc = ctx[f]
2835 2821 repo.wwrite(f, fc.data(), fc.flags())
2836 2822
2837 2823 audit_path = util.path_auditor(repo.root)
2838 2824 for f in remove[0]:
2839 2825 if repo.dirstate[f] == 'a':
2840 2826 repo.dirstate.forget(f)
2841 2827 continue
2842 2828 audit_path(f)
2843 2829 try:
2844 2830 util.unlink(repo.wjoin(f))
2845 2831 except OSError:
2846 2832 pass
2847 2833 repo.dirstate.remove(f)
2848 2834
2849 2835 normal = None
2850 2836 if node == parent:
2851 2837 # We're reverting to our parent. If possible, we'd like status
2852 2838 # to report the file as clean. We have to use normallookup for
2853 2839 # merges to avoid losing information about merged/dirty files.
2854 2840 if p2 != nullid:
2855 2841 normal = repo.dirstate.normallookup
2856 2842 else:
2857 2843 normal = repo.dirstate.normal
2858 2844 for f in revert[0]:
2859 2845 checkout(f)
2860 2846 if normal:
2861 2847 normal(f)
2862 2848
2863 2849 for f in add[0]:
2864 2850 checkout(f)
2865 2851 repo.dirstate.add(f)
2866 2852
2867 2853 normal = repo.dirstate.normallookup
2868 2854 if node == parent and p2 == nullid:
2869 2855 normal = repo.dirstate.normal
2870 2856 for f in undelete[0]:
2871 2857 checkout(f)
2872 2858 normal(f)
2873 2859
2874 2860 finally:
2875 2861 wlock.release()
2876 2862
2877 2863 def rollback(ui, repo, **opts):
2878 2864 """roll back the last transaction (dangerous)
2879 2865
2880 2866 This command should be used with care. There is only one level of
2881 2867 rollback, and there is no way to undo a rollback. It will also
2882 2868 restore the dirstate at the time of the last transaction, losing
2883 2869 any dirstate changes since that time. This command does not alter
2884 2870 the working directory.
2885 2871
2886 2872 Transactions are used to encapsulate the effects of all commands
2887 2873 that create new changesets or propagate existing changesets into a
2888 2874 repository. For example, the following commands are transactional,
2889 2875 and their effects can be rolled back:
2890 2876
2891 2877 - commit
2892 2878 - import
2893 2879 - pull
2894 2880 - push (with this repository as the destination)
2895 2881 - unbundle
2896 2882
2897 2883 This command is not intended for use on public repositories. Once
2898 2884 changes are visible for pull by other users, rolling a transaction
2899 2885 back locally is ineffective (someone else may already have pulled
2900 2886 the changes). Furthermore, a race is possible with readers of the
2901 2887 repository; for example an in-progress pull from the repository
2902 2888 may fail if a rollback is performed.
2903 2889 """
2904 2890 repo.rollback(opts.get('dry_run'))
2905 2891
2906 2892 def root(ui, repo):
2907 2893 """print the root (top) of the current working directory
2908 2894
2909 2895 Print the root directory of the current repository.
2910 2896 """
2911 2897 ui.write(repo.root + "\n")
2912 2898
2913 2899 def serve(ui, repo, **opts):
2914 2900 """start stand-alone webserver
2915 2901
2916 2902 Start a local HTTP repository browser and pull server.
2917 2903
2918 2904 By default, the server logs accesses to stdout and errors to
2919 2905 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
2920 2906 files.
2921 2907
2922 2908 To have the server choose a free port number to listen on, specify
2923 2909 a port number of 0; in this case, the server will print the port
2924 2910 number it uses.
2925 2911 """
2926 2912
2927 2913 if opts["stdio"]:
2928 2914 if repo is None:
2929 2915 raise error.RepoError(_("There is no Mercurial repository here"
2930 2916 " (.hg not found)"))
2931 2917 s = sshserver.sshserver(ui, repo)
2932 2918 s.serve_forever()
2933 2919
2934 2920 # this way we can check if something was given in the command-line
2935 2921 if opts.get('port'):
2936 2922 opts['port'] = int(opts.get('port'))
2937 2923
2938 2924 baseui = repo and repo.baseui or ui
2939 2925 optlist = ("name templates style address port prefix ipv6"
2940 2926 " accesslog errorlog certificate encoding")
2941 2927 for o in optlist.split():
2942 2928 val = opts.get(o, '')
2943 2929 if val in (None, ''): # should check against default options instead
2944 2930 continue
2945 2931 baseui.setconfig("web", o, val)
2946 2932 if repo and repo.ui != baseui:
2947 2933 repo.ui.setconfig("web", o, val)
2948 2934
2949 2935 o = opts.get('web_conf') or opts.get('webdir_conf')
2950 2936 if not o:
2951 2937 if not repo:
2952 2938 raise error.RepoError(_("There is no Mercurial repository"
2953 2939 " here (.hg not found)"))
2954 2940 o = repo.root
2955 2941
2956 2942 app = hgweb.hgweb(o, baseui=ui)
2957 2943
2958 2944 class service(object):
2959 2945 def init(self):
2960 2946 util.set_signal_handler()
2961 2947 self.httpd = hgweb.server.create_server(ui, app)
2962 2948
2963 2949 if opts['port'] and not ui.verbose:
2964 2950 return
2965 2951
2966 2952 if self.httpd.prefix:
2967 2953 prefix = self.httpd.prefix.strip('/') + '/'
2968 2954 else:
2969 2955 prefix = ''
2970 2956
2971 2957 port = ':%d' % self.httpd.port
2972 2958 if port == ':80':
2973 2959 port = ''
2974 2960
2975 2961 bindaddr = self.httpd.addr
2976 2962 if bindaddr == '0.0.0.0':
2977 2963 bindaddr = '*'
2978 2964 elif ':' in bindaddr: # IPv6
2979 2965 bindaddr = '[%s]' % bindaddr
2980 2966
2981 2967 fqaddr = self.httpd.fqaddr
2982 2968 if ':' in fqaddr:
2983 2969 fqaddr = '[%s]' % fqaddr
2984 2970 if opts['port']:
2985 2971 write = ui.status
2986 2972 else:
2987 2973 write = ui.write
2988 2974 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
2989 2975 (fqaddr, port, prefix, bindaddr, self.httpd.port))
2990 2976
2991 2977 def run(self):
2992 2978 self.httpd.serve_forever()
2993 2979
2994 2980 service = service()
2995 2981
2996 2982 cmdutil.service(opts, initfn=service.init, runfn=service.run)
2997 2983
2998 2984 def status(ui, repo, *pats, **opts):
2999 2985 """show changed files in the working directory
3000 2986
3001 2987 Show status of files in the repository. If names are given, only
3002 2988 files that match are shown. Files that are clean or ignored or
3003 2989 the source of a copy/move operation, are not listed unless
3004 2990 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
3005 2991 Unless options described with "show only ..." are given, the
3006 2992 options -mardu are used.
3007 2993
3008 2994 Option -q/--quiet hides untracked (unknown and ignored) files
3009 2995 unless explicitly requested with -u/--unknown or -i/--ignored.
3010 2996
3011 2997 NOTE: status may appear to disagree with diff if permissions have
3012 2998 changed or a merge has occurred. The standard diff format does not
3013 2999 report permission changes and diff only reports changes relative
3014 3000 to one merge parent.
3015 3001
3016 3002 If one revision is given, it is used as the base revision.
3017 3003 If two revisions are given, the differences between them are
3018 3004 shown. The --change option can also be used as a shortcut to list
3019 3005 the changed files of a revision from its first parent.
3020 3006
3021 3007 The codes used to show the status of files are::
3022 3008
3023 3009 M = modified
3024 3010 A = added
3025 3011 R = removed
3026 3012 C = clean
3027 3013 ! = missing (deleted by non-hg command, but still tracked)
3028 3014 ? = not tracked
3029 3015 I = ignored
3030 3016 = origin of the previous file listed as A (added)
3031 3017 """
3032 3018
3033 3019 revs = opts.get('rev')
3034 3020 change = opts.get('change')
3035 3021
3036 3022 if revs and change:
3037 3023 msg = _('cannot specify --rev and --change at the same time')
3038 3024 raise util.Abort(msg)
3039 3025 elif change:
3040 3026 node2 = repo.lookup(change)
3041 3027 node1 = repo[node2].parents()[0].node()
3042 3028 else:
3043 3029 node1, node2 = cmdutil.revpair(repo, revs)
3044 3030
3045 3031 cwd = (pats and repo.getcwd()) or ''
3046 3032 end = opts.get('print0') and '\0' or '\n'
3047 3033 copy = {}
3048 3034 states = 'modified added removed deleted unknown ignored clean'.split()
3049 3035 show = [k for k in states if opts.get(k)]
3050 3036 if opts.get('all'):
3051 3037 show += ui.quiet and (states[:4] + ['clean']) or states
3052 3038 if not show:
3053 3039 show = ui.quiet and states[:4] or states[:5]
3054 3040
3055 3041 stat = repo.status(node1, node2, cmdutil.match(repo, pats, opts),
3056 3042 'ignored' in show, 'clean' in show, 'unknown' in show)
3057 3043 changestates = zip(states, 'MAR!?IC', stat)
3058 3044
3059 3045 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
3060 3046 ctxn = repo[nullid]
3061 3047 ctx1 = repo[node1]
3062 3048 ctx2 = repo[node2]
3063 3049 added = stat[1]
3064 3050 if node2 is None:
3065 3051 added = stat[0] + stat[1] # merged?
3066 3052
3067 3053 for k, v in copies.copies(repo, ctx1, ctx2, ctxn)[0].iteritems():
3068 3054 if k in added:
3069 3055 copy[k] = v
3070 3056 elif v in added:
3071 3057 copy[v] = k
3072 3058
3073 3059 for state, char, files in changestates:
3074 3060 if state in show:
3075 3061 format = "%s %%s%s" % (char, end)
3076 3062 if opts.get('no_status'):
3077 3063 format = "%%s%s" % end
3078 3064
3079 3065 for f in files:
3080 3066 ui.write(format % repo.pathto(f, cwd),
3081 3067 label='status.' + state)
3082 3068 if f in copy:
3083 3069 ui.write(' %s%s' % (repo.pathto(copy[f], cwd), end),
3084 3070 label='status.copied')
3085 3071
3086 3072 def summary(ui, repo, **opts):
3087 3073 """summarize working directory state
3088 3074
3089 3075 This generates a brief summary of the working directory state,
3090 3076 including parents, branch, commit status, and available updates.
3091 3077
3092 3078 With the --remote option, this will check the default paths for
3093 3079 incoming and outgoing changes. This can be time-consuming.
3094 3080 """
3095 3081
3096 3082 ctx = repo[None]
3097 3083 parents = ctx.parents()
3098 3084 pnode = parents[0].node()
3099 3085
3100 3086 for p in parents:
3101 3087 # label with log.changeset (instead of log.parent) since this
3102 3088 # shows a working directory parent *changeset*:
3103 3089 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
3104 3090 label='log.changeset')
3105 3091 ui.write(' '.join(p.tags()), label='log.tag')
3106 3092 if p.rev() == -1:
3107 3093 if not len(repo):
3108 3094 ui.write(_(' (empty repository)'))
3109 3095 else:
3110 3096 ui.write(_(' (no revision checked out)'))
3111 3097 ui.write('\n')
3112 3098 if p.description():
3113 3099 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
3114 3100 label='log.summary')
3115 3101
3116 3102 branch = ctx.branch()
3117 3103 bheads = repo.branchheads(branch)
3118 3104 m = _('branch: %s\n') % branch
3119 3105 if branch != 'default':
3120 3106 ui.write(m, label='log.branch')
3121 3107 else:
3122 3108 ui.status(m, label='log.branch')
3123 3109
3124 3110 st = list(repo.status(unknown=True))[:6]
3125 3111 ms = mergemod.mergestate(repo)
3126 3112 st.append([f for f in ms if ms[f] == 'u'])
3127 3113 labels = [ui.label(_('%d modified'), 'status.modified'),
3128 3114 ui.label(_('%d added'), 'status.added'),
3129 3115 ui.label(_('%d removed'), 'status.removed'),
3130 3116 ui.label(_('%d deleted'), 'status.deleted'),
3131 3117 ui.label(_('%d unknown'), 'status.unknown'),
3132 3118 ui.label(_('%d ignored'), 'status.ignored'),
3133 3119 ui.label(_('%d unresolved'), 'resolve.unresolved')]
3134 3120 t = []
3135 3121 for s, l in zip(st, labels):
3136 3122 if s:
3137 3123 t.append(l % len(s))
3138 3124
3139 3125 t = ', '.join(t)
3140 3126 cleanworkdir = False
3141 3127
3142 3128 if len(parents) > 1:
3143 3129 t += _(' (merge)')
3144 3130 elif branch != parents[0].branch():
3145 3131 t += _(' (new branch)')
3146 3132 elif (not st[0] and not st[1] and not st[2]):
3147 3133 t += _(' (clean)')
3148 3134 cleanworkdir = True
3149 3135 elif pnode not in bheads:
3150 3136 t += _(' (new branch head)')
3151 3137
3152 3138 if cleanworkdir:
3153 3139 ui.status(_('commit: %s\n') % t.strip())
3154 3140 else:
3155 3141 ui.write(_('commit: %s\n') % t.strip())
3156 3142
3157 3143 # all ancestors of branch heads - all ancestors of parent = new csets
3158 3144 new = [0] * len(repo)
3159 3145 cl = repo.changelog
3160 3146 for a in [cl.rev(n) for n in bheads]:
3161 3147 new[a] = 1
3162 3148 for a in cl.ancestors(*[cl.rev(n) for n in bheads]):
3163 3149 new[a] = 1
3164 3150 for a in [p.rev() for p in parents]:
3165 3151 if a >= 0:
3166 3152 new[a] = 0
3167 3153 for a in cl.ancestors(*[p.rev() for p in parents]):
3168 3154 new[a] = 0
3169 3155 new = sum(new)
3170 3156
3171 3157 if new == 0:
3172 3158 ui.status(_('update: (current)\n'))
3173 3159 elif pnode not in bheads:
3174 3160 ui.write(_('update: %d new changesets (update)\n') % new)
3175 3161 else:
3176 3162 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
3177 3163 (new, len(bheads)))
3178 3164
3179 3165 if opts.get('remote'):
3180 3166 t = []
3181 3167 source, branches = hg.parseurl(ui.expandpath('default'))
3182 3168 other = hg.repository(cmdutil.remoteui(repo, {}), source)
3183 3169 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
3184 3170 ui.debug('comparing with %s\n' % url.hidepassword(source))
3185 3171 repo.ui.pushbuffer()
3186 3172 common, incoming, rheads = repo.findcommonincoming(other)
3187 3173 repo.ui.popbuffer()
3188 3174 if incoming:
3189 3175 t.append(_('1 or more incoming'))
3190 3176
3191 3177 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
3192 3178 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
3193 3179 other = hg.repository(cmdutil.remoteui(repo, {}), dest)
3194 3180 ui.debug('comparing with %s\n' % url.hidepassword(dest))
3195 3181 repo.ui.pushbuffer()
3196 3182 o = repo.findoutgoing(other)
3197 3183 repo.ui.popbuffer()
3198 3184 o = repo.changelog.nodesbetween(o, None)[0]
3199 3185 if o:
3200 3186 t.append(_('%d outgoing') % len(o))
3201 3187
3202 3188 if t:
3203 3189 ui.write(_('remote: %s\n') % (', '.join(t)))
3204 3190 else:
3205 3191 ui.status(_('remote: (synced)\n'))
3206 3192
3207 3193 def tag(ui, repo, name1, *names, **opts):
3208 3194 """add one or more tags for the current or given revision
3209 3195
3210 3196 Name a particular revision using <name>.
3211 3197
3212 3198 Tags are used to name particular revisions of the repository and are
3213 3199 very useful to compare different revisions, to go back to significant
3214 3200 earlier versions or to mark branch points as releases, etc.
3215 3201
3216 3202 If no revision is given, the parent of the working directory is
3217 3203 used, or tip if no revision is checked out.
3218 3204
3219 3205 To facilitate version control, distribution, and merging of tags,
3220 3206 they are stored as a file named ".hgtags" which is managed
3221 3207 similarly to other project files and can be hand-edited if
3222 3208 necessary. The file '.hg/localtags' is used for local tags (not
3223 3209 shared among repositories).
3224 3210
3225 3211 See :hg:`help dates` for a list of formats valid for -d/--date.
3226 3212 """
3227 3213
3228 3214 rev_ = "."
3229 3215 names = (name1,) + names
3230 3216 if len(names) != len(set(names)):
3231 3217 raise util.Abort(_('tag names must be unique'))
3232 3218 for n in names:
3233 3219 if n in ['tip', '.', 'null']:
3234 3220 raise util.Abort(_('the name \'%s\' is reserved') % n)
3235 3221 if opts.get('rev') and opts.get('remove'):
3236 3222 raise util.Abort(_("--rev and --remove are incompatible"))
3237 3223 if opts.get('rev'):
3238 3224 rev_ = opts['rev']
3239 3225 message = opts.get('message')
3240 3226 if opts.get('remove'):
3241 3227 expectedtype = opts.get('local') and 'local' or 'global'
3242 3228 for n in names:
3243 3229 if not repo.tagtype(n):
3244 3230 raise util.Abort(_('tag \'%s\' does not exist') % n)
3245 3231 if repo.tagtype(n) != expectedtype:
3246 3232 if expectedtype == 'global':
3247 3233 raise util.Abort(_('tag \'%s\' is not a global tag') % n)
3248 3234 else:
3249 3235 raise util.Abort(_('tag \'%s\' is not a local tag') % n)
3250 3236 rev_ = nullid
3251 3237 if not message:
3252 3238 # we don't translate commit messages
3253 3239 message = 'Removed tag %s' % ', '.join(names)
3254 3240 elif not opts.get('force'):
3255 3241 for n in names:
3256 3242 if n in repo.tags():
3257 3243 raise util.Abort(_('tag \'%s\' already exists '
3258 3244 '(use -f to force)') % n)
3259 3245 if not rev_ and repo.dirstate.parents()[1] != nullid:
3260 3246 raise util.Abort(_('uncommitted merge - please provide a '
3261 3247 'specific revision'))
3262 3248 r = repo[rev_].node()
3263 3249
3264 3250 if not message:
3265 3251 # we don't translate commit messages
3266 3252 message = ('Added tag %s for changeset %s' %
3267 3253 (', '.join(names), short(r)))
3268 3254
3269 3255 date = opts.get('date')
3270 3256 if date:
3271 3257 date = util.parsedate(date)
3272 3258
3273 3259 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
3274 3260
3275 3261 def tags(ui, repo):
3276 3262 """list repository tags
3277 3263
3278 3264 This lists both regular and local tags. When the -v/--verbose
3279 3265 switch is used, a third column "local" is printed for local tags.
3280 3266 """
3281 3267
3282 3268 hexfunc = ui.debugflag and hex or short
3283 3269 tagtype = ""
3284 3270
3285 3271 for t, n in reversed(repo.tagslist()):
3286 3272 if ui.quiet:
3287 3273 ui.write("%s\n" % t)
3288 3274 continue
3289 3275
3290 3276 try:
3291 3277 hn = hexfunc(n)
3292 3278 r = "%5d:%s" % (repo.changelog.rev(n), hn)
3293 3279 except error.LookupError:
3294 3280 r = " ?:%s" % hn
3295 3281 else:
3296 3282 spaces = " " * (30 - encoding.colwidth(t))
3297 3283 if ui.verbose:
3298 3284 if repo.tagtype(t) == 'local':
3299 3285 tagtype = " local"
3300 3286 else:
3301 3287 tagtype = ""
3302 3288 ui.write("%s%s %s%s\n" % (t, spaces, r, tagtype))
3303 3289
3304 3290 def tip(ui, repo, **opts):
3305 3291 """show the tip revision
3306 3292
3307 3293 The tip revision (usually just called the tip) is the changeset
3308 3294 most recently added to the repository (and therefore the most
3309 3295 recently changed head).
3310 3296
3311 3297 If you have just made a commit, that commit will be the tip. If
3312 3298 you have just pulled changes from another repository, the tip of
3313 3299 that repository becomes the current tip. The "tip" tag is special
3314 3300 and cannot be renamed or assigned to a different changeset.
3315 3301 """
3316 3302 displayer = cmdutil.show_changeset(ui, repo, opts)
3317 3303 displayer.show(repo[len(repo) - 1])
3318 3304 displayer.close()
3319 3305
3320 3306 def unbundle(ui, repo, fname1, *fnames, **opts):
3321 3307 """apply one or more changegroup files
3322 3308
3323 3309 Apply one or more compressed changegroup files generated by the
3324 3310 bundle command.
3325 3311 """
3326 3312 fnames = (fname1,) + fnames
3327 3313
3328 3314 lock = repo.lock()
3329 3315 try:
3330 3316 for fname in fnames:
3331 3317 f = url.open(ui, fname)
3332 3318 gen = changegroup.readbundle(f, fname)
3333 3319 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname)
3334 3320 finally:
3335 3321 lock.release()
3336 3322
3337 3323 return postincoming(ui, repo, modheads, opts.get('update'), None)
3338 3324
3339 3325 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
3340 3326 """update working directory (or switch revisions)
3341 3327
3342 3328 Update the repository's working directory to the specified
3343 3329 changeset.
3344 3330
3345 3331 If no changeset is specified, attempt to update to the head of the
3346 3332 current branch. If this head is a descendant of the working
3347 3333 directory's parent, update to it, otherwise abort.
3348 3334
3349 3335 The following rules apply when the working directory contains
3350 3336 uncommitted changes:
3351 3337
3352 3338 1. If neither -c/--check nor -C/--clean is specified, and if
3353 3339 the requested changeset is an ancestor or descendant of
3354 3340 the working directory's parent, the uncommitted changes
3355 3341 are merged into the requested changeset and the merged
3356 3342 result is left uncommitted. If the requested changeset is
3357 3343 not an ancestor or descendant (that is, it is on another
3358 3344 branch), the update is aborted and the uncommitted changes
3359 3345 are preserved.
3360 3346
3361 3347 2. With the -c/--check option, the update is aborted and the
3362 3348 uncommitted changes are preserved.
3363 3349
3364 3350 3. With the -C/--clean option, uncommitted changes are discarded and
3365 3351 the working directory is updated to the requested changeset.
3366 3352
3367 3353 Use null as the changeset to remove the working directory (like
3368 3354 :hg:`clone -U`).
3369 3355
3370 3356 If you want to update just one file to an older changeset, use :hg:`revert`.
3371 3357
3372 3358 See :hg:`help dates` for a list of formats valid for -d/--date.
3373 3359 """
3374 3360 if rev and node:
3375 3361 raise util.Abort(_("please specify just one revision"))
3376 3362
3377 3363 if not rev:
3378 3364 rev = node
3379 3365
3380 3366 if check and clean:
3381 3367 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
3382 3368
3383 3369 if check:
3384 3370 # we could use dirty() but we can ignore merge and branch trivia
3385 3371 c = repo[None]
3386 3372 if c.modified() or c.added() or c.removed():
3387 3373 raise util.Abort(_("uncommitted local changes"))
3388 3374
3389 3375 if date:
3390 3376 if rev:
3391 3377 raise util.Abort(_("you can't specify a revision and a date"))
3392 3378 rev = cmdutil.finddate(ui, repo, date)
3393 3379
3394 3380 if clean or check:
3395 3381 return hg.clean(repo, rev)
3396 3382 else:
3397 3383 return hg.update(repo, rev)
3398 3384
3399 3385 def verify(ui, repo):
3400 3386 """verify the integrity of the repository
3401 3387
3402 3388 Verify the integrity of the current repository.
3403 3389
3404 3390 This will perform an extensive check of the repository's
3405 3391 integrity, validating the hashes and checksums of each entry in
3406 3392 the changelog, manifest, and tracked files, as well as the
3407 3393 integrity of their crosslinks and indices.
3408 3394 """
3409 3395 return hg.verify(repo)
3410 3396
3411 3397 def version_(ui):
3412 3398 """output version and copyright information"""
3413 3399 ui.write(_("Mercurial Distributed SCM (version %s)\n")
3414 3400 % util.version())
3415 3401 ui.status(_(
3416 3402 "\nCopyright (C) 2005-2010 Matt Mackall <mpm@selenic.com> and others\n"
3417 3403 "This is free software; see the source for copying conditions. "
3418 3404 "There is NO\nwarranty; "
3419 3405 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
3420 3406 ))
3421 3407
3422 3408 # Command options and aliases are listed here, alphabetically
3423 3409
3424 3410 globalopts = [
3425 3411 ('R', 'repository', '',
3426 3412 _('repository root directory or name of overlay bundle file')),
3427 3413 ('', 'cwd', '', _('change working directory')),
3428 3414 ('y', 'noninteractive', None,
3429 3415 _('do not prompt, assume \'yes\' for any required answers')),
3430 3416 ('q', 'quiet', None, _('suppress output')),
3431 3417 ('v', 'verbose', None, _('enable additional output')),
3432 3418 ('', 'config', [],
3433 3419 _('set/override config option (use \'section.name=value\')')),
3434 3420 ('', 'debug', None, _('enable debugging output')),
3435 3421 ('', 'debugger', None, _('start debugger')),
3436 3422 ('', 'encoding', encoding.encoding, _('set the charset encoding')),
3437 3423 ('', 'encodingmode', encoding.encodingmode,
3438 3424 _('set the charset encoding mode')),
3439 3425 ('', 'traceback', None, _('always print a traceback on exception')),
3440 3426 ('', 'time', None, _('time how long the command takes')),
3441 3427 ('', 'profile', None, _('print command execution profile')),
3442 3428 ('', 'version', None, _('output version information and exit')),
3443 3429 ('h', 'help', None, _('display help and exit')),
3444 3430 ]
3445 3431
3446 3432 dryrunopts = [('n', 'dry-run', None,
3447 3433 _('do not perform actions, just print output'))]
3448 3434
3449 3435 remoteopts = [
3450 3436 ('e', 'ssh', '', _('specify ssh command to use')),
3451 3437 ('', 'remotecmd', '', _('specify hg command to run on the remote side')),
3452 3438 ]
3453 3439
3454 3440 walkopts = [
3455 3441 ('I', 'include', [], _('include names matching the given patterns')),
3456 3442 ('X', 'exclude', [], _('exclude names matching the given patterns')),
3457 3443 ]
3458 3444
3459 3445 commitopts = [
3460 3446 ('m', 'message', '', _('use <text> as commit message')),
3461 3447 ('l', 'logfile', '', _('read commit message from <file>')),
3462 3448 ]
3463 3449
3464 3450 commitopts2 = [
3465 3451 ('d', 'date', '', _('record datecode as commit date')),
3466 3452 ('u', 'user', '', _('record the specified user as committer')),
3467 3453 ]
3468 3454
3469 3455 templateopts = [
3470 3456 ('', 'style', '', _('display using template map file')),
3471 3457 ('', 'template', '', _('display with template')),
3472 3458 ]
3473 3459
3474 3460 logopts = [
3475 3461 ('p', 'patch', None, _('show patch')),
3476 3462 ('g', 'git', None, _('use git extended diff format')),
3477 3463 ('l', 'limit', '', _('limit number of changes displayed')),
3478 3464 ('M', 'no-merges', None, _('do not show merges')),
3479 3465 ] + templateopts
3480 3466
3481 3467 diffopts = [
3482 3468 ('a', 'text', None, _('treat all files as text')),
3483 3469 ('g', 'git', None, _('use git extended diff format')),
3484 3470 ('', 'nodates', None, _('omit dates from diff headers'))
3485 3471 ]
3486 3472
3487 3473 diffopts2 = [
3488 3474 ('p', 'show-function', None, _('show which function each change is in')),
3489 3475 ('', 'reverse', None, _('produce a diff that undoes the changes')),
3490 3476 ('w', 'ignore-all-space', None,
3491 3477 _('ignore white space when comparing lines')),
3492 3478 ('b', 'ignore-space-change', None,
3493 3479 _('ignore changes in the amount of white space')),
3494 3480 ('B', 'ignore-blank-lines', None,
3495 3481 _('ignore changes whose lines are all blank')),
3496 3482 ('U', 'unified', '', _('number of lines of context to show')),
3497 3483 ('', 'stat', None, _('output diffstat-style summary of changes')),
3498 3484 ]
3499 3485
3500 3486 similarityopts = [
3501 3487 ('s', 'similarity', '',
3502 3488 _('guess renamed files by similarity (0<=s<=100)'))
3503 3489 ]
3504 3490
3505 3491 table = {
3506 3492 "^add": (add, walkopts + dryrunopts, _('[OPTION]... [FILE]...')),
3507 3493 "addremove":
3508 3494 (addremove, similarityopts + walkopts + dryrunopts,
3509 3495 _('[OPTION]... [FILE]...')),
3510 3496 "^annotate|blame":
3511 3497 (annotate,
3512 3498 [('r', 'rev', '', _('annotate the specified revision')),
3513 3499 ('', 'follow', None,
3514 3500 _('follow copies/renames and list the filename (DEPRECATED)')),
3515 3501 ('', 'no-follow', None, _("don't follow copies and renames")),
3516 3502 ('a', 'text', None, _('treat all files as text')),
3517 3503 ('u', 'user', None, _('list the author (long with -v)')),
3518 3504 ('f', 'file', None, _('list the filename')),
3519 3505 ('d', 'date', None, _('list the date (short with -q)')),
3520 3506 ('n', 'number', None, _('list the revision number (default)')),
3521 3507 ('c', 'changeset', None, _('list the changeset')),
3522 3508 ('l', 'line-number', None,
3523 3509 _('show line number at the first appearance'))
3524 3510 ] + walkopts,
3525 3511 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...')),
3526 3512 "archive":
3527 3513 (archive,
3528 3514 [('', 'no-decode', None, _('do not pass files through decoders')),
3529 3515 ('p', 'prefix', '', _('directory prefix for files in archive')),
3530 3516 ('r', 'rev', '', _('revision to distribute')),
3531 3517 ('t', 'type', '', _('type of distribution to create')),
3532 3518 ] + walkopts,
3533 3519 _('[OPTION]... DEST')),
3534 3520 "backout":
3535 3521 (backout,
3536 3522 [('', 'merge', None,
3537 3523 _('merge with old dirstate parent after backout')),
3538 3524 ('', 'parent', '', _('parent to choose when backing out merge')),
3539 3525 ('r', 'rev', '', _('revision to backout')),
3540 3526 ] + walkopts + commitopts + commitopts2,
3541 3527 _('[OPTION]... [-r] REV')),
3542 3528 "bisect":
3543 3529 (bisect,
3544 3530 [('r', 'reset', False, _('reset bisect state')),
3545 3531 ('g', 'good', False, _('mark changeset good')),
3546 3532 ('b', 'bad', False, _('mark changeset bad')),
3547 3533 ('s', 'skip', False, _('skip testing changeset')),
3548 3534 ('c', 'command', '', _('use command to check changeset state')),
3549 3535 ('U', 'noupdate', False, _('do not update to target'))],
3550 3536 _("[-gbsr] [-U] [-c CMD] [REV]")),
3551 3537 "branch":
3552 3538 (branch,
3553 3539 [('f', 'force', None,
3554 3540 _('set branch name even if it shadows an existing branch')),
3555 3541 ('C', 'clean', None, _('reset branch name to parent branch name'))],
3556 3542 _('[-fC] [NAME]')),
3557 3543 "branches":
3558 3544 (branches,
3559 3545 [('a', 'active', False,
3560 3546 _('show only branches that have unmerged heads')),
3561 3547 ('c', 'closed', False,
3562 3548 _('show normal and closed branches'))],
3563 3549 _('[-ac]')),
3564 3550 "bundle":
3565 3551 (bundle,
3566 3552 [('f', 'force', None,
3567 3553 _('run even when the destination is unrelated')),
3568 3554 ('r', 'rev', [],
3569 3555 _('a changeset intended to be added to the destination')),
3570 3556 ('b', 'branch', [],
3571 3557 _('a specific branch you would like to bundle')),
3572 3558 ('', 'base', [],
3573 3559 _('a base changeset assumed to be available at the destination')),
3574 3560 ('a', 'all', None, _('bundle all changesets in the repository')),
3575 3561 ('t', 'type', 'bzip2', _('bundle compression type to use')),
3576 3562 ] + remoteopts,
3577 3563 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]')),
3578 3564 "cat":
3579 3565 (cat,
3580 3566 [('o', 'output', '', _('print output to file with formatted name')),
3581 3567 ('r', 'rev', '', _('print the given revision')),
3582 3568 ('', 'decode', None, _('apply any matching decode filter')),
3583 3569 ] + walkopts,
3584 3570 _('[OPTION]... FILE...')),
3585 3571 "^clone":
3586 3572 (clone,
3587 3573 [('U', 'noupdate', None,
3588 3574 _('the clone will include an empty working copy (only a repository)')),
3589 3575 ('u', 'updaterev', '',
3590 3576 _('revision, tag or branch to check out')),
3591 3577 ('r', 'rev', [],
3592 3578 _('include the specified changeset')),
3593 3579 ('b', 'branch', [],
3594 3580 _('clone only the specified branch')),
3595 3581 ('', 'pull', None, _('use pull protocol to copy metadata')),
3596 3582 ('', 'uncompressed', None,
3597 3583 _('use uncompressed transfer (fast over LAN)')),
3598 3584 ] + remoteopts,
3599 3585 _('[OPTION]... SOURCE [DEST]')),
3600 3586 "^commit|ci":
3601 3587 (commit,
3602 3588 [('A', 'addremove', None,
3603 3589 _('mark new/missing files as added/removed before committing')),
3604 3590 ('', 'close-branch', None,
3605 3591 _('mark a branch as closed, hiding it from the branch list')),
3606 3592 ] + walkopts + commitopts + commitopts2,
3607 3593 _('[OPTION]... [FILE]...')),
3608 3594 "copy|cp":
3609 3595 (copy,
3610 3596 [('A', 'after', None, _('record a copy that has already occurred')),
3611 3597 ('f', 'force', None,
3612 3598 _('forcibly copy over an existing managed file')),
3613 3599 ] + walkopts + dryrunopts,
3614 3600 _('[OPTION]... [SOURCE]... DEST')),
3615 3601 "debugancestor": (debugancestor, [], _('[INDEX] REV1 REV2')),
3616 3602 "debugcheckstate": (debugcheckstate, [], ''),
3617 3603 "debugcommands": (debugcommands, [], _('[COMMAND]')),
3618 3604 "debugcomplete":
3619 3605 (debugcomplete,
3620 3606 [('o', 'options', None, _('show the command options'))],
3621 3607 _('[-o] CMD')),
3622 3608 "debugdate":
3623 3609 (debugdate,
3624 3610 [('e', 'extended', None, _('try extended date formats'))],
3625 3611 _('[-e] DATE [RANGE]')),
3626 3612 "debugdata": (debugdata, [], _('FILE REV')),
3627 3613 "debugfsinfo": (debugfsinfo, [], _('[PATH]')),
3628 3614 "debugindex": (debugindex, [], _('FILE')),
3629 3615 "debugindexdot": (debugindexdot, [], _('FILE')),
3630 3616 "debuginstall": (debuginstall, [], ''),
3631 3617 "debugrebuildstate":
3632 3618 (debugrebuildstate,
3633 3619 [('r', 'rev', '', _('revision to rebuild to'))],
3634 3620 _('[-r REV] [REV]')),
3635 3621 "debugrename":
3636 3622 (debugrename,
3637 3623 [('r', 'rev', '', _('revision to debug'))],
3638 3624 _('[-r REV] FILE')),
3639 3625 "debugsetparents":
3640 3626 (debugsetparents, [], _('REV1 [REV2]')),
3641 3627 "debugstate":
3642 3628 (debugstate,
3643 3629 [('', 'nodates', None, _('do not display the saved mtime'))],
3644 3630 _('[OPTION]...')),
3645 3631 "debugsub":
3646 3632 (debugsub,
3647 3633 [('r', 'rev', '', _('revision to check'))],
3648 3634 _('[-r REV] [REV]')),
3649 3635 "debugwalk": (debugwalk, walkopts, _('[OPTION]... [FILE]...')),
3650 3636 "^diff":
3651 3637 (diff,
3652 3638 [('r', 'rev', [], _('revision')),
3653 3639 ('c', 'change', '', _('change made by revision'))
3654 3640 ] + diffopts + diffopts2 + walkopts,
3655 3641 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...')),
3656 3642 "^export":
3657 3643 (export,
3658 3644 [('o', 'output', '', _('print output to file with formatted name')),
3659 3645 ('', 'switch-parent', None, _('diff against the second parent')),
3660 3646 ('r', 'rev', [], _('revisions to export')),
3661 3647 ] + diffopts,
3662 3648 _('[OPTION]... [-o OUTFILESPEC] REV...')),
3663 3649 "^forget":
3664 3650 (forget,
3665 3651 [] + walkopts,
3666 3652 _('[OPTION]... FILE...')),
3667 3653 "grep":
3668 3654 (grep,
3669 3655 [('0', 'print0', None, _('end fields with NUL')),
3670 3656 ('', 'all', None, _('print all revisions that match')),
3671 3657 ('f', 'follow', None,
3672 3658 _('follow changeset history,'
3673 3659 ' or file history across copies and renames')),
3674 3660 ('i', 'ignore-case', None, _('ignore case when matching')),
3675 3661 ('l', 'files-with-matches', None,
3676 3662 _('print only filenames and revisions that match')),
3677 3663 ('n', 'line-number', None, _('print matching line numbers')),
3678 3664 ('r', 'rev', [], _('search in given revision range')),
3679 3665 ('u', 'user', None, _('list the author (long with -v)')),
3680 3666 ('d', 'date', None, _('list the date (short with -q)')),
3681 3667 ] + walkopts,
3682 3668 _('[OPTION]... PATTERN [FILE]...')),
3683 3669 "heads":
3684 3670 (heads,
3685 3671 [('r', 'rev', '', _('show only heads which are descendants of REV')),
3686 3672 ('t', 'topo', False, _('show topological heads only')),
3687 3673 ('a', 'active', False,
3688 3674 _('show active branchheads only [DEPRECATED]')),
3689 3675 ('c', 'closed', False,
3690 3676 _('show normal and closed branch heads')),
3691 3677 ] + templateopts,
3692 3678 _('[-ac] [-r STARTREV] [REV]...')),
3693 3679 "help": (help_, [], _('[TOPIC]')),
3694 3680 "identify|id":
3695 3681 (identify,
3696 3682 [('r', 'rev', '', _('identify the specified revision')),
3697 3683 ('n', 'num', None, _('show local revision number')),
3698 3684 ('i', 'id', None, _('show global revision id')),
3699 3685 ('b', 'branch', None, _('show branch')),
3700 3686 ('t', 'tags', None, _('show tags'))],
3701 3687 _('[-nibt] [-r REV] [SOURCE]')),
3702 3688 "import|patch":
3703 3689 (import_,
3704 3690 [('p', 'strip', 1,
3705 3691 _('directory strip option for patch. This has the same '
3706 3692 'meaning as the corresponding patch option')),
3707 3693 ('b', 'base', '', _('base path')),
3708 3694 ('f', 'force', None,
3709 3695 _('skip check for outstanding uncommitted changes')),
3710 3696 ('', 'no-commit', None,
3711 3697 _("don't commit, just update the working directory")),
3712 3698 ('', 'exact', None,
3713 3699 _('apply patch to the nodes from which it was generated')),
3714 3700 ('', 'import-branch', None,
3715 3701 _('use any branch information in patch (implied by --exact)'))] +
3716 3702 commitopts + commitopts2 + similarityopts,
3717 3703 _('[OPTION]... PATCH...')),
3718 3704 "incoming|in":
3719 3705 (incoming,
3720 3706 [('f', 'force', None,
3721 3707 _('run even if remote repository is unrelated')),
3722 3708 ('n', 'newest-first', None, _('show newest record first')),
3723 3709 ('', 'bundle', '', _('file to store the bundles into')),
3724 3710 ('r', 'rev', [],
3725 3711 _('a remote changeset intended to be added')),
3726 3712 ('b', 'branch', [],
3727 3713 _('a specific branch you would like to pull')),
3728 3714 ] + logopts + remoteopts,
3729 3715 _('[-p] [-n] [-M] [-f] [-r REV]...'
3730 3716 ' [--bundle FILENAME] [SOURCE]')),
3731 3717 "^init":
3732 3718 (init,
3733 3719 remoteopts,
3734 3720 _('[-e CMD] [--remotecmd CMD] [DEST]')),
3735 3721 "locate":
3736 3722 (locate,
3737 3723 [('r', 'rev', '', _('search the repository as it is in REV')),
3738 3724 ('0', 'print0', None,
3739 3725 _('end filenames with NUL, for use with xargs')),
3740 3726 ('f', 'fullpath', None,
3741 3727 _('print complete paths from the filesystem root')),
3742 3728 ] + walkopts,
3743 3729 _('[OPTION]... [PATTERN]...')),
3744 3730 "^log|history":
3745 3731 (log,
3746 3732 [('f', 'follow', None,
3747 3733 _('follow changeset history,'
3748 3734 ' or file history across copies and renames')),
3749 3735 ('', 'follow-first', None,
3750 3736 _('only follow the first parent of merge changesets')),
3751 3737 ('d', 'date', '', _('show revisions matching date spec')),
3752 3738 ('C', 'copies', None, _('show copied files')),
3753 3739 ('k', 'keyword', [], _('do case-insensitive search for a keyword')),
3754 3740 ('r', 'rev', [], _('show the specified revision or range')),
3755 3741 ('', 'removed', None, _('include revisions where files were removed')),
3756 3742 ('m', 'only-merges', None, _('show only merges')),
3757 3743 ('u', 'user', [], _('revisions committed by user')),
3758 3744 ('', 'only-branch', [],
3759 3745 _('show only changesets within the given named branch (DEPRECATED)')),
3760 3746 ('b', 'branch', [],
3761 3747 _('show changesets within the given named branch')),
3762 3748 ('P', 'prune', [],
3763 3749 _('do not display revision or any of its ancestors')),
3764 3750 ] + logopts + walkopts,
3765 3751 _('[OPTION]... [FILE]')),
3766 3752 "manifest":
3767 3753 (manifest,
3768 3754 [('r', 'rev', '', _('revision to display'))],
3769 3755 _('[-r REV]')),
3770 3756 "^merge":
3771 3757 (merge,
3772 3758 [('f', 'force', None, _('force a merge with outstanding changes')),
3773 3759 ('r', 'rev', '', _('revision to merge')),
3774 3760 ('P', 'preview', None,
3775 3761 _('review revisions to merge (no merge is performed)'))],
3776 3762 _('[-P] [-f] [[-r] REV]')),
3777 3763 "outgoing|out":
3778 3764 (outgoing,
3779 3765 [('f', 'force', None,
3780 3766 _('run even when the destination is unrelated')),
3781 3767 ('r', 'rev', [],
3782 3768 _('a changeset intended to be included in the destination')),
3783 3769 ('n', 'newest-first', None, _('show newest record first')),
3784 3770 ('b', 'branch', [],
3785 3771 _('a specific branch you would like to push')),
3786 3772 ] + logopts + remoteopts,
3787 3773 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]')),
3788 3774 "parents":
3789 3775 (parents,
3790 3776 [('r', 'rev', '', _('show parents of the specified revision')),
3791 3777 ] + templateopts,
3792 3778 _('[-r REV] [FILE]')),
3793 3779 "paths": (paths, [], _('[NAME]')),
3794 3780 "^pull":
3795 3781 (pull,
3796 3782 [('u', 'update', None,
3797 3783 _('update to new branch head if changesets were pulled')),
3798 3784 ('f', 'force', None,
3799 3785 _('run even when remote repository is unrelated')),
3800 3786 ('r', 'rev', [],
3801 3787 _('a remote changeset intended to be added')),
3802 3788 ('b', 'branch', [],
3803 3789 _('a specific branch you would like to pull')),
3804 3790 ] + remoteopts,
3805 3791 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]')),
3806 3792 "^push":
3807 3793 (push,
3808 3794 [('f', 'force', None, _('force push')),
3809 3795 ('r', 'rev', [],
3810 3796 _('a changeset intended to be included in the destination')),
3811 3797 ('b', 'branch', [],
3812 3798 _('a specific branch you would like to push')),
3813 3799 ] + remoteopts,
3814 3800 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]')),
3815 3801 "recover": (recover, []),
3816 3802 "^remove|rm":
3817 3803 (remove,
3818 3804 [('A', 'after', None, _('record delete for missing files')),
3819 3805 ('f', 'force', None,
3820 3806 _('remove (and delete) file even if added or modified')),
3821 3807 ] + walkopts,
3822 3808 _('[OPTION]... FILE...')),
3823 3809 "rename|mv":
3824 3810 (rename,
3825 3811 [('A', 'after', None, _('record a rename that has already occurred')),
3826 3812 ('f', 'force', None,
3827 3813 _('forcibly copy over an existing managed file')),
3828 3814 ] + walkopts + dryrunopts,
3829 3815 _('[OPTION]... SOURCE... DEST')),
3830 3816 "resolve":
3831 3817 (resolve,
3832 3818 [('a', 'all', None, _('select all unresolved files')),
3833 3819 ('l', 'list', None, _('list state of files needing merge')),
3834 3820 ('m', 'mark', None, _('mark files as resolved')),
3835 3821 ('u', 'unmark', None, _('unmark files as resolved')),
3836 3822 ('n', 'no-status', None, _('hide status prefix'))]
3837 3823 + walkopts,
3838 3824 _('[OPTION]... [FILE]...')),
3839 3825 "revert":
3840 3826 (revert,
3841 3827 [('a', 'all', None, _('revert all changes when no arguments given')),
3842 3828 ('d', 'date', '', _('tipmost revision matching date')),
3843 3829 ('r', 'rev', '', _('revert to the specified revision')),
3844 3830 ('', 'no-backup', None, _('do not save backup copies of files')),
3845 3831 ] + walkopts + dryrunopts,
3846 3832 _('[OPTION]... [-r REV] [NAME]...')),
3847 3833 "rollback": (rollback, dryrunopts),
3848 3834 "root": (root, []),
3849 3835 "^serve":
3850 3836 (serve,
3851 3837 [('A', 'accesslog', '', _('name of access log file to write to')),
3852 3838 ('d', 'daemon', None, _('run server in background')),
3853 3839 ('', 'daemon-pipefds', '', _('used internally by daemon mode')),
3854 3840 ('E', 'errorlog', '', _('name of error log file to write to')),
3855 3841 # use string type, then we can check if something was passed
3856 3842 ('p', 'port', '', _('port to listen on (default: 8000)')),
3857 3843 ('a', 'address', '',
3858 3844 _('address to listen on (default: all interfaces)')),
3859 3845 ('', 'prefix', '',
3860 3846 _('prefix path to serve from (default: server root)')),
3861 3847 ('n', 'name', '',
3862 3848 _('name to show in web pages (default: working directory)')),
3863 3849 ('', 'web-conf', '', _('name of the hgweb config file'
3864 3850 ' (serve more than one repository)')),
3865 3851 ('', 'webdir-conf', '', _('name of the hgweb config file'
3866 3852 ' (DEPRECATED)')),
3867 3853 ('', 'pid-file', '', _('name of file to write process ID to')),
3868 3854 ('', 'stdio', None, _('for remote clients')),
3869 3855 ('t', 'templates', '', _('web templates to use')),
3870 3856 ('', 'style', '', _('template style to use')),
3871 3857 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
3872 3858 ('', 'certificate', '', _('SSL certificate file'))],
3873 3859 _('[OPTION]...')),
3874 3860 "showconfig|debugconfig":
3875 3861 (showconfig,
3876 3862 [('u', 'untrusted', None, _('show untrusted configuration options'))],
3877 3863 _('[-u] [NAME]...')),
3878 3864 "^summary|sum":
3879 3865 (summary,
3880 3866 [('', 'remote', None, _('check for push and pull'))], '[--remote]'),
3881 3867 "^status|st":
3882 3868 (status,
3883 3869 [('A', 'all', None, _('show status of all files')),
3884 3870 ('m', 'modified', None, _('show only modified files')),
3885 3871 ('a', 'added', None, _('show only added files')),
3886 3872 ('r', 'removed', None, _('show only removed files')),
3887 3873 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
3888 3874 ('c', 'clean', None, _('show only files without changes')),
3889 3875 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
3890 3876 ('i', 'ignored', None, _('show only ignored files')),
3891 3877 ('n', 'no-status', None, _('hide status prefix')),
3892 3878 ('C', 'copies', None, _('show source of copied files')),
3893 3879 ('0', 'print0', None,
3894 3880 _('end filenames with NUL, for use with xargs')),
3895 3881 ('', 'rev', [], _('show difference from revision')),
3896 3882 ('', 'change', '', _('list the changed files of a revision')),
3897 3883 ] + walkopts,
3898 3884 _('[OPTION]... [FILE]...')),
3899 3885 "tag":
3900 3886 (tag,
3901 3887 [('f', 'force', None, _('replace existing tag')),
3902 3888 ('l', 'local', None, _('make the tag local')),
3903 3889 ('r', 'rev', '', _('revision to tag')),
3904 3890 ('', 'remove', None, _('remove a tag')),
3905 3891 # -l/--local is already there, commitopts cannot be used
3906 3892 ('m', 'message', '', _('use <text> as commit message')),
3907 3893 ] + commitopts2,
3908 3894 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...')),
3909 3895 "tags": (tags, [], ''),
3910 3896 "tip":
3911 3897 (tip,
3912 3898 [('p', 'patch', None, _('show patch')),
3913 3899 ('g', 'git', None, _('use git extended diff format')),
3914 3900 ] + templateopts,
3915 3901 _('[-p] [-g]')),
3916 3902 "unbundle":
3917 3903 (unbundle,
3918 3904 [('u', 'update', None,
3919 3905 _('update to new branch head if changesets were unbundled'))],
3920 3906 _('[-u] FILE...')),
3921 3907 "^update|up|checkout|co":
3922 3908 (update,
3923 3909 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
3924 3910 ('c', 'check', None, _('check for uncommitted changes')),
3925 3911 ('d', 'date', '', _('tipmost revision matching date')),
3926 3912 ('r', 'rev', '', _('revision'))],
3927 3913 _('[-c] [-C] [-d DATE] [[-r] REV]')),
3928 3914 "verify": (verify, []),
3929 3915 "version": (version_, []),
3930 3916 }
3931 3917
3932 3918 norepo = ("clone init version help debugcommands debugcomplete debugdata"
3933 3919 " debugindex debugindexdot debugdate debuginstall debugfsinfo")
3934 3920 optionalrepo = ("identify paths serve showconfig debugancestor")
General Comments 0
You need to be logged in to leave comments. Login now