##// END OF EJS Templates
clone: rename "rev" to "revs" since there can be many...
Martin von Zweigbergk -
r37279:54435fd0 default
parent child Browse files
Show More
@@ -1,3659 +1,3659 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 behavior 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 It may be desirable for mq changesets to be kept in the secret phase (see
42 42 :hg:`help phases`), which can be enabled with the following setting::
43 43
44 44 [mq]
45 45 secret = True
46 46
47 47 You will by default be managing a patch queue named "patches". You can
48 48 create other, independent patch queues with the :hg:`qqueue` command.
49 49
50 50 If the working directory contains uncommitted files, qpush, qpop and
51 51 qgoto abort immediately. If -f/--force is used, the changes are
52 52 discarded. Setting::
53 53
54 54 [mq]
55 55 keepchanges = True
56 56
57 57 make them behave as if --keep-changes were passed, and non-conflicting
58 58 local changes will be tolerated and preserved. If incompatible options
59 59 such as -f/--force or --exact are passed, this setting is ignored.
60 60
61 61 This extension used to provide a strip command. This command now lives
62 62 in the strip extension.
63 63 '''
64 64
65 65 from __future__ import absolute_import, print_function
66 66
67 67 import errno
68 68 import os
69 69 import re
70 70 import shutil
71 71 from mercurial.i18n import _
72 72 from mercurial.node import (
73 73 bin,
74 74 hex,
75 75 nullid,
76 76 nullrev,
77 77 short,
78 78 )
79 79 from mercurial import (
80 80 cmdutil,
81 81 commands,
82 82 dirstateguard,
83 83 encoding,
84 84 error,
85 85 extensions,
86 86 hg,
87 87 localrepo,
88 88 lock as lockmod,
89 89 logcmdutil,
90 90 patch as patchmod,
91 91 phases,
92 92 pycompat,
93 93 registrar,
94 94 revsetlang,
95 95 scmutil,
96 96 smartset,
97 97 subrepoutil,
98 98 util,
99 99 vfs as vfsmod,
100 100 )
101 101 from mercurial.utils import (
102 102 dateutil,
103 103 stringutil,
104 104 )
105 105
106 106 release = lockmod.release
107 107 seriesopts = [('s', 'summary', None, _('print first line of patch header'))]
108 108
109 109 cmdtable = {}
110 110 command = registrar.command(cmdtable)
111 111 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
112 112 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
113 113 # be specifying the version(s) of Mercurial they are tested with, or
114 114 # leave the attribute unspecified.
115 115 testedwith = 'ships-with-hg-core'
116 116
117 117 configtable = {}
118 118 configitem = registrar.configitem(configtable)
119 119
120 120 configitem('mq', 'git',
121 121 default='auto',
122 122 )
123 123 configitem('mq', 'keepchanges',
124 124 default=False,
125 125 )
126 126 configitem('mq', 'plain',
127 127 default=False,
128 128 )
129 129 configitem('mq', 'secret',
130 130 default=False,
131 131 )
132 132
133 133 # force load strip extension formerly included in mq and import some utility
134 134 try:
135 135 stripext = extensions.find('strip')
136 136 except KeyError:
137 137 # note: load is lazy so we could avoid the try-except,
138 138 # but I (marmoute) prefer this explicit code.
139 139 class dummyui(object):
140 140 def debug(self, msg):
141 141 pass
142 142 stripext = extensions.load(dummyui(), 'strip', '')
143 143
144 144 strip = stripext.strip
145 145 checksubstate = stripext.checksubstate
146 146 checklocalchanges = stripext.checklocalchanges
147 147
148 148
149 149 # Patch names looks like unix-file names.
150 150 # They must be joinable with queue directory and result in the patch path.
151 151 normname = util.normpath
152 152
153 153 class statusentry(object):
154 154 def __init__(self, node, name):
155 155 self.node, self.name = node, name
156 156
157 157 def __bytes__(self):
158 158 return hex(self.node) + ':' + self.name
159 159
160 160 __str__ = encoding.strmethod(__bytes__)
161 161 __repr__ = encoding.strmethod(__bytes__)
162 162
163 163 # The order of the headers in 'hg export' HG patches:
164 164 HGHEADERS = [
165 165 # '# HG changeset patch',
166 166 '# User ',
167 167 '# Date ',
168 168 '# ',
169 169 '# Branch ',
170 170 '# Node ID ',
171 171 '# Parent ', # can occur twice for merges - but that is not relevant for mq
172 172 ]
173 173 # The order of headers in plain 'mail style' patches:
174 174 PLAINHEADERS = {
175 175 'from': 0,
176 176 'date': 1,
177 177 'subject': 2,
178 178 }
179 179
180 180 def inserthgheader(lines, header, value):
181 181 """Assuming lines contains a HG patch header, add a header line with value.
182 182 >>> try: inserthgheader([], b'# Date ', b'z')
183 183 ... except ValueError as inst: print("oops")
184 184 oops
185 185 >>> inserthgheader([b'# HG changeset patch'], b'# Date ', b'z')
186 186 ['# HG changeset patch', '# Date z']
187 187 >>> inserthgheader([b'# HG changeset patch', b''], b'# Date ', b'z')
188 188 ['# HG changeset patch', '# Date z', '']
189 189 >>> inserthgheader([b'# HG changeset patch', b'# User y'], b'# Date ', b'z')
190 190 ['# HG changeset patch', '# User y', '# Date z']
191 191 >>> inserthgheader([b'# HG changeset patch', b'# Date x', b'# User y'],
192 192 ... b'# User ', b'z')
193 193 ['# HG changeset patch', '# Date x', '# User z']
194 194 >>> inserthgheader([b'# HG changeset patch', b'# Date y'], b'# Date ', b'z')
195 195 ['# HG changeset patch', '# Date z']
196 196 >>> inserthgheader([b'# HG changeset patch', b'', b'# Date y'],
197 197 ... b'# Date ', b'z')
198 198 ['# HG changeset patch', '# Date z', '', '# Date y']
199 199 >>> inserthgheader([b'# HG changeset patch', b'# Parent y'],
200 200 ... b'# Date ', b'z')
201 201 ['# HG changeset patch', '# Date z', '# Parent y']
202 202 """
203 203 start = lines.index('# HG changeset patch') + 1
204 204 newindex = HGHEADERS.index(header)
205 205 bestpos = len(lines)
206 206 for i in range(start, len(lines)):
207 207 line = lines[i]
208 208 if not line.startswith('# '):
209 209 bestpos = min(bestpos, i)
210 210 break
211 211 for lineindex, h in enumerate(HGHEADERS):
212 212 if line.startswith(h):
213 213 if lineindex == newindex:
214 214 lines[i] = header + value
215 215 return lines
216 216 if lineindex > newindex:
217 217 bestpos = min(bestpos, i)
218 218 break # next line
219 219 lines.insert(bestpos, header + value)
220 220 return lines
221 221
222 222 def insertplainheader(lines, header, value):
223 223 """For lines containing a plain patch header, add a header line with value.
224 224 >>> insertplainheader([], b'Date', b'z')
225 225 ['Date: z']
226 226 >>> insertplainheader([b''], b'Date', b'z')
227 227 ['Date: z', '']
228 228 >>> insertplainheader([b'x'], b'Date', b'z')
229 229 ['Date: z', '', 'x']
230 230 >>> insertplainheader([b'From: y', b'x'], b'Date', b'z')
231 231 ['From: y', 'Date: z', '', 'x']
232 232 >>> insertplainheader([b' date : x', b' from : y', b''], b'From', b'z')
233 233 [' date : x', 'From: z', '']
234 234 >>> insertplainheader([b'', b'Date: y'], b'Date', b'z')
235 235 ['Date: z', '', 'Date: y']
236 236 >>> insertplainheader([b'foo: bar', b'DATE: z', b'x'], b'From', b'y')
237 237 ['From: y', 'foo: bar', 'DATE: z', '', 'x']
238 238 """
239 239 newprio = PLAINHEADERS[header.lower()]
240 240 bestpos = len(lines)
241 241 for i, line in enumerate(lines):
242 242 if ':' in line:
243 243 lheader = line.split(':', 1)[0].strip().lower()
244 244 lprio = PLAINHEADERS.get(lheader, newprio + 1)
245 245 if lprio == newprio:
246 246 lines[i] = '%s: %s' % (header, value)
247 247 return lines
248 248 if lprio > newprio and i < bestpos:
249 249 bestpos = i
250 250 else:
251 251 if line:
252 252 lines.insert(i, '')
253 253 if i < bestpos:
254 254 bestpos = i
255 255 break
256 256 lines.insert(bestpos, '%s: %s' % (header, value))
257 257 return lines
258 258
259 259 class patchheader(object):
260 260 def __init__(self, pf, plainmode=False):
261 261 def eatdiff(lines):
262 262 while lines:
263 263 l = lines[-1]
264 264 if (l.startswith("diff -") or
265 265 l.startswith("Index:") or
266 266 l.startswith("===========")):
267 267 del lines[-1]
268 268 else:
269 269 break
270 270 def eatempty(lines):
271 271 while lines:
272 272 if not lines[-1].strip():
273 273 del lines[-1]
274 274 else:
275 275 break
276 276
277 277 message = []
278 278 comments = []
279 279 user = None
280 280 date = None
281 281 parent = None
282 282 format = None
283 283 subject = None
284 284 branch = None
285 285 nodeid = None
286 286 diffstart = 0
287 287
288 288 for line in open(pf, 'rb'):
289 289 line = line.rstrip()
290 290 if (line.startswith('diff --git')
291 291 or (diffstart and line.startswith('+++ '))):
292 292 diffstart = 2
293 293 break
294 294 diffstart = 0 # reset
295 295 if line.startswith("--- "):
296 296 diffstart = 1
297 297 continue
298 298 elif format == "hgpatch":
299 299 # parse values when importing the result of an hg export
300 300 if line.startswith("# User "):
301 301 user = line[7:]
302 302 elif line.startswith("# Date "):
303 303 date = line[7:]
304 304 elif line.startswith("# Parent "):
305 305 parent = line[9:].lstrip() # handle double trailing space
306 306 elif line.startswith("# Branch "):
307 307 branch = line[9:]
308 308 elif line.startswith("# Node ID "):
309 309 nodeid = line[10:]
310 310 elif not line.startswith("# ") and line:
311 311 message.append(line)
312 312 format = None
313 313 elif line == '# HG changeset patch':
314 314 message = []
315 315 format = "hgpatch"
316 316 elif (format != "tagdone" and (line.startswith("Subject: ") or
317 317 line.startswith("subject: "))):
318 318 subject = line[9:]
319 319 format = "tag"
320 320 elif (format != "tagdone" and (line.startswith("From: ") or
321 321 line.startswith("from: "))):
322 322 user = line[6:]
323 323 format = "tag"
324 324 elif (format != "tagdone" and (line.startswith("Date: ") or
325 325 line.startswith("date: "))):
326 326 date = line[6:]
327 327 format = "tag"
328 328 elif format == "tag" and line == "":
329 329 # when looking for tags (subject: from: etc) they
330 330 # end once you find a blank line in the source
331 331 format = "tagdone"
332 332 elif message or line:
333 333 message.append(line)
334 334 comments.append(line)
335 335
336 336 eatdiff(message)
337 337 eatdiff(comments)
338 338 # Remember the exact starting line of the patch diffs before consuming
339 339 # empty lines, for external use by TortoiseHg and others
340 340 self.diffstartline = len(comments)
341 341 eatempty(message)
342 342 eatempty(comments)
343 343
344 344 # make sure message isn't empty
345 345 if format and format.startswith("tag") and subject:
346 346 message.insert(0, subject)
347 347
348 348 self.message = message
349 349 self.comments = comments
350 350 self.user = user
351 351 self.date = date
352 352 self.parent = parent
353 353 # nodeid and branch are for external use by TortoiseHg and others
354 354 self.nodeid = nodeid
355 355 self.branch = branch
356 356 self.haspatch = diffstart > 1
357 357 self.plainmode = (plainmode or
358 358 '# HG changeset patch' not in self.comments and
359 359 any(c.startswith('Date: ') or
360 360 c.startswith('From: ')
361 361 for c in self.comments))
362 362
363 363 def setuser(self, user):
364 364 try:
365 365 inserthgheader(self.comments, '# User ', user)
366 366 except ValueError:
367 367 if self.plainmode:
368 368 insertplainheader(self.comments, 'From', user)
369 369 else:
370 370 tmp = ['# HG changeset patch', '# User ' + user]
371 371 self.comments = tmp + self.comments
372 372 self.user = user
373 373
374 374 def setdate(self, date):
375 375 try:
376 376 inserthgheader(self.comments, '# Date ', date)
377 377 except ValueError:
378 378 if self.plainmode:
379 379 insertplainheader(self.comments, 'Date', date)
380 380 else:
381 381 tmp = ['# HG changeset patch', '# Date ' + date]
382 382 self.comments = tmp + self.comments
383 383 self.date = date
384 384
385 385 def setparent(self, parent):
386 386 try:
387 387 inserthgheader(self.comments, '# Parent ', parent)
388 388 except ValueError:
389 389 if not self.plainmode:
390 390 tmp = ['# HG changeset patch', '# Parent ' + parent]
391 391 self.comments = tmp + self.comments
392 392 self.parent = parent
393 393
394 394 def setmessage(self, message):
395 395 if self.comments:
396 396 self._delmsg()
397 397 self.message = [message]
398 398 if message:
399 399 if self.plainmode and self.comments and self.comments[-1]:
400 400 self.comments.append('')
401 401 self.comments.append(message)
402 402
403 403 def __bytes__(self):
404 404 s = '\n'.join(self.comments).rstrip()
405 405 if not s:
406 406 return ''
407 407 return s + '\n\n'
408 408
409 409 __str__ = encoding.strmethod(__bytes__)
410 410
411 411 def _delmsg(self):
412 412 '''Remove existing message, keeping the rest of the comments fields.
413 413 If comments contains 'subject: ', message will prepend
414 414 the field and a blank line.'''
415 415 if self.message:
416 416 subj = 'subject: ' + self.message[0].lower()
417 417 for i in xrange(len(self.comments)):
418 418 if subj == self.comments[i].lower():
419 419 del self.comments[i]
420 420 self.message = self.message[2:]
421 421 break
422 422 ci = 0
423 423 for mi in self.message:
424 424 while mi != self.comments[ci]:
425 425 ci += 1
426 426 del self.comments[ci]
427 427
428 428 def newcommit(repo, phase, *args, **kwargs):
429 429 """helper dedicated to ensure a commit respect mq.secret setting
430 430
431 431 It should be used instead of repo.commit inside the mq source for operation
432 432 creating new changeset.
433 433 """
434 434 repo = repo.unfiltered()
435 435 if phase is None:
436 436 if repo.ui.configbool('mq', 'secret'):
437 437 phase = phases.secret
438 438 overrides = {('ui', 'allowemptycommit'): True}
439 439 if phase is not None:
440 440 overrides[('phases', 'new-commit')] = phase
441 441 with repo.ui.configoverride(overrides, 'mq'):
442 442 repo.ui.setconfig('ui', 'allowemptycommit', True)
443 443 return repo.commit(*args, **kwargs)
444 444
445 445 class AbortNoCleanup(error.Abort):
446 446 pass
447 447
448 448 class queue(object):
449 449 def __init__(self, ui, baseui, path, patchdir=None):
450 450 self.basepath = path
451 451 try:
452 452 with open(os.path.join(path, 'patches.queue'), r'rb') as fh:
453 453 cur = fh.read().rstrip()
454 454
455 455 if not cur:
456 456 curpath = os.path.join(path, 'patches')
457 457 else:
458 458 curpath = os.path.join(path, 'patches-' + cur)
459 459 except IOError:
460 460 curpath = os.path.join(path, 'patches')
461 461 self.path = patchdir or curpath
462 462 self.opener = vfsmod.vfs(self.path)
463 463 self.ui = ui
464 464 self.baseui = baseui
465 465 self.applieddirty = False
466 466 self.seriesdirty = False
467 467 self.added = []
468 468 self.seriespath = "series"
469 469 self.statuspath = "status"
470 470 self.guardspath = "guards"
471 471 self.activeguards = None
472 472 self.guardsdirty = False
473 473 # Handle mq.git as a bool with extended values
474 474 gitmode = ui.config('mq', 'git').lower()
475 475 boolmode = stringutil.parsebool(gitmode)
476 476 if boolmode is not None:
477 477 if boolmode:
478 478 gitmode = 'yes'
479 479 else:
480 480 gitmode = 'no'
481 481 self.gitmode = gitmode
482 482 # deprecated config: mq.plain
483 483 self.plainmode = ui.configbool('mq', 'plain')
484 484 self.checkapplied = True
485 485
486 486 @util.propertycache
487 487 def applied(self):
488 488 def parselines(lines):
489 489 for l in lines:
490 490 entry = l.split(':', 1)
491 491 if len(entry) > 1:
492 492 n, name = entry
493 493 yield statusentry(bin(n), name)
494 494 elif l.strip():
495 495 self.ui.warn(_('malformated mq status line: %s\n') % entry)
496 496 # else we ignore empty lines
497 497 try:
498 498 lines = self.opener.read(self.statuspath).splitlines()
499 499 return list(parselines(lines))
500 500 except IOError as e:
501 501 if e.errno == errno.ENOENT:
502 502 return []
503 503 raise
504 504
505 505 @util.propertycache
506 506 def fullseries(self):
507 507 try:
508 508 return self.opener.read(self.seriespath).splitlines()
509 509 except IOError as e:
510 510 if e.errno == errno.ENOENT:
511 511 return []
512 512 raise
513 513
514 514 @util.propertycache
515 515 def series(self):
516 516 self.parseseries()
517 517 return self.series
518 518
519 519 @util.propertycache
520 520 def seriesguards(self):
521 521 self.parseseries()
522 522 return self.seriesguards
523 523
524 524 def invalidate(self):
525 525 for a in 'applied fullseries series seriesguards'.split():
526 526 if a in self.__dict__:
527 527 delattr(self, a)
528 528 self.applieddirty = False
529 529 self.seriesdirty = False
530 530 self.guardsdirty = False
531 531 self.activeguards = None
532 532
533 533 def diffopts(self, opts=None, patchfn=None, plain=False):
534 534 """Return diff options tweaked for this mq use, possibly upgrading to
535 535 git format, and possibly plain and without lossy options."""
536 536 diffopts = patchmod.difffeatureopts(self.ui, opts,
537 537 git=True, whitespace=not plain, formatchanging=not plain)
538 538 if self.gitmode == 'auto':
539 539 diffopts.upgrade = True
540 540 elif self.gitmode == 'keep':
541 541 pass
542 542 elif self.gitmode in ('yes', 'no'):
543 543 diffopts.git = self.gitmode == 'yes'
544 544 else:
545 545 raise error.Abort(_('mq.git option can be auto/keep/yes/no'
546 546 ' got %s') % self.gitmode)
547 547 if patchfn:
548 548 diffopts = self.patchopts(diffopts, patchfn)
549 549 return diffopts
550 550
551 551 def patchopts(self, diffopts, *patches):
552 552 """Return a copy of input diff options with git set to true if
553 553 referenced patch is a git patch and should be preserved as such.
554 554 """
555 555 diffopts = diffopts.copy()
556 556 if not diffopts.git and self.gitmode == 'keep':
557 557 for patchfn in patches:
558 558 patchf = self.opener(patchfn, 'r')
559 559 # if the patch was a git patch, refresh it as a git patch
560 560 diffopts.git = any(line.startswith('diff --git')
561 561 for line in patchf)
562 562 patchf.close()
563 563 return diffopts
564 564
565 565 def join(self, *p):
566 566 return os.path.join(self.path, *p)
567 567
568 568 def findseries(self, patch):
569 569 def matchpatch(l):
570 570 l = l.split('#', 1)[0]
571 571 return l.strip() == patch
572 572 for index, l in enumerate(self.fullseries):
573 573 if matchpatch(l):
574 574 return index
575 575 return None
576 576
577 577 guard_re = re.compile(br'\s?#([-+][^-+# \t\r\n\f][^# \t\r\n\f]*)')
578 578
579 579 def parseseries(self):
580 580 self.series = []
581 581 self.seriesguards = []
582 582 for l in self.fullseries:
583 583 h = l.find('#')
584 584 if h == -1:
585 585 patch = l
586 586 comment = ''
587 587 elif h == 0:
588 588 continue
589 589 else:
590 590 patch = l[:h]
591 591 comment = l[h:]
592 592 patch = patch.strip()
593 593 if patch:
594 594 if patch in self.series:
595 595 raise error.Abort(_('%s appears more than once in %s') %
596 596 (patch, self.join(self.seriespath)))
597 597 self.series.append(patch)
598 598 self.seriesguards.append(self.guard_re.findall(comment))
599 599
600 600 def checkguard(self, guard):
601 601 if not guard:
602 602 return _('guard cannot be an empty string')
603 603 bad_chars = '# \t\r\n\f'
604 604 first = guard[0]
605 605 if first in '-+':
606 606 return (_('guard %r starts with invalid character: %r') %
607 607 (guard, first))
608 608 for c in bad_chars:
609 609 if c in guard:
610 610 return _('invalid character in guard %r: %r') % (guard, c)
611 611
612 612 def setactive(self, guards):
613 613 for guard in guards:
614 614 bad = self.checkguard(guard)
615 615 if bad:
616 616 raise error.Abort(bad)
617 617 guards = sorted(set(guards))
618 618 self.ui.debug('active guards: %s\n' % ' '.join(guards))
619 619 self.activeguards = guards
620 620 self.guardsdirty = True
621 621
622 622 def active(self):
623 623 if self.activeguards is None:
624 624 self.activeguards = []
625 625 try:
626 626 guards = self.opener.read(self.guardspath).split()
627 627 except IOError as err:
628 628 if err.errno != errno.ENOENT:
629 629 raise
630 630 guards = []
631 631 for i, guard in enumerate(guards):
632 632 bad = self.checkguard(guard)
633 633 if bad:
634 634 self.ui.warn('%s:%d: %s\n' %
635 635 (self.join(self.guardspath), i + 1, bad))
636 636 else:
637 637 self.activeguards.append(guard)
638 638 return self.activeguards
639 639
640 640 def setguards(self, idx, guards):
641 641 for g in guards:
642 642 if len(g) < 2:
643 643 raise error.Abort(_('guard %r too short') % g)
644 644 if g[0] not in '-+':
645 645 raise error.Abort(_('guard %r starts with invalid char') % g)
646 646 bad = self.checkguard(g[1:])
647 647 if bad:
648 648 raise error.Abort(bad)
649 649 drop = self.guard_re.sub('', self.fullseries[idx])
650 650 self.fullseries[idx] = drop + ''.join([' #' + g for g in guards])
651 651 self.parseseries()
652 652 self.seriesdirty = True
653 653
654 654 def pushable(self, idx):
655 655 if isinstance(idx, bytes):
656 656 idx = self.series.index(idx)
657 657 patchguards = self.seriesguards[idx]
658 658 if not patchguards:
659 659 return True, None
660 660 guards = self.active()
661 661 exactneg = [g for g in patchguards if g[0] == '-' and g[1:] in guards]
662 662 if exactneg:
663 663 return False, repr(exactneg[0])
664 664 pos = [g for g in patchguards if g[0] == '+']
665 665 exactpos = [g for g in pos if g[1:] in guards]
666 666 if pos:
667 667 if exactpos:
668 668 return True, repr(exactpos[0])
669 669 return False, ' '.join(map(repr, pos))
670 670 return True, ''
671 671
672 672 def explainpushable(self, idx, all_patches=False):
673 673 if all_patches:
674 674 write = self.ui.write
675 675 else:
676 676 write = self.ui.warn
677 677
678 678 if all_patches or self.ui.verbose:
679 679 if isinstance(idx, str):
680 680 idx = self.series.index(idx)
681 681 pushable, why = self.pushable(idx)
682 682 if all_patches and pushable:
683 683 if why is None:
684 684 write(_('allowing %s - no guards in effect\n') %
685 685 self.series[idx])
686 686 else:
687 687 if not why:
688 688 write(_('allowing %s - no matching negative guards\n') %
689 689 self.series[idx])
690 690 else:
691 691 write(_('allowing %s - guarded by %s\n') %
692 692 (self.series[idx], why))
693 693 if not pushable:
694 694 if why:
695 695 write(_('skipping %s - guarded by %s\n') %
696 696 (self.series[idx], why))
697 697 else:
698 698 write(_('skipping %s - no matching guards\n') %
699 699 self.series[idx])
700 700
701 701 def savedirty(self):
702 702 def writelist(items, path):
703 703 fp = self.opener(path, 'wb')
704 704 for i in items:
705 705 fp.write("%s\n" % i)
706 706 fp.close()
707 707 if self.applieddirty:
708 708 writelist(map(bytes, self.applied), self.statuspath)
709 709 self.applieddirty = False
710 710 if self.seriesdirty:
711 711 writelist(self.fullseries, self.seriespath)
712 712 self.seriesdirty = False
713 713 if self.guardsdirty:
714 714 writelist(self.activeguards, self.guardspath)
715 715 self.guardsdirty = False
716 716 if self.added:
717 717 qrepo = self.qrepo()
718 718 if qrepo:
719 719 qrepo[None].add(f for f in self.added if f not in qrepo[None])
720 720 self.added = []
721 721
722 722 def removeundo(self, repo):
723 723 undo = repo.sjoin('undo')
724 724 if not os.path.exists(undo):
725 725 return
726 726 try:
727 727 os.unlink(undo)
728 728 except OSError as inst:
729 729 self.ui.warn(_('error removing undo: %s\n') %
730 730 stringutil.forcebytestr(inst))
731 731
732 732 def backup(self, repo, files, copy=False):
733 733 # backup local changes in --force case
734 734 for f in sorted(files):
735 735 absf = repo.wjoin(f)
736 736 if os.path.lexists(absf):
737 737 self.ui.note(_('saving current version of %s as %s\n') %
738 738 (f, scmutil.origpath(self.ui, repo, f)))
739 739
740 740 absorig = scmutil.origpath(self.ui, repo, absf)
741 741 if copy:
742 742 util.copyfile(absf, absorig)
743 743 else:
744 744 util.rename(absf, absorig)
745 745
746 746 def printdiff(self, repo, diffopts, node1, node2=None, files=None,
747 747 fp=None, changes=None, opts=None):
748 748 if opts is None:
749 749 opts = {}
750 750 stat = opts.get('stat')
751 751 m = scmutil.match(repo[node1], files, opts)
752 752 logcmdutil.diffordiffstat(self.ui, repo, diffopts, node1, node2, m,
753 753 changes, stat, fp)
754 754
755 755 def mergeone(self, repo, mergeq, head, patch, rev, diffopts):
756 756 # first try just applying the patch
757 757 (err, n) = self.apply(repo, [patch], update_status=False,
758 758 strict=True, merge=rev)
759 759
760 760 if err == 0:
761 761 return (err, n)
762 762
763 763 if n is None:
764 764 raise error.Abort(_("apply failed for patch %s") % patch)
765 765
766 766 self.ui.warn(_("patch didn't work out, merging %s\n") % patch)
767 767
768 768 # apply failed, strip away that rev and merge.
769 769 hg.clean(repo, head)
770 770 strip(self.ui, repo, [n], update=False, backup=False)
771 771
772 772 ctx = repo[rev]
773 773 ret = hg.merge(repo, rev)
774 774 if ret:
775 775 raise error.Abort(_("update returned %d") % ret)
776 776 n = newcommit(repo, None, ctx.description(), ctx.user(), force=True)
777 777 if n is None:
778 778 raise error.Abort(_("repo commit failed"))
779 779 try:
780 780 ph = patchheader(mergeq.join(patch), self.plainmode)
781 781 except Exception:
782 782 raise error.Abort(_("unable to read %s") % patch)
783 783
784 784 diffopts = self.patchopts(diffopts, patch)
785 785 patchf = self.opener(patch, "w")
786 786 comments = bytes(ph)
787 787 if comments:
788 788 patchf.write(comments)
789 789 self.printdiff(repo, diffopts, head, n, fp=patchf)
790 790 patchf.close()
791 791 self.removeundo(repo)
792 792 return (0, n)
793 793
794 794 def qparents(self, repo, rev=None):
795 795 """return the mq handled parent or p1
796 796
797 797 In some case where mq get himself in being the parent of a merge the
798 798 appropriate parent may be p2.
799 799 (eg: an in progress merge started with mq disabled)
800 800
801 801 If no parent are managed by mq, p1 is returned.
802 802 """
803 803 if rev is None:
804 804 (p1, p2) = repo.dirstate.parents()
805 805 if p2 == nullid:
806 806 return p1
807 807 if not self.applied:
808 808 return None
809 809 return self.applied[-1].node
810 810 p1, p2 = repo.changelog.parents(rev)
811 811 if p2 != nullid and p2 in [x.node for x in self.applied]:
812 812 return p2
813 813 return p1
814 814
815 815 def mergepatch(self, repo, mergeq, series, diffopts):
816 816 if not self.applied:
817 817 # each of the patches merged in will have two parents. This
818 818 # can confuse the qrefresh, qdiff, and strip code because it
819 819 # needs to know which parent is actually in the patch queue.
820 820 # so, we insert a merge marker with only one parent. This way
821 821 # the first patch in the queue is never a merge patch
822 822 #
823 823 pname = ".hg.patches.merge.marker"
824 824 n = newcommit(repo, None, '[mq]: merge marker', force=True)
825 825 self.removeundo(repo)
826 826 self.applied.append(statusentry(n, pname))
827 827 self.applieddirty = True
828 828
829 829 head = self.qparents(repo)
830 830
831 831 for patch in series:
832 832 patch = mergeq.lookup(patch, strict=True)
833 833 if not patch:
834 834 self.ui.warn(_("patch %s does not exist\n") % patch)
835 835 return (1, None)
836 836 pushable, reason = self.pushable(patch)
837 837 if not pushable:
838 838 self.explainpushable(patch, all_patches=True)
839 839 continue
840 840 info = mergeq.isapplied(patch)
841 841 if not info:
842 842 self.ui.warn(_("patch %s is not applied\n") % patch)
843 843 return (1, None)
844 844 rev = info[1]
845 845 err, head = self.mergeone(repo, mergeq, head, patch, rev, diffopts)
846 846 if head:
847 847 self.applied.append(statusentry(head, patch))
848 848 self.applieddirty = True
849 849 if err:
850 850 return (err, head)
851 851 self.savedirty()
852 852 return (0, head)
853 853
854 854 def patch(self, repo, patchfile):
855 855 '''Apply patchfile to the working directory.
856 856 patchfile: name of patch file'''
857 857 files = set()
858 858 try:
859 859 fuzz = patchmod.patch(self.ui, repo, patchfile, strip=1,
860 860 files=files, eolmode=None)
861 861 return (True, list(files), fuzz)
862 862 except Exception as inst:
863 863 self.ui.note(stringutil.forcebytestr(inst) + '\n')
864 864 if not self.ui.verbose:
865 865 self.ui.warn(_("patch failed, unable to continue (try -v)\n"))
866 866 self.ui.traceback()
867 867 return (False, list(files), False)
868 868
869 869 def apply(self, repo, series, list=False, update_status=True,
870 870 strict=False, patchdir=None, merge=None, all_files=None,
871 871 tobackup=None, keepchanges=False):
872 872 wlock = lock = tr = None
873 873 try:
874 874 wlock = repo.wlock()
875 875 lock = repo.lock()
876 876 tr = repo.transaction("qpush")
877 877 try:
878 878 ret = self._apply(repo, series, list, update_status,
879 879 strict, patchdir, merge, all_files=all_files,
880 880 tobackup=tobackup, keepchanges=keepchanges)
881 881 tr.close()
882 882 self.savedirty()
883 883 return ret
884 884 except AbortNoCleanup:
885 885 tr.close()
886 886 self.savedirty()
887 887 raise
888 888 except: # re-raises
889 889 try:
890 890 tr.abort()
891 891 finally:
892 892 self.invalidate()
893 893 raise
894 894 finally:
895 895 release(tr, lock, wlock)
896 896 self.removeundo(repo)
897 897
898 898 def _apply(self, repo, series, list=False, update_status=True,
899 899 strict=False, patchdir=None, merge=None, all_files=None,
900 900 tobackup=None, keepchanges=False):
901 901 """returns (error, hash)
902 902
903 903 error = 1 for unable to read, 2 for patch failed, 3 for patch
904 904 fuzz. tobackup is None or a set of files to backup before they
905 905 are modified by a patch.
906 906 """
907 907 # TODO unify with commands.py
908 908 if not patchdir:
909 909 patchdir = self.path
910 910 err = 0
911 911 n = None
912 912 for patchname in series:
913 913 pushable, reason = self.pushable(patchname)
914 914 if not pushable:
915 915 self.explainpushable(patchname, all_patches=True)
916 916 continue
917 917 self.ui.status(_("applying %s\n") % patchname)
918 918 pf = os.path.join(patchdir, patchname)
919 919
920 920 try:
921 921 ph = patchheader(self.join(patchname), self.plainmode)
922 922 except IOError:
923 923 self.ui.warn(_("unable to read %s\n") % patchname)
924 924 err = 1
925 925 break
926 926
927 927 message = ph.message
928 928 if not message:
929 929 # The commit message should not be translated
930 930 message = "imported patch %s\n" % patchname
931 931 else:
932 932 if list:
933 933 # The commit message should not be translated
934 934 message.append("\nimported patch %s" % patchname)
935 935 message = '\n'.join(message)
936 936
937 937 if ph.haspatch:
938 938 if tobackup:
939 939 touched = patchmod.changedfiles(self.ui, repo, pf)
940 940 touched = set(touched) & tobackup
941 941 if touched and keepchanges:
942 942 raise AbortNoCleanup(
943 943 _("conflicting local changes found"),
944 944 hint=_("did you forget to qrefresh?"))
945 945 self.backup(repo, touched, copy=True)
946 946 tobackup = tobackup - touched
947 947 (patcherr, files, fuzz) = self.patch(repo, pf)
948 948 if all_files is not None:
949 949 all_files.update(files)
950 950 patcherr = not patcherr
951 951 else:
952 952 self.ui.warn(_("patch %s is empty\n") % patchname)
953 953 patcherr, files, fuzz = 0, [], 0
954 954
955 955 if merge and files:
956 956 # Mark as removed/merged and update dirstate parent info
957 957 removed = []
958 958 merged = []
959 959 for f in files:
960 960 if os.path.lexists(repo.wjoin(f)):
961 961 merged.append(f)
962 962 else:
963 963 removed.append(f)
964 964 with repo.dirstate.parentchange():
965 965 for f in removed:
966 966 repo.dirstate.remove(f)
967 967 for f in merged:
968 968 repo.dirstate.merge(f)
969 969 p1, p2 = repo.dirstate.parents()
970 970 repo.setparents(p1, merge)
971 971
972 972 if all_files and '.hgsubstate' in all_files:
973 973 wctx = repo[None]
974 974 pctx = repo['.']
975 975 overwrite = False
976 976 mergedsubstate = subrepoutil.submerge(repo, pctx, wctx, wctx,
977 977 overwrite)
978 978 files += mergedsubstate.keys()
979 979
980 980 match = scmutil.matchfiles(repo, files or [])
981 981 oldtip = repo['tip']
982 982 n = newcommit(repo, None, message, ph.user, ph.date, match=match,
983 983 force=True)
984 984 if repo['tip'] == oldtip:
985 985 raise error.Abort(_("qpush exactly duplicates child changeset"))
986 986 if n is None:
987 987 raise error.Abort(_("repository commit failed"))
988 988
989 989 if update_status:
990 990 self.applied.append(statusentry(n, patchname))
991 991
992 992 if patcherr:
993 993 self.ui.warn(_("patch failed, rejects left in working "
994 994 "directory\n"))
995 995 err = 2
996 996 break
997 997
998 998 if fuzz and strict:
999 999 self.ui.warn(_("fuzz found when applying patch, stopping\n"))
1000 1000 err = 3
1001 1001 break
1002 1002 return (err, n)
1003 1003
1004 1004 def _cleanup(self, patches, numrevs, keep=False):
1005 1005 if not keep:
1006 1006 r = self.qrepo()
1007 1007 if r:
1008 1008 r[None].forget(patches)
1009 1009 for p in patches:
1010 1010 try:
1011 1011 os.unlink(self.join(p))
1012 1012 except OSError as inst:
1013 1013 if inst.errno != errno.ENOENT:
1014 1014 raise
1015 1015
1016 1016 qfinished = []
1017 1017 if numrevs:
1018 1018 qfinished = self.applied[:numrevs]
1019 1019 del self.applied[:numrevs]
1020 1020 self.applieddirty = True
1021 1021
1022 1022 unknown = []
1023 1023
1024 1024 for (i, p) in sorted([(self.findseries(p), p) for p in patches],
1025 1025 reverse=True):
1026 1026 if i is not None:
1027 1027 del self.fullseries[i]
1028 1028 else:
1029 1029 unknown.append(p)
1030 1030
1031 1031 if unknown:
1032 1032 if numrevs:
1033 1033 rev = dict((entry.name, entry.node) for entry in qfinished)
1034 1034 for p in unknown:
1035 1035 msg = _('revision %s refers to unknown patches: %s\n')
1036 1036 self.ui.warn(msg % (short(rev[p]), p))
1037 1037 else:
1038 1038 msg = _('unknown patches: %s\n')
1039 1039 raise error.Abort(''.join(msg % p for p in unknown))
1040 1040
1041 1041 self.parseseries()
1042 1042 self.seriesdirty = True
1043 1043 return [entry.node for entry in qfinished]
1044 1044
1045 1045 def _revpatches(self, repo, revs):
1046 1046 firstrev = repo[self.applied[0].node].rev()
1047 1047 patches = []
1048 1048 for i, rev in enumerate(revs):
1049 1049
1050 1050 if rev < firstrev:
1051 1051 raise error.Abort(_('revision %d is not managed') % rev)
1052 1052
1053 1053 ctx = repo[rev]
1054 1054 base = self.applied[i].node
1055 1055 if ctx.node() != base:
1056 1056 msg = _('cannot delete revision %d above applied patches')
1057 1057 raise error.Abort(msg % rev)
1058 1058
1059 1059 patch = self.applied[i].name
1060 1060 for fmt in ('[mq]: %s', 'imported patch %s'):
1061 1061 if ctx.description() == fmt % patch:
1062 1062 msg = _('patch %s finalized without changeset message\n')
1063 1063 repo.ui.status(msg % patch)
1064 1064 break
1065 1065
1066 1066 patches.append(patch)
1067 1067 return patches
1068 1068
1069 1069 def finish(self, repo, revs):
1070 1070 # Manually trigger phase computation to ensure phasedefaults is
1071 1071 # executed before we remove the patches.
1072 1072 repo._phasecache
1073 1073 patches = self._revpatches(repo, sorted(revs))
1074 1074 qfinished = self._cleanup(patches, len(patches))
1075 1075 if qfinished and repo.ui.configbool('mq', 'secret'):
1076 1076 # only use this logic when the secret option is added
1077 1077 oldqbase = repo[qfinished[0]]
1078 1078 tphase = phases.newcommitphase(repo.ui)
1079 1079 if oldqbase.phase() > tphase and oldqbase.p1().phase() <= tphase:
1080 1080 with repo.transaction('qfinish') as tr:
1081 1081 phases.advanceboundary(repo, tr, tphase, qfinished)
1082 1082
1083 1083 def delete(self, repo, patches, opts):
1084 1084 if not patches and not opts.get('rev'):
1085 1085 raise error.Abort(_('qdelete requires at least one revision or '
1086 1086 'patch name'))
1087 1087
1088 1088 realpatches = []
1089 1089 for patch in patches:
1090 1090 patch = self.lookup(patch, strict=True)
1091 1091 info = self.isapplied(patch)
1092 1092 if info:
1093 1093 raise error.Abort(_("cannot delete applied patch %s") % patch)
1094 1094 if patch not in self.series:
1095 1095 raise error.Abort(_("patch %s not in series file") % patch)
1096 1096 if patch not in realpatches:
1097 1097 realpatches.append(patch)
1098 1098
1099 1099 numrevs = 0
1100 1100 if opts.get('rev'):
1101 1101 if not self.applied:
1102 1102 raise error.Abort(_('no patches applied'))
1103 1103 revs = scmutil.revrange(repo, opts.get('rev'))
1104 1104 revs.sort()
1105 1105 revpatches = self._revpatches(repo, revs)
1106 1106 realpatches += revpatches
1107 1107 numrevs = len(revpatches)
1108 1108
1109 1109 self._cleanup(realpatches, numrevs, opts.get('keep'))
1110 1110
1111 1111 def checktoppatch(self, repo):
1112 1112 '''check that working directory is at qtip'''
1113 1113 if self.applied:
1114 1114 top = self.applied[-1].node
1115 1115 patch = self.applied[-1].name
1116 1116 if repo.dirstate.p1() != top:
1117 1117 raise error.Abort(_("working directory revision is not qtip"))
1118 1118 return top, patch
1119 1119 return None, None
1120 1120
1121 1121 def putsubstate2changes(self, substatestate, changes):
1122 1122 for files in changes[:3]:
1123 1123 if '.hgsubstate' in files:
1124 1124 return # already listed up
1125 1125 # not yet listed up
1126 1126 if substatestate in 'a?':
1127 1127 changes[1].append('.hgsubstate')
1128 1128 elif substatestate in 'r':
1129 1129 changes[2].append('.hgsubstate')
1130 1130 else: # modified
1131 1131 changes[0].append('.hgsubstate')
1132 1132
1133 1133 def checklocalchanges(self, repo, force=False, refresh=True):
1134 1134 excsuffix = ''
1135 1135 if refresh:
1136 1136 excsuffix = ', qrefresh first'
1137 1137 # plain versions for i18n tool to detect them
1138 1138 _("local changes found, qrefresh first")
1139 1139 _("local changed subrepos found, qrefresh first")
1140 1140 return checklocalchanges(repo, force, excsuffix)
1141 1141
1142 1142 _reserved = ('series', 'status', 'guards', '.', '..')
1143 1143 def checkreservedname(self, name):
1144 1144 if name in self._reserved:
1145 1145 raise error.Abort(_('"%s" cannot be used as the name of a patch')
1146 1146 % name)
1147 1147 if name != name.strip():
1148 1148 # whitespace is stripped by parseseries()
1149 1149 raise error.Abort(_('patch name cannot begin or end with '
1150 1150 'whitespace'))
1151 1151 for prefix in ('.hg', '.mq'):
1152 1152 if name.startswith(prefix):
1153 1153 raise error.Abort(_('patch name cannot begin with "%s"')
1154 1154 % prefix)
1155 1155 for c in ('#', ':', '\r', '\n'):
1156 1156 if c in name:
1157 1157 raise error.Abort(_('%r cannot be used in the name of a patch')
1158 1158 % c)
1159 1159
1160 1160 def checkpatchname(self, name, force=False):
1161 1161 self.checkreservedname(name)
1162 1162 if not force and os.path.exists(self.join(name)):
1163 1163 if os.path.isdir(self.join(name)):
1164 1164 raise error.Abort(_('"%s" already exists as a directory')
1165 1165 % name)
1166 1166 else:
1167 1167 raise error.Abort(_('patch "%s" already exists') % name)
1168 1168
1169 1169 def makepatchname(self, title, fallbackname):
1170 1170 """Return a suitable filename for title, adding a suffix to make
1171 1171 it unique in the existing list"""
1172 1172 namebase = re.sub('[\s\W_]+', '_', title.lower()).strip('_')
1173 1173 namebase = namebase[:75] # avoid too long name (issue5117)
1174 1174 if namebase:
1175 1175 try:
1176 1176 self.checkreservedname(namebase)
1177 1177 except error.Abort:
1178 1178 namebase = fallbackname
1179 1179 else:
1180 1180 namebase = fallbackname
1181 1181 name = namebase
1182 1182 i = 0
1183 1183 while True:
1184 1184 if name not in self.fullseries:
1185 1185 try:
1186 1186 self.checkpatchname(name)
1187 1187 break
1188 1188 except error.Abort:
1189 1189 pass
1190 1190 i += 1
1191 1191 name = '%s__%d' % (namebase, i)
1192 1192 return name
1193 1193
1194 1194 def checkkeepchanges(self, keepchanges, force):
1195 1195 if force and keepchanges:
1196 1196 raise error.Abort(_('cannot use both --force and --keep-changes'))
1197 1197
1198 1198 def new(self, repo, patchfn, *pats, **opts):
1199 1199 """options:
1200 1200 msg: a string or a no-argument function returning a string
1201 1201 """
1202 1202 opts = pycompat.byteskwargs(opts)
1203 1203 msg = opts.get('msg')
1204 1204 edit = opts.get('edit')
1205 1205 editform = opts.get('editform', 'mq.qnew')
1206 1206 user = opts.get('user')
1207 1207 date = opts.get('date')
1208 1208 if date:
1209 1209 date = dateutil.parsedate(date)
1210 1210 diffopts = self.diffopts({'git': opts.get('git')}, plain=True)
1211 1211 if opts.get('checkname', True):
1212 1212 self.checkpatchname(patchfn)
1213 1213 inclsubs = checksubstate(repo)
1214 1214 if inclsubs:
1215 1215 substatestate = repo.dirstate['.hgsubstate']
1216 1216 if opts.get('include') or opts.get('exclude') or pats:
1217 1217 # detect missing files in pats
1218 1218 def badfn(f, msg):
1219 1219 if f != '.hgsubstate': # .hgsubstate is auto-created
1220 1220 raise error.Abort('%s: %s' % (f, msg))
1221 1221 match = scmutil.match(repo[None], pats, opts, badfn=badfn)
1222 1222 changes = repo.status(match=match)
1223 1223 else:
1224 1224 changes = self.checklocalchanges(repo, force=True)
1225 1225 commitfiles = list(inclsubs)
1226 1226 for files in changes[:3]:
1227 1227 commitfiles.extend(files)
1228 1228 match = scmutil.matchfiles(repo, commitfiles)
1229 1229 if len(repo[None].parents()) > 1:
1230 1230 raise error.Abort(_('cannot manage merge changesets'))
1231 1231 self.checktoppatch(repo)
1232 1232 insert = self.fullseriesend()
1233 1233 with repo.wlock():
1234 1234 try:
1235 1235 # if patch file write fails, abort early
1236 1236 p = self.opener(patchfn, "w")
1237 1237 except IOError as e:
1238 1238 raise error.Abort(_('cannot write patch "%s": %s')
1239 1239 % (patchfn, encoding.strtolocal(e.strerror)))
1240 1240 try:
1241 1241 defaultmsg = "[mq]: %s" % patchfn
1242 1242 editor = cmdutil.getcommiteditor(editform=editform)
1243 1243 if edit:
1244 1244 def finishdesc(desc):
1245 1245 if desc.rstrip():
1246 1246 return desc
1247 1247 else:
1248 1248 return defaultmsg
1249 1249 # i18n: this message is shown in editor with "HG: " prefix
1250 1250 extramsg = _('Leave message empty to use default message.')
1251 1251 editor = cmdutil.getcommiteditor(finishdesc=finishdesc,
1252 1252 extramsg=extramsg,
1253 1253 editform=editform)
1254 1254 commitmsg = msg
1255 1255 else:
1256 1256 commitmsg = msg or defaultmsg
1257 1257
1258 1258 n = newcommit(repo, None, commitmsg, user, date, match=match,
1259 1259 force=True, editor=editor)
1260 1260 if n is None:
1261 1261 raise error.Abort(_("repo commit failed"))
1262 1262 try:
1263 1263 self.fullseries[insert:insert] = [patchfn]
1264 1264 self.applied.append(statusentry(n, patchfn))
1265 1265 self.parseseries()
1266 1266 self.seriesdirty = True
1267 1267 self.applieddirty = True
1268 1268 nctx = repo[n]
1269 1269 ph = patchheader(self.join(patchfn), self.plainmode)
1270 1270 if user:
1271 1271 ph.setuser(user)
1272 1272 if date:
1273 1273 ph.setdate('%d %d' % date)
1274 1274 ph.setparent(hex(nctx.p1().node()))
1275 1275 msg = nctx.description().strip()
1276 1276 if msg == defaultmsg.strip():
1277 1277 msg = ''
1278 1278 ph.setmessage(msg)
1279 1279 p.write(bytes(ph))
1280 1280 if commitfiles:
1281 1281 parent = self.qparents(repo, n)
1282 1282 if inclsubs:
1283 1283 self.putsubstate2changes(substatestate, changes)
1284 1284 chunks = patchmod.diff(repo, node1=parent, node2=n,
1285 1285 changes=changes, opts=diffopts)
1286 1286 for chunk in chunks:
1287 1287 p.write(chunk)
1288 1288 p.close()
1289 1289 r = self.qrepo()
1290 1290 if r:
1291 1291 r[None].add([patchfn])
1292 1292 except: # re-raises
1293 1293 repo.rollback()
1294 1294 raise
1295 1295 except Exception:
1296 1296 patchpath = self.join(patchfn)
1297 1297 try:
1298 1298 os.unlink(patchpath)
1299 1299 except OSError:
1300 1300 self.ui.warn(_('error unlinking %s\n') % patchpath)
1301 1301 raise
1302 1302 self.removeundo(repo)
1303 1303
1304 1304 def isapplied(self, patch):
1305 1305 """returns (index, rev, patch)"""
1306 1306 for i, a in enumerate(self.applied):
1307 1307 if a.name == patch:
1308 1308 return (i, a.node, a.name)
1309 1309 return None
1310 1310
1311 1311 # if the exact patch name does not exist, we try a few
1312 1312 # variations. If strict is passed, we try only #1
1313 1313 #
1314 1314 # 1) a number (as string) to indicate an offset in the series file
1315 1315 # 2) a unique substring of the patch name was given
1316 1316 # 3) patchname[-+]num to indicate an offset in the series file
1317 1317 def lookup(self, patch, strict=False):
1318 1318 def partialname(s):
1319 1319 if s in self.series:
1320 1320 return s
1321 1321 matches = [x for x in self.series if s in x]
1322 1322 if len(matches) > 1:
1323 1323 self.ui.warn(_('patch name "%s" is ambiguous:\n') % s)
1324 1324 for m in matches:
1325 1325 self.ui.warn(' %s\n' % m)
1326 1326 return None
1327 1327 if matches:
1328 1328 return matches[0]
1329 1329 if self.series and self.applied:
1330 1330 if s == 'qtip':
1331 1331 return self.series[self.seriesend(True) - 1]
1332 1332 if s == 'qbase':
1333 1333 return self.series[0]
1334 1334 return None
1335 1335
1336 1336 if patch in self.series:
1337 1337 return patch
1338 1338
1339 1339 if not os.path.isfile(self.join(patch)):
1340 1340 try:
1341 1341 sno = int(patch)
1342 1342 except (ValueError, OverflowError):
1343 1343 pass
1344 1344 else:
1345 1345 if -len(self.series) <= sno < len(self.series):
1346 1346 return self.series[sno]
1347 1347
1348 1348 if not strict:
1349 1349 res = partialname(patch)
1350 1350 if res:
1351 1351 return res
1352 1352 minus = patch.rfind('-')
1353 1353 if minus >= 0:
1354 1354 res = partialname(patch[:minus])
1355 1355 if res:
1356 1356 i = self.series.index(res)
1357 1357 try:
1358 1358 off = int(patch[minus + 1:] or 1)
1359 1359 except (ValueError, OverflowError):
1360 1360 pass
1361 1361 else:
1362 1362 if i - off >= 0:
1363 1363 return self.series[i - off]
1364 1364 plus = patch.rfind('+')
1365 1365 if plus >= 0:
1366 1366 res = partialname(patch[:plus])
1367 1367 if res:
1368 1368 i = self.series.index(res)
1369 1369 try:
1370 1370 off = int(patch[plus + 1:] or 1)
1371 1371 except (ValueError, OverflowError):
1372 1372 pass
1373 1373 else:
1374 1374 if i + off < len(self.series):
1375 1375 return self.series[i + off]
1376 1376 raise error.Abort(_("patch %s not in series") % patch)
1377 1377
1378 1378 def push(self, repo, patch=None, force=False, list=False, mergeq=None,
1379 1379 all=False, move=False, exact=False, nobackup=False,
1380 1380 keepchanges=False):
1381 1381 self.checkkeepchanges(keepchanges, force)
1382 1382 diffopts = self.diffopts()
1383 1383 with repo.wlock():
1384 1384 heads = []
1385 1385 for hs in repo.branchmap().itervalues():
1386 1386 heads.extend(hs)
1387 1387 if not heads:
1388 1388 heads = [nullid]
1389 1389 if repo.dirstate.p1() not in heads and not exact:
1390 1390 self.ui.status(_("(working directory not at a head)\n"))
1391 1391
1392 1392 if not self.series:
1393 1393 self.ui.warn(_('no patches in series\n'))
1394 1394 return 0
1395 1395
1396 1396 # Suppose our series file is: A B C and the current 'top'
1397 1397 # patch is B. qpush C should be performed (moving forward)
1398 1398 # qpush B is a NOP (no change) qpush A is an error (can't
1399 1399 # go backwards with qpush)
1400 1400 if patch:
1401 1401 patch = self.lookup(patch)
1402 1402 info = self.isapplied(patch)
1403 1403 if info and info[0] >= len(self.applied) - 1:
1404 1404 self.ui.warn(
1405 1405 _('qpush: %s is already at the top\n') % patch)
1406 1406 return 0
1407 1407
1408 1408 pushable, reason = self.pushable(patch)
1409 1409 if pushable:
1410 1410 if self.series.index(patch) < self.seriesend():
1411 1411 raise error.Abort(
1412 1412 _("cannot push to a previous patch: %s") % patch)
1413 1413 else:
1414 1414 if reason:
1415 1415 reason = _('guarded by %s') % reason
1416 1416 else:
1417 1417 reason = _('no matching guards')
1418 1418 self.ui.warn(_("cannot push '%s' - %s\n") % (patch, reason))
1419 1419 return 1
1420 1420 elif all:
1421 1421 patch = self.series[-1]
1422 1422 if self.isapplied(patch):
1423 1423 self.ui.warn(_('all patches are currently applied\n'))
1424 1424 return 0
1425 1425
1426 1426 # Following the above example, starting at 'top' of B:
1427 1427 # qpush should be performed (pushes C), but a subsequent
1428 1428 # qpush without an argument is an error (nothing to
1429 1429 # apply). This allows a loop of "...while hg qpush..." to
1430 1430 # work as it detects an error when done
1431 1431 start = self.seriesend()
1432 1432 if start == len(self.series):
1433 1433 self.ui.warn(_('patch series already fully applied\n'))
1434 1434 return 1
1435 1435 if not force and not keepchanges:
1436 1436 self.checklocalchanges(repo, refresh=self.applied)
1437 1437
1438 1438 if exact:
1439 1439 if keepchanges:
1440 1440 raise error.Abort(
1441 1441 _("cannot use --exact and --keep-changes together"))
1442 1442 if move:
1443 1443 raise error.Abort(_('cannot use --exact and --move '
1444 1444 'together'))
1445 1445 if self.applied:
1446 1446 raise error.Abort(_('cannot push --exact with applied '
1447 1447 'patches'))
1448 1448 root = self.series[start]
1449 1449 target = patchheader(self.join(root), self.plainmode).parent
1450 1450 if not target:
1451 1451 raise error.Abort(
1452 1452 _("%s does not have a parent recorded") % root)
1453 1453 if not repo[target] == repo['.']:
1454 1454 hg.update(repo, target)
1455 1455
1456 1456 if move:
1457 1457 if not patch:
1458 1458 raise error.Abort(_("please specify the patch to move"))
1459 1459 for fullstart, rpn in enumerate(self.fullseries):
1460 1460 # strip markers for patch guards
1461 1461 if self.guard_re.split(rpn, 1)[0] == self.series[start]:
1462 1462 break
1463 1463 for i, rpn in enumerate(self.fullseries[fullstart:]):
1464 1464 # strip markers for patch guards
1465 1465 if self.guard_re.split(rpn, 1)[0] == patch:
1466 1466 break
1467 1467 index = fullstart + i
1468 1468 assert index < len(self.fullseries)
1469 1469 fullpatch = self.fullseries[index]
1470 1470 del self.fullseries[index]
1471 1471 self.fullseries.insert(fullstart, fullpatch)
1472 1472 self.parseseries()
1473 1473 self.seriesdirty = True
1474 1474
1475 1475 self.applieddirty = True
1476 1476 if start > 0:
1477 1477 self.checktoppatch(repo)
1478 1478 if not patch:
1479 1479 patch = self.series[start]
1480 1480 end = start + 1
1481 1481 else:
1482 1482 end = self.series.index(patch, start) + 1
1483 1483
1484 1484 tobackup = set()
1485 1485 if (not nobackup and force) or keepchanges:
1486 1486 status = self.checklocalchanges(repo, force=True)
1487 1487 if keepchanges:
1488 1488 tobackup.update(status.modified + status.added +
1489 1489 status.removed + status.deleted)
1490 1490 else:
1491 1491 tobackup.update(status.modified + status.added)
1492 1492
1493 1493 s = self.series[start:end]
1494 1494 all_files = set()
1495 1495 try:
1496 1496 if mergeq:
1497 1497 ret = self.mergepatch(repo, mergeq, s, diffopts)
1498 1498 else:
1499 1499 ret = self.apply(repo, s, list, all_files=all_files,
1500 1500 tobackup=tobackup, keepchanges=keepchanges)
1501 1501 except AbortNoCleanup:
1502 1502 raise
1503 1503 except: # re-raises
1504 1504 self.ui.warn(_('cleaning up working directory...\n'))
1505 1505 cmdutil.revert(self.ui, repo, repo['.'],
1506 1506 repo.dirstate.parents(), no_backup=True)
1507 1507 # only remove unknown files that we know we touched or
1508 1508 # created while patching
1509 1509 for f in all_files:
1510 1510 if f not in repo.dirstate:
1511 1511 repo.wvfs.unlinkpath(f, ignoremissing=True)
1512 1512 self.ui.warn(_('done\n'))
1513 1513 raise
1514 1514
1515 1515 if not self.applied:
1516 1516 return ret[0]
1517 1517 top = self.applied[-1].name
1518 1518 if ret[0] and ret[0] > 1:
1519 1519 msg = _("errors during apply, please fix and qrefresh %s\n")
1520 1520 self.ui.write(msg % top)
1521 1521 else:
1522 1522 self.ui.write(_("now at: %s\n") % top)
1523 1523 return ret[0]
1524 1524
1525 1525 def pop(self, repo, patch=None, force=False, update=True, all=False,
1526 1526 nobackup=False, keepchanges=False):
1527 1527 self.checkkeepchanges(keepchanges, force)
1528 1528 with repo.wlock():
1529 1529 if patch:
1530 1530 # index, rev, patch
1531 1531 info = self.isapplied(patch)
1532 1532 if not info:
1533 1533 patch = self.lookup(patch)
1534 1534 info = self.isapplied(patch)
1535 1535 if not info:
1536 1536 raise error.Abort(_("patch %s is not applied") % patch)
1537 1537
1538 1538 if not self.applied:
1539 1539 # Allow qpop -a to work repeatedly,
1540 1540 # but not qpop without an argument
1541 1541 self.ui.warn(_("no patches applied\n"))
1542 1542 return not all
1543 1543
1544 1544 if all:
1545 1545 start = 0
1546 1546 elif patch:
1547 1547 start = info[0] + 1
1548 1548 else:
1549 1549 start = len(self.applied) - 1
1550 1550
1551 1551 if start >= len(self.applied):
1552 1552 self.ui.warn(_("qpop: %s is already at the top\n") % patch)
1553 1553 return
1554 1554
1555 1555 if not update:
1556 1556 parents = repo.dirstate.parents()
1557 1557 rr = [x.node for x in self.applied]
1558 1558 for p in parents:
1559 1559 if p in rr:
1560 1560 self.ui.warn(_("qpop: forcing dirstate update\n"))
1561 1561 update = True
1562 1562 else:
1563 1563 parents = [p.node() for p in repo[None].parents()]
1564 1564 update = any(entry.node in parents
1565 1565 for entry in self.applied[start:])
1566 1566
1567 1567 tobackup = set()
1568 1568 if update:
1569 1569 s = self.checklocalchanges(repo, force=force or keepchanges)
1570 1570 if force:
1571 1571 if not nobackup:
1572 1572 tobackup.update(s.modified + s.added)
1573 1573 elif keepchanges:
1574 1574 tobackup.update(s.modified + s.added +
1575 1575 s.removed + s.deleted)
1576 1576
1577 1577 self.applieddirty = True
1578 1578 end = len(self.applied)
1579 1579 rev = self.applied[start].node
1580 1580
1581 1581 try:
1582 1582 heads = repo.changelog.heads(rev)
1583 1583 except error.LookupError:
1584 1584 node = short(rev)
1585 1585 raise error.Abort(_('trying to pop unknown node %s') % node)
1586 1586
1587 1587 if heads != [self.applied[-1].node]:
1588 1588 raise error.Abort(_("popping would remove a revision not "
1589 1589 "managed by this patch queue"))
1590 1590 if not repo[self.applied[-1].node].mutable():
1591 1591 raise error.Abort(
1592 1592 _("popping would remove a public revision"),
1593 1593 hint=_("see 'hg help phases' for details"))
1594 1594
1595 1595 # we know there are no local changes, so we can make a simplified
1596 1596 # form of hg.update.
1597 1597 if update:
1598 1598 qp = self.qparents(repo, rev)
1599 1599 ctx = repo[qp]
1600 1600 m, a, r, d = repo.status(qp, '.')[:4]
1601 1601 if d:
1602 1602 raise error.Abort(_("deletions found between repo revs"))
1603 1603
1604 1604 tobackup = set(a + m + r) & tobackup
1605 1605 if keepchanges and tobackup:
1606 1606 raise error.Abort(_("local changes found, qrefresh first"))
1607 1607 self.backup(repo, tobackup)
1608 1608 with repo.dirstate.parentchange():
1609 1609 for f in a:
1610 1610 repo.wvfs.unlinkpath(f, ignoremissing=True)
1611 1611 repo.dirstate.drop(f)
1612 1612 for f in m + r:
1613 1613 fctx = ctx[f]
1614 1614 repo.wwrite(f, fctx.data(), fctx.flags())
1615 1615 repo.dirstate.normal(f)
1616 1616 repo.setparents(qp, nullid)
1617 1617 for patch in reversed(self.applied[start:end]):
1618 1618 self.ui.status(_("popping %s\n") % patch.name)
1619 1619 del self.applied[start:end]
1620 1620 strip(self.ui, repo, [rev], update=False, backup=False)
1621 1621 for s, state in repo['.'].substate.items():
1622 1622 repo['.'].sub(s).get(state)
1623 1623 if self.applied:
1624 1624 self.ui.write(_("now at: %s\n") % self.applied[-1].name)
1625 1625 else:
1626 1626 self.ui.write(_("patch queue now empty\n"))
1627 1627
1628 1628 def diff(self, repo, pats, opts):
1629 1629 top, patch = self.checktoppatch(repo)
1630 1630 if not top:
1631 1631 self.ui.write(_("no patches applied\n"))
1632 1632 return
1633 1633 qp = self.qparents(repo, top)
1634 1634 if opts.get('reverse'):
1635 1635 node1, node2 = None, qp
1636 1636 else:
1637 1637 node1, node2 = qp, None
1638 1638 diffopts = self.diffopts(opts, patch)
1639 1639 self.printdiff(repo, diffopts, node1, node2, files=pats, opts=opts)
1640 1640
1641 1641 def refresh(self, repo, pats=None, **opts):
1642 1642 opts = pycompat.byteskwargs(opts)
1643 1643 if not self.applied:
1644 1644 self.ui.write(_("no patches applied\n"))
1645 1645 return 1
1646 1646 msg = opts.get('msg', '').rstrip()
1647 1647 edit = opts.get('edit')
1648 1648 editform = opts.get('editform', 'mq.qrefresh')
1649 1649 newuser = opts.get('user')
1650 1650 newdate = opts.get('date')
1651 1651 if newdate:
1652 1652 newdate = '%d %d' % dateutil.parsedate(newdate)
1653 1653 wlock = repo.wlock()
1654 1654
1655 1655 try:
1656 1656 self.checktoppatch(repo)
1657 1657 (top, patchfn) = (self.applied[-1].node, self.applied[-1].name)
1658 1658 if repo.changelog.heads(top) != [top]:
1659 1659 raise error.Abort(_("cannot qrefresh a revision with children"))
1660 1660 if not repo[top].mutable():
1661 1661 raise error.Abort(_("cannot qrefresh public revision"),
1662 1662 hint=_("see 'hg help phases' for details"))
1663 1663
1664 1664 cparents = repo.changelog.parents(top)
1665 1665 patchparent = self.qparents(repo, top)
1666 1666
1667 1667 inclsubs = checksubstate(repo, hex(patchparent))
1668 1668 if inclsubs:
1669 1669 substatestate = repo.dirstate['.hgsubstate']
1670 1670
1671 1671 ph = patchheader(self.join(patchfn), self.plainmode)
1672 1672 diffopts = self.diffopts({'git': opts.get('git')}, patchfn,
1673 1673 plain=True)
1674 1674 if newuser:
1675 1675 ph.setuser(newuser)
1676 1676 if newdate:
1677 1677 ph.setdate(newdate)
1678 1678 ph.setparent(hex(patchparent))
1679 1679
1680 1680 # only commit new patch when write is complete
1681 1681 patchf = self.opener(patchfn, 'w', atomictemp=True)
1682 1682
1683 1683 # update the dirstate in place, strip off the qtip commit
1684 1684 # and then commit.
1685 1685 #
1686 1686 # this should really read:
1687 1687 # mm, dd, aa = repo.status(top, patchparent)[:3]
1688 1688 # but we do it backwards to take advantage of manifest/changelog
1689 1689 # caching against the next repo.status call
1690 1690 mm, aa, dd = repo.status(patchparent, top)[:3]
1691 1691 changes = repo.changelog.read(top)
1692 1692 man = repo.manifestlog[changes[0]].read()
1693 1693 aaa = aa[:]
1694 1694 match1 = scmutil.match(repo[None], pats, opts)
1695 1695 # in short mode, we only diff the files included in the
1696 1696 # patch already plus specified files
1697 1697 if opts.get('short'):
1698 1698 # if amending a patch, we start with existing
1699 1699 # files plus specified files - unfiltered
1700 1700 match = scmutil.matchfiles(repo, mm + aa + dd + match1.files())
1701 1701 # filter with include/exclude options
1702 1702 match1 = scmutil.match(repo[None], opts=opts)
1703 1703 else:
1704 1704 match = scmutil.matchall(repo)
1705 1705 m, a, r, d = repo.status(match=match)[:4]
1706 1706 mm = set(mm)
1707 1707 aa = set(aa)
1708 1708 dd = set(dd)
1709 1709
1710 1710 # we might end up with files that were added between
1711 1711 # qtip and the dirstate parent, but then changed in the
1712 1712 # local dirstate. in this case, we want them to only
1713 1713 # show up in the added section
1714 1714 for x in m:
1715 1715 if x not in aa:
1716 1716 mm.add(x)
1717 1717 # we might end up with files added by the local dirstate that
1718 1718 # were deleted by the patch. In this case, they should only
1719 1719 # show up in the changed section.
1720 1720 for x in a:
1721 1721 if x in dd:
1722 1722 dd.remove(x)
1723 1723 mm.add(x)
1724 1724 else:
1725 1725 aa.add(x)
1726 1726 # make sure any files deleted in the local dirstate
1727 1727 # are not in the add or change column of the patch
1728 1728 forget = []
1729 1729 for x in d + r:
1730 1730 if x in aa:
1731 1731 aa.remove(x)
1732 1732 forget.append(x)
1733 1733 continue
1734 1734 else:
1735 1735 mm.discard(x)
1736 1736 dd.add(x)
1737 1737
1738 1738 m = list(mm)
1739 1739 r = list(dd)
1740 1740 a = list(aa)
1741 1741
1742 1742 # create 'match' that includes the files to be recommitted.
1743 1743 # apply match1 via repo.status to ensure correct case handling.
1744 1744 cm, ca, cr, cd = repo.status(patchparent, match=match1)[:4]
1745 1745 allmatches = set(cm + ca + cr + cd)
1746 1746 refreshchanges = [x.intersection(allmatches) for x in (mm, aa, dd)]
1747 1747
1748 1748 files = set(inclsubs)
1749 1749 for x in refreshchanges:
1750 1750 files.update(x)
1751 1751 match = scmutil.matchfiles(repo, files)
1752 1752
1753 1753 bmlist = repo[top].bookmarks()
1754 1754
1755 1755 dsguard = None
1756 1756 try:
1757 1757 dsguard = dirstateguard.dirstateguard(repo, 'mq.refresh')
1758 1758 if diffopts.git or diffopts.upgrade:
1759 1759 copies = {}
1760 1760 for dst in a:
1761 1761 src = repo.dirstate.copied(dst)
1762 1762 # during qfold, the source file for copies may
1763 1763 # be removed. Treat this as a simple add.
1764 1764 if src is not None and src in repo.dirstate:
1765 1765 copies.setdefault(src, []).append(dst)
1766 1766 repo.dirstate.add(dst)
1767 1767 # remember the copies between patchparent and qtip
1768 1768 for dst in aaa:
1769 1769 f = repo.file(dst)
1770 1770 src = f.renamed(man[dst])
1771 1771 if src:
1772 1772 copies.setdefault(src[0], []).extend(
1773 1773 copies.get(dst, []))
1774 1774 if dst in a:
1775 1775 copies[src[0]].append(dst)
1776 1776 # we can't copy a file created by the patch itself
1777 1777 if dst in copies:
1778 1778 del copies[dst]
1779 1779 for src, dsts in copies.iteritems():
1780 1780 for dst in dsts:
1781 1781 repo.dirstate.copy(src, dst)
1782 1782 else:
1783 1783 for dst in a:
1784 1784 repo.dirstate.add(dst)
1785 1785 # Drop useless copy information
1786 1786 for f in list(repo.dirstate.copies()):
1787 1787 repo.dirstate.copy(None, f)
1788 1788 for f in r:
1789 1789 repo.dirstate.remove(f)
1790 1790 # if the patch excludes a modified file, mark that
1791 1791 # file with mtime=0 so status can see it.
1792 1792 mm = []
1793 1793 for i in xrange(len(m) - 1, -1, -1):
1794 1794 if not match1(m[i]):
1795 1795 mm.append(m[i])
1796 1796 del m[i]
1797 1797 for f in m:
1798 1798 repo.dirstate.normal(f)
1799 1799 for f in mm:
1800 1800 repo.dirstate.normallookup(f)
1801 1801 for f in forget:
1802 1802 repo.dirstate.drop(f)
1803 1803
1804 1804 user = ph.user or changes[1]
1805 1805
1806 1806 oldphase = repo[top].phase()
1807 1807
1808 1808 # assumes strip can roll itself back if interrupted
1809 1809 repo.setparents(*cparents)
1810 1810 self.applied.pop()
1811 1811 self.applieddirty = True
1812 1812 strip(self.ui, repo, [top], update=False, backup=False)
1813 1813 dsguard.close()
1814 1814 finally:
1815 1815 release(dsguard)
1816 1816
1817 1817 try:
1818 1818 # might be nice to attempt to roll back strip after this
1819 1819
1820 1820 defaultmsg = "[mq]: %s" % patchfn
1821 1821 editor = cmdutil.getcommiteditor(editform=editform)
1822 1822 if edit:
1823 1823 def finishdesc(desc):
1824 1824 if desc.rstrip():
1825 1825 ph.setmessage(desc)
1826 1826 return desc
1827 1827 return defaultmsg
1828 1828 # i18n: this message is shown in editor with "HG: " prefix
1829 1829 extramsg = _('Leave message empty to use default message.')
1830 1830 editor = cmdutil.getcommiteditor(finishdesc=finishdesc,
1831 1831 extramsg=extramsg,
1832 1832 editform=editform)
1833 1833 message = msg or "\n".join(ph.message)
1834 1834 elif not msg:
1835 1835 if not ph.message:
1836 1836 message = defaultmsg
1837 1837 else:
1838 1838 message = "\n".join(ph.message)
1839 1839 else:
1840 1840 message = msg
1841 1841 ph.setmessage(msg)
1842 1842
1843 1843 # Ensure we create a new changeset in the same phase than
1844 1844 # the old one.
1845 1845 lock = tr = None
1846 1846 try:
1847 1847 lock = repo.lock()
1848 1848 tr = repo.transaction('mq')
1849 1849 n = newcommit(repo, oldphase, message, user, ph.date,
1850 1850 match=match, force=True, editor=editor)
1851 1851 # only write patch after a successful commit
1852 1852 c = [list(x) for x in refreshchanges]
1853 1853 if inclsubs:
1854 1854 self.putsubstate2changes(substatestate, c)
1855 1855 chunks = patchmod.diff(repo, patchparent,
1856 1856 changes=c, opts=diffopts)
1857 1857 comments = bytes(ph)
1858 1858 if comments:
1859 1859 patchf.write(comments)
1860 1860 for chunk in chunks:
1861 1861 patchf.write(chunk)
1862 1862 patchf.close()
1863 1863
1864 1864 marks = repo._bookmarks
1865 1865 marks.applychanges(repo, tr, [(bm, n) for bm in bmlist])
1866 1866 tr.close()
1867 1867
1868 1868 self.applied.append(statusentry(n, patchfn))
1869 1869 finally:
1870 1870 lockmod.release(tr, lock)
1871 1871 except: # re-raises
1872 1872 ctx = repo[cparents[0]]
1873 1873 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1874 1874 self.savedirty()
1875 1875 self.ui.warn(_('qrefresh interrupted while patch was popped! '
1876 1876 '(revert --all, qpush to recover)\n'))
1877 1877 raise
1878 1878 finally:
1879 1879 wlock.release()
1880 1880 self.removeundo(repo)
1881 1881
1882 1882 def init(self, repo, create=False):
1883 1883 if not create and os.path.isdir(self.path):
1884 1884 raise error.Abort(_("patch queue directory already exists"))
1885 1885 try:
1886 1886 os.mkdir(self.path)
1887 1887 except OSError as inst:
1888 1888 if inst.errno != errno.EEXIST or not create:
1889 1889 raise
1890 1890 if create:
1891 1891 return self.qrepo(create=True)
1892 1892
1893 1893 def unapplied(self, repo, patch=None):
1894 1894 if patch and patch not in self.series:
1895 1895 raise error.Abort(_("patch %s is not in series file") % patch)
1896 1896 if not patch:
1897 1897 start = self.seriesend()
1898 1898 else:
1899 1899 start = self.series.index(patch) + 1
1900 1900 unapplied = []
1901 1901 for i in xrange(start, len(self.series)):
1902 1902 pushable, reason = self.pushable(i)
1903 1903 if pushable:
1904 1904 unapplied.append((i, self.series[i]))
1905 1905 self.explainpushable(i)
1906 1906 return unapplied
1907 1907
1908 1908 def qseries(self, repo, missing=None, start=0, length=None, status=None,
1909 1909 summary=False):
1910 1910 def displayname(pfx, patchname, state):
1911 1911 if pfx:
1912 1912 self.ui.write(pfx)
1913 1913 if summary:
1914 1914 ph = patchheader(self.join(patchname), self.plainmode)
1915 1915 if ph.message:
1916 1916 msg = ph.message[0]
1917 1917 else:
1918 1918 msg = ''
1919 1919
1920 1920 if self.ui.formatted():
1921 1921 width = self.ui.termwidth() - len(pfx) - len(patchname) - 2
1922 1922 if width > 0:
1923 1923 msg = stringutil.ellipsis(msg, width)
1924 1924 else:
1925 1925 msg = ''
1926 1926 self.ui.write(patchname, label='qseries.' + state)
1927 1927 self.ui.write(': ')
1928 1928 self.ui.write(msg, label='qseries.message.' + state)
1929 1929 else:
1930 1930 self.ui.write(patchname, label='qseries.' + state)
1931 1931 self.ui.write('\n')
1932 1932
1933 1933 applied = set([p.name for p in self.applied])
1934 1934 if length is None:
1935 1935 length = len(self.series) - start
1936 1936 if not missing:
1937 1937 if self.ui.verbose:
1938 1938 idxwidth = len("%d" % (start + length - 1))
1939 1939 for i in xrange(start, start + length):
1940 1940 patch = self.series[i]
1941 1941 if patch in applied:
1942 1942 char, state = 'A', 'applied'
1943 1943 elif self.pushable(i)[0]:
1944 1944 char, state = 'U', 'unapplied'
1945 1945 else:
1946 1946 char, state = 'G', 'guarded'
1947 1947 pfx = ''
1948 1948 if self.ui.verbose:
1949 1949 pfx = '%*d %s ' % (idxwidth, i, char)
1950 1950 elif status and status != char:
1951 1951 continue
1952 1952 displayname(pfx, patch, state)
1953 1953 else:
1954 1954 msng_list = []
1955 1955 for root, dirs, files in os.walk(self.path):
1956 1956 d = root[len(self.path) + 1:]
1957 1957 for f in files:
1958 1958 fl = os.path.join(d, f)
1959 1959 if (fl not in self.series and
1960 1960 fl not in (self.statuspath, self.seriespath,
1961 1961 self.guardspath)
1962 1962 and not fl.startswith('.')):
1963 1963 msng_list.append(fl)
1964 1964 for x in sorted(msng_list):
1965 1965 pfx = self.ui.verbose and ('D ') or ''
1966 1966 displayname(pfx, x, 'missing')
1967 1967
1968 1968 def issaveline(self, l):
1969 1969 if l.name == '.hg.patches.save.line':
1970 1970 return True
1971 1971
1972 1972 def qrepo(self, create=False):
1973 1973 ui = self.baseui.copy()
1974 1974 # copy back attributes set by ui.pager()
1975 1975 if self.ui.pageractive and not ui.pageractive:
1976 1976 ui.pageractive = self.ui.pageractive
1977 1977 # internal config: ui.formatted
1978 1978 ui.setconfig('ui', 'formatted',
1979 1979 self.ui.config('ui', 'formatted'), 'mqpager')
1980 1980 ui.setconfig('ui', 'interactive',
1981 1981 self.ui.config('ui', 'interactive'), 'mqpager')
1982 1982 if create or os.path.isdir(self.join(".hg")):
1983 1983 return hg.repository(ui, path=self.path, create=create)
1984 1984
1985 1985 def restore(self, repo, rev, delete=None, qupdate=None):
1986 1986 desc = repo[rev].description().strip()
1987 1987 lines = desc.splitlines()
1988 1988 i = 0
1989 1989 datastart = None
1990 1990 series = []
1991 1991 applied = []
1992 1992 qpp = None
1993 1993 for i, line in enumerate(lines):
1994 1994 if line == 'Patch Data:':
1995 1995 datastart = i + 1
1996 1996 elif line.startswith('Dirstate:'):
1997 1997 l = line.rstrip()
1998 1998 l = l[10:].split(' ')
1999 1999 qpp = [bin(x) for x in l]
2000 2000 elif datastart is not None:
2001 2001 l = line.rstrip()
2002 2002 n, name = l.split(':', 1)
2003 2003 if n:
2004 2004 applied.append(statusentry(bin(n), name))
2005 2005 else:
2006 2006 series.append(l)
2007 2007 if datastart is None:
2008 2008 self.ui.warn(_("no saved patch data found\n"))
2009 2009 return 1
2010 2010 self.ui.warn(_("restoring status: %s\n") % lines[0])
2011 2011 self.fullseries = series
2012 2012 self.applied = applied
2013 2013 self.parseseries()
2014 2014 self.seriesdirty = True
2015 2015 self.applieddirty = True
2016 2016 heads = repo.changelog.heads()
2017 2017 if delete:
2018 2018 if rev not in heads:
2019 2019 self.ui.warn(_("save entry has children, leaving it alone\n"))
2020 2020 else:
2021 2021 self.ui.warn(_("removing save entry %s\n") % short(rev))
2022 2022 pp = repo.dirstate.parents()
2023 2023 if rev in pp:
2024 2024 update = True
2025 2025 else:
2026 2026 update = False
2027 2027 strip(self.ui, repo, [rev], update=update, backup=False)
2028 2028 if qpp:
2029 2029 self.ui.warn(_("saved queue repository parents: %s %s\n") %
2030 2030 (short(qpp[0]), short(qpp[1])))
2031 2031 if qupdate:
2032 2032 self.ui.status(_("updating queue directory\n"))
2033 2033 r = self.qrepo()
2034 2034 if not r:
2035 2035 self.ui.warn(_("unable to load queue repository\n"))
2036 2036 return 1
2037 2037 hg.clean(r, qpp[0])
2038 2038
2039 2039 def save(self, repo, msg=None):
2040 2040 if not self.applied:
2041 2041 self.ui.warn(_("save: no patches applied, exiting\n"))
2042 2042 return 1
2043 2043 if self.issaveline(self.applied[-1]):
2044 2044 self.ui.warn(_("status is already saved\n"))
2045 2045 return 1
2046 2046
2047 2047 if not msg:
2048 2048 msg = _("hg patches saved state")
2049 2049 else:
2050 2050 msg = "hg patches: " + msg.rstrip('\r\n')
2051 2051 r = self.qrepo()
2052 2052 if r:
2053 2053 pp = r.dirstate.parents()
2054 2054 msg += "\nDirstate: %s %s" % (hex(pp[0]), hex(pp[1]))
2055 2055 msg += "\n\nPatch Data:\n"
2056 2056 msg += ''.join('%s\n' % x for x in self.applied)
2057 2057 msg += ''.join(':%s\n' % x for x in self.fullseries)
2058 2058 n = repo.commit(msg, force=True)
2059 2059 if not n:
2060 2060 self.ui.warn(_("repo commit failed\n"))
2061 2061 return 1
2062 2062 self.applied.append(statusentry(n, '.hg.patches.save.line'))
2063 2063 self.applieddirty = True
2064 2064 self.removeundo(repo)
2065 2065
2066 2066 def fullseriesend(self):
2067 2067 if self.applied:
2068 2068 p = self.applied[-1].name
2069 2069 end = self.findseries(p)
2070 2070 if end is None:
2071 2071 return len(self.fullseries)
2072 2072 return end + 1
2073 2073 return 0
2074 2074
2075 2075 def seriesend(self, all_patches=False):
2076 2076 """If all_patches is False, return the index of the next pushable patch
2077 2077 in the series, or the series length. If all_patches is True, return the
2078 2078 index of the first patch past the last applied one.
2079 2079 """
2080 2080 end = 0
2081 2081 def nextpatch(start):
2082 2082 if all_patches or start >= len(self.series):
2083 2083 return start
2084 2084 for i in xrange(start, len(self.series)):
2085 2085 p, reason = self.pushable(i)
2086 2086 if p:
2087 2087 return i
2088 2088 self.explainpushable(i)
2089 2089 return len(self.series)
2090 2090 if self.applied:
2091 2091 p = self.applied[-1].name
2092 2092 try:
2093 2093 end = self.series.index(p)
2094 2094 except ValueError:
2095 2095 return 0
2096 2096 return nextpatch(end + 1)
2097 2097 return nextpatch(end)
2098 2098
2099 2099 def appliedname(self, index):
2100 2100 pname = self.applied[index].name
2101 2101 if not self.ui.verbose:
2102 2102 p = pname
2103 2103 else:
2104 2104 p = ("%d" % self.series.index(pname)) + " " + pname
2105 2105 return p
2106 2106
2107 2107 def qimport(self, repo, files, patchname=None, rev=None, existing=None,
2108 2108 force=None, git=False):
2109 2109 def checkseries(patchname):
2110 2110 if patchname in self.series:
2111 2111 raise error.Abort(_('patch %s is already in the series file')
2112 2112 % patchname)
2113 2113
2114 2114 if rev:
2115 2115 if files:
2116 2116 raise error.Abort(_('option "-r" not valid when importing '
2117 2117 'files'))
2118 2118 rev = scmutil.revrange(repo, rev)
2119 2119 rev.sort(reverse=True)
2120 2120 elif not files:
2121 2121 raise error.Abort(_('no files or revisions specified'))
2122 2122 if (len(files) > 1 or len(rev) > 1) and patchname:
2123 2123 raise error.Abort(_('option "-n" not valid when importing multiple '
2124 2124 'patches'))
2125 2125 imported = []
2126 2126 if rev:
2127 2127 # If mq patches are applied, we can only import revisions
2128 2128 # that form a linear path to qbase.
2129 2129 # Otherwise, they should form a linear path to a head.
2130 2130 heads = repo.changelog.heads(repo.changelog.node(rev.first()))
2131 2131 if len(heads) > 1:
2132 2132 raise error.Abort(_('revision %d is the root of more than one '
2133 2133 'branch') % rev.last())
2134 2134 if self.applied:
2135 2135 base = repo.changelog.node(rev.first())
2136 2136 if base in [n.node for n in self.applied]:
2137 2137 raise error.Abort(_('revision %d is already managed')
2138 2138 % rev.first())
2139 2139 if heads != [self.applied[-1].node]:
2140 2140 raise error.Abort(_('revision %d is not the parent of '
2141 2141 'the queue') % rev.first())
2142 2142 base = repo.changelog.rev(self.applied[0].node)
2143 2143 lastparent = repo.changelog.parentrevs(base)[0]
2144 2144 else:
2145 2145 if heads != [repo.changelog.node(rev.first())]:
2146 2146 raise error.Abort(_('revision %d has unmanaged children')
2147 2147 % rev.first())
2148 2148 lastparent = None
2149 2149
2150 2150 diffopts = self.diffopts({'git': git})
2151 2151 with repo.transaction('qimport') as tr:
2152 2152 for r in rev:
2153 2153 if not repo[r].mutable():
2154 2154 raise error.Abort(_('revision %d is not mutable') % r,
2155 2155 hint=_("see 'hg help phases' "
2156 2156 'for details'))
2157 2157 p1, p2 = repo.changelog.parentrevs(r)
2158 2158 n = repo.changelog.node(r)
2159 2159 if p2 != nullrev:
2160 2160 raise error.Abort(_('cannot import merge revision %d')
2161 2161 % r)
2162 2162 if lastparent and lastparent != r:
2163 2163 raise error.Abort(_('revision %d is not the parent of '
2164 2164 '%d')
2165 2165 % (r, lastparent))
2166 2166 lastparent = p1
2167 2167
2168 2168 if not patchname:
2169 2169 patchname = self.makepatchname(
2170 2170 repo[r].description().split('\n', 1)[0],
2171 2171 '%d.diff' % r)
2172 2172 checkseries(patchname)
2173 2173 self.checkpatchname(patchname, force)
2174 2174 self.fullseries.insert(0, patchname)
2175 2175
2176 2176 patchf = self.opener(patchname, "w")
2177 2177 cmdutil.export(repo, [n], fp=patchf, opts=diffopts)
2178 2178 patchf.close()
2179 2179
2180 2180 se = statusentry(n, patchname)
2181 2181 self.applied.insert(0, se)
2182 2182
2183 2183 self.added.append(patchname)
2184 2184 imported.append(patchname)
2185 2185 patchname = None
2186 2186 if rev and repo.ui.configbool('mq', 'secret'):
2187 2187 # if we added anything with --rev, move the secret root
2188 2188 phases.retractboundary(repo, tr, phases.secret, [n])
2189 2189 self.parseseries()
2190 2190 self.applieddirty = True
2191 2191 self.seriesdirty = True
2192 2192
2193 2193 for i, filename in enumerate(files):
2194 2194 if existing:
2195 2195 if filename == '-':
2196 2196 raise error.Abort(_('-e is incompatible with import from -')
2197 2197 )
2198 2198 filename = normname(filename)
2199 2199 self.checkreservedname(filename)
2200 2200 if util.url(filename).islocal():
2201 2201 originpath = self.join(filename)
2202 2202 if not os.path.isfile(originpath):
2203 2203 raise error.Abort(
2204 2204 _("patch %s does not exist") % filename)
2205 2205
2206 2206 if patchname:
2207 2207 self.checkpatchname(patchname, force)
2208 2208
2209 2209 self.ui.write(_('renaming %s to %s\n')
2210 2210 % (filename, patchname))
2211 2211 util.rename(originpath, self.join(patchname))
2212 2212 else:
2213 2213 patchname = filename
2214 2214
2215 2215 else:
2216 2216 if filename == '-' and not patchname:
2217 2217 raise error.Abort(_('need --name to import a patch from -'))
2218 2218 elif not patchname:
2219 2219 patchname = normname(os.path.basename(filename.rstrip('/')))
2220 2220 self.checkpatchname(patchname, force)
2221 2221 try:
2222 2222 if filename == '-':
2223 2223 text = self.ui.fin.read()
2224 2224 else:
2225 2225 fp = hg.openpath(self.ui, filename)
2226 2226 text = fp.read()
2227 2227 fp.close()
2228 2228 except (OSError, IOError):
2229 2229 raise error.Abort(_("unable to read file %s") % filename)
2230 2230 patchf = self.opener(patchname, "w")
2231 2231 patchf.write(text)
2232 2232 patchf.close()
2233 2233 if not force:
2234 2234 checkseries(patchname)
2235 2235 if patchname not in self.series:
2236 2236 index = self.fullseriesend() + i
2237 2237 self.fullseries[index:index] = [patchname]
2238 2238 self.parseseries()
2239 2239 self.seriesdirty = True
2240 2240 self.ui.warn(_("adding %s to series file\n") % patchname)
2241 2241 self.added.append(patchname)
2242 2242 imported.append(patchname)
2243 2243 patchname = None
2244 2244
2245 2245 self.removeundo(repo)
2246 2246 return imported
2247 2247
2248 2248 def fixkeepchangesopts(ui, opts):
2249 2249 if (not ui.configbool('mq', 'keepchanges') or opts.get('force')
2250 2250 or opts.get('exact')):
2251 2251 return opts
2252 2252 opts = dict(opts)
2253 2253 opts['keep_changes'] = True
2254 2254 return opts
2255 2255
2256 2256 @command("qdelete|qremove|qrm",
2257 2257 [('k', 'keep', None, _('keep patch file')),
2258 2258 ('r', 'rev', [],
2259 2259 _('stop managing a revision (DEPRECATED)'), _('REV'))],
2260 2260 _('hg qdelete [-k] [PATCH]...'))
2261 2261 def delete(ui, repo, *patches, **opts):
2262 2262 """remove patches from queue
2263 2263
2264 2264 The patches must not be applied, and at least one patch is required. Exact
2265 2265 patch identifiers must be given. With -k/--keep, the patch files are
2266 2266 preserved in the patch directory.
2267 2267
2268 2268 To stop managing a patch and move it into permanent history,
2269 2269 use the :hg:`qfinish` command."""
2270 2270 q = repo.mq
2271 2271 q.delete(repo, patches, pycompat.byteskwargs(opts))
2272 2272 q.savedirty()
2273 2273 return 0
2274 2274
2275 2275 @command("qapplied",
2276 2276 [('1', 'last', None, _('show only the preceding applied patch'))
2277 2277 ] + seriesopts,
2278 2278 _('hg qapplied [-1] [-s] [PATCH]'))
2279 2279 def applied(ui, repo, patch=None, **opts):
2280 2280 """print the patches already applied
2281 2281
2282 2282 Returns 0 on success."""
2283 2283
2284 2284 q = repo.mq
2285 2285 opts = pycompat.byteskwargs(opts)
2286 2286
2287 2287 if patch:
2288 2288 if patch not in q.series:
2289 2289 raise error.Abort(_("patch %s is not in series file") % patch)
2290 2290 end = q.series.index(patch) + 1
2291 2291 else:
2292 2292 end = q.seriesend(True)
2293 2293
2294 2294 if opts.get('last') and not end:
2295 2295 ui.write(_("no patches applied\n"))
2296 2296 return 1
2297 2297 elif opts.get('last') and end == 1:
2298 2298 ui.write(_("only one patch applied\n"))
2299 2299 return 1
2300 2300 elif opts.get('last'):
2301 2301 start = end - 2
2302 2302 end = 1
2303 2303 else:
2304 2304 start = 0
2305 2305
2306 2306 q.qseries(repo, length=end, start=start, status='A',
2307 2307 summary=opts.get('summary'))
2308 2308
2309 2309
2310 2310 @command("qunapplied",
2311 2311 [('1', 'first', None, _('show only the first patch'))] + seriesopts,
2312 2312 _('hg qunapplied [-1] [-s] [PATCH]'))
2313 2313 def unapplied(ui, repo, patch=None, **opts):
2314 2314 """print the patches not yet applied
2315 2315
2316 2316 Returns 0 on success."""
2317 2317
2318 2318 q = repo.mq
2319 2319 opts = pycompat.byteskwargs(opts)
2320 2320 if patch:
2321 2321 if patch not in q.series:
2322 2322 raise error.Abort(_("patch %s is not in series file") % patch)
2323 2323 start = q.series.index(patch) + 1
2324 2324 else:
2325 2325 start = q.seriesend(True)
2326 2326
2327 2327 if start == len(q.series) and opts.get('first'):
2328 2328 ui.write(_("all patches applied\n"))
2329 2329 return 1
2330 2330
2331 2331 if opts.get('first'):
2332 2332 length = 1
2333 2333 else:
2334 2334 length = None
2335 2335 q.qseries(repo, start=start, length=length, status='U',
2336 2336 summary=opts.get('summary'))
2337 2337
2338 2338 @command("qimport",
2339 2339 [('e', 'existing', None, _('import file in patch directory')),
2340 2340 ('n', 'name', '',
2341 2341 _('name of patch file'), _('NAME')),
2342 2342 ('f', 'force', None, _('overwrite existing files')),
2343 2343 ('r', 'rev', [],
2344 2344 _('place existing revisions under mq control'), _('REV')),
2345 2345 ('g', 'git', None, _('use git extended diff format')),
2346 2346 ('P', 'push', None, _('qpush after importing'))],
2347 2347 _('hg qimport [-e] [-n NAME] [-f] [-g] [-P] [-r REV]... [FILE]...'))
2348 2348 def qimport(ui, repo, *filename, **opts):
2349 2349 """import a patch or existing changeset
2350 2350
2351 2351 The patch is inserted into the series after the last applied
2352 2352 patch. If no patches have been applied, qimport prepends the patch
2353 2353 to the series.
2354 2354
2355 2355 The patch will have the same name as its source file unless you
2356 2356 give it a new one with -n/--name.
2357 2357
2358 2358 You can register an existing patch inside the patch directory with
2359 2359 the -e/--existing flag.
2360 2360
2361 2361 With -f/--force, an existing patch of the same name will be
2362 2362 overwritten.
2363 2363
2364 2364 An existing changeset may be placed under mq control with -r/--rev
2365 2365 (e.g. qimport --rev . -n patch will place the current revision
2366 2366 under mq control). With -g/--git, patches imported with --rev will
2367 2367 use the git diff format. See the diffs help topic for information
2368 2368 on why this is important for preserving rename/copy information
2369 2369 and permission changes. Use :hg:`qfinish` to remove changesets
2370 2370 from mq control.
2371 2371
2372 2372 To import a patch from standard input, pass - as the patch file.
2373 2373 When importing from standard input, a patch name must be specified
2374 2374 using the --name flag.
2375 2375
2376 2376 To import an existing patch while renaming it::
2377 2377
2378 2378 hg qimport -e existing-patch -n new-name
2379 2379
2380 2380 Returns 0 if import succeeded.
2381 2381 """
2382 2382 opts = pycompat.byteskwargs(opts)
2383 2383 with repo.lock(): # cause this may move phase
2384 2384 q = repo.mq
2385 2385 try:
2386 2386 imported = q.qimport(
2387 2387 repo, filename, patchname=opts.get('name'),
2388 2388 existing=opts.get('existing'), force=opts.get('force'),
2389 2389 rev=opts.get('rev'), git=opts.get('git'))
2390 2390 finally:
2391 2391 q.savedirty()
2392 2392
2393 2393 if imported and opts.get('push') and not opts.get('rev'):
2394 2394 return q.push(repo, imported[-1])
2395 2395 return 0
2396 2396
2397 2397 def qinit(ui, repo, create):
2398 2398 """initialize a new queue repository
2399 2399
2400 2400 This command also creates a series file for ordering patches, and
2401 2401 an mq-specific .hgignore file in the queue repository, to exclude
2402 2402 the status and guards files (these contain mostly transient state).
2403 2403
2404 2404 Returns 0 if initialization succeeded."""
2405 2405 q = repo.mq
2406 2406 r = q.init(repo, create)
2407 2407 q.savedirty()
2408 2408 if r:
2409 2409 if not os.path.exists(r.wjoin('.hgignore')):
2410 2410 fp = r.wvfs('.hgignore', 'w')
2411 2411 fp.write('^\\.hg\n')
2412 2412 fp.write('^\\.mq\n')
2413 2413 fp.write('syntax: glob\n')
2414 2414 fp.write('status\n')
2415 2415 fp.write('guards\n')
2416 2416 fp.close()
2417 2417 if not os.path.exists(r.wjoin('series')):
2418 2418 r.wvfs('series', 'w').close()
2419 2419 r[None].add(['.hgignore', 'series'])
2420 2420 commands.add(ui, r)
2421 2421 return 0
2422 2422
2423 2423 @command("^qinit",
2424 2424 [('c', 'create-repo', None, _('create queue repository'))],
2425 2425 _('hg qinit [-c]'))
2426 2426 def init(ui, repo, **opts):
2427 2427 """init a new queue repository (DEPRECATED)
2428 2428
2429 2429 The queue repository is unversioned by default. If
2430 2430 -c/--create-repo is specified, qinit will create a separate nested
2431 2431 repository for patches (qinit -c may also be run later to convert
2432 2432 an unversioned patch repository into a versioned one). You can use
2433 2433 qcommit to commit changes to this queue repository.
2434 2434
2435 2435 This command is deprecated. Without -c, it's implied by other relevant
2436 2436 commands. With -c, use :hg:`init --mq` instead."""
2437 2437 return qinit(ui, repo, create=opts.get(r'create_repo'))
2438 2438
2439 2439 @command("qclone",
2440 2440 [('', 'pull', None, _('use pull protocol to copy metadata')),
2441 2441 ('U', 'noupdate', None,
2442 2442 _('do not update the new working directories')),
2443 2443 ('', 'uncompressed', None,
2444 2444 _('use uncompressed transfer (fast over LAN)')),
2445 2445 ('p', 'patches', '',
2446 2446 _('location of source patch repository'), _('REPO')),
2447 2447 ] + cmdutil.remoteopts,
2448 2448 _('hg qclone [OPTION]... SOURCE [DEST]'),
2449 2449 norepo=True)
2450 2450 def clone(ui, source, dest=None, **opts):
2451 2451 '''clone main and patch repository at same time
2452 2452
2453 2453 If source is local, destination will have no patches applied. If
2454 2454 source is remote, this command can not check if patches are
2455 2455 applied in source, so cannot guarantee that patches are not
2456 2456 applied in destination. If you clone remote repository, be sure
2457 2457 before that it has no patches applied.
2458 2458
2459 2459 Source patch repository is looked for in <src>/.hg/patches by
2460 2460 default. Use -p <url> to change.
2461 2461
2462 2462 The patch directory must be a nested Mercurial repository, as
2463 2463 would be created by :hg:`init --mq`.
2464 2464
2465 2465 Return 0 on success.
2466 2466 '''
2467 2467 opts = pycompat.byteskwargs(opts)
2468 2468 def patchdir(repo):
2469 2469 """compute a patch repo url from a repo object"""
2470 2470 url = repo.url()
2471 2471 if url.endswith('/'):
2472 2472 url = url[:-1]
2473 2473 return url + '/.hg/patches'
2474 2474
2475 2475 # main repo (destination and sources)
2476 2476 if dest is None:
2477 2477 dest = hg.defaultdest(source)
2478 2478 sr = hg.peer(ui, opts, ui.expandpath(source))
2479 2479
2480 2480 # patches repo (source only)
2481 2481 if opts.get('patches'):
2482 2482 patchespath = ui.expandpath(opts.get('patches'))
2483 2483 else:
2484 2484 patchespath = patchdir(sr)
2485 2485 try:
2486 2486 hg.peer(ui, opts, patchespath)
2487 2487 except error.RepoError:
2488 2488 raise error.Abort(_('versioned patch repository not found'
2489 2489 ' (see init --mq)'))
2490 2490 qbase, destrev = None, None
2491 2491 if sr.local():
2492 2492 repo = sr.local()
2493 2493 if repo.mq.applied and repo[qbase].phase() != phases.secret:
2494 2494 qbase = repo.mq.applied[0].node
2495 2495 if not hg.islocal(dest):
2496 2496 heads = set(repo.heads())
2497 2497 destrev = list(heads.difference(repo.heads(qbase)))
2498 2498 destrev.append(repo.changelog.parents(qbase)[0])
2499 2499 elif sr.capable('lookup'):
2500 2500 try:
2501 2501 qbase = sr.lookup('qbase')
2502 2502 except error.RepoError:
2503 2503 pass
2504 2504
2505 2505 ui.note(_('cloning main repository\n'))
2506 2506 sr, dr = hg.clone(ui, opts, sr.url(), dest,
2507 2507 pull=opts.get('pull'),
2508 rev=destrev,
2508 revs=destrev,
2509 2509 update=False,
2510 2510 stream=opts.get('uncompressed'))
2511 2511
2512 2512 ui.note(_('cloning patch repository\n'))
2513 2513 hg.clone(ui, opts, opts.get('patches') or patchdir(sr), patchdir(dr),
2514 2514 pull=opts.get('pull'), update=not opts.get('noupdate'),
2515 2515 stream=opts.get('uncompressed'))
2516 2516
2517 2517 if dr.local():
2518 2518 repo = dr.local()
2519 2519 if qbase:
2520 2520 ui.note(_('stripping applied patches from destination '
2521 2521 'repository\n'))
2522 2522 strip(ui, repo, [qbase], update=False, backup=None)
2523 2523 if not opts.get('noupdate'):
2524 2524 ui.note(_('updating destination repository\n'))
2525 2525 hg.update(repo, repo.changelog.tip())
2526 2526
2527 2527 @command("qcommit|qci",
2528 2528 commands.table["^commit|ci"][1],
2529 2529 _('hg qcommit [OPTION]... [FILE]...'),
2530 2530 inferrepo=True)
2531 2531 def commit(ui, repo, *pats, **opts):
2532 2532 """commit changes in the queue repository (DEPRECATED)
2533 2533
2534 2534 This command is deprecated; use :hg:`commit --mq` instead."""
2535 2535 q = repo.mq
2536 2536 r = q.qrepo()
2537 2537 if not r:
2538 2538 raise error.Abort('no queue repository')
2539 2539 commands.commit(r.ui, r, *pats, **opts)
2540 2540
2541 2541 @command("qseries",
2542 2542 [('m', 'missing', None, _('print patches not in series')),
2543 2543 ] + seriesopts,
2544 2544 _('hg qseries [-ms]'))
2545 2545 def series(ui, repo, **opts):
2546 2546 """print the entire series file
2547 2547
2548 2548 Returns 0 on success."""
2549 2549 repo.mq.qseries(repo, missing=opts.get(r'missing'),
2550 2550 summary=opts.get(r'summary'))
2551 2551 return 0
2552 2552
2553 2553 @command("qtop", seriesopts, _('hg qtop [-s]'))
2554 2554 def top(ui, repo, **opts):
2555 2555 """print the name of the current patch
2556 2556
2557 2557 Returns 0 on success."""
2558 2558 q = repo.mq
2559 2559 if q.applied:
2560 2560 t = q.seriesend(True)
2561 2561 else:
2562 2562 t = 0
2563 2563
2564 2564 if t:
2565 2565 q.qseries(repo, start=t - 1, length=1, status='A',
2566 2566 summary=opts.get(r'summary'))
2567 2567 else:
2568 2568 ui.write(_("no patches applied\n"))
2569 2569 return 1
2570 2570
2571 2571 @command("qnext", seriesopts, _('hg qnext [-s]'))
2572 2572 def next(ui, repo, **opts):
2573 2573 """print the name of the next pushable patch
2574 2574
2575 2575 Returns 0 on success."""
2576 2576 q = repo.mq
2577 2577 end = q.seriesend()
2578 2578 if end == len(q.series):
2579 2579 ui.write(_("all patches applied\n"))
2580 2580 return 1
2581 2581 q.qseries(repo, start=end, length=1, summary=opts.get(r'summary'))
2582 2582
2583 2583 @command("qprev", seriesopts, _('hg qprev [-s]'))
2584 2584 def prev(ui, repo, **opts):
2585 2585 """print the name of the preceding applied patch
2586 2586
2587 2587 Returns 0 on success."""
2588 2588 q = repo.mq
2589 2589 l = len(q.applied)
2590 2590 if l == 1:
2591 2591 ui.write(_("only one patch applied\n"))
2592 2592 return 1
2593 2593 if not l:
2594 2594 ui.write(_("no patches applied\n"))
2595 2595 return 1
2596 2596 idx = q.series.index(q.applied[-2].name)
2597 2597 q.qseries(repo, start=idx, length=1, status='A',
2598 2598 summary=opts.get(r'summary'))
2599 2599
2600 2600 def setupheaderopts(ui, opts):
2601 2601 if not opts.get('user') and opts.get('currentuser'):
2602 2602 opts['user'] = ui.username()
2603 2603 if not opts.get('date') and opts.get('currentdate'):
2604 2604 opts['date'] = "%d %d" % dateutil.makedate()
2605 2605
2606 2606 @command("^qnew",
2607 2607 [('e', 'edit', None, _('invoke editor on commit messages')),
2608 2608 ('f', 'force', None, _('import uncommitted changes (DEPRECATED)')),
2609 2609 ('g', 'git', None, _('use git extended diff format')),
2610 2610 ('U', 'currentuser', None, _('add "From: <current user>" to patch')),
2611 2611 ('u', 'user', '',
2612 2612 _('add "From: <USER>" to patch'), _('USER')),
2613 2613 ('D', 'currentdate', None, _('add "Date: <current date>" to patch')),
2614 2614 ('d', 'date', '',
2615 2615 _('add "Date: <DATE>" to patch'), _('DATE'))
2616 2616 ] + cmdutil.walkopts + cmdutil.commitopts,
2617 2617 _('hg qnew [-e] [-m TEXT] [-l FILE] PATCH [FILE]...'),
2618 2618 inferrepo=True)
2619 2619 def new(ui, repo, patch, *args, **opts):
2620 2620 """create a new patch
2621 2621
2622 2622 qnew creates a new patch on top of the currently-applied patch (if
2623 2623 any). The patch will be initialized with any outstanding changes
2624 2624 in the working directory. You may also use -I/--include,
2625 2625 -X/--exclude, and/or a list of files after the patch name to add
2626 2626 only changes to matching files to the new patch, leaving the rest
2627 2627 as uncommitted modifications.
2628 2628
2629 2629 -u/--user and -d/--date can be used to set the (given) user and
2630 2630 date, respectively. -U/--currentuser and -D/--currentdate set user
2631 2631 to current user and date to current date.
2632 2632
2633 2633 -e/--edit, -m/--message or -l/--logfile set the patch header as
2634 2634 well as the commit message. If none is specified, the header is
2635 2635 empty and the commit message is '[mq]: PATCH'.
2636 2636
2637 2637 Use the -g/--git option to keep the patch in the git extended diff
2638 2638 format. Read the diffs help topic for more information on why this
2639 2639 is important for preserving permission changes and copy/rename
2640 2640 information.
2641 2641
2642 2642 Returns 0 on successful creation of a new patch.
2643 2643 """
2644 2644 opts = pycompat.byteskwargs(opts)
2645 2645 msg = cmdutil.logmessage(ui, opts)
2646 2646 q = repo.mq
2647 2647 opts['msg'] = msg
2648 2648 setupheaderopts(ui, opts)
2649 2649 q.new(repo, patch, *args, **pycompat.strkwargs(opts))
2650 2650 q.savedirty()
2651 2651 return 0
2652 2652
2653 2653 @command("^qrefresh",
2654 2654 [('e', 'edit', None, _('invoke editor on commit messages')),
2655 2655 ('g', 'git', None, _('use git extended diff format')),
2656 2656 ('s', 'short', None,
2657 2657 _('refresh only files already in the patch and specified files')),
2658 2658 ('U', 'currentuser', None,
2659 2659 _('add/update author field in patch with current user')),
2660 2660 ('u', 'user', '',
2661 2661 _('add/update author field in patch with given user'), _('USER')),
2662 2662 ('D', 'currentdate', None,
2663 2663 _('add/update date field in patch with current date')),
2664 2664 ('d', 'date', '',
2665 2665 _('add/update date field in patch with given date'), _('DATE'))
2666 2666 ] + cmdutil.walkopts + cmdutil.commitopts,
2667 2667 _('hg qrefresh [-I] [-X] [-e] [-m TEXT] [-l FILE] [-s] [FILE]...'),
2668 2668 inferrepo=True)
2669 2669 def refresh(ui, repo, *pats, **opts):
2670 2670 """update the current patch
2671 2671
2672 2672 If any file patterns are provided, the refreshed patch will
2673 2673 contain only the modifications that match those patterns; the
2674 2674 remaining modifications will remain in the working directory.
2675 2675
2676 2676 If -s/--short is specified, files currently included in the patch
2677 2677 will be refreshed just like matched files and remain in the patch.
2678 2678
2679 2679 If -e/--edit is specified, Mercurial will start your configured editor for
2680 2680 you to enter a message. In case qrefresh fails, you will find a backup of
2681 2681 your message in ``.hg/last-message.txt``.
2682 2682
2683 2683 hg add/remove/copy/rename work as usual, though you might want to
2684 2684 use git-style patches (-g/--git or [diff] git=1) to track copies
2685 2685 and renames. See the diffs help topic for more information on the
2686 2686 git diff format.
2687 2687
2688 2688 Returns 0 on success.
2689 2689 """
2690 2690 opts = pycompat.byteskwargs(opts)
2691 2691 q = repo.mq
2692 2692 message = cmdutil.logmessage(ui, opts)
2693 2693 setupheaderopts(ui, opts)
2694 2694 with repo.wlock():
2695 2695 ret = q.refresh(repo, pats, msg=message, **pycompat.strkwargs(opts))
2696 2696 q.savedirty()
2697 2697 return ret
2698 2698
2699 2699 @command("^qdiff",
2700 2700 cmdutil.diffopts + cmdutil.diffopts2 + cmdutil.walkopts,
2701 2701 _('hg qdiff [OPTION]... [FILE]...'),
2702 2702 inferrepo=True)
2703 2703 def diff(ui, repo, *pats, **opts):
2704 2704 """diff of the current patch and subsequent modifications
2705 2705
2706 2706 Shows a diff which includes the current patch as well as any
2707 2707 changes which have been made in the working directory since the
2708 2708 last refresh (thus showing what the current patch would become
2709 2709 after a qrefresh).
2710 2710
2711 2711 Use :hg:`diff` if you only want to see the changes made since the
2712 2712 last qrefresh, or :hg:`export qtip` if you want to see changes
2713 2713 made by the current patch without including changes made since the
2714 2714 qrefresh.
2715 2715
2716 2716 Returns 0 on success.
2717 2717 """
2718 2718 ui.pager('qdiff')
2719 2719 repo.mq.diff(repo, pats, pycompat.byteskwargs(opts))
2720 2720 return 0
2721 2721
2722 2722 @command('qfold',
2723 2723 [('e', 'edit', None, _('invoke editor on commit messages')),
2724 2724 ('k', 'keep', None, _('keep folded patch files')),
2725 2725 ] + cmdutil.commitopts,
2726 2726 _('hg qfold [-e] [-k] [-m TEXT] [-l FILE] PATCH...'))
2727 2727 def fold(ui, repo, *files, **opts):
2728 2728 """fold the named patches into the current patch
2729 2729
2730 2730 Patches must not yet be applied. Each patch will be successively
2731 2731 applied to the current patch in the order given. If all the
2732 2732 patches apply successfully, the current patch will be refreshed
2733 2733 with the new cumulative patch, and the folded patches will be
2734 2734 deleted. With -k/--keep, the folded patch files will not be
2735 2735 removed afterwards.
2736 2736
2737 2737 The header for each folded patch will be concatenated with the
2738 2738 current patch header, separated by a line of ``* * *``.
2739 2739
2740 2740 Returns 0 on success."""
2741 2741 opts = pycompat.byteskwargs(opts)
2742 2742 q = repo.mq
2743 2743 if not files:
2744 2744 raise error.Abort(_('qfold requires at least one patch name'))
2745 2745 if not q.checktoppatch(repo)[0]:
2746 2746 raise error.Abort(_('no patches applied'))
2747 2747 q.checklocalchanges(repo)
2748 2748
2749 2749 message = cmdutil.logmessage(ui, opts)
2750 2750
2751 2751 parent = q.lookup('qtip')
2752 2752 patches = []
2753 2753 messages = []
2754 2754 for f in files:
2755 2755 p = q.lookup(f)
2756 2756 if p in patches or p == parent:
2757 2757 ui.warn(_('skipping already folded patch %s\n') % p)
2758 2758 if q.isapplied(p):
2759 2759 raise error.Abort(_('qfold cannot fold already applied patch %s')
2760 2760 % p)
2761 2761 patches.append(p)
2762 2762
2763 2763 for p in patches:
2764 2764 if not message:
2765 2765 ph = patchheader(q.join(p), q.plainmode)
2766 2766 if ph.message:
2767 2767 messages.append(ph.message)
2768 2768 pf = q.join(p)
2769 2769 (patchsuccess, files, fuzz) = q.patch(repo, pf)
2770 2770 if not patchsuccess:
2771 2771 raise error.Abort(_('error folding patch %s') % p)
2772 2772
2773 2773 if not message:
2774 2774 ph = patchheader(q.join(parent), q.plainmode)
2775 2775 message = ph.message
2776 2776 for msg in messages:
2777 2777 if msg:
2778 2778 if message:
2779 2779 message.append('* * *')
2780 2780 message.extend(msg)
2781 2781 message = '\n'.join(message)
2782 2782
2783 2783 diffopts = q.patchopts(q.diffopts(), *patches)
2784 2784 with repo.wlock():
2785 2785 q.refresh(repo, msg=message, git=diffopts.git, edit=opts.get('edit'),
2786 2786 editform='mq.qfold')
2787 2787 q.delete(repo, patches, opts)
2788 2788 q.savedirty()
2789 2789
2790 2790 @command("qgoto",
2791 2791 [('', 'keep-changes', None,
2792 2792 _('tolerate non-conflicting local changes')),
2793 2793 ('f', 'force', None, _('overwrite any local changes')),
2794 2794 ('', 'no-backup', None, _('do not save backup copies of files'))],
2795 2795 _('hg qgoto [OPTION]... PATCH'))
2796 2796 def goto(ui, repo, patch, **opts):
2797 2797 '''push or pop patches until named patch is at top of stack
2798 2798
2799 2799 Returns 0 on success.'''
2800 2800 opts = pycompat.byteskwargs(opts)
2801 2801 opts = fixkeepchangesopts(ui, opts)
2802 2802 q = repo.mq
2803 2803 patch = q.lookup(patch)
2804 2804 nobackup = opts.get('no_backup')
2805 2805 keepchanges = opts.get('keep_changes')
2806 2806 if q.isapplied(patch):
2807 2807 ret = q.pop(repo, patch, force=opts.get('force'), nobackup=nobackup,
2808 2808 keepchanges=keepchanges)
2809 2809 else:
2810 2810 ret = q.push(repo, patch, force=opts.get('force'), nobackup=nobackup,
2811 2811 keepchanges=keepchanges)
2812 2812 q.savedirty()
2813 2813 return ret
2814 2814
2815 2815 @command("qguard",
2816 2816 [('l', 'list', None, _('list all patches and guards')),
2817 2817 ('n', 'none', None, _('drop all guards'))],
2818 2818 _('hg qguard [-l] [-n] [PATCH] [-- [+GUARD]... [-GUARD]...]'))
2819 2819 def guard(ui, repo, *args, **opts):
2820 2820 '''set or print guards for a patch
2821 2821
2822 2822 Guards control whether a patch can be pushed. A patch with no
2823 2823 guards is always pushed. A patch with a positive guard ("+foo") is
2824 2824 pushed only if the :hg:`qselect` command has activated it. A patch with
2825 2825 a negative guard ("-foo") is never pushed if the :hg:`qselect` command
2826 2826 has activated it.
2827 2827
2828 2828 With no arguments, print the currently active guards.
2829 2829 With arguments, set guards for the named patch.
2830 2830
2831 2831 .. note::
2832 2832
2833 2833 Specifying negative guards now requires '--'.
2834 2834
2835 2835 To set guards on another patch::
2836 2836
2837 2837 hg qguard other.patch -- +2.6.17 -stable
2838 2838
2839 2839 Returns 0 on success.
2840 2840 '''
2841 2841 def status(idx):
2842 2842 guards = q.seriesguards[idx] or ['unguarded']
2843 2843 if q.series[idx] in applied:
2844 2844 state = 'applied'
2845 2845 elif q.pushable(idx)[0]:
2846 2846 state = 'unapplied'
2847 2847 else:
2848 2848 state = 'guarded'
2849 2849 label = 'qguard.patch qguard.%s qseries.%s' % (state, state)
2850 2850 ui.write('%s: ' % ui.label(q.series[idx], label))
2851 2851
2852 2852 for i, guard in enumerate(guards):
2853 2853 if guard.startswith('+'):
2854 2854 ui.write(guard, label='qguard.positive')
2855 2855 elif guard.startswith('-'):
2856 2856 ui.write(guard, label='qguard.negative')
2857 2857 else:
2858 2858 ui.write(guard, label='qguard.unguarded')
2859 2859 if i != len(guards) - 1:
2860 2860 ui.write(' ')
2861 2861 ui.write('\n')
2862 2862 q = repo.mq
2863 2863 applied = set(p.name for p in q.applied)
2864 2864 patch = None
2865 2865 args = list(args)
2866 2866 if opts.get(r'list'):
2867 2867 if args or opts.get('none'):
2868 2868 raise error.Abort(_('cannot mix -l/--list with options or '
2869 2869 'arguments'))
2870 2870 for i in xrange(len(q.series)):
2871 2871 status(i)
2872 2872 return
2873 2873 if not args or args[0][0:1] in '-+':
2874 2874 if not q.applied:
2875 2875 raise error.Abort(_('no patches applied'))
2876 2876 patch = q.applied[-1].name
2877 2877 if patch is None and args[0][0:1] not in '-+':
2878 2878 patch = args.pop(0)
2879 2879 if patch is None:
2880 2880 raise error.Abort(_('no patch to work with'))
2881 2881 if args or opts.get('none'):
2882 2882 idx = q.findseries(patch)
2883 2883 if idx is None:
2884 2884 raise error.Abort(_('no patch named %s') % patch)
2885 2885 q.setguards(idx, args)
2886 2886 q.savedirty()
2887 2887 else:
2888 2888 status(q.series.index(q.lookup(patch)))
2889 2889
2890 2890 @command("qheader", [], _('hg qheader [PATCH]'))
2891 2891 def header(ui, repo, patch=None):
2892 2892 """print the header of the topmost or specified patch
2893 2893
2894 2894 Returns 0 on success."""
2895 2895 q = repo.mq
2896 2896
2897 2897 if patch:
2898 2898 patch = q.lookup(patch)
2899 2899 else:
2900 2900 if not q.applied:
2901 2901 ui.write(_('no patches applied\n'))
2902 2902 return 1
2903 2903 patch = q.lookup('qtip')
2904 2904 ph = patchheader(q.join(patch), q.plainmode)
2905 2905
2906 2906 ui.write('\n'.join(ph.message) + '\n')
2907 2907
2908 2908 def lastsavename(path):
2909 2909 (directory, base) = os.path.split(path)
2910 2910 names = os.listdir(directory)
2911 2911 namere = re.compile("%s.([0-9]+)" % base)
2912 2912 maxindex = None
2913 2913 maxname = None
2914 2914 for f in names:
2915 2915 m = namere.match(f)
2916 2916 if m:
2917 2917 index = int(m.group(1))
2918 2918 if maxindex is None or index > maxindex:
2919 2919 maxindex = index
2920 2920 maxname = f
2921 2921 if maxname:
2922 2922 return (os.path.join(directory, maxname), maxindex)
2923 2923 return (None, None)
2924 2924
2925 2925 def savename(path):
2926 2926 (last, index) = lastsavename(path)
2927 2927 if last is None:
2928 2928 index = 0
2929 2929 newpath = path + ".%d" % (index + 1)
2930 2930 return newpath
2931 2931
2932 2932 @command("^qpush",
2933 2933 [('', 'keep-changes', None,
2934 2934 _('tolerate non-conflicting local changes')),
2935 2935 ('f', 'force', None, _('apply on top of local changes')),
2936 2936 ('e', 'exact', None,
2937 2937 _('apply the target patch to its recorded parent')),
2938 2938 ('l', 'list', None, _('list patch name in commit text')),
2939 2939 ('a', 'all', None, _('apply all patches')),
2940 2940 ('m', 'merge', None, _('merge from another queue (DEPRECATED)')),
2941 2941 ('n', 'name', '',
2942 2942 _('merge queue name (DEPRECATED)'), _('NAME')),
2943 2943 ('', 'move', None,
2944 2944 _('reorder patch series and apply only the patch')),
2945 2945 ('', 'no-backup', None, _('do not save backup copies of files'))],
2946 2946 _('hg qpush [-f] [-l] [-a] [--move] [PATCH | INDEX]'))
2947 2947 def push(ui, repo, patch=None, **opts):
2948 2948 """push the next patch onto the stack
2949 2949
2950 2950 By default, abort if the working directory contains uncommitted
2951 2951 changes. With --keep-changes, abort only if the uncommitted files
2952 2952 overlap with patched files. With -f/--force, backup and patch over
2953 2953 uncommitted changes.
2954 2954
2955 2955 Return 0 on success.
2956 2956 """
2957 2957 q = repo.mq
2958 2958 mergeq = None
2959 2959
2960 2960 opts = pycompat.byteskwargs(opts)
2961 2961 opts = fixkeepchangesopts(ui, opts)
2962 2962 if opts.get('merge'):
2963 2963 if opts.get('name'):
2964 2964 newpath = repo.vfs.join(opts.get('name'))
2965 2965 else:
2966 2966 newpath, i = lastsavename(q.path)
2967 2967 if not newpath:
2968 2968 ui.warn(_("no saved queues found, please use -n\n"))
2969 2969 return 1
2970 2970 mergeq = queue(ui, repo.baseui, repo.path, newpath)
2971 2971 ui.warn(_("merging with queue at: %s\n") % mergeq.path)
2972 2972 ret = q.push(repo, patch, force=opts.get('force'), list=opts.get('list'),
2973 2973 mergeq=mergeq, all=opts.get('all'), move=opts.get('move'),
2974 2974 exact=opts.get('exact'), nobackup=opts.get('no_backup'),
2975 2975 keepchanges=opts.get('keep_changes'))
2976 2976 return ret
2977 2977
2978 2978 @command("^qpop",
2979 2979 [('a', 'all', None, _('pop all patches')),
2980 2980 ('n', 'name', '',
2981 2981 _('queue name to pop (DEPRECATED)'), _('NAME')),
2982 2982 ('', 'keep-changes', None,
2983 2983 _('tolerate non-conflicting local changes')),
2984 2984 ('f', 'force', None, _('forget any local changes to patched files')),
2985 2985 ('', 'no-backup', None, _('do not save backup copies of files'))],
2986 2986 _('hg qpop [-a] [-f] [PATCH | INDEX]'))
2987 2987 def pop(ui, repo, patch=None, **opts):
2988 2988 """pop the current patch off the stack
2989 2989
2990 2990 Without argument, pops off the top of the patch stack. If given a
2991 2991 patch name, keeps popping off patches until the named patch is at
2992 2992 the top of the stack.
2993 2993
2994 2994 By default, abort if the working directory contains uncommitted
2995 2995 changes. With --keep-changes, abort only if the uncommitted files
2996 2996 overlap with patched files. With -f/--force, backup and discard
2997 2997 changes made to such files.
2998 2998
2999 2999 Return 0 on success.
3000 3000 """
3001 3001 opts = pycompat.byteskwargs(opts)
3002 3002 opts = fixkeepchangesopts(ui, opts)
3003 3003 localupdate = True
3004 3004 if opts.get('name'):
3005 3005 q = queue(ui, repo.baseui, repo.path, repo.vfs.join(opts.get('name')))
3006 3006 ui.warn(_('using patch queue: %s\n') % q.path)
3007 3007 localupdate = False
3008 3008 else:
3009 3009 q = repo.mq
3010 3010 ret = q.pop(repo, patch, force=opts.get('force'), update=localupdate,
3011 3011 all=opts.get('all'), nobackup=opts.get('no_backup'),
3012 3012 keepchanges=opts.get('keep_changes'))
3013 3013 q.savedirty()
3014 3014 return ret
3015 3015
3016 3016 @command("qrename|qmv", [], _('hg qrename PATCH1 [PATCH2]'))
3017 3017 def rename(ui, repo, patch, name=None, **opts):
3018 3018 """rename a patch
3019 3019
3020 3020 With one argument, renames the current patch to PATCH1.
3021 3021 With two arguments, renames PATCH1 to PATCH2.
3022 3022
3023 3023 Returns 0 on success."""
3024 3024 q = repo.mq
3025 3025 if not name:
3026 3026 name = patch
3027 3027 patch = None
3028 3028
3029 3029 if patch:
3030 3030 patch = q.lookup(patch)
3031 3031 else:
3032 3032 if not q.applied:
3033 3033 ui.write(_('no patches applied\n'))
3034 3034 return
3035 3035 patch = q.lookup('qtip')
3036 3036 absdest = q.join(name)
3037 3037 if os.path.isdir(absdest):
3038 3038 name = normname(os.path.join(name, os.path.basename(patch)))
3039 3039 absdest = q.join(name)
3040 3040 q.checkpatchname(name)
3041 3041
3042 3042 ui.note(_('renaming %s to %s\n') % (patch, name))
3043 3043 i = q.findseries(patch)
3044 3044 guards = q.guard_re.findall(q.fullseries[i])
3045 3045 q.fullseries[i] = name + ''.join([' #' + g for g in guards])
3046 3046 q.parseseries()
3047 3047 q.seriesdirty = True
3048 3048
3049 3049 info = q.isapplied(patch)
3050 3050 if info:
3051 3051 q.applied[info[0]] = statusentry(info[1], name)
3052 3052 q.applieddirty = True
3053 3053
3054 3054 destdir = os.path.dirname(absdest)
3055 3055 if not os.path.isdir(destdir):
3056 3056 os.makedirs(destdir)
3057 3057 util.rename(q.join(patch), absdest)
3058 3058 r = q.qrepo()
3059 3059 if r and patch in r.dirstate:
3060 3060 wctx = r[None]
3061 3061 with r.wlock():
3062 3062 if r.dirstate[patch] == 'a':
3063 3063 r.dirstate.drop(patch)
3064 3064 r.dirstate.add(name)
3065 3065 else:
3066 3066 wctx.copy(patch, name)
3067 3067 wctx.forget([patch])
3068 3068
3069 3069 q.savedirty()
3070 3070
3071 3071 @command("qrestore",
3072 3072 [('d', 'delete', None, _('delete save entry')),
3073 3073 ('u', 'update', None, _('update queue working directory'))],
3074 3074 _('hg qrestore [-d] [-u] REV'))
3075 3075 def restore(ui, repo, rev, **opts):
3076 3076 """restore the queue state saved by a revision (DEPRECATED)
3077 3077
3078 3078 This command is deprecated, use :hg:`rebase` instead."""
3079 3079 rev = repo.lookup(rev)
3080 3080 q = repo.mq
3081 3081 q.restore(repo, rev, delete=opts.get(r'delete'),
3082 3082 qupdate=opts.get(r'update'))
3083 3083 q.savedirty()
3084 3084 return 0
3085 3085
3086 3086 @command("qsave",
3087 3087 [('c', 'copy', None, _('copy patch directory')),
3088 3088 ('n', 'name', '',
3089 3089 _('copy directory name'), _('NAME')),
3090 3090 ('e', 'empty', None, _('clear queue status file')),
3091 3091 ('f', 'force', None, _('force copy'))] + cmdutil.commitopts,
3092 3092 _('hg qsave [-m TEXT] [-l FILE] [-c] [-n NAME] [-e] [-f]'))
3093 3093 def save(ui, repo, **opts):
3094 3094 """save current queue state (DEPRECATED)
3095 3095
3096 3096 This command is deprecated, use :hg:`rebase` instead."""
3097 3097 q = repo.mq
3098 3098 opts = pycompat.byteskwargs(opts)
3099 3099 message = cmdutil.logmessage(ui, opts)
3100 3100 ret = q.save(repo, msg=message)
3101 3101 if ret:
3102 3102 return ret
3103 3103 q.savedirty() # save to .hg/patches before copying
3104 3104 if opts.get('copy'):
3105 3105 path = q.path
3106 3106 if opts.get('name'):
3107 3107 newpath = os.path.join(q.basepath, opts.get('name'))
3108 3108 if os.path.exists(newpath):
3109 3109 if not os.path.isdir(newpath):
3110 3110 raise error.Abort(_('destination %s exists and is not '
3111 3111 'a directory') % newpath)
3112 3112 if not opts.get('force'):
3113 3113 raise error.Abort(_('destination %s exists, '
3114 3114 'use -f to force') % newpath)
3115 3115 else:
3116 3116 newpath = savename(path)
3117 3117 ui.warn(_("copy %s to %s\n") % (path, newpath))
3118 3118 util.copyfiles(path, newpath)
3119 3119 if opts.get('empty'):
3120 3120 del q.applied[:]
3121 3121 q.applieddirty = True
3122 3122 q.savedirty()
3123 3123 return 0
3124 3124
3125 3125
3126 3126 @command("qselect",
3127 3127 [('n', 'none', None, _('disable all guards')),
3128 3128 ('s', 'series', None, _('list all guards in series file')),
3129 3129 ('', 'pop', None, _('pop to before first guarded applied patch')),
3130 3130 ('', 'reapply', None, _('pop, then reapply patches'))],
3131 3131 _('hg qselect [OPTION]... [GUARD]...'))
3132 3132 def select(ui, repo, *args, **opts):
3133 3133 '''set or print guarded patches to push
3134 3134
3135 3135 Use the :hg:`qguard` command to set or print guards on patch, then use
3136 3136 qselect to tell mq which guards to use. A patch will be pushed if
3137 3137 it has no guards or any positive guards match the currently
3138 3138 selected guard, but will not be pushed if any negative guards
3139 3139 match the current guard. For example::
3140 3140
3141 3141 qguard foo.patch -- -stable (negative guard)
3142 3142 qguard bar.patch +stable (positive guard)
3143 3143 qselect stable
3144 3144
3145 3145 This activates the "stable" guard. mq will skip foo.patch (because
3146 3146 it has a negative match) but push bar.patch (because it has a
3147 3147 positive match).
3148 3148
3149 3149 With no arguments, prints the currently active guards.
3150 3150 With one argument, sets the active guard.
3151 3151
3152 3152 Use -n/--none to deactivate guards (no other arguments needed).
3153 3153 When no guards are active, patches with positive guards are
3154 3154 skipped and patches with negative guards are pushed.
3155 3155
3156 3156 qselect can change the guards on applied patches. It does not pop
3157 3157 guarded patches by default. Use --pop to pop back to the last
3158 3158 applied patch that is not guarded. Use --reapply (which implies
3159 3159 --pop) to push back to the current patch afterwards, but skip
3160 3160 guarded patches.
3161 3161
3162 3162 Use -s/--series to print a list of all guards in the series file
3163 3163 (no other arguments needed). Use -v for more information.
3164 3164
3165 3165 Returns 0 on success.'''
3166 3166
3167 3167 q = repo.mq
3168 3168 opts = pycompat.byteskwargs(opts)
3169 3169 guards = q.active()
3170 3170 pushable = lambda i: q.pushable(q.applied[i].name)[0]
3171 3171 if args or opts.get('none'):
3172 3172 old_unapplied = q.unapplied(repo)
3173 3173 old_guarded = [i for i in xrange(len(q.applied)) if not pushable(i)]
3174 3174 q.setactive(args)
3175 3175 q.savedirty()
3176 3176 if not args:
3177 3177 ui.status(_('guards deactivated\n'))
3178 3178 if not opts.get('pop') and not opts.get('reapply'):
3179 3179 unapplied = q.unapplied(repo)
3180 3180 guarded = [i for i in xrange(len(q.applied)) if not pushable(i)]
3181 3181 if len(unapplied) != len(old_unapplied):
3182 3182 ui.status(_('number of unguarded, unapplied patches has '
3183 3183 'changed from %d to %d\n') %
3184 3184 (len(old_unapplied), len(unapplied)))
3185 3185 if len(guarded) != len(old_guarded):
3186 3186 ui.status(_('number of guarded, applied patches has changed '
3187 3187 'from %d to %d\n') %
3188 3188 (len(old_guarded), len(guarded)))
3189 3189 elif opts.get('series'):
3190 3190 guards = {}
3191 3191 noguards = 0
3192 3192 for gs in q.seriesguards:
3193 3193 if not gs:
3194 3194 noguards += 1
3195 3195 for g in gs:
3196 3196 guards.setdefault(g, 0)
3197 3197 guards[g] += 1
3198 3198 if ui.verbose:
3199 3199 guards['NONE'] = noguards
3200 3200 guards = list(guards.items())
3201 3201 guards.sort(key=lambda x: x[0][1:])
3202 3202 if guards:
3203 3203 ui.note(_('guards in series file:\n'))
3204 3204 for guard, count in guards:
3205 3205 ui.note('%2d ' % count)
3206 3206 ui.write(guard, '\n')
3207 3207 else:
3208 3208 ui.note(_('no guards in series file\n'))
3209 3209 else:
3210 3210 if guards:
3211 3211 ui.note(_('active guards:\n'))
3212 3212 for g in guards:
3213 3213 ui.write(g, '\n')
3214 3214 else:
3215 3215 ui.write(_('no active guards\n'))
3216 3216 reapply = opts.get('reapply') and q.applied and q.applied[-1].name
3217 3217 popped = False
3218 3218 if opts.get('pop') or opts.get('reapply'):
3219 3219 for i in xrange(len(q.applied)):
3220 3220 if not pushable(i):
3221 3221 ui.status(_('popping guarded patches\n'))
3222 3222 popped = True
3223 3223 if i == 0:
3224 3224 q.pop(repo, all=True)
3225 3225 else:
3226 3226 q.pop(repo, q.applied[i - 1].name)
3227 3227 break
3228 3228 if popped:
3229 3229 try:
3230 3230 if reapply:
3231 3231 ui.status(_('reapplying unguarded patches\n'))
3232 3232 q.push(repo, reapply)
3233 3233 finally:
3234 3234 q.savedirty()
3235 3235
3236 3236 @command("qfinish",
3237 3237 [('a', 'applied', None, _('finish all applied changesets'))],
3238 3238 _('hg qfinish [-a] [REV]...'))
3239 3239 def finish(ui, repo, *revrange, **opts):
3240 3240 """move applied patches into repository history
3241 3241
3242 3242 Finishes the specified revisions (corresponding to applied
3243 3243 patches) by moving them out of mq control into regular repository
3244 3244 history.
3245 3245
3246 3246 Accepts a revision range or the -a/--applied option. If --applied
3247 3247 is specified, all applied mq revisions are removed from mq
3248 3248 control. Otherwise, the given revisions must be at the base of the
3249 3249 stack of applied patches.
3250 3250
3251 3251 This can be especially useful if your changes have been applied to
3252 3252 an upstream repository, or if you are about to push your changes
3253 3253 to upstream.
3254 3254
3255 3255 Returns 0 on success.
3256 3256 """
3257 3257 if not opts.get(r'applied') and not revrange:
3258 3258 raise error.Abort(_('no revisions specified'))
3259 3259 elif opts.get(r'applied'):
3260 3260 revrange = ('qbase::qtip',) + revrange
3261 3261
3262 3262 q = repo.mq
3263 3263 if not q.applied:
3264 3264 ui.status(_('no patches applied\n'))
3265 3265 return 0
3266 3266
3267 3267 revs = scmutil.revrange(repo, revrange)
3268 3268 if repo['.'].rev() in revs and repo[None].files():
3269 3269 ui.warn(_('warning: uncommitted changes in the working directory\n'))
3270 3270 # queue.finish may changes phases but leave the responsibility to lock the
3271 3271 # repo to the caller to avoid deadlock with wlock. This command code is
3272 3272 # responsibility for this locking.
3273 3273 with repo.lock():
3274 3274 q.finish(repo, revs)
3275 3275 q.savedirty()
3276 3276 return 0
3277 3277
3278 3278 @command("qqueue",
3279 3279 [('l', 'list', False, _('list all available queues')),
3280 3280 ('', 'active', False, _('print name of active queue')),
3281 3281 ('c', 'create', False, _('create new queue')),
3282 3282 ('', 'rename', False, _('rename active queue')),
3283 3283 ('', 'delete', False, _('delete reference to queue')),
3284 3284 ('', 'purge', False, _('delete queue, and remove patch dir')),
3285 3285 ],
3286 3286 _('[OPTION] [QUEUE]'))
3287 3287 def qqueue(ui, repo, name=None, **opts):
3288 3288 '''manage multiple patch queues
3289 3289
3290 3290 Supports switching between different patch queues, as well as creating
3291 3291 new patch queues and deleting existing ones.
3292 3292
3293 3293 Omitting a queue name or specifying -l/--list will show you the registered
3294 3294 queues - by default the "normal" patches queue is registered. The currently
3295 3295 active queue will be marked with "(active)". Specifying --active will print
3296 3296 only the name of the active queue.
3297 3297
3298 3298 To create a new queue, use -c/--create. The queue is automatically made
3299 3299 active, except in the case where there are applied patches from the
3300 3300 currently active queue in the repository. Then the queue will only be
3301 3301 created and switching will fail.
3302 3302
3303 3303 To delete an existing queue, use --delete. You cannot delete the currently
3304 3304 active queue.
3305 3305
3306 3306 Returns 0 on success.
3307 3307 '''
3308 3308 q = repo.mq
3309 3309 _defaultqueue = 'patches'
3310 3310 _allqueues = 'patches.queues'
3311 3311 _activequeue = 'patches.queue'
3312 3312
3313 3313 def _getcurrent():
3314 3314 cur = os.path.basename(q.path)
3315 3315 if cur.startswith('patches-'):
3316 3316 cur = cur[8:]
3317 3317 return cur
3318 3318
3319 3319 def _noqueues():
3320 3320 try:
3321 3321 fh = repo.vfs(_allqueues, 'r')
3322 3322 fh.close()
3323 3323 except IOError:
3324 3324 return True
3325 3325
3326 3326 return False
3327 3327
3328 3328 def _getqueues():
3329 3329 current = _getcurrent()
3330 3330
3331 3331 try:
3332 3332 fh = repo.vfs(_allqueues, 'r')
3333 3333 queues = [queue.strip() for queue in fh if queue.strip()]
3334 3334 fh.close()
3335 3335 if current not in queues:
3336 3336 queues.append(current)
3337 3337 except IOError:
3338 3338 queues = [_defaultqueue]
3339 3339
3340 3340 return sorted(queues)
3341 3341
3342 3342 def _setactive(name):
3343 3343 if q.applied:
3344 3344 raise error.Abort(_('new queue created, but cannot make active '
3345 3345 'as patches are applied'))
3346 3346 _setactivenocheck(name)
3347 3347
3348 3348 def _setactivenocheck(name):
3349 3349 fh = repo.vfs(_activequeue, 'w')
3350 3350 if name != 'patches':
3351 3351 fh.write(name)
3352 3352 fh.close()
3353 3353
3354 3354 def _addqueue(name):
3355 3355 fh = repo.vfs(_allqueues, 'a')
3356 3356 fh.write('%s\n' % (name,))
3357 3357 fh.close()
3358 3358
3359 3359 def _queuedir(name):
3360 3360 if name == 'patches':
3361 3361 return repo.vfs.join('patches')
3362 3362 else:
3363 3363 return repo.vfs.join('patches-' + name)
3364 3364
3365 3365 def _validname(name):
3366 3366 for n in name:
3367 3367 if n in ':\\/.':
3368 3368 return False
3369 3369 return True
3370 3370
3371 3371 def _delete(name):
3372 3372 if name not in existing:
3373 3373 raise error.Abort(_('cannot delete queue that does not exist'))
3374 3374
3375 3375 current = _getcurrent()
3376 3376
3377 3377 if name == current:
3378 3378 raise error.Abort(_('cannot delete currently active queue'))
3379 3379
3380 3380 fh = repo.vfs('patches.queues.new', 'w')
3381 3381 for queue in existing:
3382 3382 if queue == name:
3383 3383 continue
3384 3384 fh.write('%s\n' % (queue,))
3385 3385 fh.close()
3386 3386 repo.vfs.rename('patches.queues.new', _allqueues)
3387 3387
3388 3388 opts = pycompat.byteskwargs(opts)
3389 3389 if not name or opts.get('list') or opts.get('active'):
3390 3390 current = _getcurrent()
3391 3391 if opts.get('active'):
3392 3392 ui.write('%s\n' % (current,))
3393 3393 return
3394 3394 for queue in _getqueues():
3395 3395 ui.write('%s' % (queue,))
3396 3396 if queue == current and not ui.quiet:
3397 3397 ui.write(_(' (active)\n'))
3398 3398 else:
3399 3399 ui.write('\n')
3400 3400 return
3401 3401
3402 3402 if not _validname(name):
3403 3403 raise error.Abort(
3404 3404 _('invalid queue name, may not contain the characters ":\\/."'))
3405 3405
3406 3406 with repo.wlock():
3407 3407 existing = _getqueues()
3408 3408
3409 3409 if opts.get('create'):
3410 3410 if name in existing:
3411 3411 raise error.Abort(_('queue "%s" already exists') % name)
3412 3412 if _noqueues():
3413 3413 _addqueue(_defaultqueue)
3414 3414 _addqueue(name)
3415 3415 _setactive(name)
3416 3416 elif opts.get('rename'):
3417 3417 current = _getcurrent()
3418 3418 if name == current:
3419 3419 raise error.Abort(_('can\'t rename "%s" to its current name')
3420 3420 % name)
3421 3421 if name in existing:
3422 3422 raise error.Abort(_('queue "%s" already exists') % name)
3423 3423
3424 3424 olddir = _queuedir(current)
3425 3425 newdir = _queuedir(name)
3426 3426
3427 3427 if os.path.exists(newdir):
3428 3428 raise error.Abort(_('non-queue directory "%s" already exists') %
3429 3429 newdir)
3430 3430
3431 3431 fh = repo.vfs('patches.queues.new', 'w')
3432 3432 for queue in existing:
3433 3433 if queue == current:
3434 3434 fh.write('%s\n' % (name,))
3435 3435 if os.path.exists(olddir):
3436 3436 util.rename(olddir, newdir)
3437 3437 else:
3438 3438 fh.write('%s\n' % (queue,))
3439 3439 fh.close()
3440 3440 repo.vfs.rename('patches.queues.new', _allqueues)
3441 3441 _setactivenocheck(name)
3442 3442 elif opts.get('delete'):
3443 3443 _delete(name)
3444 3444 elif opts.get('purge'):
3445 3445 if name in existing:
3446 3446 _delete(name)
3447 3447 qdir = _queuedir(name)
3448 3448 if os.path.exists(qdir):
3449 3449 shutil.rmtree(qdir)
3450 3450 else:
3451 3451 if name not in existing:
3452 3452 raise error.Abort(_('use --create to create a new queue'))
3453 3453 _setactive(name)
3454 3454
3455 3455 def mqphasedefaults(repo, roots):
3456 3456 """callback used to set mq changeset as secret when no phase data exists"""
3457 3457 if repo.mq.applied:
3458 3458 if repo.ui.configbool('mq', 'secret'):
3459 3459 mqphase = phases.secret
3460 3460 else:
3461 3461 mqphase = phases.draft
3462 3462 qbase = repo[repo.mq.applied[0].node]
3463 3463 roots[mqphase].add(qbase.node())
3464 3464 return roots
3465 3465
3466 3466 def reposetup(ui, repo):
3467 3467 class mqrepo(repo.__class__):
3468 3468 @localrepo.unfilteredpropertycache
3469 3469 def mq(self):
3470 3470 return queue(self.ui, self.baseui, self.path)
3471 3471
3472 3472 def invalidateall(self):
3473 3473 super(mqrepo, self).invalidateall()
3474 3474 if localrepo.hasunfilteredcache(self, 'mq'):
3475 3475 # recreate mq in case queue path was changed
3476 3476 delattr(self.unfiltered(), 'mq')
3477 3477
3478 3478 def abortifwdirpatched(self, errmsg, force=False):
3479 3479 if self.mq.applied and self.mq.checkapplied and not force:
3480 3480 parents = self.dirstate.parents()
3481 3481 patches = [s.node for s in self.mq.applied]
3482 3482 if parents[0] in patches or parents[1] in patches:
3483 3483 raise error.Abort(errmsg)
3484 3484
3485 3485 def commit(self, text="", user=None, date=None, match=None,
3486 3486 force=False, editor=False, extra=None):
3487 3487 if extra is None:
3488 3488 extra = {}
3489 3489 self.abortifwdirpatched(
3490 3490 _('cannot commit over an applied mq patch'),
3491 3491 force)
3492 3492
3493 3493 return super(mqrepo, self).commit(text, user, date, match, force,
3494 3494 editor, extra)
3495 3495
3496 3496 def checkpush(self, pushop):
3497 3497 if self.mq.applied and self.mq.checkapplied and not pushop.force:
3498 3498 outapplied = [e.node for e in self.mq.applied]
3499 3499 if pushop.revs:
3500 3500 # Assume applied patches have no non-patch descendants and
3501 3501 # are not on remote already. Filtering any changeset not
3502 3502 # pushed.
3503 3503 heads = set(pushop.revs)
3504 3504 for node in reversed(outapplied):
3505 3505 if node in heads:
3506 3506 break
3507 3507 else:
3508 3508 outapplied.pop()
3509 3509 # looking for pushed and shared changeset
3510 3510 for node in outapplied:
3511 3511 if self[node].phase() < phases.secret:
3512 3512 raise error.Abort(_('source has mq patches applied'))
3513 3513 # no non-secret patches pushed
3514 3514 super(mqrepo, self).checkpush(pushop)
3515 3515
3516 3516 def _findtags(self):
3517 3517 '''augment tags from base class with patch tags'''
3518 3518 result = super(mqrepo, self)._findtags()
3519 3519
3520 3520 q = self.mq
3521 3521 if not q.applied:
3522 3522 return result
3523 3523
3524 3524 mqtags = [(patch.node, patch.name) for patch in q.applied]
3525 3525
3526 3526 try:
3527 3527 # for now ignore filtering business
3528 3528 self.unfiltered().changelog.rev(mqtags[-1][0])
3529 3529 except error.LookupError:
3530 3530 self.ui.warn(_('mq status file refers to unknown node %s\n')
3531 3531 % short(mqtags[-1][0]))
3532 3532 return result
3533 3533
3534 3534 # do not add fake tags for filtered revisions
3535 3535 included = self.changelog.hasnode
3536 3536 mqtags = [mqt for mqt in mqtags if included(mqt[0])]
3537 3537 if not mqtags:
3538 3538 return result
3539 3539
3540 3540 mqtags.append((mqtags[-1][0], 'qtip'))
3541 3541 mqtags.append((mqtags[0][0], 'qbase'))
3542 3542 mqtags.append((self.changelog.parents(mqtags[0][0])[0], 'qparent'))
3543 3543 tags = result[0]
3544 3544 for patch in mqtags:
3545 3545 if patch[1] in tags:
3546 3546 self.ui.warn(_('tag %s overrides mq patch of the same '
3547 3547 'name\n') % patch[1])
3548 3548 else:
3549 3549 tags[patch[1]] = patch[0]
3550 3550
3551 3551 return result
3552 3552
3553 3553 if repo.local():
3554 3554 repo.__class__ = mqrepo
3555 3555
3556 3556 repo._phasedefaults.append(mqphasedefaults)
3557 3557
3558 3558 def mqimport(orig, ui, repo, *args, **kwargs):
3559 3559 if (util.safehasattr(repo, 'abortifwdirpatched')
3560 3560 and not kwargs.get(r'no_commit', False)):
3561 3561 repo.abortifwdirpatched(_('cannot import over an applied patch'),
3562 3562 kwargs.get(r'force'))
3563 3563 return orig(ui, repo, *args, **kwargs)
3564 3564
3565 3565 def mqinit(orig, ui, *args, **kwargs):
3566 3566 mq = kwargs.pop(r'mq', None)
3567 3567
3568 3568 if not mq:
3569 3569 return orig(ui, *args, **kwargs)
3570 3570
3571 3571 if args:
3572 3572 repopath = args[0]
3573 3573 if not hg.islocal(repopath):
3574 3574 raise error.Abort(_('only a local queue repository '
3575 3575 'may be initialized'))
3576 3576 else:
3577 3577 repopath = cmdutil.findrepo(pycompat.getcwd())
3578 3578 if not repopath:
3579 3579 raise error.Abort(_('there is no Mercurial repository here '
3580 3580 '(.hg not found)'))
3581 3581 repo = hg.repository(ui, repopath)
3582 3582 return qinit(ui, repo, True)
3583 3583
3584 3584 def mqcommand(orig, ui, repo, *args, **kwargs):
3585 3585 """Add --mq option to operate on patch repository instead of main"""
3586 3586
3587 3587 # some commands do not like getting unknown options
3588 3588 mq = kwargs.pop(r'mq', None)
3589 3589
3590 3590 if not mq:
3591 3591 return orig(ui, repo, *args, **kwargs)
3592 3592
3593 3593 q = repo.mq
3594 3594 r = q.qrepo()
3595 3595 if not r:
3596 3596 raise error.Abort(_('no queue repository'))
3597 3597 return orig(r.ui, r, *args, **kwargs)
3598 3598
3599 3599 def summaryhook(ui, repo):
3600 3600 q = repo.mq
3601 3601 m = []
3602 3602 a, u = len(q.applied), len(q.unapplied(repo))
3603 3603 if a:
3604 3604 m.append(ui.label(_("%d applied"), 'qseries.applied') % a)
3605 3605 if u:
3606 3606 m.append(ui.label(_("%d unapplied"), 'qseries.unapplied') % u)
3607 3607 if m:
3608 3608 # i18n: column positioning for "hg summary"
3609 3609 ui.write(_("mq: %s\n") % ', '.join(m))
3610 3610 else:
3611 3611 # i18n: column positioning for "hg summary"
3612 3612 ui.note(_("mq: (empty queue)\n"))
3613 3613
3614 3614 revsetpredicate = registrar.revsetpredicate()
3615 3615
3616 3616 @revsetpredicate('mq()')
3617 3617 def revsetmq(repo, subset, x):
3618 3618 """Changesets managed by MQ.
3619 3619 """
3620 3620 revsetlang.getargs(x, 0, 0, _("mq takes no arguments"))
3621 3621 applied = set([repo[r.node].rev() for r in repo.mq.applied])
3622 3622 return smartset.baseset([r for r in subset if r in applied])
3623 3623
3624 3624 # tell hggettext to extract docstrings from these functions:
3625 3625 i18nfunctions = [revsetmq]
3626 3626
3627 3627 def extsetup(ui):
3628 3628 # Ensure mq wrappers are called first, regardless of extension load order by
3629 3629 # NOT wrapping in uisetup() and instead deferring to init stage two here.
3630 3630 mqopt = [('', 'mq', None, _("operate on patch repository"))]
3631 3631
3632 3632 extensions.wrapcommand(commands.table, 'import', mqimport)
3633 3633 cmdutil.summaryhooks.add('mq', summaryhook)
3634 3634
3635 3635 entry = extensions.wrapcommand(commands.table, 'init', mqinit)
3636 3636 entry[1].extend(mqopt)
3637 3637
3638 3638 def dotable(cmdtable):
3639 3639 for cmd, entry in cmdtable.iteritems():
3640 3640 cmd = cmdutil.parsealiases(cmd)[0]
3641 3641 func = entry[0]
3642 3642 if func.norepo:
3643 3643 continue
3644 3644 entry = extensions.wrapcommand(cmdtable, cmd, mqcommand)
3645 3645 entry[1].extend(mqopt)
3646 3646
3647 3647 dotable(commands.table)
3648 3648
3649 3649 for extname, extmodule in extensions.extensions():
3650 3650 if extmodule.__file__ != __file__:
3651 3651 dotable(getattr(extmodule, 'cmdtable', {}))
3652 3652
3653 3653 colortable = {'qguard.negative': 'red',
3654 3654 'qguard.positive': 'yellow',
3655 3655 'qguard.unguarded': 'green',
3656 3656 'qseries.applied': 'blue bold underline',
3657 3657 'qseries.guarded': 'black bold',
3658 3658 'qseries.missing': 'red bold',
3659 3659 'qseries.unapplied': 'black bold'}
@@ -1,5640 +1,5640 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 __future__ import absolute_import
9 9
10 10 import difflib
11 11 import errno
12 12 import os
13 13 import re
14 14 import sys
15 15
16 16 from .i18n import _
17 17 from .node import (
18 18 hex,
19 19 nullid,
20 20 nullrev,
21 21 short,
22 22 )
23 23 from . import (
24 24 archival,
25 25 bookmarks,
26 26 bundle2,
27 27 changegroup,
28 28 cmdutil,
29 29 copies,
30 30 debugcommands as debugcommandsmod,
31 31 destutil,
32 32 dirstateguard,
33 33 discovery,
34 34 encoding,
35 35 error,
36 36 exchange,
37 37 extensions,
38 38 formatter,
39 39 graphmod,
40 40 hbisect,
41 41 help,
42 42 hg,
43 43 lock as lockmod,
44 44 logcmdutil,
45 45 merge as mergemod,
46 46 obsolete,
47 47 obsutil,
48 48 patch,
49 49 phases,
50 50 pycompat,
51 51 rcutil,
52 52 registrar,
53 53 revsetlang,
54 54 rewriteutil,
55 55 scmutil,
56 56 server,
57 57 streamclone,
58 58 tags as tagsmod,
59 59 templatekw,
60 60 ui as uimod,
61 61 util,
62 62 wireprotoserver,
63 63 )
64 64 from .utils import (
65 65 dateutil,
66 66 procutil,
67 67 stringutil,
68 68 )
69 69
70 70 release = lockmod.release
71 71
72 72 table = {}
73 73 table.update(debugcommandsmod.command._table)
74 74
75 75 command = registrar.command(table)
76 76 readonly = registrar.command.readonly
77 77
78 78 # common command options
79 79
80 80 globalopts = [
81 81 ('R', 'repository', '',
82 82 _('repository root directory or name of overlay bundle file'),
83 83 _('REPO')),
84 84 ('', 'cwd', '',
85 85 _('change working directory'), _('DIR')),
86 86 ('y', 'noninteractive', None,
87 87 _('do not prompt, automatically pick the first choice for all prompts')),
88 88 ('q', 'quiet', None, _('suppress output')),
89 89 ('v', 'verbose', None, _('enable additional output')),
90 90 ('', 'color', '',
91 91 # i18n: 'always', 'auto', 'never', and 'debug' are keywords
92 92 # and should not be translated
93 93 _("when to colorize (boolean, always, auto, never, or debug)"),
94 94 _('TYPE')),
95 95 ('', 'config', [],
96 96 _('set/override config option (use \'section.name=value\')'),
97 97 _('CONFIG')),
98 98 ('', 'debug', None, _('enable debugging output')),
99 99 ('', 'debugger', None, _('start debugger')),
100 100 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
101 101 _('ENCODE')),
102 102 ('', 'encodingmode', encoding.encodingmode,
103 103 _('set the charset encoding mode'), _('MODE')),
104 104 ('', 'traceback', None, _('always print a traceback on exception')),
105 105 ('', 'time', None, _('time how long the command takes')),
106 106 ('', 'profile', None, _('print command execution profile')),
107 107 ('', 'version', None, _('output version information and exit')),
108 108 ('h', 'help', None, _('display help and exit')),
109 109 ('', 'hidden', False, _('consider hidden changesets')),
110 110 ('', 'pager', 'auto',
111 111 _("when to paginate (boolean, always, auto, or never)"), _('TYPE')),
112 112 ]
113 113
114 114 dryrunopts = cmdutil.dryrunopts
115 115 remoteopts = cmdutil.remoteopts
116 116 walkopts = cmdutil.walkopts
117 117 commitopts = cmdutil.commitopts
118 118 commitopts2 = cmdutil.commitopts2
119 119 formatteropts = cmdutil.formatteropts
120 120 templateopts = cmdutil.templateopts
121 121 logopts = cmdutil.logopts
122 122 diffopts = cmdutil.diffopts
123 123 diffwsopts = cmdutil.diffwsopts
124 124 diffopts2 = cmdutil.diffopts2
125 125 mergetoolopts = cmdutil.mergetoolopts
126 126 similarityopts = cmdutil.similarityopts
127 127 subrepoopts = cmdutil.subrepoopts
128 128 debugrevlogopts = cmdutil.debugrevlogopts
129 129
130 130 # Commands start here, listed alphabetically
131 131
132 132 @command('^add',
133 133 walkopts + subrepoopts + dryrunopts,
134 134 _('[OPTION]... [FILE]...'),
135 135 inferrepo=True)
136 136 def add(ui, repo, *pats, **opts):
137 137 """add the specified files on the next commit
138 138
139 139 Schedule files to be version controlled and added to the
140 140 repository.
141 141
142 142 The files will be added to the repository at the next commit. To
143 143 undo an add before that, see :hg:`forget`.
144 144
145 145 If no names are given, add all files to the repository (except
146 146 files matching ``.hgignore``).
147 147
148 148 .. container:: verbose
149 149
150 150 Examples:
151 151
152 152 - New (unknown) files are added
153 153 automatically by :hg:`add`::
154 154
155 155 $ ls
156 156 foo.c
157 157 $ hg status
158 158 ? foo.c
159 159 $ hg add
160 160 adding foo.c
161 161 $ hg status
162 162 A foo.c
163 163
164 164 - Specific files to be added can be specified::
165 165
166 166 $ ls
167 167 bar.c foo.c
168 168 $ hg status
169 169 ? bar.c
170 170 ? foo.c
171 171 $ hg add bar.c
172 172 $ hg status
173 173 A bar.c
174 174 ? foo.c
175 175
176 176 Returns 0 if all files are successfully added.
177 177 """
178 178
179 179 m = scmutil.match(repo[None], pats, pycompat.byteskwargs(opts))
180 180 rejected = cmdutil.add(ui, repo, m, "", False, **opts)
181 181 return rejected and 1 or 0
182 182
183 183 @command('addremove',
184 184 similarityopts + subrepoopts + walkopts + dryrunopts,
185 185 _('[OPTION]... [FILE]...'),
186 186 inferrepo=True)
187 187 def addremove(ui, repo, *pats, **opts):
188 188 """add all new files, delete all missing files
189 189
190 190 Add all new files and remove all missing files from the
191 191 repository.
192 192
193 193 Unless names are given, new files are ignored if they match any of
194 194 the patterns in ``.hgignore``. As with add, these changes take
195 195 effect at the next commit.
196 196
197 197 Use the -s/--similarity option to detect renamed files. This
198 198 option takes a percentage between 0 (disabled) and 100 (files must
199 199 be identical) as its parameter. With a parameter greater than 0,
200 200 this compares every removed file with every added file and records
201 201 those similar enough as renames. Detecting renamed files this way
202 202 can be expensive. After using this option, :hg:`status -C` can be
203 203 used to check which files were identified as moved or renamed. If
204 204 not specified, -s/--similarity defaults to 100 and only renames of
205 205 identical files are detected.
206 206
207 207 .. container:: verbose
208 208
209 209 Examples:
210 210
211 211 - A number of files (bar.c and foo.c) are new,
212 212 while foobar.c has been removed (without using :hg:`remove`)
213 213 from the repository::
214 214
215 215 $ ls
216 216 bar.c foo.c
217 217 $ hg status
218 218 ! foobar.c
219 219 ? bar.c
220 220 ? foo.c
221 221 $ hg addremove
222 222 adding bar.c
223 223 adding foo.c
224 224 removing foobar.c
225 225 $ hg status
226 226 A bar.c
227 227 A foo.c
228 228 R foobar.c
229 229
230 230 - A file foobar.c was moved to foo.c without using :hg:`rename`.
231 231 Afterwards, it was edited slightly::
232 232
233 233 $ ls
234 234 foo.c
235 235 $ hg status
236 236 ! foobar.c
237 237 ? foo.c
238 238 $ hg addremove --similarity 90
239 239 removing foobar.c
240 240 adding foo.c
241 241 recording removal of foobar.c as rename to foo.c (94% similar)
242 242 $ hg status -C
243 243 A foo.c
244 244 foobar.c
245 245 R foobar.c
246 246
247 247 Returns 0 if all files are successfully added.
248 248 """
249 249 opts = pycompat.byteskwargs(opts)
250 250 try:
251 251 sim = float(opts.get('similarity') or 100)
252 252 except ValueError:
253 253 raise error.Abort(_('similarity must be a number'))
254 254 if sim < 0 or sim > 100:
255 255 raise error.Abort(_('similarity must be between 0 and 100'))
256 256 matcher = scmutil.match(repo[None], pats, opts)
257 257 return scmutil.addremove(repo, matcher, "", opts, similarity=sim / 100.0)
258 258
259 259 @command('^annotate|blame',
260 260 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
261 261 ('', 'follow', None,
262 262 _('follow copies/renames and list the filename (DEPRECATED)')),
263 263 ('', 'no-follow', None, _("don't follow copies and renames")),
264 264 ('a', 'text', None, _('treat all files as text')),
265 265 ('u', 'user', None, _('list the author (long with -v)')),
266 266 ('f', 'file', None, _('list the filename')),
267 267 ('d', 'date', None, _('list the date (short with -q)')),
268 268 ('n', 'number', None, _('list the revision number (default)')),
269 269 ('c', 'changeset', None, _('list the changeset')),
270 270 ('l', 'line-number', None, _('show line number at the first appearance')),
271 271 ('', 'skip', [], _('revision to not display (EXPERIMENTAL)'), _('REV')),
272 272 ] + diffwsopts + walkopts + formatteropts,
273 273 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'),
274 274 inferrepo=True)
275 275 def annotate(ui, repo, *pats, **opts):
276 276 """show changeset information by line for each file
277 277
278 278 List changes in files, showing the revision id responsible for
279 279 each line.
280 280
281 281 This command is useful for discovering when a change was made and
282 282 by whom.
283 283
284 284 If you include --file, --user, or --date, the revision number is
285 285 suppressed unless you also include --number.
286 286
287 287 Without the -a/--text option, annotate will avoid processing files
288 288 it detects as binary. With -a, annotate will annotate the file
289 289 anyway, although the results will probably be neither useful
290 290 nor desirable.
291 291
292 292 Returns 0 on success.
293 293 """
294 294 opts = pycompat.byteskwargs(opts)
295 295 if not pats:
296 296 raise error.Abort(_('at least one filename or pattern is required'))
297 297
298 298 if opts.get('follow'):
299 299 # --follow is deprecated and now just an alias for -f/--file
300 300 # to mimic the behavior of Mercurial before version 1.5
301 301 opts['file'] = True
302 302
303 303 rev = opts.get('rev')
304 304 if rev:
305 305 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
306 306 ctx = scmutil.revsingle(repo, rev)
307 307
308 308 rootfm = ui.formatter('annotate', opts)
309 309 if ui.quiet:
310 310 datefunc = dateutil.shortdate
311 311 else:
312 312 datefunc = dateutil.datestr
313 313 if ctx.rev() is None:
314 314 def hexfn(node):
315 315 if node is None:
316 316 return None
317 317 else:
318 318 return rootfm.hexfunc(node)
319 319 if opts.get('changeset'):
320 320 # omit "+" suffix which is appended to node hex
321 321 def formatrev(rev):
322 322 if rev is None:
323 323 return '%d' % ctx.p1().rev()
324 324 else:
325 325 return '%d' % rev
326 326 else:
327 327 def formatrev(rev):
328 328 if rev is None:
329 329 return '%d+' % ctx.p1().rev()
330 330 else:
331 331 return '%d ' % rev
332 332 def formathex(hex):
333 333 if hex is None:
334 334 return '%s+' % rootfm.hexfunc(ctx.p1().node())
335 335 else:
336 336 return '%s ' % hex
337 337 else:
338 338 hexfn = rootfm.hexfunc
339 339 formatrev = formathex = pycompat.bytestr
340 340
341 341 opmap = [('user', ' ', lambda x: x.fctx.user(), ui.shortuser),
342 342 ('number', ' ', lambda x: x.fctx.rev(), formatrev),
343 343 ('changeset', ' ', lambda x: hexfn(x.fctx.node()), formathex),
344 344 ('date', ' ', lambda x: x.fctx.date(), util.cachefunc(datefunc)),
345 345 ('file', ' ', lambda x: x.fctx.path(), pycompat.bytestr),
346 346 ('line_number', ':', lambda x: x.lineno, pycompat.bytestr),
347 347 ]
348 348 fieldnamemap = {'number': 'rev', 'changeset': 'node'}
349 349
350 350 if (not opts.get('user') and not opts.get('changeset')
351 351 and not opts.get('date') and not opts.get('file')):
352 352 opts['number'] = True
353 353
354 354 linenumber = opts.get('line_number') is not None
355 355 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
356 356 raise error.Abort(_('at least one of -n/-c is required for -l'))
357 357
358 358 ui.pager('annotate')
359 359
360 360 if rootfm.isplain():
361 361 def makefunc(get, fmt):
362 362 return lambda x: fmt(get(x))
363 363 else:
364 364 def makefunc(get, fmt):
365 365 return get
366 366 funcmap = [(makefunc(get, fmt), sep) for op, sep, get, fmt in opmap
367 367 if opts.get(op)]
368 368 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
369 369 fields = ' '.join(fieldnamemap.get(op, op) for op, sep, get, fmt in opmap
370 370 if opts.get(op))
371 371
372 372 def bad(x, y):
373 373 raise error.Abort("%s: %s" % (x, y))
374 374
375 375 m = scmutil.match(ctx, pats, opts, badfn=bad)
376 376
377 377 follow = not opts.get('no_follow')
378 378 diffopts = patch.difffeatureopts(ui, opts, section='annotate',
379 379 whitespace=True)
380 380 skiprevs = opts.get('skip')
381 381 if skiprevs:
382 382 skiprevs = scmutil.revrange(repo, skiprevs)
383 383
384 384 for abs in ctx.walk(m):
385 385 fctx = ctx[abs]
386 386 rootfm.startitem()
387 387 rootfm.data(abspath=abs, path=m.rel(abs))
388 388 if not opts.get('text') and fctx.isbinary():
389 389 rootfm.plain(_("%s: binary file\n")
390 390 % ((pats and m.rel(abs)) or abs))
391 391 continue
392 392
393 393 fm = rootfm.nested('lines')
394 394 lines = fctx.annotate(follow=follow, skiprevs=skiprevs,
395 395 diffopts=diffopts)
396 396 if not lines:
397 397 fm.end()
398 398 continue
399 399 formats = []
400 400 pieces = []
401 401
402 402 for f, sep in funcmap:
403 403 l = [f(n) for n in lines]
404 404 if fm.isplain():
405 405 sizes = [encoding.colwidth(x) for x in l]
406 406 ml = max(sizes)
407 407 formats.append([sep + ' ' * (ml - w) + '%s' for w in sizes])
408 408 else:
409 409 formats.append(['%s' for x in l])
410 410 pieces.append(l)
411 411
412 412 for f, p, n in zip(zip(*formats), zip(*pieces), lines):
413 413 fm.startitem()
414 414 fm.context(fctx=n.fctx)
415 415 fm.write(fields, "".join(f), *p)
416 416 if n.skip:
417 417 fmt = "* %s"
418 418 else:
419 419 fmt = ": %s"
420 420 fm.write('line', fmt, n.text)
421 421
422 422 if not lines[-1].text.endswith('\n'):
423 423 fm.plain('\n')
424 424 fm.end()
425 425
426 426 rootfm.end()
427 427
428 428 @command('archive',
429 429 [('', 'no-decode', None, _('do not pass files through decoders')),
430 430 ('p', 'prefix', '', _('directory prefix for files in archive'),
431 431 _('PREFIX')),
432 432 ('r', 'rev', '', _('revision to distribute'), _('REV')),
433 433 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
434 434 ] + subrepoopts + walkopts,
435 435 _('[OPTION]... DEST'))
436 436 def archive(ui, repo, dest, **opts):
437 437 '''create an unversioned archive of a repository revision
438 438
439 439 By default, the revision used is the parent of the working
440 440 directory; use -r/--rev to specify a different revision.
441 441
442 442 The archive type is automatically detected based on file
443 443 extension (to override, use -t/--type).
444 444
445 445 .. container:: verbose
446 446
447 447 Examples:
448 448
449 449 - create a zip file containing the 1.0 release::
450 450
451 451 hg archive -r 1.0 project-1.0.zip
452 452
453 453 - create a tarball excluding .hg files::
454 454
455 455 hg archive project.tar.gz -X ".hg*"
456 456
457 457 Valid types are:
458 458
459 459 :``files``: a directory full of files (default)
460 460 :``tar``: tar archive, uncompressed
461 461 :``tbz2``: tar archive, compressed using bzip2
462 462 :``tgz``: tar archive, compressed using gzip
463 463 :``uzip``: zip archive, uncompressed
464 464 :``zip``: zip archive, compressed using deflate
465 465
466 466 The exact name of the destination archive or directory is given
467 467 using a format string; see :hg:`help export` for details.
468 468
469 469 Each member added to an archive file has a directory prefix
470 470 prepended. Use -p/--prefix to specify a format string for the
471 471 prefix. The default is the basename of the archive, with suffixes
472 472 removed.
473 473
474 474 Returns 0 on success.
475 475 '''
476 476
477 477 opts = pycompat.byteskwargs(opts)
478 478 rev = opts.get('rev')
479 479 if rev:
480 480 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
481 481 ctx = scmutil.revsingle(repo, rev)
482 482 if not ctx:
483 483 raise error.Abort(_('no working directory: please specify a revision'))
484 484 node = ctx.node()
485 485 dest = cmdutil.makefilename(ctx, dest)
486 486 if os.path.realpath(dest) == repo.root:
487 487 raise error.Abort(_('repository root cannot be destination'))
488 488
489 489 kind = opts.get('type') or archival.guesskind(dest) or 'files'
490 490 prefix = opts.get('prefix')
491 491
492 492 if dest == '-':
493 493 if kind == 'files':
494 494 raise error.Abort(_('cannot archive plain files to stdout'))
495 495 dest = cmdutil.makefileobj(ctx, dest)
496 496 if not prefix:
497 497 prefix = os.path.basename(repo.root) + '-%h'
498 498
499 499 prefix = cmdutil.makefilename(ctx, prefix)
500 500 match = scmutil.match(ctx, [], opts)
501 501 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
502 502 match, prefix, subrepos=opts.get('subrepos'))
503 503
504 504 @command('backout',
505 505 [('', 'merge', None, _('merge with old dirstate parent after backout')),
506 506 ('', 'commit', None,
507 507 _('commit if no conflicts were encountered (DEPRECATED)')),
508 508 ('', 'no-commit', None, _('do not commit')),
509 509 ('', 'parent', '',
510 510 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
511 511 ('r', 'rev', '', _('revision to backout'), _('REV')),
512 512 ('e', 'edit', False, _('invoke editor on commit messages')),
513 513 ] + mergetoolopts + walkopts + commitopts + commitopts2,
514 514 _('[OPTION]... [-r] REV'))
515 515 def backout(ui, repo, node=None, rev=None, **opts):
516 516 '''reverse effect of earlier changeset
517 517
518 518 Prepare a new changeset with the effect of REV undone in the
519 519 current working directory. If no conflicts were encountered,
520 520 it will be committed immediately.
521 521
522 522 If REV is the parent of the working directory, then this new changeset
523 523 is committed automatically (unless --no-commit is specified).
524 524
525 525 .. note::
526 526
527 527 :hg:`backout` cannot be used to fix either an unwanted or
528 528 incorrect merge.
529 529
530 530 .. container:: verbose
531 531
532 532 Examples:
533 533
534 534 - Reverse the effect of the parent of the working directory.
535 535 This backout will be committed immediately::
536 536
537 537 hg backout -r .
538 538
539 539 - Reverse the effect of previous bad revision 23::
540 540
541 541 hg backout -r 23
542 542
543 543 - Reverse the effect of previous bad revision 23 and
544 544 leave changes uncommitted::
545 545
546 546 hg backout -r 23 --no-commit
547 547 hg commit -m "Backout revision 23"
548 548
549 549 By default, the pending changeset will have one parent,
550 550 maintaining a linear history. With --merge, the pending
551 551 changeset will instead have two parents: the old parent of the
552 552 working directory and a new child of REV that simply undoes REV.
553 553
554 554 Before version 1.7, the behavior without --merge was equivalent
555 555 to specifying --merge followed by :hg:`update --clean .` to
556 556 cancel the merge and leave the child of REV as a head to be
557 557 merged separately.
558 558
559 559 See :hg:`help dates` for a list of formats valid for -d/--date.
560 560
561 561 See :hg:`help revert` for a way to restore files to the state
562 562 of another revision.
563 563
564 564 Returns 0 on success, 1 if nothing to backout or there are unresolved
565 565 files.
566 566 '''
567 567 wlock = lock = None
568 568 try:
569 569 wlock = repo.wlock()
570 570 lock = repo.lock()
571 571 return _dobackout(ui, repo, node, rev, **opts)
572 572 finally:
573 573 release(lock, wlock)
574 574
575 575 def _dobackout(ui, repo, node=None, rev=None, **opts):
576 576 opts = pycompat.byteskwargs(opts)
577 577 if opts.get('commit') and opts.get('no_commit'):
578 578 raise error.Abort(_("cannot use --commit with --no-commit"))
579 579 if opts.get('merge') and opts.get('no_commit'):
580 580 raise error.Abort(_("cannot use --merge with --no-commit"))
581 581
582 582 if rev and node:
583 583 raise error.Abort(_("please specify just one revision"))
584 584
585 585 if not rev:
586 586 rev = node
587 587
588 588 if not rev:
589 589 raise error.Abort(_("please specify a revision to backout"))
590 590
591 591 date = opts.get('date')
592 592 if date:
593 593 opts['date'] = dateutil.parsedate(date)
594 594
595 595 cmdutil.checkunfinished(repo)
596 596 cmdutil.bailifchanged(repo)
597 597 node = scmutil.revsingle(repo, rev).node()
598 598
599 599 op1, op2 = repo.dirstate.parents()
600 600 if not repo.changelog.isancestor(node, op1):
601 601 raise error.Abort(_('cannot backout change that is not an ancestor'))
602 602
603 603 p1, p2 = repo.changelog.parents(node)
604 604 if p1 == nullid:
605 605 raise error.Abort(_('cannot backout a change with no parents'))
606 606 if p2 != nullid:
607 607 if not opts.get('parent'):
608 608 raise error.Abort(_('cannot backout a merge changeset'))
609 609 p = repo.lookup(opts['parent'])
610 610 if p not in (p1, p2):
611 611 raise error.Abort(_('%s is not a parent of %s') %
612 612 (short(p), short(node)))
613 613 parent = p
614 614 else:
615 615 if opts.get('parent'):
616 616 raise error.Abort(_('cannot use --parent on non-merge changeset'))
617 617 parent = p1
618 618
619 619 # the backout should appear on the same branch
620 620 branch = repo.dirstate.branch()
621 621 bheads = repo.branchheads(branch)
622 622 rctx = scmutil.revsingle(repo, hex(parent))
623 623 if not opts.get('merge') and op1 != node:
624 624 dsguard = dirstateguard.dirstateguard(repo, 'backout')
625 625 try:
626 626 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
627 627 'backout')
628 628 stats = mergemod.update(repo, parent, True, True, node, False)
629 629 repo.setparents(op1, op2)
630 630 dsguard.close()
631 631 hg._showstats(repo, stats)
632 632 if stats.unresolvedcount:
633 633 repo.ui.status(_("use 'hg resolve' to retry unresolved "
634 634 "file merges\n"))
635 635 return 1
636 636 finally:
637 637 ui.setconfig('ui', 'forcemerge', '', '')
638 638 lockmod.release(dsguard)
639 639 else:
640 640 hg.clean(repo, node, show_stats=False)
641 641 repo.dirstate.setbranch(branch)
642 642 cmdutil.revert(ui, repo, rctx, repo.dirstate.parents())
643 643
644 644 if opts.get('no_commit'):
645 645 msg = _("changeset %s backed out, "
646 646 "don't forget to commit.\n")
647 647 ui.status(msg % short(node))
648 648 return 0
649 649
650 650 def commitfunc(ui, repo, message, match, opts):
651 651 editform = 'backout'
652 652 e = cmdutil.getcommiteditor(editform=editform,
653 653 **pycompat.strkwargs(opts))
654 654 if not message:
655 655 # we don't translate commit messages
656 656 message = "Backed out changeset %s" % short(node)
657 657 e = cmdutil.getcommiteditor(edit=True, editform=editform)
658 658 return repo.commit(message, opts.get('user'), opts.get('date'),
659 659 match, editor=e)
660 660 newnode = cmdutil.commit(ui, repo, commitfunc, [], opts)
661 661 if not newnode:
662 662 ui.status(_("nothing changed\n"))
663 663 return 1
664 664 cmdutil.commitstatus(repo, newnode, branch, bheads)
665 665
666 666 def nice(node):
667 667 return '%d:%s' % (repo.changelog.rev(node), short(node))
668 668 ui.status(_('changeset %s backs out changeset %s\n') %
669 669 (nice(repo.changelog.tip()), nice(node)))
670 670 if opts.get('merge') and op1 != node:
671 671 hg.clean(repo, op1, show_stats=False)
672 672 ui.status(_('merging with changeset %s\n')
673 673 % nice(repo.changelog.tip()))
674 674 try:
675 675 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
676 676 'backout')
677 677 return hg.merge(repo, hex(repo.changelog.tip()))
678 678 finally:
679 679 ui.setconfig('ui', 'forcemerge', '', '')
680 680 return 0
681 681
682 682 @command('bisect',
683 683 [('r', 'reset', False, _('reset bisect state')),
684 684 ('g', 'good', False, _('mark changeset good')),
685 685 ('b', 'bad', False, _('mark changeset bad')),
686 686 ('s', 'skip', False, _('skip testing changeset')),
687 687 ('e', 'extend', False, _('extend the bisect range')),
688 688 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
689 689 ('U', 'noupdate', False, _('do not update to target'))],
690 690 _("[-gbsr] [-U] [-c CMD] [REV]"))
691 691 def bisect(ui, repo, rev=None, extra=None, command=None,
692 692 reset=None, good=None, bad=None, skip=None, extend=None,
693 693 noupdate=None):
694 694 """subdivision search of changesets
695 695
696 696 This command helps to find changesets which introduce problems. To
697 697 use, mark the earliest changeset you know exhibits the problem as
698 698 bad, then mark the latest changeset which is free from the problem
699 699 as good. Bisect will update your working directory to a revision
700 700 for testing (unless the -U/--noupdate option is specified). Once
701 701 you have performed tests, mark the working directory as good or
702 702 bad, and bisect will either update to another candidate changeset
703 703 or announce that it has found the bad revision.
704 704
705 705 As a shortcut, you can also use the revision argument to mark a
706 706 revision as good or bad without checking it out first.
707 707
708 708 If you supply a command, it will be used for automatic bisection.
709 709 The environment variable HG_NODE will contain the ID of the
710 710 changeset being tested. The exit status of the command will be
711 711 used to mark revisions as good or bad: status 0 means good, 125
712 712 means to skip the revision, 127 (command not found) will abort the
713 713 bisection, and any other non-zero exit status means the revision
714 714 is bad.
715 715
716 716 .. container:: verbose
717 717
718 718 Some examples:
719 719
720 720 - start a bisection with known bad revision 34, and good revision 12::
721 721
722 722 hg bisect --bad 34
723 723 hg bisect --good 12
724 724
725 725 - advance the current bisection by marking current revision as good or
726 726 bad::
727 727
728 728 hg bisect --good
729 729 hg bisect --bad
730 730
731 731 - mark the current revision, or a known revision, to be skipped (e.g. if
732 732 that revision is not usable because of another issue)::
733 733
734 734 hg bisect --skip
735 735 hg bisect --skip 23
736 736
737 737 - skip all revisions that do not touch directories ``foo`` or ``bar``::
738 738
739 739 hg bisect --skip "!( file('path:foo') & file('path:bar') )"
740 740
741 741 - forget the current bisection::
742 742
743 743 hg bisect --reset
744 744
745 745 - use 'make && make tests' to automatically find the first broken
746 746 revision::
747 747
748 748 hg bisect --reset
749 749 hg bisect --bad 34
750 750 hg bisect --good 12
751 751 hg bisect --command "make && make tests"
752 752
753 753 - see all changesets whose states are already known in the current
754 754 bisection::
755 755
756 756 hg log -r "bisect(pruned)"
757 757
758 758 - see the changeset currently being bisected (especially useful
759 759 if running with -U/--noupdate)::
760 760
761 761 hg log -r "bisect(current)"
762 762
763 763 - see all changesets that took part in the current bisection::
764 764
765 765 hg log -r "bisect(range)"
766 766
767 767 - you can even get a nice graph::
768 768
769 769 hg log --graph -r "bisect(range)"
770 770
771 771 See :hg:`help revisions.bisect` for more about the `bisect()` predicate.
772 772
773 773 Returns 0 on success.
774 774 """
775 775 # backward compatibility
776 776 if rev in "good bad reset init".split():
777 777 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
778 778 cmd, rev, extra = rev, extra, None
779 779 if cmd == "good":
780 780 good = True
781 781 elif cmd == "bad":
782 782 bad = True
783 783 else:
784 784 reset = True
785 785 elif extra:
786 786 raise error.Abort(_('incompatible arguments'))
787 787
788 788 incompatibles = {
789 789 '--bad': bad,
790 790 '--command': bool(command),
791 791 '--extend': extend,
792 792 '--good': good,
793 793 '--reset': reset,
794 794 '--skip': skip,
795 795 }
796 796
797 797 enabled = [x for x in incompatibles if incompatibles[x]]
798 798
799 799 if len(enabled) > 1:
800 800 raise error.Abort(_('%s and %s are incompatible') %
801 801 tuple(sorted(enabled)[0:2]))
802 802
803 803 if reset:
804 804 hbisect.resetstate(repo)
805 805 return
806 806
807 807 state = hbisect.load_state(repo)
808 808
809 809 # update state
810 810 if good or bad or skip:
811 811 if rev:
812 812 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
813 813 else:
814 814 nodes = [repo.lookup('.')]
815 815 if good:
816 816 state['good'] += nodes
817 817 elif bad:
818 818 state['bad'] += nodes
819 819 elif skip:
820 820 state['skip'] += nodes
821 821 hbisect.save_state(repo, state)
822 822 if not (state['good'] and state['bad']):
823 823 return
824 824
825 825 def mayupdate(repo, node, show_stats=True):
826 826 """common used update sequence"""
827 827 if noupdate:
828 828 return
829 829 cmdutil.checkunfinished(repo)
830 830 cmdutil.bailifchanged(repo)
831 831 return hg.clean(repo, node, show_stats=show_stats)
832 832
833 833 displayer = logcmdutil.changesetdisplayer(ui, repo, {})
834 834
835 835 if command:
836 836 changesets = 1
837 837 if noupdate:
838 838 try:
839 839 node = state['current'][0]
840 840 except LookupError:
841 841 raise error.Abort(_('current bisect revision is unknown - '
842 842 'start a new bisect to fix'))
843 843 else:
844 844 node, p2 = repo.dirstate.parents()
845 845 if p2 != nullid:
846 846 raise error.Abort(_('current bisect revision is a merge'))
847 847 if rev:
848 848 node = repo[scmutil.revsingle(repo, rev, node)].node()
849 849 try:
850 850 while changesets:
851 851 # update state
852 852 state['current'] = [node]
853 853 hbisect.save_state(repo, state)
854 854 status = ui.system(command, environ={'HG_NODE': hex(node)},
855 855 blockedtag='bisect_check')
856 856 if status == 125:
857 857 transition = "skip"
858 858 elif status == 0:
859 859 transition = "good"
860 860 # status < 0 means process was killed
861 861 elif status == 127:
862 862 raise error.Abort(_("failed to execute %s") % command)
863 863 elif status < 0:
864 864 raise error.Abort(_("%s killed") % command)
865 865 else:
866 866 transition = "bad"
867 867 state[transition].append(node)
868 868 ctx = repo[node]
869 869 ui.status(_('changeset %d:%s: %s\n') % (ctx.rev(), ctx,
870 870 transition))
871 871 hbisect.checkstate(state)
872 872 # bisect
873 873 nodes, changesets, bgood = hbisect.bisect(repo, state)
874 874 # update to next check
875 875 node = nodes[0]
876 876 mayupdate(repo, node, show_stats=False)
877 877 finally:
878 878 state['current'] = [node]
879 879 hbisect.save_state(repo, state)
880 880 hbisect.printresult(ui, repo, state, displayer, nodes, bgood)
881 881 return
882 882
883 883 hbisect.checkstate(state)
884 884
885 885 # actually bisect
886 886 nodes, changesets, good = hbisect.bisect(repo, state)
887 887 if extend:
888 888 if not changesets:
889 889 extendnode = hbisect.extendrange(repo, state, nodes, good)
890 890 if extendnode is not None:
891 891 ui.write(_("Extending search to changeset %d:%s\n")
892 892 % (extendnode.rev(), extendnode))
893 893 state['current'] = [extendnode.node()]
894 894 hbisect.save_state(repo, state)
895 895 return mayupdate(repo, extendnode.node())
896 896 raise error.Abort(_("nothing to extend"))
897 897
898 898 if changesets == 0:
899 899 hbisect.printresult(ui, repo, state, displayer, nodes, good)
900 900 else:
901 901 assert len(nodes) == 1 # only a single node can be tested next
902 902 node = nodes[0]
903 903 # compute the approximate number of remaining tests
904 904 tests, size = 0, 2
905 905 while size <= changesets:
906 906 tests, size = tests + 1, size * 2
907 907 rev = repo.changelog.rev(node)
908 908 ui.write(_("Testing changeset %d:%s "
909 909 "(%d changesets remaining, ~%d tests)\n")
910 910 % (rev, short(node), changesets, tests))
911 911 state['current'] = [node]
912 912 hbisect.save_state(repo, state)
913 913 return mayupdate(repo, node)
914 914
915 915 @command('bookmarks|bookmark',
916 916 [('f', 'force', False, _('force')),
917 917 ('r', 'rev', '', _('revision for bookmark action'), _('REV')),
918 918 ('d', 'delete', False, _('delete a given bookmark')),
919 919 ('m', 'rename', '', _('rename a given bookmark'), _('OLD')),
920 920 ('i', 'inactive', False, _('mark a bookmark inactive')),
921 921 ] + formatteropts,
922 922 _('hg bookmarks [OPTIONS]... [NAME]...'))
923 923 def bookmark(ui, repo, *names, **opts):
924 924 '''create a new bookmark or list existing bookmarks
925 925
926 926 Bookmarks are labels on changesets to help track lines of development.
927 927 Bookmarks are unversioned and can be moved, renamed and deleted.
928 928 Deleting or moving a bookmark has no effect on the associated changesets.
929 929
930 930 Creating or updating to a bookmark causes it to be marked as 'active'.
931 931 The active bookmark is indicated with a '*'.
932 932 When a commit is made, the active bookmark will advance to the new commit.
933 933 A plain :hg:`update` will also advance an active bookmark, if possible.
934 934 Updating away from a bookmark will cause it to be deactivated.
935 935
936 936 Bookmarks can be pushed and pulled between repositories (see
937 937 :hg:`help push` and :hg:`help pull`). If a shared bookmark has
938 938 diverged, a new 'divergent bookmark' of the form 'name@path' will
939 939 be created. Using :hg:`merge` will resolve the divergence.
940 940
941 941 Specifying bookmark as '.' to -m or -d options is equivalent to specifying
942 942 the active bookmark's name.
943 943
944 944 A bookmark named '@' has the special property that :hg:`clone` will
945 945 check it out by default if it exists.
946 946
947 947 .. container:: verbose
948 948
949 949 Examples:
950 950
951 951 - create an active bookmark for a new line of development::
952 952
953 953 hg book new-feature
954 954
955 955 - create an inactive bookmark as a place marker::
956 956
957 957 hg book -i reviewed
958 958
959 959 - create an inactive bookmark on another changeset::
960 960
961 961 hg book -r .^ tested
962 962
963 963 - rename bookmark turkey to dinner::
964 964
965 965 hg book -m turkey dinner
966 966
967 967 - move the '@' bookmark from another branch::
968 968
969 969 hg book -f @
970 970 '''
971 971 force = opts.get(r'force')
972 972 rev = opts.get(r'rev')
973 973 delete = opts.get(r'delete')
974 974 rename = opts.get(r'rename')
975 975 inactive = opts.get(r'inactive')
976 976
977 977 if delete and rename:
978 978 raise error.Abort(_("--delete and --rename are incompatible"))
979 979 if delete and rev:
980 980 raise error.Abort(_("--rev is incompatible with --delete"))
981 981 if rename and rev:
982 982 raise error.Abort(_("--rev is incompatible with --rename"))
983 983 if not names and (delete or rev):
984 984 raise error.Abort(_("bookmark name required"))
985 985
986 986 if delete or rename or names or inactive:
987 987 with repo.wlock(), repo.lock(), repo.transaction('bookmark') as tr:
988 988 if delete:
989 989 names = pycompat.maplist(repo._bookmarks.expandname, names)
990 990 bookmarks.delete(repo, tr, names)
991 991 elif rename:
992 992 if not names:
993 993 raise error.Abort(_("new bookmark name required"))
994 994 elif len(names) > 1:
995 995 raise error.Abort(_("only one new bookmark name allowed"))
996 996 rename = repo._bookmarks.expandname(rename)
997 997 bookmarks.rename(repo, tr, rename, names[0], force, inactive)
998 998 elif names:
999 999 bookmarks.addbookmarks(repo, tr, names, rev, force, inactive)
1000 1000 elif inactive:
1001 1001 if len(repo._bookmarks) == 0:
1002 1002 ui.status(_("no bookmarks set\n"))
1003 1003 elif not repo._activebookmark:
1004 1004 ui.status(_("no active bookmark\n"))
1005 1005 else:
1006 1006 bookmarks.deactivate(repo)
1007 1007 else: # show bookmarks
1008 1008 bookmarks.printbookmarks(ui, repo, **opts)
1009 1009
1010 1010 @command('branch',
1011 1011 [('f', 'force', None,
1012 1012 _('set branch name even if it shadows an existing branch')),
1013 1013 ('C', 'clean', None, _('reset branch name to parent branch name')),
1014 1014 ('r', 'rev', [], _('change branches of the given revs (EXPERIMENTAL)')),
1015 1015 ],
1016 1016 _('[-fC] [NAME]'))
1017 1017 def branch(ui, repo, label=None, **opts):
1018 1018 """set or show the current branch name
1019 1019
1020 1020 .. note::
1021 1021
1022 1022 Branch names are permanent and global. Use :hg:`bookmark` to create a
1023 1023 light-weight bookmark instead. See :hg:`help glossary` for more
1024 1024 information about named branches and bookmarks.
1025 1025
1026 1026 With no argument, show the current branch name. With one argument,
1027 1027 set the working directory branch name (the branch will not exist
1028 1028 in the repository until the next commit). Standard practice
1029 1029 recommends that primary development take place on the 'default'
1030 1030 branch.
1031 1031
1032 1032 Unless -f/--force is specified, branch will not let you set a
1033 1033 branch name that already exists.
1034 1034
1035 1035 Use -C/--clean to reset the working directory branch to that of
1036 1036 the parent of the working directory, negating a previous branch
1037 1037 change.
1038 1038
1039 1039 Use the command :hg:`update` to switch to an existing branch. Use
1040 1040 :hg:`commit --close-branch` to mark this branch head as closed.
1041 1041 When all heads of a branch are closed, the branch will be
1042 1042 considered closed.
1043 1043
1044 1044 Returns 0 on success.
1045 1045 """
1046 1046 opts = pycompat.byteskwargs(opts)
1047 1047 revs = opts.get('rev')
1048 1048 if label:
1049 1049 label = label.strip()
1050 1050
1051 1051 if not opts.get('clean') and not label:
1052 1052 if revs:
1053 1053 raise error.Abort(_("no branch name specified for the revisions"))
1054 1054 ui.write("%s\n" % repo.dirstate.branch())
1055 1055 return
1056 1056
1057 1057 with repo.wlock():
1058 1058 if opts.get('clean'):
1059 1059 label = repo[None].p1().branch()
1060 1060 repo.dirstate.setbranch(label)
1061 1061 ui.status(_('reset working directory to branch %s\n') % label)
1062 1062 elif label:
1063 1063
1064 1064 scmutil.checknewlabel(repo, label, 'branch')
1065 1065 if revs:
1066 1066 return cmdutil.changebranch(ui, repo, revs, label)
1067 1067
1068 1068 if not opts.get('force') and label in repo.branchmap():
1069 1069 if label not in [p.branch() for p in repo[None].parents()]:
1070 1070 raise error.Abort(_('a branch of the same name already'
1071 1071 ' exists'),
1072 1072 # i18n: "it" refers to an existing branch
1073 1073 hint=_("use 'hg update' to switch to it"))
1074 1074
1075 1075 repo.dirstate.setbranch(label)
1076 1076 ui.status(_('marked working directory as branch %s\n') % label)
1077 1077
1078 1078 # find any open named branches aside from default
1079 1079 others = [n for n, h, t, c in repo.branchmap().iterbranches()
1080 1080 if n != "default" and not c]
1081 1081 if not others:
1082 1082 ui.status(_('(branches are permanent and global, '
1083 1083 'did you want a bookmark?)\n'))
1084 1084
1085 1085 @command('branches',
1086 1086 [('a', 'active', False,
1087 1087 _('show only branches that have unmerged heads (DEPRECATED)')),
1088 1088 ('c', 'closed', False, _('show normal and closed branches')),
1089 1089 ] + formatteropts,
1090 1090 _('[-c]'), cmdtype=readonly)
1091 1091 def branches(ui, repo, active=False, closed=False, **opts):
1092 1092 """list repository named branches
1093 1093
1094 1094 List the repository's named branches, indicating which ones are
1095 1095 inactive. If -c/--closed is specified, also list branches which have
1096 1096 been marked closed (see :hg:`commit --close-branch`).
1097 1097
1098 1098 Use the command :hg:`update` to switch to an existing branch.
1099 1099
1100 1100 Returns 0.
1101 1101 """
1102 1102
1103 1103 opts = pycompat.byteskwargs(opts)
1104 1104 ui.pager('branches')
1105 1105 fm = ui.formatter('branches', opts)
1106 1106 hexfunc = fm.hexfunc
1107 1107
1108 1108 allheads = set(repo.heads())
1109 1109 branches = []
1110 1110 for tag, heads, tip, isclosed in repo.branchmap().iterbranches():
1111 1111 isactive = False
1112 1112 if not isclosed:
1113 1113 openheads = set(repo.branchmap().iteropen(heads))
1114 1114 isactive = bool(openheads & allheads)
1115 1115 branches.append((tag, repo[tip], isactive, not isclosed))
1116 1116 branches.sort(key=lambda i: (i[2], i[1].rev(), i[0], i[3]),
1117 1117 reverse=True)
1118 1118
1119 1119 for tag, ctx, isactive, isopen in branches:
1120 1120 if active and not isactive:
1121 1121 continue
1122 1122 if isactive:
1123 1123 label = 'branches.active'
1124 1124 notice = ''
1125 1125 elif not isopen:
1126 1126 if not closed:
1127 1127 continue
1128 1128 label = 'branches.closed'
1129 1129 notice = _(' (closed)')
1130 1130 else:
1131 1131 label = 'branches.inactive'
1132 1132 notice = _(' (inactive)')
1133 1133 current = (tag == repo.dirstate.branch())
1134 1134 if current:
1135 1135 label = 'branches.current'
1136 1136
1137 1137 fm.startitem()
1138 1138 fm.write('branch', '%s', tag, label=label)
1139 1139 rev = ctx.rev()
1140 1140 padsize = max(31 - len("%d" % rev) - encoding.colwidth(tag), 0)
1141 1141 fmt = ' ' * padsize + ' %d:%s'
1142 1142 fm.condwrite(not ui.quiet, 'rev node', fmt, rev, hexfunc(ctx.node()),
1143 1143 label='log.changeset changeset.%s' % ctx.phasestr())
1144 1144 fm.context(ctx=ctx)
1145 1145 fm.data(active=isactive, closed=not isopen, current=current)
1146 1146 if not ui.quiet:
1147 1147 fm.plain(notice)
1148 1148 fm.plain('\n')
1149 1149 fm.end()
1150 1150
1151 1151 @command('bundle',
1152 1152 [('f', 'force', None, _('run even when the destination is unrelated')),
1153 1153 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
1154 1154 _('REV')),
1155 1155 ('b', 'branch', [], _('a specific branch you would like to bundle'),
1156 1156 _('BRANCH')),
1157 1157 ('', 'base', [],
1158 1158 _('a base changeset assumed to be available at the destination'),
1159 1159 _('REV')),
1160 1160 ('a', 'all', None, _('bundle all changesets in the repository')),
1161 1161 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
1162 1162 ] + remoteopts,
1163 1163 _('[-f] [-t BUNDLESPEC] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
1164 1164 def bundle(ui, repo, fname, dest=None, **opts):
1165 1165 """create a bundle file
1166 1166
1167 1167 Generate a bundle file containing data to be transferred to another
1168 1168 repository.
1169 1169
1170 1170 To create a bundle containing all changesets, use -a/--all
1171 1171 (or --base null). Otherwise, hg assumes the destination will have
1172 1172 all the nodes you specify with --base parameters. Otherwise, hg
1173 1173 will assume the repository has all the nodes in destination, or
1174 1174 default-push/default if no destination is specified, where destination
1175 1175 is the repository you provide through DEST option.
1176 1176
1177 1177 You can change bundle format with the -t/--type option. See
1178 1178 :hg:`help bundlespec` for documentation on this format. By default,
1179 1179 the most appropriate format is used and compression defaults to
1180 1180 bzip2.
1181 1181
1182 1182 The bundle file can then be transferred using conventional means
1183 1183 and applied to another repository with the unbundle or pull
1184 1184 command. This is useful when direct push and pull are not
1185 1185 available or when exporting an entire repository is undesirable.
1186 1186
1187 1187 Applying bundles preserves all changeset contents including
1188 1188 permissions, copy/rename information, and revision history.
1189 1189
1190 1190 Returns 0 on success, 1 if no changes found.
1191 1191 """
1192 1192 opts = pycompat.byteskwargs(opts)
1193 1193 revs = None
1194 1194 if 'rev' in opts:
1195 1195 revstrings = opts['rev']
1196 1196 revs = scmutil.revrange(repo, revstrings)
1197 1197 if revstrings and not revs:
1198 1198 raise error.Abort(_('no commits to bundle'))
1199 1199
1200 1200 bundletype = opts.get('type', 'bzip2').lower()
1201 1201 try:
1202 1202 bundlespec = exchange.parsebundlespec(repo, bundletype, strict=False)
1203 1203 except error.UnsupportedBundleSpecification as e:
1204 1204 raise error.Abort(pycompat.bytestr(e),
1205 1205 hint=_("see 'hg help bundlespec' for supported "
1206 1206 "values for --type"))
1207 1207 cgversion = bundlespec.contentopts["cg.version"]
1208 1208
1209 1209 # Packed bundles are a pseudo bundle format for now.
1210 1210 if cgversion == 's1':
1211 1211 raise error.Abort(_('packed bundles cannot be produced by "hg bundle"'),
1212 1212 hint=_("use 'hg debugcreatestreamclonebundle'"))
1213 1213
1214 1214 if opts.get('all'):
1215 1215 if dest:
1216 1216 raise error.Abort(_("--all is incompatible with specifying "
1217 1217 "a destination"))
1218 1218 if opts.get('base'):
1219 1219 ui.warn(_("ignoring --base because --all was specified\n"))
1220 1220 base = ['null']
1221 1221 else:
1222 1222 base = scmutil.revrange(repo, opts.get('base'))
1223 1223 if cgversion not in changegroup.supportedoutgoingversions(repo):
1224 1224 raise error.Abort(_("repository does not support bundle version %s") %
1225 1225 cgversion)
1226 1226
1227 1227 if base:
1228 1228 if dest:
1229 1229 raise error.Abort(_("--base is incompatible with specifying "
1230 1230 "a destination"))
1231 1231 common = [repo.lookup(rev) for rev in base]
1232 1232 heads = [repo.lookup(r) for r in revs] if revs else None
1233 1233 outgoing = discovery.outgoing(repo, common, heads)
1234 1234 else:
1235 1235 dest = ui.expandpath(dest or 'default-push', dest or 'default')
1236 1236 dest, branches = hg.parseurl(dest, opts.get('branch'))
1237 1237 other = hg.peer(repo, opts, dest)
1238 1238 revs, checkout = hg.addbranchrevs(repo, repo, branches, revs)
1239 1239 heads = revs and map(repo.lookup, revs) or revs
1240 1240 outgoing = discovery.findcommonoutgoing(repo, other,
1241 1241 onlyheads=heads,
1242 1242 force=opts.get('force'),
1243 1243 portable=True)
1244 1244
1245 1245 if not outgoing.missing:
1246 1246 scmutil.nochangesfound(ui, repo, not base and outgoing.excluded)
1247 1247 return 1
1248 1248
1249 1249 bcompression = bundlespec.compression
1250 1250 if cgversion == '01': #bundle1
1251 1251 if bcompression is None:
1252 1252 bcompression = 'UN'
1253 1253 bversion = 'HG10' + bcompression
1254 1254 bcompression = None
1255 1255 elif cgversion in ('02', '03'):
1256 1256 bversion = 'HG20'
1257 1257 else:
1258 1258 raise error.ProgrammingError(
1259 1259 'bundle: unexpected changegroup version %s' % cgversion)
1260 1260
1261 1261 # TODO compression options should be derived from bundlespec parsing.
1262 1262 # This is a temporary hack to allow adjusting bundle compression
1263 1263 # level without a) formalizing the bundlespec changes to declare it
1264 1264 # b) introducing a command flag.
1265 1265 compopts = {}
1266 1266 complevel = ui.configint('experimental', 'bundlecomplevel')
1267 1267 if complevel is not None:
1268 1268 compopts['level'] = complevel
1269 1269
1270 1270 # Allow overriding the bundling of obsmarker in phases through
1271 1271 # configuration while we don't have a bundle version that include them
1272 1272 if repo.ui.configbool('experimental', 'evolution.bundle-obsmarker'):
1273 1273 bundlespec.contentopts['obsolescence'] = True
1274 1274 if repo.ui.configbool('experimental', 'bundle-phases'):
1275 1275 bundlespec.contentopts['phases'] = True
1276 1276
1277 1277 bundle2.writenewbundle(ui, repo, 'bundle', fname, bversion, outgoing,
1278 1278 bundlespec.contentopts, compression=bcompression,
1279 1279 compopts=compopts)
1280 1280
1281 1281 @command('cat',
1282 1282 [('o', 'output', '',
1283 1283 _('print output to file with formatted name'), _('FORMAT')),
1284 1284 ('r', 'rev', '', _('print the given revision'), _('REV')),
1285 1285 ('', 'decode', None, _('apply any matching decode filter')),
1286 1286 ] + walkopts + formatteropts,
1287 1287 _('[OPTION]... FILE...'),
1288 1288 inferrepo=True, cmdtype=readonly)
1289 1289 def cat(ui, repo, file1, *pats, **opts):
1290 1290 """output the current or given revision of files
1291 1291
1292 1292 Print the specified files as they were at the given revision. If
1293 1293 no revision is given, the parent of the working directory is used.
1294 1294
1295 1295 Output may be to a file, in which case the name of the file is
1296 1296 given using a template string. See :hg:`help templates`. In addition
1297 1297 to the common template keywords, the following formatting rules are
1298 1298 supported:
1299 1299
1300 1300 :``%%``: literal "%" character
1301 1301 :``%s``: basename of file being printed
1302 1302 :``%d``: dirname of file being printed, or '.' if in repository root
1303 1303 :``%p``: root-relative path name of file being printed
1304 1304 :``%H``: changeset hash (40 hexadecimal digits)
1305 1305 :``%R``: changeset revision number
1306 1306 :``%h``: short-form changeset hash (12 hexadecimal digits)
1307 1307 :``%r``: zero-padded changeset revision number
1308 1308 :``%b``: basename of the exporting repository
1309 1309 :``\\``: literal "\\" character
1310 1310
1311 1311 Returns 0 on success.
1312 1312 """
1313 1313 opts = pycompat.byteskwargs(opts)
1314 1314 rev = opts.get('rev')
1315 1315 if rev:
1316 1316 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
1317 1317 ctx = scmutil.revsingle(repo, rev)
1318 1318 m = scmutil.match(ctx, (file1,) + pats, opts)
1319 1319 fntemplate = opts.pop('output', '')
1320 1320 if cmdutil.isstdiofilename(fntemplate):
1321 1321 fntemplate = ''
1322 1322
1323 1323 if fntemplate:
1324 1324 fm = formatter.nullformatter(ui, 'cat')
1325 1325 else:
1326 1326 ui.pager('cat')
1327 1327 fm = ui.formatter('cat', opts)
1328 1328 with fm:
1329 1329 return cmdutil.cat(ui, repo, ctx, m, fm, fntemplate, '',
1330 1330 **pycompat.strkwargs(opts))
1331 1331
1332 1332 @command('^clone',
1333 1333 [('U', 'noupdate', None, _('the clone will include an empty working '
1334 1334 'directory (only a repository)')),
1335 1335 ('u', 'updaterev', '', _('revision, tag, or branch to check out'),
1336 1336 _('REV')),
1337 1337 ('r', 'rev', [], _('do not clone everything, but include this changeset'
1338 1338 ' and its ancestors'), _('REV')),
1339 1339 ('b', 'branch', [], _('do not clone everything, but include this branch\'s'
1340 1340 ' changesets and their ancestors'), _('BRANCH')),
1341 1341 ('', 'pull', None, _('use pull protocol to copy metadata')),
1342 1342 ('', 'uncompressed', None,
1343 1343 _('an alias to --stream (DEPRECATED)')),
1344 1344 ('', 'stream', None,
1345 1345 _('clone with minimal data processing')),
1346 1346 ] + remoteopts,
1347 1347 _('[OPTION]... SOURCE [DEST]'),
1348 1348 norepo=True)
1349 1349 def clone(ui, source, dest=None, **opts):
1350 1350 """make a copy of an existing repository
1351 1351
1352 1352 Create a copy of an existing repository in a new directory.
1353 1353
1354 1354 If no destination directory name is specified, it defaults to the
1355 1355 basename of the source.
1356 1356
1357 1357 The location of the source is added to the new repository's
1358 1358 ``.hg/hgrc`` file, as the default to be used for future pulls.
1359 1359
1360 1360 Only local paths and ``ssh://`` URLs are supported as
1361 1361 destinations. For ``ssh://`` destinations, no working directory or
1362 1362 ``.hg/hgrc`` will be created on the remote side.
1363 1363
1364 1364 If the source repository has a bookmark called '@' set, that
1365 1365 revision will be checked out in the new repository by default.
1366 1366
1367 1367 To check out a particular version, use -u/--update, or
1368 1368 -U/--noupdate to create a clone with no working directory.
1369 1369
1370 1370 To pull only a subset of changesets, specify one or more revisions
1371 1371 identifiers with -r/--rev or branches with -b/--branch. The
1372 1372 resulting clone will contain only the specified changesets and
1373 1373 their ancestors. These options (or 'clone src#rev dest') imply
1374 1374 --pull, even for local source repositories.
1375 1375
1376 1376 In normal clone mode, the remote normalizes repository data into a common
1377 1377 exchange format and the receiving end translates this data into its local
1378 1378 storage format. --stream activates a different clone mode that essentially
1379 1379 copies repository files from the remote with minimal data processing. This
1380 1380 significantly reduces the CPU cost of a clone both remotely and locally.
1381 1381 However, it often increases the transferred data size by 30-40%. This can
1382 1382 result in substantially faster clones where I/O throughput is plentiful,
1383 1383 especially for larger repositories. A side-effect of --stream clones is
1384 1384 that storage settings and requirements on the remote are applied locally:
1385 1385 a modern client may inherit legacy or inefficient storage used by the
1386 1386 remote or a legacy Mercurial client may not be able to clone from a
1387 1387 modern Mercurial remote.
1388 1388
1389 1389 .. note::
1390 1390
1391 1391 Specifying a tag will include the tagged changeset but not the
1392 1392 changeset containing the tag.
1393 1393
1394 1394 .. container:: verbose
1395 1395
1396 1396 For efficiency, hardlinks are used for cloning whenever the
1397 1397 source and destination are on the same filesystem (note this
1398 1398 applies only to the repository data, not to the working
1399 1399 directory). Some filesystems, such as AFS, implement hardlinking
1400 1400 incorrectly, but do not report errors. In these cases, use the
1401 1401 --pull option to avoid hardlinking.
1402 1402
1403 1403 Mercurial will update the working directory to the first applicable
1404 1404 revision from this list:
1405 1405
1406 1406 a) null if -U or the source repository has no changesets
1407 1407 b) if -u . and the source repository is local, the first parent of
1408 1408 the source repository's working directory
1409 1409 c) the changeset specified with -u (if a branch name, this means the
1410 1410 latest head of that branch)
1411 1411 d) the changeset specified with -r
1412 1412 e) the tipmost head specified with -b
1413 1413 f) the tipmost head specified with the url#branch source syntax
1414 1414 g) the revision marked with the '@' bookmark, if present
1415 1415 h) the tipmost head of the default branch
1416 1416 i) tip
1417 1417
1418 1418 When cloning from servers that support it, Mercurial may fetch
1419 1419 pre-generated data from a server-advertised URL. When this is done,
1420 1420 hooks operating on incoming changesets and changegroups may fire twice,
1421 1421 once for the bundle fetched from the URL and another for any additional
1422 1422 data not fetched from this URL. In addition, if an error occurs, the
1423 1423 repository may be rolled back to a partial clone. This behavior may
1424 1424 change in future releases. See :hg:`help -e clonebundles` for more.
1425 1425
1426 1426 Examples:
1427 1427
1428 1428 - clone a remote repository to a new directory named hg/::
1429 1429
1430 1430 hg clone https://www.mercurial-scm.org/repo/hg/
1431 1431
1432 1432 - create a lightweight local clone::
1433 1433
1434 1434 hg clone project/ project-feature/
1435 1435
1436 1436 - clone from an absolute path on an ssh server (note double-slash)::
1437 1437
1438 1438 hg clone ssh://user@server//home/projects/alpha/
1439 1439
1440 1440 - do a streaming clone while checking out a specified version::
1441 1441
1442 1442 hg clone --stream http://server/repo -u 1.5
1443 1443
1444 1444 - create a repository without changesets after a particular revision::
1445 1445
1446 1446 hg clone -r 04e544 experimental/ good/
1447 1447
1448 1448 - clone (and track) a particular named branch::
1449 1449
1450 1450 hg clone https://www.mercurial-scm.org/repo/hg/#stable
1451 1451
1452 1452 See :hg:`help urls` for details on specifying URLs.
1453 1453
1454 1454 Returns 0 on success.
1455 1455 """
1456 1456 opts = pycompat.byteskwargs(opts)
1457 1457 if opts.get('noupdate') and opts.get('updaterev'):
1458 1458 raise error.Abort(_("cannot specify both --noupdate and --updaterev"))
1459 1459
1460 1460 r = hg.clone(ui, opts, source, dest,
1461 1461 pull=opts.get('pull'),
1462 1462 stream=opts.get('stream') or opts.get('uncompressed'),
1463 rev=opts.get('rev'),
1463 revs=opts.get('rev'),
1464 1464 update=opts.get('updaterev') or not opts.get('noupdate'),
1465 1465 branch=opts.get('branch'),
1466 1466 shareopts=opts.get('shareopts'))
1467 1467
1468 1468 return r is None
1469 1469
1470 1470 @command('^commit|ci',
1471 1471 [('A', 'addremove', None,
1472 1472 _('mark new/missing files as added/removed before committing')),
1473 1473 ('', 'close-branch', None,
1474 1474 _('mark a branch head as closed')),
1475 1475 ('', 'amend', None, _('amend the parent of the working directory')),
1476 1476 ('s', 'secret', None, _('use the secret phase for committing')),
1477 1477 ('e', 'edit', None, _('invoke editor on commit messages')),
1478 1478 ('i', 'interactive', None, _('use interactive mode')),
1479 1479 ] + walkopts + commitopts + commitopts2 + subrepoopts,
1480 1480 _('[OPTION]... [FILE]...'),
1481 1481 inferrepo=True)
1482 1482 def commit(ui, repo, *pats, **opts):
1483 1483 """commit the specified files or all outstanding changes
1484 1484
1485 1485 Commit changes to the given files into the repository. Unlike a
1486 1486 centralized SCM, this operation is a local operation. See
1487 1487 :hg:`push` for a way to actively distribute your changes.
1488 1488
1489 1489 If a list of files is omitted, all changes reported by :hg:`status`
1490 1490 will be committed.
1491 1491
1492 1492 If you are committing the result of a merge, do not provide any
1493 1493 filenames or -I/-X filters.
1494 1494
1495 1495 If no commit message is specified, Mercurial starts your
1496 1496 configured editor where you can enter a message. In case your
1497 1497 commit fails, you will find a backup of your message in
1498 1498 ``.hg/last-message.txt``.
1499 1499
1500 1500 The --close-branch flag can be used to mark the current branch
1501 1501 head closed. When all heads of a branch are closed, the branch
1502 1502 will be considered closed and no longer listed.
1503 1503
1504 1504 The --amend flag can be used to amend the parent of the
1505 1505 working directory with a new commit that contains the changes
1506 1506 in the parent in addition to those currently reported by :hg:`status`,
1507 1507 if there are any. The old commit is stored in a backup bundle in
1508 1508 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
1509 1509 on how to restore it).
1510 1510
1511 1511 Message, user and date are taken from the amended commit unless
1512 1512 specified. When a message isn't specified on the command line,
1513 1513 the editor will open with the message of the amended commit.
1514 1514
1515 1515 It is not possible to amend public changesets (see :hg:`help phases`)
1516 1516 or changesets that have children.
1517 1517
1518 1518 See :hg:`help dates` for a list of formats valid for -d/--date.
1519 1519
1520 1520 Returns 0 on success, 1 if nothing changed.
1521 1521
1522 1522 .. container:: verbose
1523 1523
1524 1524 Examples:
1525 1525
1526 1526 - commit all files ending in .py::
1527 1527
1528 1528 hg commit --include "set:**.py"
1529 1529
1530 1530 - commit all non-binary files::
1531 1531
1532 1532 hg commit --exclude "set:binary()"
1533 1533
1534 1534 - amend the current commit and set the date to now::
1535 1535
1536 1536 hg commit --amend --date now
1537 1537 """
1538 1538 wlock = lock = None
1539 1539 try:
1540 1540 wlock = repo.wlock()
1541 1541 lock = repo.lock()
1542 1542 return _docommit(ui, repo, *pats, **opts)
1543 1543 finally:
1544 1544 release(lock, wlock)
1545 1545
1546 1546 def _docommit(ui, repo, *pats, **opts):
1547 1547 if opts.get(r'interactive'):
1548 1548 opts.pop(r'interactive')
1549 1549 ret = cmdutil.dorecord(ui, repo, commit, None, False,
1550 1550 cmdutil.recordfilter, *pats,
1551 1551 **opts)
1552 1552 # ret can be 0 (no changes to record) or the value returned by
1553 1553 # commit(), 1 if nothing changed or None on success.
1554 1554 return 1 if ret == 0 else ret
1555 1555
1556 1556 opts = pycompat.byteskwargs(opts)
1557 1557 if opts.get('subrepos'):
1558 1558 if opts.get('amend'):
1559 1559 raise error.Abort(_('cannot amend with --subrepos'))
1560 1560 # Let --subrepos on the command line override config setting.
1561 1561 ui.setconfig('ui', 'commitsubrepos', True, 'commit')
1562 1562
1563 1563 cmdutil.checkunfinished(repo, commit=True)
1564 1564
1565 1565 branch = repo[None].branch()
1566 1566 bheads = repo.branchheads(branch)
1567 1567
1568 1568 extra = {}
1569 1569 if opts.get('close_branch'):
1570 1570 extra['close'] = '1'
1571 1571
1572 1572 if not bheads:
1573 1573 raise error.Abort(_('can only close branch heads'))
1574 1574 elif opts.get('amend'):
1575 1575 if repo[None].parents()[0].p1().branch() != branch and \
1576 1576 repo[None].parents()[0].p2().branch() != branch:
1577 1577 raise error.Abort(_('can only close branch heads'))
1578 1578
1579 1579 if opts.get('amend'):
1580 1580 if ui.configbool('ui', 'commitsubrepos'):
1581 1581 raise error.Abort(_('cannot amend with ui.commitsubrepos enabled'))
1582 1582
1583 1583 old = repo['.']
1584 1584 rewriteutil.precheck(repo, [old.rev()], 'amend')
1585 1585
1586 1586 # Currently histedit gets confused if an amend happens while histedit
1587 1587 # is in progress. Since we have a checkunfinished command, we are
1588 1588 # temporarily honoring it.
1589 1589 #
1590 1590 # Note: eventually this guard will be removed. Please do not expect
1591 1591 # this behavior to remain.
1592 1592 if not obsolete.isenabled(repo, obsolete.createmarkersopt):
1593 1593 cmdutil.checkunfinished(repo)
1594 1594
1595 1595 node = cmdutil.amend(ui, repo, old, extra, pats, opts)
1596 1596 if node == old.node():
1597 1597 ui.status(_("nothing changed\n"))
1598 1598 return 1
1599 1599 else:
1600 1600 def commitfunc(ui, repo, message, match, opts):
1601 1601 overrides = {}
1602 1602 if opts.get('secret'):
1603 1603 overrides[('phases', 'new-commit')] = 'secret'
1604 1604
1605 1605 baseui = repo.baseui
1606 1606 with baseui.configoverride(overrides, 'commit'):
1607 1607 with ui.configoverride(overrides, 'commit'):
1608 1608 editform = cmdutil.mergeeditform(repo[None],
1609 1609 'commit.normal')
1610 1610 editor = cmdutil.getcommiteditor(
1611 1611 editform=editform, **pycompat.strkwargs(opts))
1612 1612 return repo.commit(message,
1613 1613 opts.get('user'),
1614 1614 opts.get('date'),
1615 1615 match,
1616 1616 editor=editor,
1617 1617 extra=extra)
1618 1618
1619 1619 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1620 1620
1621 1621 if not node:
1622 1622 stat = cmdutil.postcommitstatus(repo, pats, opts)
1623 1623 if stat[3]:
1624 1624 ui.status(_("nothing changed (%d missing files, see "
1625 1625 "'hg status')\n") % len(stat[3]))
1626 1626 else:
1627 1627 ui.status(_("nothing changed\n"))
1628 1628 return 1
1629 1629
1630 1630 cmdutil.commitstatus(repo, node, branch, bheads, opts)
1631 1631
1632 1632 @command('config|showconfig|debugconfig',
1633 1633 [('u', 'untrusted', None, _('show untrusted configuration options')),
1634 1634 ('e', 'edit', None, _('edit user config')),
1635 1635 ('l', 'local', None, _('edit repository config')),
1636 1636 ('g', 'global', None, _('edit global config'))] + formatteropts,
1637 1637 _('[-u] [NAME]...'),
1638 1638 optionalrepo=True, cmdtype=readonly)
1639 1639 def config(ui, repo, *values, **opts):
1640 1640 """show combined config settings from all hgrc files
1641 1641
1642 1642 With no arguments, print names and values of all config items.
1643 1643
1644 1644 With one argument of the form section.name, print just the value
1645 1645 of that config item.
1646 1646
1647 1647 With multiple arguments, print names and values of all config
1648 1648 items with matching section names or section.names.
1649 1649
1650 1650 With --edit, start an editor on the user-level config file. With
1651 1651 --global, edit the system-wide config file. With --local, edit the
1652 1652 repository-level config file.
1653 1653
1654 1654 With --debug, the source (filename and line number) is printed
1655 1655 for each config item.
1656 1656
1657 1657 See :hg:`help config` for more information about config files.
1658 1658
1659 1659 Returns 0 on success, 1 if NAME does not exist.
1660 1660
1661 1661 """
1662 1662
1663 1663 opts = pycompat.byteskwargs(opts)
1664 1664 if opts.get('edit') or opts.get('local') or opts.get('global'):
1665 1665 if opts.get('local') and opts.get('global'):
1666 1666 raise error.Abort(_("can't use --local and --global together"))
1667 1667
1668 1668 if opts.get('local'):
1669 1669 if not repo:
1670 1670 raise error.Abort(_("can't use --local outside a repository"))
1671 1671 paths = [repo.vfs.join('hgrc')]
1672 1672 elif opts.get('global'):
1673 1673 paths = rcutil.systemrcpath()
1674 1674 else:
1675 1675 paths = rcutil.userrcpath()
1676 1676
1677 1677 for f in paths:
1678 1678 if os.path.exists(f):
1679 1679 break
1680 1680 else:
1681 1681 if opts.get('global'):
1682 1682 samplehgrc = uimod.samplehgrcs['global']
1683 1683 elif opts.get('local'):
1684 1684 samplehgrc = uimod.samplehgrcs['local']
1685 1685 else:
1686 1686 samplehgrc = uimod.samplehgrcs['user']
1687 1687
1688 1688 f = paths[0]
1689 1689 fp = open(f, "wb")
1690 1690 fp.write(util.tonativeeol(samplehgrc))
1691 1691 fp.close()
1692 1692
1693 1693 editor = ui.geteditor()
1694 1694 ui.system("%s \"%s\"" % (editor, f),
1695 1695 onerr=error.Abort, errprefix=_("edit failed"),
1696 1696 blockedtag='config_edit')
1697 1697 return
1698 1698 ui.pager('config')
1699 1699 fm = ui.formatter('config', opts)
1700 1700 for t, f in rcutil.rccomponents():
1701 1701 if t == 'path':
1702 1702 ui.debug('read config from: %s\n' % f)
1703 1703 elif t == 'items':
1704 1704 for section, name, value, source in f:
1705 1705 ui.debug('set config by: %s\n' % source)
1706 1706 else:
1707 1707 raise error.ProgrammingError('unknown rctype: %s' % t)
1708 1708 untrusted = bool(opts.get('untrusted'))
1709 1709
1710 1710 selsections = selentries = []
1711 1711 if values:
1712 1712 selsections = [v for v in values if '.' not in v]
1713 1713 selentries = [v for v in values if '.' in v]
1714 1714 uniquesel = (len(selentries) == 1 and not selsections)
1715 1715 selsections = set(selsections)
1716 1716 selentries = set(selentries)
1717 1717
1718 1718 matched = False
1719 1719 for section, name, value in ui.walkconfig(untrusted=untrusted):
1720 1720 source = ui.configsource(section, name, untrusted)
1721 1721 value = pycompat.bytestr(value)
1722 1722 if fm.isplain():
1723 1723 source = source or 'none'
1724 1724 value = value.replace('\n', '\\n')
1725 1725 entryname = section + '.' + name
1726 1726 if values and not (section in selsections or entryname in selentries):
1727 1727 continue
1728 1728 fm.startitem()
1729 1729 fm.condwrite(ui.debugflag, 'source', '%s: ', source)
1730 1730 if uniquesel:
1731 1731 fm.data(name=entryname)
1732 1732 fm.write('value', '%s\n', value)
1733 1733 else:
1734 1734 fm.write('name value', '%s=%s\n', entryname, value)
1735 1735 matched = True
1736 1736 fm.end()
1737 1737 if matched:
1738 1738 return 0
1739 1739 return 1
1740 1740
1741 1741 @command('copy|cp',
1742 1742 [('A', 'after', None, _('record a copy that has already occurred')),
1743 1743 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1744 1744 ] + walkopts + dryrunopts,
1745 1745 _('[OPTION]... [SOURCE]... DEST'))
1746 1746 def copy(ui, repo, *pats, **opts):
1747 1747 """mark files as copied for the next commit
1748 1748
1749 1749 Mark dest as having copies of source files. If dest is a
1750 1750 directory, copies are put in that directory. If dest is a file,
1751 1751 the source must be a single file.
1752 1752
1753 1753 By default, this command copies the contents of files as they
1754 1754 exist in the working directory. If invoked with -A/--after, the
1755 1755 operation is recorded, but no copying is performed.
1756 1756
1757 1757 This command takes effect with the next commit. To undo a copy
1758 1758 before that, see :hg:`revert`.
1759 1759
1760 1760 Returns 0 on success, 1 if errors are encountered.
1761 1761 """
1762 1762 opts = pycompat.byteskwargs(opts)
1763 1763 with repo.wlock(False):
1764 1764 return cmdutil.copy(ui, repo, pats, opts)
1765 1765
1766 1766 @command('debugcommands', [], _('[COMMAND]'), norepo=True)
1767 1767 def debugcommands(ui, cmd='', *args):
1768 1768 """list all available commands and options"""
1769 1769 for cmd, vals in sorted(table.iteritems()):
1770 1770 cmd = cmd.split('|')[0].strip('^')
1771 1771 opts = ', '.join([i[1] for i in vals[1]])
1772 1772 ui.write('%s: %s\n' % (cmd, opts))
1773 1773
1774 1774 @command('debugcomplete',
1775 1775 [('o', 'options', None, _('show the command options'))],
1776 1776 _('[-o] CMD'),
1777 1777 norepo=True)
1778 1778 def debugcomplete(ui, cmd='', **opts):
1779 1779 """returns the completion list associated with the given command"""
1780 1780
1781 1781 if opts.get(r'options'):
1782 1782 options = []
1783 1783 otables = [globalopts]
1784 1784 if cmd:
1785 1785 aliases, entry = cmdutil.findcmd(cmd, table, False)
1786 1786 otables.append(entry[1])
1787 1787 for t in otables:
1788 1788 for o in t:
1789 1789 if "(DEPRECATED)" in o[3]:
1790 1790 continue
1791 1791 if o[0]:
1792 1792 options.append('-%s' % o[0])
1793 1793 options.append('--%s' % o[1])
1794 1794 ui.write("%s\n" % "\n".join(options))
1795 1795 return
1796 1796
1797 1797 cmdlist, unused_allcmds = cmdutil.findpossible(cmd, table)
1798 1798 if ui.verbose:
1799 1799 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1800 1800 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1801 1801
1802 1802 @command('^diff',
1803 1803 [('r', 'rev', [], _('revision'), _('REV')),
1804 1804 ('c', 'change', '', _('change made by revision'), _('REV'))
1805 1805 ] + diffopts + diffopts2 + walkopts + subrepoopts,
1806 1806 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'),
1807 1807 inferrepo=True, cmdtype=readonly)
1808 1808 def diff(ui, repo, *pats, **opts):
1809 1809 """diff repository (or selected files)
1810 1810
1811 1811 Show differences between revisions for the specified files.
1812 1812
1813 1813 Differences between files are shown using the unified diff format.
1814 1814
1815 1815 .. note::
1816 1816
1817 1817 :hg:`diff` may generate unexpected results for merges, as it will
1818 1818 default to comparing against the working directory's first
1819 1819 parent changeset if no revisions are specified.
1820 1820
1821 1821 When two revision arguments are given, then changes are shown
1822 1822 between those revisions. If only one revision is specified then
1823 1823 that revision is compared to the working directory, and, when no
1824 1824 revisions are specified, the working directory files are compared
1825 1825 to its first parent.
1826 1826
1827 1827 Alternatively you can specify -c/--change with a revision to see
1828 1828 the changes in that changeset relative to its first parent.
1829 1829
1830 1830 Without the -a/--text option, diff will avoid generating diffs of
1831 1831 files it detects as binary. With -a, diff will generate a diff
1832 1832 anyway, probably with undesirable results.
1833 1833
1834 1834 Use the -g/--git option to generate diffs in the git extended diff
1835 1835 format. For more information, read :hg:`help diffs`.
1836 1836
1837 1837 .. container:: verbose
1838 1838
1839 1839 Examples:
1840 1840
1841 1841 - compare a file in the current working directory to its parent::
1842 1842
1843 1843 hg diff foo.c
1844 1844
1845 1845 - compare two historical versions of a directory, with rename info::
1846 1846
1847 1847 hg diff --git -r 1.0:1.2 lib/
1848 1848
1849 1849 - get change stats relative to the last change on some date::
1850 1850
1851 1851 hg diff --stat -r "date('may 2')"
1852 1852
1853 1853 - diff all newly-added files that contain a keyword::
1854 1854
1855 1855 hg diff "set:added() and grep(GNU)"
1856 1856
1857 1857 - compare a revision and its parents::
1858 1858
1859 1859 hg diff -c 9353 # compare against first parent
1860 1860 hg diff -r 9353^:9353 # same using revset syntax
1861 1861 hg diff -r 9353^2:9353 # compare against the second parent
1862 1862
1863 1863 Returns 0 on success.
1864 1864 """
1865 1865
1866 1866 opts = pycompat.byteskwargs(opts)
1867 1867 revs = opts.get('rev')
1868 1868 change = opts.get('change')
1869 1869 stat = opts.get('stat')
1870 1870 reverse = opts.get('reverse')
1871 1871
1872 1872 if revs and change:
1873 1873 msg = _('cannot specify --rev and --change at the same time')
1874 1874 raise error.Abort(msg)
1875 1875 elif change:
1876 1876 repo = scmutil.unhidehashlikerevs(repo, [change], 'nowarn')
1877 1877 ctx2 = scmutil.revsingle(repo, change, None)
1878 1878 ctx1 = ctx2.p1()
1879 1879 else:
1880 1880 repo = scmutil.unhidehashlikerevs(repo, revs, 'nowarn')
1881 1881 ctx1, ctx2 = scmutil.revpair(repo, revs)
1882 1882 node1, node2 = ctx1.node(), ctx2.node()
1883 1883
1884 1884 if reverse:
1885 1885 node1, node2 = node2, node1
1886 1886
1887 1887 diffopts = patch.diffallopts(ui, opts)
1888 1888 m = scmutil.match(ctx2, pats, opts)
1889 1889 ui.pager('diff')
1890 1890 logcmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
1891 1891 listsubrepos=opts.get('subrepos'),
1892 1892 root=opts.get('root'))
1893 1893
1894 1894 @command('^export',
1895 1895 [('o', 'output', '',
1896 1896 _('print output to file with formatted name'), _('FORMAT')),
1897 1897 ('', 'switch-parent', None, _('diff against the second parent')),
1898 1898 ('r', 'rev', [], _('revisions to export'), _('REV')),
1899 1899 ] + diffopts,
1900 1900 _('[OPTION]... [-o OUTFILESPEC] [-r] [REV]...'), cmdtype=readonly)
1901 1901 def export(ui, repo, *changesets, **opts):
1902 1902 """dump the header and diffs for one or more changesets
1903 1903
1904 1904 Print the changeset header and diffs for one or more revisions.
1905 1905 If no revision is given, the parent of the working directory is used.
1906 1906
1907 1907 The information shown in the changeset header is: author, date,
1908 1908 branch name (if non-default), changeset hash, parent(s) and commit
1909 1909 comment.
1910 1910
1911 1911 .. note::
1912 1912
1913 1913 :hg:`export` may generate unexpected diff output for merge
1914 1914 changesets, as it will compare the merge changeset against its
1915 1915 first parent only.
1916 1916
1917 1917 Output may be to a file, in which case the name of the file is
1918 1918 given using a template string. See :hg:`help templates`. In addition
1919 1919 to the common template keywords, the following formatting rules are
1920 1920 supported:
1921 1921
1922 1922 :``%%``: literal "%" character
1923 1923 :``%H``: changeset hash (40 hexadecimal digits)
1924 1924 :``%N``: number of patches being generated
1925 1925 :``%R``: changeset revision number
1926 1926 :``%b``: basename of the exporting repository
1927 1927 :``%h``: short-form changeset hash (12 hexadecimal digits)
1928 1928 :``%m``: first line of the commit message (only alphanumeric characters)
1929 1929 :``%n``: zero-padded sequence number, starting at 1
1930 1930 :``%r``: zero-padded changeset revision number
1931 1931 :``\\``: literal "\\" character
1932 1932
1933 1933 Without the -a/--text option, export will avoid generating diffs
1934 1934 of files it detects as binary. With -a, export will generate a
1935 1935 diff anyway, probably with undesirable results.
1936 1936
1937 1937 Use the -g/--git option to generate diffs in the git extended diff
1938 1938 format. See :hg:`help diffs` for more information.
1939 1939
1940 1940 With the --switch-parent option, the diff will be against the
1941 1941 second parent. It can be useful to review a merge.
1942 1942
1943 1943 .. container:: verbose
1944 1944
1945 1945 Examples:
1946 1946
1947 1947 - use export and import to transplant a bugfix to the current
1948 1948 branch::
1949 1949
1950 1950 hg export -r 9353 | hg import -
1951 1951
1952 1952 - export all the changesets between two revisions to a file with
1953 1953 rename information::
1954 1954
1955 1955 hg export --git -r 123:150 > changes.txt
1956 1956
1957 1957 - split outgoing changes into a series of patches with
1958 1958 descriptive names::
1959 1959
1960 1960 hg export -r "outgoing()" -o "%n-%m.patch"
1961 1961
1962 1962 Returns 0 on success.
1963 1963 """
1964 1964 opts = pycompat.byteskwargs(opts)
1965 1965 changesets += tuple(opts.get('rev', []))
1966 1966 if not changesets:
1967 1967 changesets = ['.']
1968 1968 repo = scmutil.unhidehashlikerevs(repo, changesets, 'nowarn')
1969 1969 revs = scmutil.revrange(repo, changesets)
1970 1970 if not revs:
1971 1971 raise error.Abort(_("export requires at least one changeset"))
1972 1972 if len(revs) > 1:
1973 1973 ui.note(_('exporting patches:\n'))
1974 1974 else:
1975 1975 ui.note(_('exporting patch:\n'))
1976 1976 ui.pager('export')
1977 1977 cmdutil.export(repo, revs, fntemplate=opts.get('output'),
1978 1978 switch_parent=opts.get('switch_parent'),
1979 1979 opts=patch.diffallopts(ui, opts))
1980 1980
1981 1981 @command('files',
1982 1982 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
1983 1983 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
1984 1984 ] + walkopts + formatteropts + subrepoopts,
1985 1985 _('[OPTION]... [FILE]...'), cmdtype=readonly)
1986 1986 def files(ui, repo, *pats, **opts):
1987 1987 """list tracked files
1988 1988
1989 1989 Print files under Mercurial control in the working directory or
1990 1990 specified revision for given files (excluding removed files).
1991 1991 Files can be specified as filenames or filesets.
1992 1992
1993 1993 If no files are given to match, this command prints the names
1994 1994 of all files under Mercurial control.
1995 1995
1996 1996 .. container:: verbose
1997 1997
1998 1998 Examples:
1999 1999
2000 2000 - list all files under the current directory::
2001 2001
2002 2002 hg files .
2003 2003
2004 2004 - shows sizes and flags for current revision::
2005 2005
2006 2006 hg files -vr .
2007 2007
2008 2008 - list all files named README::
2009 2009
2010 2010 hg files -I "**/README"
2011 2011
2012 2012 - list all binary files::
2013 2013
2014 2014 hg files "set:binary()"
2015 2015
2016 2016 - find files containing a regular expression::
2017 2017
2018 2018 hg files "set:grep('bob')"
2019 2019
2020 2020 - search tracked file contents with xargs and grep::
2021 2021
2022 2022 hg files -0 | xargs -0 grep foo
2023 2023
2024 2024 See :hg:`help patterns` and :hg:`help filesets` for more information
2025 2025 on specifying file patterns.
2026 2026
2027 2027 Returns 0 if a match is found, 1 otherwise.
2028 2028
2029 2029 """
2030 2030
2031 2031 opts = pycompat.byteskwargs(opts)
2032 2032 rev = opts.get('rev')
2033 2033 if rev:
2034 2034 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
2035 2035 ctx = scmutil.revsingle(repo, rev, None)
2036 2036
2037 2037 end = '\n'
2038 2038 if opts.get('print0'):
2039 2039 end = '\0'
2040 2040 fmt = '%s' + end
2041 2041
2042 2042 m = scmutil.match(ctx, pats, opts)
2043 2043 ui.pager('files')
2044 2044 with ui.formatter('files', opts) as fm:
2045 2045 return cmdutil.files(ui, ctx, m, fm, fmt, opts.get('subrepos'))
2046 2046
2047 2047 @command(
2048 2048 '^forget',
2049 2049 walkopts + dryrunopts,
2050 2050 _('[OPTION]... FILE...'), inferrepo=True)
2051 2051 def forget(ui, repo, *pats, **opts):
2052 2052 """forget the specified files on the next commit
2053 2053
2054 2054 Mark the specified files so they will no longer be tracked
2055 2055 after the next commit.
2056 2056
2057 2057 This only removes files from the current branch, not from the
2058 2058 entire project history, and it does not delete them from the
2059 2059 working directory.
2060 2060
2061 2061 To delete the file from the working directory, see :hg:`remove`.
2062 2062
2063 2063 To undo a forget before the next commit, see :hg:`add`.
2064 2064
2065 2065 .. container:: verbose
2066 2066
2067 2067 Examples:
2068 2068
2069 2069 - forget newly-added binary files::
2070 2070
2071 2071 hg forget "set:added() and binary()"
2072 2072
2073 2073 - forget files that would be excluded by .hgignore::
2074 2074
2075 2075 hg forget "set:hgignore()"
2076 2076
2077 2077 Returns 0 on success.
2078 2078 """
2079 2079
2080 2080 opts = pycompat.byteskwargs(opts)
2081 2081 if not pats:
2082 2082 raise error.Abort(_('no files specified'))
2083 2083
2084 2084 m = scmutil.match(repo[None], pats, opts)
2085 2085 dryrun = opts.get(r'dry_run')
2086 2086 rejected = cmdutil.forget(ui, repo, m, prefix="",
2087 2087 explicitonly=False, dryrun=dryrun)[0]
2088 2088 return rejected and 1 or 0
2089 2089
2090 2090 @command(
2091 2091 'graft',
2092 2092 [('r', 'rev', [], _('revisions to graft'), _('REV')),
2093 2093 ('c', 'continue', False, _('resume interrupted graft')),
2094 2094 ('e', 'edit', False, _('invoke editor on commit messages')),
2095 2095 ('', 'log', None, _('append graft info to log message')),
2096 2096 ('f', 'force', False, _('force graft')),
2097 2097 ('D', 'currentdate', False,
2098 2098 _('record the current date as commit date')),
2099 2099 ('U', 'currentuser', False,
2100 2100 _('record the current user as committer'), _('DATE'))]
2101 2101 + commitopts2 + mergetoolopts + dryrunopts,
2102 2102 _('[OPTION]... [-r REV]... REV...'))
2103 2103 def graft(ui, repo, *revs, **opts):
2104 2104 '''copy changes from other branches onto the current branch
2105 2105
2106 2106 This command uses Mercurial's merge logic to copy individual
2107 2107 changes from other branches without merging branches in the
2108 2108 history graph. This is sometimes known as 'backporting' or
2109 2109 'cherry-picking'. By default, graft will copy user, date, and
2110 2110 description from the source changesets.
2111 2111
2112 2112 Changesets that are ancestors of the current revision, that have
2113 2113 already been grafted, or that are merges will be skipped.
2114 2114
2115 2115 If --log is specified, log messages will have a comment appended
2116 2116 of the form::
2117 2117
2118 2118 (grafted from CHANGESETHASH)
2119 2119
2120 2120 If --force is specified, revisions will be grafted even if they
2121 2121 are already ancestors of, or have been grafted to, the destination.
2122 2122 This is useful when the revisions have since been backed out.
2123 2123
2124 2124 If a graft merge results in conflicts, the graft process is
2125 2125 interrupted so that the current merge can be manually resolved.
2126 2126 Once all conflicts are addressed, the graft process can be
2127 2127 continued with the -c/--continue option.
2128 2128
2129 2129 .. note::
2130 2130
2131 2131 The -c/--continue option does not reapply earlier options, except
2132 2132 for --force.
2133 2133
2134 2134 .. container:: verbose
2135 2135
2136 2136 Examples:
2137 2137
2138 2138 - copy a single change to the stable branch and edit its description::
2139 2139
2140 2140 hg update stable
2141 2141 hg graft --edit 9393
2142 2142
2143 2143 - graft a range of changesets with one exception, updating dates::
2144 2144
2145 2145 hg graft -D "2085::2093 and not 2091"
2146 2146
2147 2147 - continue a graft after resolving conflicts::
2148 2148
2149 2149 hg graft -c
2150 2150
2151 2151 - show the source of a grafted changeset::
2152 2152
2153 2153 hg log --debug -r .
2154 2154
2155 2155 - show revisions sorted by date::
2156 2156
2157 2157 hg log -r "sort(all(), date)"
2158 2158
2159 2159 See :hg:`help revisions` for more about specifying revisions.
2160 2160
2161 2161 Returns 0 on successful completion.
2162 2162 '''
2163 2163 with repo.wlock():
2164 2164 return _dograft(ui, repo, *revs, **opts)
2165 2165
2166 2166 def _dograft(ui, repo, *revs, **opts):
2167 2167 opts = pycompat.byteskwargs(opts)
2168 2168 if revs and opts.get('rev'):
2169 2169 ui.warn(_('warning: inconsistent use of --rev might give unexpected '
2170 2170 'revision ordering!\n'))
2171 2171
2172 2172 revs = list(revs)
2173 2173 revs.extend(opts.get('rev'))
2174 2174
2175 2175 if not opts.get('user') and opts.get('currentuser'):
2176 2176 opts['user'] = ui.username()
2177 2177 if not opts.get('date') and opts.get('currentdate'):
2178 2178 opts['date'] = "%d %d" % dateutil.makedate()
2179 2179
2180 2180 editor = cmdutil.getcommiteditor(editform='graft',
2181 2181 **pycompat.strkwargs(opts))
2182 2182
2183 2183 cont = False
2184 2184 if opts.get('continue'):
2185 2185 cont = True
2186 2186 if revs:
2187 2187 raise error.Abort(_("can't specify --continue and revisions"))
2188 2188 # read in unfinished revisions
2189 2189 try:
2190 2190 nodes = repo.vfs.read('graftstate').splitlines()
2191 2191 revs = [repo[node].rev() for node in nodes]
2192 2192 except IOError as inst:
2193 2193 if inst.errno != errno.ENOENT:
2194 2194 raise
2195 2195 cmdutil.wrongtooltocontinue(repo, _('graft'))
2196 2196 else:
2197 2197 if not revs:
2198 2198 raise error.Abort(_('no revisions specified'))
2199 2199 cmdutil.checkunfinished(repo)
2200 2200 cmdutil.bailifchanged(repo)
2201 2201 revs = scmutil.revrange(repo, revs)
2202 2202
2203 2203 skipped = set()
2204 2204 # check for merges
2205 2205 for rev in repo.revs('%ld and merge()', revs):
2206 2206 ui.warn(_('skipping ungraftable merge revision %d\n') % rev)
2207 2207 skipped.add(rev)
2208 2208 revs = [r for r in revs if r not in skipped]
2209 2209 if not revs:
2210 2210 return -1
2211 2211
2212 2212 # Don't check in the --continue case, in effect retaining --force across
2213 2213 # --continues. That's because without --force, any revisions we decided to
2214 2214 # skip would have been filtered out here, so they wouldn't have made their
2215 2215 # way to the graftstate. With --force, any revisions we would have otherwise
2216 2216 # skipped would not have been filtered out, and if they hadn't been applied
2217 2217 # already, they'd have been in the graftstate.
2218 2218 if not (cont or opts.get('force')):
2219 2219 # check for ancestors of dest branch
2220 2220 crev = repo['.'].rev()
2221 2221 ancestors = repo.changelog.ancestors([crev], inclusive=True)
2222 2222 # XXX make this lazy in the future
2223 2223 # don't mutate while iterating, create a copy
2224 2224 for rev in list(revs):
2225 2225 if rev in ancestors:
2226 2226 ui.warn(_('skipping ancestor revision %d:%s\n') %
2227 2227 (rev, repo[rev]))
2228 2228 # XXX remove on list is slow
2229 2229 revs.remove(rev)
2230 2230 if not revs:
2231 2231 return -1
2232 2232
2233 2233 # analyze revs for earlier grafts
2234 2234 ids = {}
2235 2235 for ctx in repo.set("%ld", revs):
2236 2236 ids[ctx.hex()] = ctx.rev()
2237 2237 n = ctx.extra().get('source')
2238 2238 if n:
2239 2239 ids[n] = ctx.rev()
2240 2240
2241 2241 # check ancestors for earlier grafts
2242 2242 ui.debug('scanning for duplicate grafts\n')
2243 2243
2244 2244 # The only changesets we can be sure doesn't contain grafts of any
2245 2245 # revs, are the ones that are common ancestors of *all* revs:
2246 2246 for rev in repo.revs('only(%d,ancestor(%ld))', crev, revs):
2247 2247 ctx = repo[rev]
2248 2248 n = ctx.extra().get('source')
2249 2249 if n in ids:
2250 2250 try:
2251 2251 r = repo[n].rev()
2252 2252 except error.RepoLookupError:
2253 2253 r = None
2254 2254 if r in revs:
2255 2255 ui.warn(_('skipping revision %d:%s '
2256 2256 '(already grafted to %d:%s)\n')
2257 2257 % (r, repo[r], rev, ctx))
2258 2258 revs.remove(r)
2259 2259 elif ids[n] in revs:
2260 2260 if r is None:
2261 2261 ui.warn(_('skipping already grafted revision %d:%s '
2262 2262 '(%d:%s also has unknown origin %s)\n')
2263 2263 % (ids[n], repo[ids[n]], rev, ctx, n[:12]))
2264 2264 else:
2265 2265 ui.warn(_('skipping already grafted revision %d:%s '
2266 2266 '(%d:%s also has origin %d:%s)\n')
2267 2267 % (ids[n], repo[ids[n]], rev, ctx, r, n[:12]))
2268 2268 revs.remove(ids[n])
2269 2269 elif ctx.hex() in ids:
2270 2270 r = ids[ctx.hex()]
2271 2271 ui.warn(_('skipping already grafted revision %d:%s '
2272 2272 '(was grafted from %d:%s)\n') %
2273 2273 (r, repo[r], rev, ctx))
2274 2274 revs.remove(r)
2275 2275 if not revs:
2276 2276 return -1
2277 2277
2278 2278 for pos, ctx in enumerate(repo.set("%ld", revs)):
2279 2279 desc = '%d:%s "%s"' % (ctx.rev(), ctx,
2280 2280 ctx.description().split('\n', 1)[0])
2281 2281 names = repo.nodetags(ctx.node()) + repo.nodebookmarks(ctx.node())
2282 2282 if names:
2283 2283 desc += ' (%s)' % ' '.join(names)
2284 2284 ui.status(_('grafting %s\n') % desc)
2285 2285 if opts.get('dry_run'):
2286 2286 continue
2287 2287
2288 2288 source = ctx.extra().get('source')
2289 2289 extra = {}
2290 2290 if source:
2291 2291 extra['source'] = source
2292 2292 extra['intermediate-source'] = ctx.hex()
2293 2293 else:
2294 2294 extra['source'] = ctx.hex()
2295 2295 user = ctx.user()
2296 2296 if opts.get('user'):
2297 2297 user = opts['user']
2298 2298 date = ctx.date()
2299 2299 if opts.get('date'):
2300 2300 date = opts['date']
2301 2301 message = ctx.description()
2302 2302 if opts.get('log'):
2303 2303 message += '\n(grafted from %s)' % ctx.hex()
2304 2304
2305 2305 # we don't merge the first commit when continuing
2306 2306 if not cont:
2307 2307 # perform the graft merge with p1(rev) as 'ancestor'
2308 2308 try:
2309 2309 # ui.forcemerge is an internal variable, do not document
2310 2310 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
2311 2311 'graft')
2312 2312 stats = mergemod.graft(repo, ctx, ctx.p1(),
2313 2313 ['local', 'graft'])
2314 2314 finally:
2315 2315 repo.ui.setconfig('ui', 'forcemerge', '', 'graft')
2316 2316 # report any conflicts
2317 2317 if stats.unresolvedcount > 0:
2318 2318 # write out state for --continue
2319 2319 nodelines = [repo[rev].hex() + "\n" for rev in revs[pos:]]
2320 2320 repo.vfs.write('graftstate', ''.join(nodelines))
2321 2321 extra = ''
2322 2322 if opts.get('user'):
2323 2323 extra += ' --user %s' % procutil.shellquote(opts['user'])
2324 2324 if opts.get('date'):
2325 2325 extra += ' --date %s' % procutil.shellquote(opts['date'])
2326 2326 if opts.get('log'):
2327 2327 extra += ' --log'
2328 2328 hint=_("use 'hg resolve' and 'hg graft --continue%s'") % extra
2329 2329 raise error.Abort(
2330 2330 _("unresolved conflicts, can't continue"),
2331 2331 hint=hint)
2332 2332 else:
2333 2333 cont = False
2334 2334
2335 2335 # commit
2336 2336 node = repo.commit(text=message, user=user,
2337 2337 date=date, extra=extra, editor=editor)
2338 2338 if node is None:
2339 2339 ui.warn(
2340 2340 _('note: graft of %d:%s created no changes to commit\n') %
2341 2341 (ctx.rev(), ctx))
2342 2342
2343 2343 # remove state when we complete successfully
2344 2344 if not opts.get('dry_run'):
2345 2345 repo.vfs.unlinkpath('graftstate', ignoremissing=True)
2346 2346
2347 2347 return 0
2348 2348
2349 2349 @command('grep',
2350 2350 [('0', 'print0', None, _('end fields with NUL')),
2351 2351 ('', 'all', None, _('print all revisions that match')),
2352 2352 ('a', 'text', None, _('treat all files as text')),
2353 2353 ('f', 'follow', None,
2354 2354 _('follow changeset history,'
2355 2355 ' or file history across copies and renames')),
2356 2356 ('i', 'ignore-case', None, _('ignore case when matching')),
2357 2357 ('l', 'files-with-matches', None,
2358 2358 _('print only filenames and revisions that match')),
2359 2359 ('n', 'line-number', None, _('print matching line numbers')),
2360 2360 ('r', 'rev', [],
2361 2361 _('only search files changed within revision range'), _('REV')),
2362 2362 ('u', 'user', None, _('list the author (long with -v)')),
2363 2363 ('d', 'date', None, _('list the date (short with -q)')),
2364 2364 ] + formatteropts + walkopts,
2365 2365 _('[OPTION]... PATTERN [FILE]...'),
2366 2366 inferrepo=True, cmdtype=readonly)
2367 2367 def grep(ui, repo, pattern, *pats, **opts):
2368 2368 """search revision history for a pattern in specified files
2369 2369
2370 2370 Search revision history for a regular expression in the specified
2371 2371 files or the entire project.
2372 2372
2373 2373 By default, grep prints the most recent revision number for each
2374 2374 file in which it finds a match. To get it to print every revision
2375 2375 that contains a change in match status ("-" for a match that becomes
2376 2376 a non-match, or "+" for a non-match that becomes a match), use the
2377 2377 --all flag.
2378 2378
2379 2379 PATTERN can be any Python (roughly Perl-compatible) regular
2380 2380 expression.
2381 2381
2382 2382 If no FILEs are specified (and -f/--follow isn't set), all files in
2383 2383 the repository are searched, including those that don't exist in the
2384 2384 current branch or have been deleted in a prior changeset.
2385 2385
2386 2386 Returns 0 if a match is found, 1 otherwise.
2387 2387 """
2388 2388 opts = pycompat.byteskwargs(opts)
2389 2389 reflags = re.M
2390 2390 if opts.get('ignore_case'):
2391 2391 reflags |= re.I
2392 2392 try:
2393 2393 regexp = util.re.compile(pattern, reflags)
2394 2394 except re.error as inst:
2395 2395 ui.warn(_("grep: invalid match pattern: %s\n") % pycompat.bytestr(inst))
2396 2396 return 1
2397 2397 sep, eol = ':', '\n'
2398 2398 if opts.get('print0'):
2399 2399 sep = eol = '\0'
2400 2400
2401 2401 getfile = util.lrucachefunc(repo.file)
2402 2402
2403 2403 def matchlines(body):
2404 2404 begin = 0
2405 2405 linenum = 0
2406 2406 while begin < len(body):
2407 2407 match = regexp.search(body, begin)
2408 2408 if not match:
2409 2409 break
2410 2410 mstart, mend = match.span()
2411 2411 linenum += body.count('\n', begin, mstart) + 1
2412 2412 lstart = body.rfind('\n', begin, mstart) + 1 or begin
2413 2413 begin = body.find('\n', mend) + 1 or len(body) + 1
2414 2414 lend = begin - 1
2415 2415 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
2416 2416
2417 2417 class linestate(object):
2418 2418 def __init__(self, line, linenum, colstart, colend):
2419 2419 self.line = line
2420 2420 self.linenum = linenum
2421 2421 self.colstart = colstart
2422 2422 self.colend = colend
2423 2423
2424 2424 def __hash__(self):
2425 2425 return hash((self.linenum, self.line))
2426 2426
2427 2427 def __eq__(self, other):
2428 2428 return self.line == other.line
2429 2429
2430 2430 def findpos(self):
2431 2431 """Iterate all (start, end) indices of matches"""
2432 2432 yield self.colstart, self.colend
2433 2433 p = self.colend
2434 2434 while p < len(self.line):
2435 2435 m = regexp.search(self.line, p)
2436 2436 if not m:
2437 2437 break
2438 2438 yield m.span()
2439 2439 p = m.end()
2440 2440
2441 2441 matches = {}
2442 2442 copies = {}
2443 2443 def grepbody(fn, rev, body):
2444 2444 matches[rev].setdefault(fn, [])
2445 2445 m = matches[rev][fn]
2446 2446 for lnum, cstart, cend, line in matchlines(body):
2447 2447 s = linestate(line, lnum, cstart, cend)
2448 2448 m.append(s)
2449 2449
2450 2450 def difflinestates(a, b):
2451 2451 sm = difflib.SequenceMatcher(None, a, b)
2452 2452 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2453 2453 if tag == 'insert':
2454 2454 for i in xrange(blo, bhi):
2455 2455 yield ('+', b[i])
2456 2456 elif tag == 'delete':
2457 2457 for i in xrange(alo, ahi):
2458 2458 yield ('-', a[i])
2459 2459 elif tag == 'replace':
2460 2460 for i in xrange(alo, ahi):
2461 2461 yield ('-', a[i])
2462 2462 for i in xrange(blo, bhi):
2463 2463 yield ('+', b[i])
2464 2464
2465 2465 def display(fm, fn, ctx, pstates, states):
2466 2466 rev = ctx.rev()
2467 2467 if fm.isplain():
2468 2468 formatuser = ui.shortuser
2469 2469 else:
2470 2470 formatuser = str
2471 2471 if ui.quiet:
2472 2472 datefmt = '%Y-%m-%d'
2473 2473 else:
2474 2474 datefmt = '%a %b %d %H:%M:%S %Y %1%2'
2475 2475 found = False
2476 2476 @util.cachefunc
2477 2477 def binary():
2478 2478 flog = getfile(fn)
2479 2479 return stringutil.binary(flog.read(ctx.filenode(fn)))
2480 2480
2481 2481 fieldnamemap = {'filename': 'file', 'linenumber': 'line_number'}
2482 2482 if opts.get('all'):
2483 2483 iter = difflinestates(pstates, states)
2484 2484 else:
2485 2485 iter = [('', l) for l in states]
2486 2486 for change, l in iter:
2487 2487 fm.startitem()
2488 2488 fm.data(node=fm.hexfunc(ctx.node()))
2489 2489 cols = [
2490 2490 ('filename', fn, True),
2491 2491 ('rev', rev, True),
2492 2492 ('linenumber', l.linenum, opts.get('line_number')),
2493 2493 ]
2494 2494 if opts.get('all'):
2495 2495 cols.append(('change', change, True))
2496 2496 cols.extend([
2497 2497 ('user', formatuser(ctx.user()), opts.get('user')),
2498 2498 ('date', fm.formatdate(ctx.date(), datefmt), opts.get('date')),
2499 2499 ])
2500 2500 lastcol = next(name for name, data, cond in reversed(cols) if cond)
2501 2501 for name, data, cond in cols:
2502 2502 field = fieldnamemap.get(name, name)
2503 2503 fm.condwrite(cond, field, '%s', data, label='grep.%s' % name)
2504 2504 if cond and name != lastcol:
2505 2505 fm.plain(sep, label='grep.sep')
2506 2506 if not opts.get('files_with_matches'):
2507 2507 fm.plain(sep, label='grep.sep')
2508 2508 if not opts.get('text') and binary():
2509 2509 fm.plain(_(" Binary file matches"))
2510 2510 else:
2511 2511 displaymatches(fm.nested('texts'), l)
2512 2512 fm.plain(eol)
2513 2513 found = True
2514 2514 if opts.get('files_with_matches'):
2515 2515 break
2516 2516 return found
2517 2517
2518 2518 def displaymatches(fm, l):
2519 2519 p = 0
2520 2520 for s, e in l.findpos():
2521 2521 if p < s:
2522 2522 fm.startitem()
2523 2523 fm.write('text', '%s', l.line[p:s])
2524 2524 fm.data(matched=False)
2525 2525 fm.startitem()
2526 2526 fm.write('text', '%s', l.line[s:e], label='grep.match')
2527 2527 fm.data(matched=True)
2528 2528 p = e
2529 2529 if p < len(l.line):
2530 2530 fm.startitem()
2531 2531 fm.write('text', '%s', l.line[p:])
2532 2532 fm.data(matched=False)
2533 2533 fm.end()
2534 2534
2535 2535 skip = {}
2536 2536 revfiles = {}
2537 2537 match = scmutil.match(repo[None], pats, opts)
2538 2538 found = False
2539 2539 follow = opts.get('follow')
2540 2540
2541 2541 def prep(ctx, fns):
2542 2542 rev = ctx.rev()
2543 2543 pctx = ctx.p1()
2544 2544 parent = pctx.rev()
2545 2545 matches.setdefault(rev, {})
2546 2546 matches.setdefault(parent, {})
2547 2547 files = revfiles.setdefault(rev, [])
2548 2548 for fn in fns:
2549 2549 flog = getfile(fn)
2550 2550 try:
2551 2551 fnode = ctx.filenode(fn)
2552 2552 except error.LookupError:
2553 2553 continue
2554 2554
2555 2555 copied = flog.renamed(fnode)
2556 2556 copy = follow and copied and copied[0]
2557 2557 if copy:
2558 2558 copies.setdefault(rev, {})[fn] = copy
2559 2559 if fn in skip:
2560 2560 if copy:
2561 2561 skip[copy] = True
2562 2562 continue
2563 2563 files.append(fn)
2564 2564
2565 2565 if fn not in matches[rev]:
2566 2566 grepbody(fn, rev, flog.read(fnode))
2567 2567
2568 2568 pfn = copy or fn
2569 2569 if pfn not in matches[parent]:
2570 2570 try:
2571 2571 fnode = pctx.filenode(pfn)
2572 2572 grepbody(pfn, parent, flog.read(fnode))
2573 2573 except error.LookupError:
2574 2574 pass
2575 2575
2576 2576 ui.pager('grep')
2577 2577 fm = ui.formatter('grep', opts)
2578 2578 for ctx in cmdutil.walkchangerevs(repo, match, opts, prep):
2579 2579 rev = ctx.rev()
2580 2580 parent = ctx.p1().rev()
2581 2581 for fn in sorted(revfiles.get(rev, [])):
2582 2582 states = matches[rev][fn]
2583 2583 copy = copies.get(rev, {}).get(fn)
2584 2584 if fn in skip:
2585 2585 if copy:
2586 2586 skip[copy] = True
2587 2587 continue
2588 2588 pstates = matches.get(parent, {}).get(copy or fn, [])
2589 2589 if pstates or states:
2590 2590 r = display(fm, fn, ctx, pstates, states)
2591 2591 found = found or r
2592 2592 if r and not opts.get('all'):
2593 2593 skip[fn] = True
2594 2594 if copy:
2595 2595 skip[copy] = True
2596 2596 del revfiles[rev]
2597 2597 # We will keep the matches dict for the duration of the window
2598 2598 # clear the matches dict once the window is over
2599 2599 if not revfiles:
2600 2600 matches.clear()
2601 2601 fm.end()
2602 2602
2603 2603 return not found
2604 2604
2605 2605 @command('heads',
2606 2606 [('r', 'rev', '',
2607 2607 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
2608 2608 ('t', 'topo', False, _('show topological heads only')),
2609 2609 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
2610 2610 ('c', 'closed', False, _('show normal and closed branch heads')),
2611 2611 ] + templateopts,
2612 2612 _('[-ct] [-r STARTREV] [REV]...'), cmdtype=readonly)
2613 2613 def heads(ui, repo, *branchrevs, **opts):
2614 2614 """show branch heads
2615 2615
2616 2616 With no arguments, show all open branch heads in the repository.
2617 2617 Branch heads are changesets that have no descendants on the
2618 2618 same branch. They are where development generally takes place and
2619 2619 are the usual targets for update and merge operations.
2620 2620
2621 2621 If one or more REVs are given, only open branch heads on the
2622 2622 branches associated with the specified changesets are shown. This
2623 2623 means that you can use :hg:`heads .` to see the heads on the
2624 2624 currently checked-out branch.
2625 2625
2626 2626 If -c/--closed is specified, also show branch heads marked closed
2627 2627 (see :hg:`commit --close-branch`).
2628 2628
2629 2629 If STARTREV is specified, only those heads that are descendants of
2630 2630 STARTREV will be displayed.
2631 2631
2632 2632 If -t/--topo is specified, named branch mechanics will be ignored and only
2633 2633 topological heads (changesets with no children) will be shown.
2634 2634
2635 2635 Returns 0 if matching heads are found, 1 if not.
2636 2636 """
2637 2637
2638 2638 opts = pycompat.byteskwargs(opts)
2639 2639 start = None
2640 2640 rev = opts.get('rev')
2641 2641 if rev:
2642 2642 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
2643 2643 start = scmutil.revsingle(repo, rev, None).node()
2644 2644
2645 2645 if opts.get('topo'):
2646 2646 heads = [repo[h] for h in repo.heads(start)]
2647 2647 else:
2648 2648 heads = []
2649 2649 for branch in repo.branchmap():
2650 2650 heads += repo.branchheads(branch, start, opts.get('closed'))
2651 2651 heads = [repo[h] for h in heads]
2652 2652
2653 2653 if branchrevs:
2654 2654 branches = set(repo[br].branch() for br in branchrevs)
2655 2655 heads = [h for h in heads if h.branch() in branches]
2656 2656
2657 2657 if opts.get('active') and branchrevs:
2658 2658 dagheads = repo.heads(start)
2659 2659 heads = [h for h in heads if h.node() in dagheads]
2660 2660
2661 2661 if branchrevs:
2662 2662 haveheads = set(h.branch() for h in heads)
2663 2663 if branches - haveheads:
2664 2664 headless = ', '.join(b for b in branches - haveheads)
2665 2665 msg = _('no open branch heads found on branches %s')
2666 2666 if opts.get('rev'):
2667 2667 msg += _(' (started at %s)') % opts['rev']
2668 2668 ui.warn((msg + '\n') % headless)
2669 2669
2670 2670 if not heads:
2671 2671 return 1
2672 2672
2673 2673 ui.pager('heads')
2674 2674 heads = sorted(heads, key=lambda x: -x.rev())
2675 2675 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
2676 2676 for ctx in heads:
2677 2677 displayer.show(ctx)
2678 2678 displayer.close()
2679 2679
2680 2680 @command('help',
2681 2681 [('e', 'extension', None, _('show only help for extensions')),
2682 2682 ('c', 'command', None, _('show only help for commands')),
2683 2683 ('k', 'keyword', None, _('show topics matching keyword')),
2684 2684 ('s', 'system', [], _('show help for specific platform(s)')),
2685 2685 ],
2686 2686 _('[-ecks] [TOPIC]'),
2687 2687 norepo=True, cmdtype=readonly)
2688 2688 def help_(ui, name=None, **opts):
2689 2689 """show help for a given topic or a help overview
2690 2690
2691 2691 With no arguments, print a list of commands with short help messages.
2692 2692
2693 2693 Given a topic, extension, or command name, print help for that
2694 2694 topic.
2695 2695
2696 2696 Returns 0 if successful.
2697 2697 """
2698 2698
2699 2699 keep = opts.get(r'system') or []
2700 2700 if len(keep) == 0:
2701 2701 if pycompat.sysplatform.startswith('win'):
2702 2702 keep.append('windows')
2703 2703 elif pycompat.sysplatform == 'OpenVMS':
2704 2704 keep.append('vms')
2705 2705 elif pycompat.sysplatform == 'plan9':
2706 2706 keep.append('plan9')
2707 2707 else:
2708 2708 keep.append('unix')
2709 2709 keep.append(pycompat.sysplatform.lower())
2710 2710 if ui.verbose:
2711 2711 keep.append('verbose')
2712 2712
2713 2713 commands = sys.modules[__name__]
2714 2714 formatted = help.formattedhelp(ui, commands, name, keep=keep, **opts)
2715 2715 ui.pager('help')
2716 2716 ui.write(formatted)
2717 2717
2718 2718
2719 2719 @command('identify|id',
2720 2720 [('r', 'rev', '',
2721 2721 _('identify the specified revision'), _('REV')),
2722 2722 ('n', 'num', None, _('show local revision number')),
2723 2723 ('i', 'id', None, _('show global revision id')),
2724 2724 ('b', 'branch', None, _('show branch')),
2725 2725 ('t', 'tags', None, _('show tags')),
2726 2726 ('B', 'bookmarks', None, _('show bookmarks')),
2727 2727 ] + remoteopts + formatteropts,
2728 2728 _('[-nibtB] [-r REV] [SOURCE]'),
2729 2729 optionalrepo=True, cmdtype=readonly)
2730 2730 def identify(ui, repo, source=None, rev=None,
2731 2731 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
2732 2732 """identify the working directory or specified revision
2733 2733
2734 2734 Print a summary identifying the repository state at REV using one or
2735 2735 two parent hash identifiers, followed by a "+" if the working
2736 2736 directory has uncommitted changes, the branch name (if not default),
2737 2737 a list of tags, and a list of bookmarks.
2738 2738
2739 2739 When REV is not given, print a summary of the current state of the
2740 2740 repository including the working directory. Specify -r. to get information
2741 2741 of the working directory parent without scanning uncommitted changes.
2742 2742
2743 2743 Specifying a path to a repository root or Mercurial bundle will
2744 2744 cause lookup to operate on that repository/bundle.
2745 2745
2746 2746 .. container:: verbose
2747 2747
2748 2748 Examples:
2749 2749
2750 2750 - generate a build identifier for the working directory::
2751 2751
2752 2752 hg id --id > build-id.dat
2753 2753
2754 2754 - find the revision corresponding to a tag::
2755 2755
2756 2756 hg id -n -r 1.3
2757 2757
2758 2758 - check the most recent revision of a remote repository::
2759 2759
2760 2760 hg id -r tip https://www.mercurial-scm.org/repo/hg/
2761 2761
2762 2762 See :hg:`log` for generating more information about specific revisions,
2763 2763 including full hash identifiers.
2764 2764
2765 2765 Returns 0 if successful.
2766 2766 """
2767 2767
2768 2768 opts = pycompat.byteskwargs(opts)
2769 2769 if not repo and not source:
2770 2770 raise error.Abort(_("there is no Mercurial repository here "
2771 2771 "(.hg not found)"))
2772 2772
2773 2773 if ui.debugflag:
2774 2774 hexfunc = hex
2775 2775 else:
2776 2776 hexfunc = short
2777 2777 default = not (num or id or branch or tags or bookmarks)
2778 2778 output = []
2779 2779 revs = []
2780 2780
2781 2781 if source:
2782 2782 source, branches = hg.parseurl(ui.expandpath(source))
2783 2783 peer = hg.peer(repo or ui, opts, source) # only pass ui when no repo
2784 2784 repo = peer.local()
2785 2785 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
2786 2786
2787 2787 fm = ui.formatter('identify', opts)
2788 2788 fm.startitem()
2789 2789
2790 2790 if not repo:
2791 2791 if num or branch or tags:
2792 2792 raise error.Abort(
2793 2793 _("can't query remote revision number, branch, or tags"))
2794 2794 if not rev and revs:
2795 2795 rev = revs[0]
2796 2796 if not rev:
2797 2797 rev = "tip"
2798 2798
2799 2799 remoterev = peer.lookup(rev)
2800 2800 hexrev = hexfunc(remoterev)
2801 2801 if default or id:
2802 2802 output = [hexrev]
2803 2803 fm.data(id=hexrev)
2804 2804
2805 2805 def getbms():
2806 2806 bms = []
2807 2807
2808 2808 if 'bookmarks' in peer.listkeys('namespaces'):
2809 2809 hexremoterev = hex(remoterev)
2810 2810 bms = [bm for bm, bmr in peer.listkeys('bookmarks').iteritems()
2811 2811 if bmr == hexremoterev]
2812 2812
2813 2813 return sorted(bms)
2814 2814
2815 2815 bms = getbms()
2816 2816 if bookmarks:
2817 2817 output.extend(bms)
2818 2818 elif default and not ui.quiet:
2819 2819 # multiple bookmarks for a single parent separated by '/'
2820 2820 bm = '/'.join(bms)
2821 2821 if bm:
2822 2822 output.append(bm)
2823 2823
2824 2824 fm.data(node=hex(remoterev))
2825 2825 fm.data(bookmarks=fm.formatlist(bms, name='bookmark'))
2826 2826 else:
2827 2827 if rev:
2828 2828 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
2829 2829 ctx = scmutil.revsingle(repo, rev, None)
2830 2830
2831 2831 if ctx.rev() is None:
2832 2832 ctx = repo[None]
2833 2833 parents = ctx.parents()
2834 2834 taglist = []
2835 2835 for p in parents:
2836 2836 taglist.extend(p.tags())
2837 2837
2838 2838 dirty = ""
2839 2839 if ctx.dirty(missing=True, merge=False, branch=False):
2840 2840 dirty = '+'
2841 2841 fm.data(dirty=dirty)
2842 2842
2843 2843 hexoutput = [hexfunc(p.node()) for p in parents]
2844 2844 if default or id:
2845 2845 output = ["%s%s" % ('+'.join(hexoutput), dirty)]
2846 2846 fm.data(id="%s%s" % ('+'.join(hexoutput), dirty))
2847 2847
2848 2848 if num:
2849 2849 numoutput = ["%d" % p.rev() for p in parents]
2850 2850 output.append("%s%s" % ('+'.join(numoutput), dirty))
2851 2851
2852 2852 fn = fm.nested('parents')
2853 2853 for p in parents:
2854 2854 fn.startitem()
2855 2855 fn.data(rev=p.rev())
2856 2856 fn.data(node=p.hex())
2857 2857 fn.context(ctx=p)
2858 2858 fn.end()
2859 2859 else:
2860 2860 hexoutput = hexfunc(ctx.node())
2861 2861 if default or id:
2862 2862 output = [hexoutput]
2863 2863 fm.data(id=hexoutput)
2864 2864
2865 2865 if num:
2866 2866 output.append(pycompat.bytestr(ctx.rev()))
2867 2867 taglist = ctx.tags()
2868 2868
2869 2869 if default and not ui.quiet:
2870 2870 b = ctx.branch()
2871 2871 if b != 'default':
2872 2872 output.append("(%s)" % b)
2873 2873
2874 2874 # multiple tags for a single parent separated by '/'
2875 2875 t = '/'.join(taglist)
2876 2876 if t:
2877 2877 output.append(t)
2878 2878
2879 2879 # multiple bookmarks for a single parent separated by '/'
2880 2880 bm = '/'.join(ctx.bookmarks())
2881 2881 if bm:
2882 2882 output.append(bm)
2883 2883 else:
2884 2884 if branch:
2885 2885 output.append(ctx.branch())
2886 2886
2887 2887 if tags:
2888 2888 output.extend(taglist)
2889 2889
2890 2890 if bookmarks:
2891 2891 output.extend(ctx.bookmarks())
2892 2892
2893 2893 fm.data(node=ctx.hex())
2894 2894 fm.data(branch=ctx.branch())
2895 2895 fm.data(tags=fm.formatlist(taglist, name='tag', sep=':'))
2896 2896 fm.data(bookmarks=fm.formatlist(ctx.bookmarks(), name='bookmark'))
2897 2897 fm.context(ctx=ctx)
2898 2898
2899 2899 fm.plain("%s\n" % ' '.join(output))
2900 2900 fm.end()
2901 2901
2902 2902 @command('import|patch',
2903 2903 [('p', 'strip', 1,
2904 2904 _('directory strip option for patch. This has the same '
2905 2905 'meaning as the corresponding patch option'), _('NUM')),
2906 2906 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
2907 2907 ('e', 'edit', False, _('invoke editor on commit messages')),
2908 2908 ('f', 'force', None,
2909 2909 _('skip check for outstanding uncommitted changes (DEPRECATED)')),
2910 2910 ('', 'no-commit', None,
2911 2911 _("don't commit, just update the working directory")),
2912 2912 ('', 'bypass', None,
2913 2913 _("apply patch without touching the working directory")),
2914 2914 ('', 'partial', None,
2915 2915 _('commit even if some hunks fail')),
2916 2916 ('', 'exact', None,
2917 2917 _('abort if patch would apply lossily')),
2918 2918 ('', 'prefix', '',
2919 2919 _('apply patch to subdirectory'), _('DIR')),
2920 2920 ('', 'import-branch', None,
2921 2921 _('use any branch information in patch (implied by --exact)'))] +
2922 2922 commitopts + commitopts2 + similarityopts,
2923 2923 _('[OPTION]... PATCH...'))
2924 2924 def import_(ui, repo, patch1=None, *patches, **opts):
2925 2925 """import an ordered set of patches
2926 2926
2927 2927 Import a list of patches and commit them individually (unless
2928 2928 --no-commit is specified).
2929 2929
2930 2930 To read a patch from standard input (stdin), use "-" as the patch
2931 2931 name. If a URL is specified, the patch will be downloaded from
2932 2932 there.
2933 2933
2934 2934 Import first applies changes to the working directory (unless
2935 2935 --bypass is specified), import will abort if there are outstanding
2936 2936 changes.
2937 2937
2938 2938 Use --bypass to apply and commit patches directly to the
2939 2939 repository, without affecting the working directory. Without
2940 2940 --exact, patches will be applied on top of the working directory
2941 2941 parent revision.
2942 2942
2943 2943 You can import a patch straight from a mail message. Even patches
2944 2944 as attachments work (to use the body part, it must have type
2945 2945 text/plain or text/x-patch). From and Subject headers of email
2946 2946 message are used as default committer and commit message. All
2947 2947 text/plain body parts before first diff are added to the commit
2948 2948 message.
2949 2949
2950 2950 If the imported patch was generated by :hg:`export`, user and
2951 2951 description from patch override values from message headers and
2952 2952 body. Values given on command line with -m/--message and -u/--user
2953 2953 override these.
2954 2954
2955 2955 If --exact is specified, import will set the working directory to
2956 2956 the parent of each patch before applying it, and will abort if the
2957 2957 resulting changeset has a different ID than the one recorded in
2958 2958 the patch. This will guard against various ways that portable
2959 2959 patch formats and mail systems might fail to transfer Mercurial
2960 2960 data or metadata. See :hg:`bundle` for lossless transmission.
2961 2961
2962 2962 Use --partial to ensure a changeset will be created from the patch
2963 2963 even if some hunks fail to apply. Hunks that fail to apply will be
2964 2964 written to a <target-file>.rej file. Conflicts can then be resolved
2965 2965 by hand before :hg:`commit --amend` is run to update the created
2966 2966 changeset. This flag exists to let people import patches that
2967 2967 partially apply without losing the associated metadata (author,
2968 2968 date, description, ...).
2969 2969
2970 2970 .. note::
2971 2971
2972 2972 When no hunks apply cleanly, :hg:`import --partial` will create
2973 2973 an empty changeset, importing only the patch metadata.
2974 2974
2975 2975 With -s/--similarity, hg will attempt to discover renames and
2976 2976 copies in the patch in the same way as :hg:`addremove`.
2977 2977
2978 2978 It is possible to use external patch programs to perform the patch
2979 2979 by setting the ``ui.patch`` configuration option. For the default
2980 2980 internal tool, the fuzz can also be configured via ``patch.fuzz``.
2981 2981 See :hg:`help config` for more information about configuration
2982 2982 files and how to use these options.
2983 2983
2984 2984 See :hg:`help dates` for a list of formats valid for -d/--date.
2985 2985
2986 2986 .. container:: verbose
2987 2987
2988 2988 Examples:
2989 2989
2990 2990 - import a traditional patch from a website and detect renames::
2991 2991
2992 2992 hg import -s 80 http://example.com/bugfix.patch
2993 2993
2994 2994 - import a changeset from an hgweb server::
2995 2995
2996 2996 hg import https://www.mercurial-scm.org/repo/hg/rev/5ca8c111e9aa
2997 2997
2998 2998 - import all the patches in an Unix-style mbox::
2999 2999
3000 3000 hg import incoming-patches.mbox
3001 3001
3002 3002 - import patches from stdin::
3003 3003
3004 3004 hg import -
3005 3005
3006 3006 - attempt to exactly restore an exported changeset (not always
3007 3007 possible)::
3008 3008
3009 3009 hg import --exact proposed-fix.patch
3010 3010
3011 3011 - use an external tool to apply a patch which is too fuzzy for
3012 3012 the default internal tool.
3013 3013
3014 3014 hg import --config ui.patch="patch --merge" fuzzy.patch
3015 3015
3016 3016 - change the default fuzzing from 2 to a less strict 7
3017 3017
3018 3018 hg import --config ui.fuzz=7 fuzz.patch
3019 3019
3020 3020 Returns 0 on success, 1 on partial success (see --partial).
3021 3021 """
3022 3022
3023 3023 opts = pycompat.byteskwargs(opts)
3024 3024 if not patch1:
3025 3025 raise error.Abort(_('need at least one patch to import'))
3026 3026
3027 3027 patches = (patch1,) + patches
3028 3028
3029 3029 date = opts.get('date')
3030 3030 if date:
3031 3031 opts['date'] = dateutil.parsedate(date)
3032 3032
3033 3033 exact = opts.get('exact')
3034 3034 update = not opts.get('bypass')
3035 3035 if not update and opts.get('no_commit'):
3036 3036 raise error.Abort(_('cannot use --no-commit with --bypass'))
3037 3037 try:
3038 3038 sim = float(opts.get('similarity') or 0)
3039 3039 except ValueError:
3040 3040 raise error.Abort(_('similarity must be a number'))
3041 3041 if sim < 0 or sim > 100:
3042 3042 raise error.Abort(_('similarity must be between 0 and 100'))
3043 3043 if sim and not update:
3044 3044 raise error.Abort(_('cannot use --similarity with --bypass'))
3045 3045 if exact:
3046 3046 if opts.get('edit'):
3047 3047 raise error.Abort(_('cannot use --exact with --edit'))
3048 3048 if opts.get('prefix'):
3049 3049 raise error.Abort(_('cannot use --exact with --prefix'))
3050 3050
3051 3051 base = opts["base"]
3052 3052 wlock = dsguard = lock = tr = None
3053 3053 msgs = []
3054 3054 ret = 0
3055 3055
3056 3056
3057 3057 try:
3058 3058 wlock = repo.wlock()
3059 3059
3060 3060 if update:
3061 3061 cmdutil.checkunfinished(repo)
3062 3062 if (exact or not opts.get('force')):
3063 3063 cmdutil.bailifchanged(repo)
3064 3064
3065 3065 if not opts.get('no_commit'):
3066 3066 lock = repo.lock()
3067 3067 tr = repo.transaction('import')
3068 3068 else:
3069 3069 dsguard = dirstateguard.dirstateguard(repo, 'import')
3070 3070 parents = repo[None].parents()
3071 3071 for patchurl in patches:
3072 3072 if patchurl == '-':
3073 3073 ui.status(_('applying patch from stdin\n'))
3074 3074 patchfile = ui.fin
3075 3075 patchurl = 'stdin' # for error message
3076 3076 else:
3077 3077 patchurl = os.path.join(base, patchurl)
3078 3078 ui.status(_('applying %s\n') % patchurl)
3079 3079 patchfile = hg.openpath(ui, patchurl)
3080 3080
3081 3081 haspatch = False
3082 3082 for hunk in patch.split(patchfile):
3083 3083 (msg, node, rej) = cmdutil.tryimportone(ui, repo, hunk,
3084 3084 parents, opts,
3085 3085 msgs, hg.clean)
3086 3086 if msg:
3087 3087 haspatch = True
3088 3088 ui.note(msg + '\n')
3089 3089 if update or exact:
3090 3090 parents = repo[None].parents()
3091 3091 else:
3092 3092 parents = [repo[node]]
3093 3093 if rej:
3094 3094 ui.write_err(_("patch applied partially\n"))
3095 3095 ui.write_err(_("(fix the .rej files and run "
3096 3096 "`hg commit --amend`)\n"))
3097 3097 ret = 1
3098 3098 break
3099 3099
3100 3100 if not haspatch:
3101 3101 raise error.Abort(_('%s: no diffs found') % patchurl)
3102 3102
3103 3103 if tr:
3104 3104 tr.close()
3105 3105 if msgs:
3106 3106 repo.savecommitmessage('\n* * *\n'.join(msgs))
3107 3107 if dsguard:
3108 3108 dsguard.close()
3109 3109 return ret
3110 3110 finally:
3111 3111 if tr:
3112 3112 tr.release()
3113 3113 release(lock, dsguard, wlock)
3114 3114
3115 3115 @command('incoming|in',
3116 3116 [('f', 'force', None,
3117 3117 _('run even if remote repository is unrelated')),
3118 3118 ('n', 'newest-first', None, _('show newest record first')),
3119 3119 ('', 'bundle', '',
3120 3120 _('file to store the bundles into'), _('FILE')),
3121 3121 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3122 3122 ('B', 'bookmarks', False, _("compare bookmarks")),
3123 3123 ('b', 'branch', [],
3124 3124 _('a specific branch you would like to pull'), _('BRANCH')),
3125 3125 ] + logopts + remoteopts + subrepoopts,
3126 3126 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3127 3127 def incoming(ui, repo, source="default", **opts):
3128 3128 """show new changesets found in source
3129 3129
3130 3130 Show new changesets found in the specified path/URL or the default
3131 3131 pull location. These are the changesets that would have been pulled
3132 3132 by :hg:`pull` at the time you issued this command.
3133 3133
3134 3134 See pull for valid source format details.
3135 3135
3136 3136 .. container:: verbose
3137 3137
3138 3138 With -B/--bookmarks, the result of bookmark comparison between
3139 3139 local and remote repositories is displayed. With -v/--verbose,
3140 3140 status is also displayed for each bookmark like below::
3141 3141
3142 3142 BM1 01234567890a added
3143 3143 BM2 1234567890ab advanced
3144 3144 BM3 234567890abc diverged
3145 3145 BM4 34567890abcd changed
3146 3146
3147 3147 The action taken locally when pulling depends on the
3148 3148 status of each bookmark:
3149 3149
3150 3150 :``added``: pull will create it
3151 3151 :``advanced``: pull will update it
3152 3152 :``diverged``: pull will create a divergent bookmark
3153 3153 :``changed``: result depends on remote changesets
3154 3154
3155 3155 From the point of view of pulling behavior, bookmark
3156 3156 existing only in the remote repository are treated as ``added``,
3157 3157 even if it is in fact locally deleted.
3158 3158
3159 3159 .. container:: verbose
3160 3160
3161 3161 For remote repository, using --bundle avoids downloading the
3162 3162 changesets twice if the incoming is followed by a pull.
3163 3163
3164 3164 Examples:
3165 3165
3166 3166 - show incoming changes with patches and full description::
3167 3167
3168 3168 hg incoming -vp
3169 3169
3170 3170 - show incoming changes excluding merges, store a bundle::
3171 3171
3172 3172 hg in -vpM --bundle incoming.hg
3173 3173 hg pull incoming.hg
3174 3174
3175 3175 - briefly list changes inside a bundle::
3176 3176
3177 3177 hg in changes.hg -T "{desc|firstline}\\n"
3178 3178
3179 3179 Returns 0 if there are incoming changes, 1 otherwise.
3180 3180 """
3181 3181 opts = pycompat.byteskwargs(opts)
3182 3182 if opts.get('graph'):
3183 3183 logcmdutil.checkunsupportedgraphflags([], opts)
3184 3184 def display(other, chlist, displayer):
3185 3185 revdag = logcmdutil.graphrevs(other, chlist, opts)
3186 3186 logcmdutil.displaygraph(ui, repo, revdag, displayer,
3187 3187 graphmod.asciiedges)
3188 3188
3189 3189 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
3190 3190 return 0
3191 3191
3192 3192 if opts.get('bundle') and opts.get('subrepos'):
3193 3193 raise error.Abort(_('cannot combine --bundle and --subrepos'))
3194 3194
3195 3195 if opts.get('bookmarks'):
3196 3196 source, branches = hg.parseurl(ui.expandpath(source),
3197 3197 opts.get('branch'))
3198 3198 other = hg.peer(repo, opts, source)
3199 3199 if 'bookmarks' not in other.listkeys('namespaces'):
3200 3200 ui.warn(_("remote doesn't support bookmarks\n"))
3201 3201 return 0
3202 3202 ui.pager('incoming')
3203 3203 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3204 3204 return bookmarks.incoming(ui, repo, other)
3205 3205
3206 3206 repo._subtoppath = ui.expandpath(source)
3207 3207 try:
3208 3208 return hg.incoming(ui, repo, source, opts)
3209 3209 finally:
3210 3210 del repo._subtoppath
3211 3211
3212 3212
3213 3213 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'),
3214 3214 norepo=True)
3215 3215 def init(ui, dest=".", **opts):
3216 3216 """create a new repository in the given directory
3217 3217
3218 3218 Initialize a new repository in the given directory. If the given
3219 3219 directory does not exist, it will be created.
3220 3220
3221 3221 If no directory is given, the current directory is used.
3222 3222
3223 3223 It is possible to specify an ``ssh://`` URL as the destination.
3224 3224 See :hg:`help urls` for more information.
3225 3225
3226 3226 Returns 0 on success.
3227 3227 """
3228 3228 opts = pycompat.byteskwargs(opts)
3229 3229 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3230 3230
3231 3231 @command('locate',
3232 3232 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3233 3233 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3234 3234 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3235 3235 ] + walkopts,
3236 3236 _('[OPTION]... [PATTERN]...'))
3237 3237 def locate(ui, repo, *pats, **opts):
3238 3238 """locate files matching specific patterns (DEPRECATED)
3239 3239
3240 3240 Print files under Mercurial control in the working directory whose
3241 3241 names match the given patterns.
3242 3242
3243 3243 By default, this command searches all directories in the working
3244 3244 directory. To search just the current directory and its
3245 3245 subdirectories, use "--include .".
3246 3246
3247 3247 If no patterns are given to match, this command prints the names
3248 3248 of all files under Mercurial control in the working directory.
3249 3249
3250 3250 If you want to feed the output of this command into the "xargs"
3251 3251 command, use the -0 option to both this command and "xargs". This
3252 3252 will avoid the problem of "xargs" treating single filenames that
3253 3253 contain whitespace as multiple filenames.
3254 3254
3255 3255 See :hg:`help files` for a more versatile command.
3256 3256
3257 3257 Returns 0 if a match is found, 1 otherwise.
3258 3258 """
3259 3259 opts = pycompat.byteskwargs(opts)
3260 3260 if opts.get('print0'):
3261 3261 end = '\0'
3262 3262 else:
3263 3263 end = '\n'
3264 3264 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
3265 3265
3266 3266 ret = 1
3267 3267 m = scmutil.match(ctx, pats, opts, default='relglob',
3268 3268 badfn=lambda x, y: False)
3269 3269
3270 3270 ui.pager('locate')
3271 3271 for abs in ctx.matches(m):
3272 3272 if opts.get('fullpath'):
3273 3273 ui.write(repo.wjoin(abs), end)
3274 3274 else:
3275 3275 ui.write(((pats and m.rel(abs)) or abs), end)
3276 3276 ret = 0
3277 3277
3278 3278 return ret
3279 3279
3280 3280 @command('^log|history',
3281 3281 [('f', 'follow', None,
3282 3282 _('follow changeset history, or file history across copies and renames')),
3283 3283 ('', 'follow-first', None,
3284 3284 _('only follow the first parent of merge changesets (DEPRECATED)')),
3285 3285 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3286 3286 ('C', 'copies', None, _('show copied files')),
3287 3287 ('k', 'keyword', [],
3288 3288 _('do case-insensitive search for a given text'), _('TEXT')),
3289 3289 ('r', 'rev', [], _('show the specified revision or revset'), _('REV')),
3290 3290 ('L', 'line-range', [],
3291 3291 _('follow line range of specified file (EXPERIMENTAL)'),
3292 3292 _('FILE,RANGE')),
3293 3293 ('', 'removed', None, _('include revisions where files were removed')),
3294 3294 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
3295 3295 ('u', 'user', [], _('revisions committed by user'), _('USER')),
3296 3296 ('', 'only-branch', [],
3297 3297 _('show only changesets within the given named branch (DEPRECATED)'),
3298 3298 _('BRANCH')),
3299 3299 ('b', 'branch', [],
3300 3300 _('show changesets within the given named branch'), _('BRANCH')),
3301 3301 ('P', 'prune', [],
3302 3302 _('do not display revision or any of its ancestors'), _('REV')),
3303 3303 ] + logopts + walkopts,
3304 3304 _('[OPTION]... [FILE]'),
3305 3305 inferrepo=True, cmdtype=readonly)
3306 3306 def log(ui, repo, *pats, **opts):
3307 3307 """show revision history of entire repository or files
3308 3308
3309 3309 Print the revision history of the specified files or the entire
3310 3310 project.
3311 3311
3312 3312 If no revision range is specified, the default is ``tip:0`` unless
3313 3313 --follow is set, in which case the working directory parent is
3314 3314 used as the starting revision.
3315 3315
3316 3316 File history is shown without following rename or copy history of
3317 3317 files. Use -f/--follow with a filename to follow history across
3318 3318 renames and copies. --follow without a filename will only show
3319 3319 ancestors of the starting revision.
3320 3320
3321 3321 By default this command prints revision number and changeset id,
3322 3322 tags, non-trivial parents, user, date and time, and a summary for
3323 3323 each commit. When the -v/--verbose switch is used, the list of
3324 3324 changed files and full commit message are shown.
3325 3325
3326 3326 With --graph the revisions are shown as an ASCII art DAG with the most
3327 3327 recent changeset at the top.
3328 3328 'o' is a changeset, '@' is a working directory parent, '_' closes a branch,
3329 3329 'x' is obsolete, '*' is unstable, and '+' represents a fork where the
3330 3330 changeset from the lines below is a parent of the 'o' merge on the same
3331 3331 line.
3332 3332 Paths in the DAG are represented with '|', '/' and so forth. ':' in place
3333 3333 of a '|' indicates one or more revisions in a path are omitted.
3334 3334
3335 3335 .. container:: verbose
3336 3336
3337 3337 Use -L/--line-range FILE,M:N options to follow the history of lines
3338 3338 from M to N in FILE. With -p/--patch only diff hunks affecting
3339 3339 specified line range will be shown. This option requires --follow;
3340 3340 it can be specified multiple times. Currently, this option is not
3341 3341 compatible with --graph. This option is experimental.
3342 3342
3343 3343 .. note::
3344 3344
3345 3345 :hg:`log --patch` may generate unexpected diff output for merge
3346 3346 changesets, as it will only compare the merge changeset against
3347 3347 its first parent. Also, only files different from BOTH parents
3348 3348 will appear in files:.
3349 3349
3350 3350 .. note::
3351 3351
3352 3352 For performance reasons, :hg:`log FILE` may omit duplicate changes
3353 3353 made on branches and will not show removals or mode changes. To
3354 3354 see all such changes, use the --removed switch.
3355 3355
3356 3356 .. container:: verbose
3357 3357
3358 3358 .. note::
3359 3359
3360 3360 The history resulting from -L/--line-range options depends on diff
3361 3361 options; for instance if white-spaces are ignored, respective changes
3362 3362 with only white-spaces in specified line range will not be listed.
3363 3363
3364 3364 .. container:: verbose
3365 3365
3366 3366 Some examples:
3367 3367
3368 3368 - changesets with full descriptions and file lists::
3369 3369
3370 3370 hg log -v
3371 3371
3372 3372 - changesets ancestral to the working directory::
3373 3373
3374 3374 hg log -f
3375 3375
3376 3376 - last 10 commits on the current branch::
3377 3377
3378 3378 hg log -l 10 -b .
3379 3379
3380 3380 - changesets showing all modifications of a file, including removals::
3381 3381
3382 3382 hg log --removed file.c
3383 3383
3384 3384 - all changesets that touch a directory, with diffs, excluding merges::
3385 3385
3386 3386 hg log -Mp lib/
3387 3387
3388 3388 - all revision numbers that match a keyword::
3389 3389
3390 3390 hg log -k bug --template "{rev}\\n"
3391 3391
3392 3392 - the full hash identifier of the working directory parent::
3393 3393
3394 3394 hg log -r . --template "{node}\\n"
3395 3395
3396 3396 - list available log templates::
3397 3397
3398 3398 hg log -T list
3399 3399
3400 3400 - check if a given changeset is included in a tagged release::
3401 3401
3402 3402 hg log -r "a21ccf and ancestor(1.9)"
3403 3403
3404 3404 - find all changesets by some user in a date range::
3405 3405
3406 3406 hg log -k alice -d "may 2008 to jul 2008"
3407 3407
3408 3408 - summary of all changesets after the last tag::
3409 3409
3410 3410 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
3411 3411
3412 3412 - changesets touching lines 13 to 23 for file.c::
3413 3413
3414 3414 hg log -L file.c,13:23
3415 3415
3416 3416 - changesets touching lines 13 to 23 for file.c and lines 2 to 6 of
3417 3417 main.c with patch::
3418 3418
3419 3419 hg log -L file.c,13:23 -L main.c,2:6 -p
3420 3420
3421 3421 See :hg:`help dates` for a list of formats valid for -d/--date.
3422 3422
3423 3423 See :hg:`help revisions` for more about specifying and ordering
3424 3424 revisions.
3425 3425
3426 3426 See :hg:`help templates` for more about pre-packaged styles and
3427 3427 specifying custom templates. The default template used by the log
3428 3428 command can be customized via the ``ui.logtemplate`` configuration
3429 3429 setting.
3430 3430
3431 3431 Returns 0 on success.
3432 3432
3433 3433 """
3434 3434 opts = pycompat.byteskwargs(opts)
3435 3435 linerange = opts.get('line_range')
3436 3436
3437 3437 if linerange and not opts.get('follow'):
3438 3438 raise error.Abort(_('--line-range requires --follow'))
3439 3439
3440 3440 if linerange and pats:
3441 3441 # TODO: take pats as patterns with no line-range filter
3442 3442 raise error.Abort(
3443 3443 _('FILE arguments are not compatible with --line-range option')
3444 3444 )
3445 3445
3446 3446 repo = scmutil.unhidehashlikerevs(repo, opts.get('rev'), 'nowarn')
3447 3447 revs, differ = logcmdutil.getrevs(repo, pats, opts)
3448 3448 if linerange:
3449 3449 # TODO: should follow file history from logcmdutil._initialrevs(),
3450 3450 # then filter the result by logcmdutil._makerevset() and --limit
3451 3451 revs, differ = logcmdutil.getlinerangerevs(repo, revs, opts)
3452 3452
3453 3453 getrenamed = None
3454 3454 if opts.get('copies'):
3455 3455 endrev = None
3456 3456 if opts.get('rev'):
3457 3457 endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1
3458 3458 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
3459 3459
3460 3460 ui.pager('log')
3461 3461 displayer = logcmdutil.changesetdisplayer(ui, repo, opts, differ,
3462 3462 buffered=True)
3463 3463 if opts.get('graph'):
3464 3464 displayfn = logcmdutil.displaygraphrevs
3465 3465 else:
3466 3466 displayfn = logcmdutil.displayrevs
3467 3467 displayfn(ui, repo, revs, displayer, getrenamed)
3468 3468
3469 3469 @command('manifest',
3470 3470 [('r', 'rev', '', _('revision to display'), _('REV')),
3471 3471 ('', 'all', False, _("list files from all revisions"))]
3472 3472 + formatteropts,
3473 3473 _('[-r REV]'), cmdtype=readonly)
3474 3474 def manifest(ui, repo, node=None, rev=None, **opts):
3475 3475 """output the current or given revision of the project manifest
3476 3476
3477 3477 Print a list of version controlled files for the given revision.
3478 3478 If no revision is given, the first parent of the working directory
3479 3479 is used, or the null revision if no revision is checked out.
3480 3480
3481 3481 With -v, print file permissions, symlink and executable bits.
3482 3482 With --debug, print file revision hashes.
3483 3483
3484 3484 If option --all is specified, the list of all files from all revisions
3485 3485 is printed. This includes deleted and renamed files.
3486 3486
3487 3487 Returns 0 on success.
3488 3488 """
3489 3489 opts = pycompat.byteskwargs(opts)
3490 3490 fm = ui.formatter('manifest', opts)
3491 3491
3492 3492 if opts.get('all'):
3493 3493 if rev or node:
3494 3494 raise error.Abort(_("can't specify a revision with --all"))
3495 3495
3496 3496 res = []
3497 3497 prefix = "data/"
3498 3498 suffix = ".i"
3499 3499 plen = len(prefix)
3500 3500 slen = len(suffix)
3501 3501 with repo.lock():
3502 3502 for fn, b, size in repo.store.datafiles():
3503 3503 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
3504 3504 res.append(fn[plen:-slen])
3505 3505 ui.pager('manifest')
3506 3506 for f in res:
3507 3507 fm.startitem()
3508 3508 fm.write("path", '%s\n', f)
3509 3509 fm.end()
3510 3510 return
3511 3511
3512 3512 if rev and node:
3513 3513 raise error.Abort(_("please specify just one revision"))
3514 3514
3515 3515 if not node:
3516 3516 node = rev
3517 3517
3518 3518 char = {'l': '@', 'x': '*', '': '', 't': 'd'}
3519 3519 mode = {'l': '644', 'x': '755', '': '644', 't': '755'}
3520 3520 if node:
3521 3521 repo = scmutil.unhidehashlikerevs(repo, [node], 'nowarn')
3522 3522 ctx = scmutil.revsingle(repo, node)
3523 3523 mf = ctx.manifest()
3524 3524 ui.pager('manifest')
3525 3525 for f in ctx:
3526 3526 fm.startitem()
3527 3527 fl = ctx[f].flags()
3528 3528 fm.condwrite(ui.debugflag, 'hash', '%s ', hex(mf[f]))
3529 3529 fm.condwrite(ui.verbose, 'mode type', '%s %1s ', mode[fl], char[fl])
3530 3530 fm.write('path', '%s\n', f)
3531 3531 fm.end()
3532 3532
3533 3533 @command('^merge',
3534 3534 [('f', 'force', None,
3535 3535 _('force a merge including outstanding changes (DEPRECATED)')),
3536 3536 ('r', 'rev', '', _('revision to merge'), _('REV')),
3537 3537 ('P', 'preview', None,
3538 3538 _('review revisions to merge (no merge is performed)')),
3539 3539 ('', 'abort', None, _('abort the ongoing merge')),
3540 3540 ] + mergetoolopts,
3541 3541 _('[-P] [[-r] REV]'))
3542 3542 def merge(ui, repo, node=None, **opts):
3543 3543 """merge another revision into working directory
3544 3544
3545 3545 The current working directory is updated with all changes made in
3546 3546 the requested revision since the last common predecessor revision.
3547 3547
3548 3548 Files that changed between either parent are marked as changed for
3549 3549 the next commit and a commit must be performed before any further
3550 3550 updates to the repository are allowed. The next commit will have
3551 3551 two parents.
3552 3552
3553 3553 ``--tool`` can be used to specify the merge tool used for file
3554 3554 merges. It overrides the HGMERGE environment variable and your
3555 3555 configuration files. See :hg:`help merge-tools` for options.
3556 3556
3557 3557 If no revision is specified, the working directory's parent is a
3558 3558 head revision, and the current branch contains exactly one other
3559 3559 head, the other head is merged with by default. Otherwise, an
3560 3560 explicit revision with which to merge with must be provided.
3561 3561
3562 3562 See :hg:`help resolve` for information on handling file conflicts.
3563 3563
3564 3564 To undo an uncommitted merge, use :hg:`merge --abort` which
3565 3565 will check out a clean copy of the original merge parent, losing
3566 3566 all changes.
3567 3567
3568 3568 Returns 0 on success, 1 if there are unresolved files.
3569 3569 """
3570 3570
3571 3571 opts = pycompat.byteskwargs(opts)
3572 3572 abort = opts.get('abort')
3573 3573 if abort and repo.dirstate.p2() == nullid:
3574 3574 cmdutil.wrongtooltocontinue(repo, _('merge'))
3575 3575 if abort:
3576 3576 if node:
3577 3577 raise error.Abort(_("cannot specify a node with --abort"))
3578 3578 if opts.get('rev'):
3579 3579 raise error.Abort(_("cannot specify both --rev and --abort"))
3580 3580 if opts.get('preview'):
3581 3581 raise error.Abort(_("cannot specify --preview with --abort"))
3582 3582 if opts.get('rev') and node:
3583 3583 raise error.Abort(_("please specify just one revision"))
3584 3584 if not node:
3585 3585 node = opts.get('rev')
3586 3586
3587 3587 if node:
3588 3588 node = scmutil.revsingle(repo, node).node()
3589 3589
3590 3590 if not node and not abort:
3591 3591 node = repo[destutil.destmerge(repo)].node()
3592 3592
3593 3593 if opts.get('preview'):
3594 3594 # find nodes that are ancestors of p2 but not of p1
3595 3595 p1 = repo.lookup('.')
3596 3596 p2 = repo.lookup(node)
3597 3597 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
3598 3598
3599 3599 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
3600 3600 for node in nodes:
3601 3601 displayer.show(repo[node])
3602 3602 displayer.close()
3603 3603 return 0
3604 3604
3605 3605 try:
3606 3606 # ui.forcemerge is an internal variable, do not document
3607 3607 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''), 'merge')
3608 3608 force = opts.get('force')
3609 3609 labels = ['working copy', 'merge rev']
3610 3610 return hg.merge(repo, node, force=force, mergeforce=force,
3611 3611 labels=labels, abort=abort)
3612 3612 finally:
3613 3613 ui.setconfig('ui', 'forcemerge', '', 'merge')
3614 3614
3615 3615 @command('outgoing|out',
3616 3616 [('f', 'force', None, _('run even when the destination is unrelated')),
3617 3617 ('r', 'rev', [],
3618 3618 _('a changeset intended to be included in the destination'), _('REV')),
3619 3619 ('n', 'newest-first', None, _('show newest record first')),
3620 3620 ('B', 'bookmarks', False, _('compare bookmarks')),
3621 3621 ('b', 'branch', [], _('a specific branch you would like to push'),
3622 3622 _('BRANCH')),
3623 3623 ] + logopts + remoteopts + subrepoopts,
3624 3624 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
3625 3625 def outgoing(ui, repo, dest=None, **opts):
3626 3626 """show changesets not found in the destination
3627 3627
3628 3628 Show changesets not found in the specified destination repository
3629 3629 or the default push location. These are the changesets that would
3630 3630 be pushed if a push was requested.
3631 3631
3632 3632 See pull for details of valid destination formats.
3633 3633
3634 3634 .. container:: verbose
3635 3635
3636 3636 With -B/--bookmarks, the result of bookmark comparison between
3637 3637 local and remote repositories is displayed. With -v/--verbose,
3638 3638 status is also displayed for each bookmark like below::
3639 3639
3640 3640 BM1 01234567890a added
3641 3641 BM2 deleted
3642 3642 BM3 234567890abc advanced
3643 3643 BM4 34567890abcd diverged
3644 3644 BM5 4567890abcde changed
3645 3645
3646 3646 The action taken when pushing depends on the
3647 3647 status of each bookmark:
3648 3648
3649 3649 :``added``: push with ``-B`` will create it
3650 3650 :``deleted``: push with ``-B`` will delete it
3651 3651 :``advanced``: push will update it
3652 3652 :``diverged``: push with ``-B`` will update it
3653 3653 :``changed``: push with ``-B`` will update it
3654 3654
3655 3655 From the point of view of pushing behavior, bookmarks
3656 3656 existing only in the remote repository are treated as
3657 3657 ``deleted``, even if it is in fact added remotely.
3658 3658
3659 3659 Returns 0 if there are outgoing changes, 1 otherwise.
3660 3660 """
3661 3661 opts = pycompat.byteskwargs(opts)
3662 3662 if opts.get('graph'):
3663 3663 logcmdutil.checkunsupportedgraphflags([], opts)
3664 3664 o, other = hg._outgoing(ui, repo, dest, opts)
3665 3665 if not o:
3666 3666 cmdutil.outgoinghooks(ui, repo, other, opts, o)
3667 3667 return
3668 3668
3669 3669 revdag = logcmdutil.graphrevs(repo, o, opts)
3670 3670 ui.pager('outgoing')
3671 3671 displayer = logcmdutil.changesetdisplayer(ui, repo, opts, buffered=True)
3672 3672 logcmdutil.displaygraph(ui, repo, revdag, displayer,
3673 3673 graphmod.asciiedges)
3674 3674 cmdutil.outgoinghooks(ui, repo, other, opts, o)
3675 3675 return 0
3676 3676
3677 3677 if opts.get('bookmarks'):
3678 3678 dest = ui.expandpath(dest or 'default-push', dest or 'default')
3679 3679 dest, branches = hg.parseurl(dest, opts.get('branch'))
3680 3680 other = hg.peer(repo, opts, dest)
3681 3681 if 'bookmarks' not in other.listkeys('namespaces'):
3682 3682 ui.warn(_("remote doesn't support bookmarks\n"))
3683 3683 return 0
3684 3684 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
3685 3685 ui.pager('outgoing')
3686 3686 return bookmarks.outgoing(ui, repo, other)
3687 3687
3688 3688 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
3689 3689 try:
3690 3690 return hg.outgoing(ui, repo, dest, opts)
3691 3691 finally:
3692 3692 del repo._subtoppath
3693 3693
3694 3694 @command('parents',
3695 3695 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
3696 3696 ] + templateopts,
3697 3697 _('[-r REV] [FILE]'),
3698 3698 inferrepo=True)
3699 3699 def parents(ui, repo, file_=None, **opts):
3700 3700 """show the parents of the working directory or revision (DEPRECATED)
3701 3701
3702 3702 Print the working directory's parent revisions. If a revision is
3703 3703 given via -r/--rev, the parent of that revision will be printed.
3704 3704 If a file argument is given, the revision in which the file was
3705 3705 last changed (before the working directory revision or the
3706 3706 argument to --rev if given) is printed.
3707 3707
3708 3708 This command is equivalent to::
3709 3709
3710 3710 hg log -r "p1()+p2()" or
3711 3711 hg log -r "p1(REV)+p2(REV)" or
3712 3712 hg log -r "max(::p1() and file(FILE))+max(::p2() and file(FILE))" or
3713 3713 hg log -r "max(::p1(REV) and file(FILE))+max(::p2(REV) and file(FILE))"
3714 3714
3715 3715 See :hg:`summary` and :hg:`help revsets` for related information.
3716 3716
3717 3717 Returns 0 on success.
3718 3718 """
3719 3719
3720 3720 opts = pycompat.byteskwargs(opts)
3721 3721 rev = opts.get('rev')
3722 3722 if rev:
3723 3723 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
3724 3724 ctx = scmutil.revsingle(repo, rev, None)
3725 3725
3726 3726 if file_:
3727 3727 m = scmutil.match(ctx, (file_,), opts)
3728 3728 if m.anypats() or len(m.files()) != 1:
3729 3729 raise error.Abort(_('can only specify an explicit filename'))
3730 3730 file_ = m.files()[0]
3731 3731 filenodes = []
3732 3732 for cp in ctx.parents():
3733 3733 if not cp:
3734 3734 continue
3735 3735 try:
3736 3736 filenodes.append(cp.filenode(file_))
3737 3737 except error.LookupError:
3738 3738 pass
3739 3739 if not filenodes:
3740 3740 raise error.Abort(_("'%s' not found in manifest!") % file_)
3741 3741 p = []
3742 3742 for fn in filenodes:
3743 3743 fctx = repo.filectx(file_, fileid=fn)
3744 3744 p.append(fctx.node())
3745 3745 else:
3746 3746 p = [cp.node() for cp in ctx.parents()]
3747 3747
3748 3748 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
3749 3749 for n in p:
3750 3750 if n != nullid:
3751 3751 displayer.show(repo[n])
3752 3752 displayer.close()
3753 3753
3754 3754 @command('paths', formatteropts, _('[NAME]'), optionalrepo=True,
3755 3755 cmdtype=readonly)
3756 3756 def paths(ui, repo, search=None, **opts):
3757 3757 """show aliases for remote repositories
3758 3758
3759 3759 Show definition of symbolic path name NAME. If no name is given,
3760 3760 show definition of all available names.
3761 3761
3762 3762 Option -q/--quiet suppresses all output when searching for NAME
3763 3763 and shows only the path names when listing all definitions.
3764 3764
3765 3765 Path names are defined in the [paths] section of your
3766 3766 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
3767 3767 repository, ``.hg/hgrc`` is used, too.
3768 3768
3769 3769 The path names ``default`` and ``default-push`` have a special
3770 3770 meaning. When performing a push or pull operation, they are used
3771 3771 as fallbacks if no location is specified on the command-line.
3772 3772 When ``default-push`` is set, it will be used for push and
3773 3773 ``default`` will be used for pull; otherwise ``default`` is used
3774 3774 as the fallback for both. When cloning a repository, the clone
3775 3775 source is written as ``default`` in ``.hg/hgrc``.
3776 3776
3777 3777 .. note::
3778 3778
3779 3779 ``default`` and ``default-push`` apply to all inbound (e.g.
3780 3780 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email`
3781 3781 and :hg:`bundle`) operations.
3782 3782
3783 3783 See :hg:`help urls` for more information.
3784 3784
3785 3785 Returns 0 on success.
3786 3786 """
3787 3787
3788 3788 opts = pycompat.byteskwargs(opts)
3789 3789 ui.pager('paths')
3790 3790 if search:
3791 3791 pathitems = [(name, path) for name, path in ui.paths.iteritems()
3792 3792 if name == search]
3793 3793 else:
3794 3794 pathitems = sorted(ui.paths.iteritems())
3795 3795
3796 3796 fm = ui.formatter('paths', opts)
3797 3797 if fm.isplain():
3798 3798 hidepassword = util.hidepassword
3799 3799 else:
3800 3800 hidepassword = bytes
3801 3801 if ui.quiet:
3802 3802 namefmt = '%s\n'
3803 3803 else:
3804 3804 namefmt = '%s = '
3805 3805 showsubopts = not search and not ui.quiet
3806 3806
3807 3807 for name, path in pathitems:
3808 3808 fm.startitem()
3809 3809 fm.condwrite(not search, 'name', namefmt, name)
3810 3810 fm.condwrite(not ui.quiet, 'url', '%s\n', hidepassword(path.rawloc))
3811 3811 for subopt, value in sorted(path.suboptions.items()):
3812 3812 assert subopt not in ('name', 'url')
3813 3813 if showsubopts:
3814 3814 fm.plain('%s:%s = ' % (name, subopt))
3815 3815 fm.condwrite(showsubopts, subopt, '%s\n', value)
3816 3816
3817 3817 fm.end()
3818 3818
3819 3819 if search and not pathitems:
3820 3820 if not ui.quiet:
3821 3821 ui.warn(_("not found!\n"))
3822 3822 return 1
3823 3823 else:
3824 3824 return 0
3825 3825
3826 3826 @command('phase',
3827 3827 [('p', 'public', False, _('set changeset phase to public')),
3828 3828 ('d', 'draft', False, _('set changeset phase to draft')),
3829 3829 ('s', 'secret', False, _('set changeset phase to secret')),
3830 3830 ('f', 'force', False, _('allow to move boundary backward')),
3831 3831 ('r', 'rev', [], _('target revision'), _('REV')),
3832 3832 ],
3833 3833 _('[-p|-d|-s] [-f] [-r] [REV...]'))
3834 3834 def phase(ui, repo, *revs, **opts):
3835 3835 """set or show the current phase name
3836 3836
3837 3837 With no argument, show the phase name of the current revision(s).
3838 3838
3839 3839 With one of -p/--public, -d/--draft or -s/--secret, change the
3840 3840 phase value of the specified revisions.
3841 3841
3842 3842 Unless -f/--force is specified, :hg:`phase` won't move changesets from a
3843 3843 lower phase to a higher phase. Phases are ordered as follows::
3844 3844
3845 3845 public < draft < secret
3846 3846
3847 3847 Returns 0 on success, 1 if some phases could not be changed.
3848 3848
3849 3849 (For more information about the phases concept, see :hg:`help phases`.)
3850 3850 """
3851 3851 opts = pycompat.byteskwargs(opts)
3852 3852 # search for a unique phase argument
3853 3853 targetphase = None
3854 3854 for idx, name in enumerate(phases.phasenames):
3855 3855 if opts[name]:
3856 3856 if targetphase is not None:
3857 3857 raise error.Abort(_('only one phase can be specified'))
3858 3858 targetphase = idx
3859 3859
3860 3860 # look for specified revision
3861 3861 revs = list(revs)
3862 3862 revs.extend(opts['rev'])
3863 3863 if not revs:
3864 3864 # display both parents as the second parent phase can influence
3865 3865 # the phase of a merge commit
3866 3866 revs = [c.rev() for c in repo[None].parents()]
3867 3867
3868 3868 revs = scmutil.revrange(repo, revs)
3869 3869
3870 3870 ret = 0
3871 3871 if targetphase is None:
3872 3872 # display
3873 3873 for r in revs:
3874 3874 ctx = repo[r]
3875 3875 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
3876 3876 else:
3877 3877 with repo.lock(), repo.transaction("phase") as tr:
3878 3878 # set phase
3879 3879 if not revs:
3880 3880 raise error.Abort(_('empty revision set'))
3881 3881 nodes = [repo[r].node() for r in revs]
3882 3882 # moving revision from public to draft may hide them
3883 3883 # We have to check result on an unfiltered repository
3884 3884 unfi = repo.unfiltered()
3885 3885 getphase = unfi._phasecache.phase
3886 3886 olddata = [getphase(unfi, r) for r in unfi]
3887 3887 phases.advanceboundary(repo, tr, targetphase, nodes)
3888 3888 if opts['force']:
3889 3889 phases.retractboundary(repo, tr, targetphase, nodes)
3890 3890 getphase = unfi._phasecache.phase
3891 3891 newdata = [getphase(unfi, r) for r in unfi]
3892 3892 changes = sum(newdata[r] != olddata[r] for r in unfi)
3893 3893 cl = unfi.changelog
3894 3894 rejected = [n for n in nodes
3895 3895 if newdata[cl.rev(n)] < targetphase]
3896 3896 if rejected:
3897 3897 ui.warn(_('cannot move %i changesets to a higher '
3898 3898 'phase, use --force\n') % len(rejected))
3899 3899 ret = 1
3900 3900 if changes:
3901 3901 msg = _('phase changed for %i changesets\n') % changes
3902 3902 if ret:
3903 3903 ui.status(msg)
3904 3904 else:
3905 3905 ui.note(msg)
3906 3906 else:
3907 3907 ui.warn(_('no phases changed\n'))
3908 3908 return ret
3909 3909
3910 3910 def postincoming(ui, repo, modheads, optupdate, checkout, brev):
3911 3911 """Run after a changegroup has been added via pull/unbundle
3912 3912
3913 3913 This takes arguments below:
3914 3914
3915 3915 :modheads: change of heads by pull/unbundle
3916 3916 :optupdate: updating working directory is needed or not
3917 3917 :checkout: update destination revision (or None to default destination)
3918 3918 :brev: a name, which might be a bookmark to be activated after updating
3919 3919 """
3920 3920 if modheads == 0:
3921 3921 return
3922 3922 if optupdate:
3923 3923 try:
3924 3924 return hg.updatetotally(ui, repo, checkout, brev)
3925 3925 except error.UpdateAbort as inst:
3926 3926 msg = _("not updating: %s") % stringutil.forcebytestr(inst)
3927 3927 hint = inst.hint
3928 3928 raise error.UpdateAbort(msg, hint=hint)
3929 3929 if modheads > 1:
3930 3930 currentbranchheads = len(repo.branchheads())
3931 3931 if currentbranchheads == modheads:
3932 3932 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
3933 3933 elif currentbranchheads > 1:
3934 3934 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to "
3935 3935 "merge)\n"))
3936 3936 else:
3937 3937 ui.status(_("(run 'hg heads' to see heads)\n"))
3938 3938 elif not ui.configbool('commands', 'update.requiredest'):
3939 3939 ui.status(_("(run 'hg update' to get a working copy)\n"))
3940 3940
3941 3941 @command('^pull',
3942 3942 [('u', 'update', None,
3943 3943 _('update to new branch head if new descendants were pulled')),
3944 3944 ('f', 'force', None, _('run even when remote repository is unrelated')),
3945 3945 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3946 3946 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
3947 3947 ('b', 'branch', [], _('a specific branch you would like to pull'),
3948 3948 _('BRANCH')),
3949 3949 ] + remoteopts,
3950 3950 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
3951 3951 def pull(ui, repo, source="default", **opts):
3952 3952 """pull changes from the specified source
3953 3953
3954 3954 Pull changes from a remote repository to a local one.
3955 3955
3956 3956 This finds all changes from the repository at the specified path
3957 3957 or URL and adds them to a local repository (the current one unless
3958 3958 -R is specified). By default, this does not update the copy of the
3959 3959 project in the working directory.
3960 3960
3961 3961 Use :hg:`incoming` if you want to see what would have been added
3962 3962 by a pull at the time you issued this command. If you then decide
3963 3963 to add those changes to the repository, you should use :hg:`pull
3964 3964 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
3965 3965
3966 3966 If SOURCE is omitted, the 'default' path will be used.
3967 3967 See :hg:`help urls` for more information.
3968 3968
3969 3969 Specifying bookmark as ``.`` is equivalent to specifying the active
3970 3970 bookmark's name.
3971 3971
3972 3972 Returns 0 on success, 1 if an update had unresolved files.
3973 3973 """
3974 3974
3975 3975 opts = pycompat.byteskwargs(opts)
3976 3976 if ui.configbool('commands', 'update.requiredest') and opts.get('update'):
3977 3977 msg = _('update destination required by configuration')
3978 3978 hint = _('use hg pull followed by hg update DEST')
3979 3979 raise error.Abort(msg, hint=hint)
3980 3980
3981 3981 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
3982 3982 ui.status(_('pulling from %s\n') % util.hidepassword(source))
3983 3983 other = hg.peer(repo, opts, source)
3984 3984 try:
3985 3985 revs, checkout = hg.addbranchrevs(repo, other, branches,
3986 3986 opts.get('rev'))
3987 3987
3988 3988
3989 3989 pullopargs = {}
3990 3990 if opts.get('bookmark'):
3991 3991 if not revs:
3992 3992 revs = []
3993 3993 # The list of bookmark used here is not the one used to actually
3994 3994 # update the bookmark name. This can result in the revision pulled
3995 3995 # not ending up with the name of the bookmark because of a race
3996 3996 # condition on the server. (See issue 4689 for details)
3997 3997 remotebookmarks = other.listkeys('bookmarks')
3998 3998 remotebookmarks = bookmarks.unhexlifybookmarks(remotebookmarks)
3999 3999 pullopargs['remotebookmarks'] = remotebookmarks
4000 4000 for b in opts['bookmark']:
4001 4001 b = repo._bookmarks.expandname(b)
4002 4002 if b not in remotebookmarks:
4003 4003 raise error.Abort(_('remote bookmark %s not found!') % b)
4004 4004 revs.append(hex(remotebookmarks[b]))
4005 4005
4006 4006 if revs:
4007 4007 try:
4008 4008 # When 'rev' is a bookmark name, we cannot guarantee that it
4009 4009 # will be updated with that name because of a race condition
4010 4010 # server side. (See issue 4689 for details)
4011 4011 oldrevs = revs
4012 4012 revs = [] # actually, nodes
4013 4013 for r in oldrevs:
4014 4014 node = other.lookup(r)
4015 4015 revs.append(node)
4016 4016 if r == checkout:
4017 4017 checkout = node
4018 4018 except error.CapabilityError:
4019 4019 err = _("other repository doesn't support revision lookup, "
4020 4020 "so a rev cannot be specified.")
4021 4021 raise error.Abort(err)
4022 4022
4023 4023 wlock = util.nullcontextmanager()
4024 4024 if opts.get('update'):
4025 4025 wlock = repo.wlock()
4026 4026 with wlock:
4027 4027 pullopargs.update(opts.get('opargs', {}))
4028 4028 modheads = exchange.pull(repo, other, heads=revs,
4029 4029 force=opts.get('force'),
4030 4030 bookmarks=opts.get('bookmark', ()),
4031 4031 opargs=pullopargs).cgresult
4032 4032
4033 4033 # brev is a name, which might be a bookmark to be activated at
4034 4034 # the end of the update. In other words, it is an explicit
4035 4035 # destination of the update
4036 4036 brev = None
4037 4037
4038 4038 if checkout:
4039 4039 checkout = "%d" % repo.changelog.rev(checkout)
4040 4040
4041 4041 # order below depends on implementation of
4042 4042 # hg.addbranchrevs(). opts['bookmark'] is ignored,
4043 4043 # because 'checkout' is determined without it.
4044 4044 if opts.get('rev'):
4045 4045 brev = opts['rev'][0]
4046 4046 elif opts.get('branch'):
4047 4047 brev = opts['branch'][0]
4048 4048 else:
4049 4049 brev = branches[0]
4050 4050 repo._subtoppath = source
4051 4051 try:
4052 4052 ret = postincoming(ui, repo, modheads, opts.get('update'),
4053 4053 checkout, brev)
4054 4054
4055 4055 finally:
4056 4056 del repo._subtoppath
4057 4057
4058 4058 finally:
4059 4059 other.close()
4060 4060 return ret
4061 4061
4062 4062 @command('^push',
4063 4063 [('f', 'force', None, _('force push')),
4064 4064 ('r', 'rev', [],
4065 4065 _('a changeset intended to be included in the destination'),
4066 4066 _('REV')),
4067 4067 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4068 4068 ('b', 'branch', [],
4069 4069 _('a specific branch you would like to push'), _('BRANCH')),
4070 4070 ('', 'new-branch', False, _('allow pushing a new branch')),
4071 4071 ('', 'pushvars', [], _('variables that can be sent to server (ADVANCED)')),
4072 4072 ] + remoteopts,
4073 4073 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
4074 4074 def push(ui, repo, dest=None, **opts):
4075 4075 """push changes to the specified destination
4076 4076
4077 4077 Push changesets from the local repository to the specified
4078 4078 destination.
4079 4079
4080 4080 This operation is symmetrical to pull: it is identical to a pull
4081 4081 in the destination repository from the current one.
4082 4082
4083 4083 By default, push will not allow creation of new heads at the
4084 4084 destination, since multiple heads would make it unclear which head
4085 4085 to use. In this situation, it is recommended to pull and merge
4086 4086 before pushing.
4087 4087
4088 4088 Use --new-branch if you want to allow push to create a new named
4089 4089 branch that is not present at the destination. This allows you to
4090 4090 only create a new branch without forcing other changes.
4091 4091
4092 4092 .. note::
4093 4093
4094 4094 Extra care should be taken with the -f/--force option,
4095 4095 which will push all new heads on all branches, an action which will
4096 4096 almost always cause confusion for collaborators.
4097 4097
4098 4098 If -r/--rev is used, the specified revision and all its ancestors
4099 4099 will be pushed to the remote repository.
4100 4100
4101 4101 If -B/--bookmark is used, the specified bookmarked revision, its
4102 4102 ancestors, and the bookmark will be pushed to the remote
4103 4103 repository. Specifying ``.`` is equivalent to specifying the active
4104 4104 bookmark's name.
4105 4105
4106 4106 Please see :hg:`help urls` for important details about ``ssh://``
4107 4107 URLs. If DESTINATION is omitted, a default path will be used.
4108 4108
4109 4109 .. container:: verbose
4110 4110
4111 4111 The --pushvars option sends strings to the server that become
4112 4112 environment variables prepended with ``HG_USERVAR_``. For example,
4113 4113 ``--pushvars ENABLE_FEATURE=true``, provides the server side hooks with
4114 4114 ``HG_USERVAR_ENABLE_FEATURE=true`` as part of their environment.
4115 4115
4116 4116 pushvars can provide for user-overridable hooks as well as set debug
4117 4117 levels. One example is having a hook that blocks commits containing
4118 4118 conflict markers, but enables the user to override the hook if the file
4119 4119 is using conflict markers for testing purposes or the file format has
4120 4120 strings that look like conflict markers.
4121 4121
4122 4122 By default, servers will ignore `--pushvars`. To enable it add the
4123 4123 following to your configuration file::
4124 4124
4125 4125 [push]
4126 4126 pushvars.server = true
4127 4127
4128 4128 Returns 0 if push was successful, 1 if nothing to push.
4129 4129 """
4130 4130
4131 4131 opts = pycompat.byteskwargs(opts)
4132 4132 if opts.get('bookmark'):
4133 4133 ui.setconfig('bookmarks', 'pushing', opts['bookmark'], 'push')
4134 4134 for b in opts['bookmark']:
4135 4135 # translate -B options to -r so changesets get pushed
4136 4136 b = repo._bookmarks.expandname(b)
4137 4137 if b in repo._bookmarks:
4138 4138 opts.setdefault('rev', []).append(b)
4139 4139 else:
4140 4140 # if we try to push a deleted bookmark, translate it to null
4141 4141 # this lets simultaneous -r, -b options continue working
4142 4142 opts.setdefault('rev', []).append("null")
4143 4143
4144 4144 path = ui.paths.getpath(dest, default=('default-push', 'default'))
4145 4145 if not path:
4146 4146 raise error.Abort(_('default repository not configured!'),
4147 4147 hint=_("see 'hg help config.paths'"))
4148 4148 dest = path.pushloc or path.loc
4149 4149 branches = (path.branch, opts.get('branch') or [])
4150 4150 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
4151 4151 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
4152 4152 other = hg.peer(repo, opts, dest)
4153 4153
4154 4154 if revs:
4155 4155 revs = [repo.lookup(r) for r in scmutil.revrange(repo, revs)]
4156 4156 if not revs:
4157 4157 raise error.Abort(_("specified revisions evaluate to an empty set"),
4158 4158 hint=_("use different revision arguments"))
4159 4159 elif path.pushrev:
4160 4160 # It doesn't make any sense to specify ancestor revisions. So limit
4161 4161 # to DAG heads to make discovery simpler.
4162 4162 expr = revsetlang.formatspec('heads(%r)', path.pushrev)
4163 4163 revs = scmutil.revrange(repo, [expr])
4164 4164 revs = [repo[rev].node() for rev in revs]
4165 4165 if not revs:
4166 4166 raise error.Abort(_('default push revset for path evaluates to an '
4167 4167 'empty set'))
4168 4168
4169 4169 repo._subtoppath = dest
4170 4170 try:
4171 4171 # push subrepos depth-first for coherent ordering
4172 4172 c = repo['.']
4173 4173 subs = c.substate # only repos that are committed
4174 4174 for s in sorted(subs):
4175 4175 result = c.sub(s).push(opts)
4176 4176 if result == 0:
4177 4177 return not result
4178 4178 finally:
4179 4179 del repo._subtoppath
4180 4180
4181 4181 opargs = dict(opts.get('opargs', {})) # copy opargs since we may mutate it
4182 4182 opargs.setdefault('pushvars', []).extend(opts.get('pushvars', []))
4183 4183
4184 4184 pushop = exchange.push(repo, other, opts.get('force'), revs=revs,
4185 4185 newbranch=opts.get('new_branch'),
4186 4186 bookmarks=opts.get('bookmark', ()),
4187 4187 opargs=opargs)
4188 4188
4189 4189 result = not pushop.cgresult
4190 4190
4191 4191 if pushop.bkresult is not None:
4192 4192 if pushop.bkresult == 2:
4193 4193 result = 2
4194 4194 elif not result and pushop.bkresult:
4195 4195 result = 2
4196 4196
4197 4197 return result
4198 4198
4199 4199 @command('recover', [])
4200 4200 def recover(ui, repo):
4201 4201 """roll back an interrupted transaction
4202 4202
4203 4203 Recover from an interrupted commit or pull.
4204 4204
4205 4205 This command tries to fix the repository status after an
4206 4206 interrupted operation. It should only be necessary when Mercurial
4207 4207 suggests it.
4208 4208
4209 4209 Returns 0 if successful, 1 if nothing to recover or verify fails.
4210 4210 """
4211 4211 if repo.recover():
4212 4212 return hg.verify(repo)
4213 4213 return 1
4214 4214
4215 4215 @command('^remove|rm',
4216 4216 [('A', 'after', None, _('record delete for missing files')),
4217 4217 ('f', 'force', None,
4218 4218 _('forget added files, delete modified files')),
4219 4219 ] + subrepoopts + walkopts + dryrunopts,
4220 4220 _('[OPTION]... FILE...'),
4221 4221 inferrepo=True)
4222 4222 def remove(ui, repo, *pats, **opts):
4223 4223 """remove the specified files on the next commit
4224 4224
4225 4225 Schedule the indicated files for removal from the current branch.
4226 4226
4227 4227 This command schedules the files to be removed at the next commit.
4228 4228 To undo a remove before that, see :hg:`revert`. To undo added
4229 4229 files, see :hg:`forget`.
4230 4230
4231 4231 .. container:: verbose
4232 4232
4233 4233 -A/--after can be used to remove only files that have already
4234 4234 been deleted, -f/--force can be used to force deletion, and -Af
4235 4235 can be used to remove files from the next revision without
4236 4236 deleting them from the working directory.
4237 4237
4238 4238 The following table details the behavior of remove for different
4239 4239 file states (columns) and option combinations (rows). The file
4240 4240 states are Added [A], Clean [C], Modified [M] and Missing [!]
4241 4241 (as reported by :hg:`status`). The actions are Warn, Remove
4242 4242 (from branch) and Delete (from disk):
4243 4243
4244 4244 ========= == == == ==
4245 4245 opt/state A C M !
4246 4246 ========= == == == ==
4247 4247 none W RD W R
4248 4248 -f R RD RD R
4249 4249 -A W W W R
4250 4250 -Af R R R R
4251 4251 ========= == == == ==
4252 4252
4253 4253 .. note::
4254 4254
4255 4255 :hg:`remove` never deletes files in Added [A] state from the
4256 4256 working directory, not even if ``--force`` is specified.
4257 4257
4258 4258 Returns 0 on success, 1 if any warnings encountered.
4259 4259 """
4260 4260
4261 4261 opts = pycompat.byteskwargs(opts)
4262 4262 after, force = opts.get('after'), opts.get('force')
4263 4263 dryrun = opts.get('dry_run')
4264 4264 if not pats and not after:
4265 4265 raise error.Abort(_('no files specified'))
4266 4266
4267 4267 m = scmutil.match(repo[None], pats, opts)
4268 4268 subrepos = opts.get('subrepos')
4269 4269 return cmdutil.remove(ui, repo, m, "", after, force, subrepos,
4270 4270 dryrun=dryrun)
4271 4271
4272 4272 @command('rename|move|mv',
4273 4273 [('A', 'after', None, _('record a rename that has already occurred')),
4274 4274 ('f', 'force', None, _('forcibly copy over an existing managed file')),
4275 4275 ] + walkopts + dryrunopts,
4276 4276 _('[OPTION]... SOURCE... DEST'))
4277 4277 def rename(ui, repo, *pats, **opts):
4278 4278 """rename files; equivalent of copy + remove
4279 4279
4280 4280 Mark dest as copies of sources; mark sources for deletion. If dest
4281 4281 is a directory, copies are put in that directory. If dest is a
4282 4282 file, there can only be one source.
4283 4283
4284 4284 By default, this command copies the contents of files as they
4285 4285 exist in the working directory. If invoked with -A/--after, the
4286 4286 operation is recorded, but no copying is performed.
4287 4287
4288 4288 This command takes effect at the next commit. To undo a rename
4289 4289 before that, see :hg:`revert`.
4290 4290
4291 4291 Returns 0 on success, 1 if errors are encountered.
4292 4292 """
4293 4293 opts = pycompat.byteskwargs(opts)
4294 4294 with repo.wlock(False):
4295 4295 return cmdutil.copy(ui, repo, pats, opts, rename=True)
4296 4296
4297 4297 @command('resolve',
4298 4298 [('a', 'all', None, _('select all unresolved files')),
4299 4299 ('l', 'list', None, _('list state of files needing merge')),
4300 4300 ('m', 'mark', None, _('mark files as resolved')),
4301 4301 ('u', 'unmark', None, _('mark files as unresolved')),
4302 4302 ('n', 'no-status', None, _('hide status prefix'))]
4303 4303 + mergetoolopts + walkopts + formatteropts,
4304 4304 _('[OPTION]... [FILE]...'),
4305 4305 inferrepo=True)
4306 4306 def resolve(ui, repo, *pats, **opts):
4307 4307 """redo merges or set/view the merge status of files
4308 4308
4309 4309 Merges with unresolved conflicts are often the result of
4310 4310 non-interactive merging using the ``internal:merge`` configuration
4311 4311 setting, or a command-line merge tool like ``diff3``. The resolve
4312 4312 command is used to manage the files involved in a merge, after
4313 4313 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4314 4314 working directory must have two parents). See :hg:`help
4315 4315 merge-tools` for information on configuring merge tools.
4316 4316
4317 4317 The resolve command can be used in the following ways:
4318 4318
4319 4319 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4320 4320 files, discarding any previous merge attempts. Re-merging is not
4321 4321 performed for files already marked as resolved. Use ``--all/-a``
4322 4322 to select all unresolved files. ``--tool`` can be used to specify
4323 4323 the merge tool used for the given files. It overrides the HGMERGE
4324 4324 environment variable and your configuration files. Previous file
4325 4325 contents are saved with a ``.orig`` suffix.
4326 4326
4327 4327 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4328 4328 (e.g. after having manually fixed-up the files). The default is
4329 4329 to mark all unresolved files.
4330 4330
4331 4331 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4332 4332 default is to mark all resolved files.
4333 4333
4334 4334 - :hg:`resolve -l`: list files which had or still have conflicts.
4335 4335 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4336 4336 You can use ``set:unresolved()`` or ``set:resolved()`` to filter
4337 4337 the list. See :hg:`help filesets` for details.
4338 4338
4339 4339 .. note::
4340 4340
4341 4341 Mercurial will not let you commit files with unresolved merge
4342 4342 conflicts. You must use :hg:`resolve -m ...` before you can
4343 4343 commit after a conflicting merge.
4344 4344
4345 4345 Returns 0 on success, 1 if any files fail a resolve attempt.
4346 4346 """
4347 4347
4348 4348 opts = pycompat.byteskwargs(opts)
4349 4349 flaglist = 'all mark unmark list no_status'.split()
4350 4350 all, mark, unmark, show, nostatus = \
4351 4351 [opts.get(o) for o in flaglist]
4352 4352
4353 4353 if (show and (mark or unmark)) or (mark and unmark):
4354 4354 raise error.Abort(_("too many options specified"))
4355 4355 if pats and all:
4356 4356 raise error.Abort(_("can't specify --all and patterns"))
4357 4357 if not (all or pats or show or mark or unmark):
4358 4358 raise error.Abort(_('no files or directories specified'),
4359 4359 hint=('use --all to re-merge all unresolved files'))
4360 4360
4361 4361 if show:
4362 4362 ui.pager('resolve')
4363 4363 fm = ui.formatter('resolve', opts)
4364 4364 ms = mergemod.mergestate.read(repo)
4365 4365 m = scmutil.match(repo[None], pats, opts)
4366 4366
4367 4367 # Labels and keys based on merge state. Unresolved path conflicts show
4368 4368 # as 'P'. Resolved path conflicts show as 'R', the same as normal
4369 4369 # resolved conflicts.
4370 4370 mergestateinfo = {
4371 4371 mergemod.MERGE_RECORD_UNRESOLVED: ('resolve.unresolved', 'U'),
4372 4372 mergemod.MERGE_RECORD_RESOLVED: ('resolve.resolved', 'R'),
4373 4373 mergemod.MERGE_RECORD_UNRESOLVED_PATH: ('resolve.unresolved', 'P'),
4374 4374 mergemod.MERGE_RECORD_RESOLVED_PATH: ('resolve.resolved', 'R'),
4375 4375 mergemod.MERGE_RECORD_DRIVER_RESOLVED: ('resolve.driverresolved',
4376 4376 'D'),
4377 4377 }
4378 4378
4379 4379 for f in ms:
4380 4380 if not m(f):
4381 4381 continue
4382 4382
4383 4383 label, key = mergestateinfo[ms[f]]
4384 4384 fm.startitem()
4385 4385 fm.condwrite(not nostatus, 'status', '%s ', key, label=label)
4386 4386 fm.write('path', '%s\n', f, label=label)
4387 4387 fm.end()
4388 4388 return 0
4389 4389
4390 4390 with repo.wlock():
4391 4391 ms = mergemod.mergestate.read(repo)
4392 4392
4393 4393 if not (ms.active() or repo.dirstate.p2() != nullid):
4394 4394 raise error.Abort(
4395 4395 _('resolve command not applicable when not merging'))
4396 4396
4397 4397 wctx = repo[None]
4398 4398
4399 4399 if (ms.mergedriver
4400 4400 and ms.mdstate() == mergemod.MERGE_DRIVER_STATE_UNMARKED):
4401 4401 proceed = mergemod.driverpreprocess(repo, ms, wctx)
4402 4402 ms.commit()
4403 4403 # allow mark and unmark to go through
4404 4404 if not mark and not unmark and not proceed:
4405 4405 return 1
4406 4406
4407 4407 m = scmutil.match(wctx, pats, opts)
4408 4408 ret = 0
4409 4409 didwork = False
4410 4410 runconclude = False
4411 4411
4412 4412 tocomplete = []
4413 4413 for f in ms:
4414 4414 if not m(f):
4415 4415 continue
4416 4416
4417 4417 didwork = True
4418 4418
4419 4419 # don't let driver-resolved files be marked, and run the conclude
4420 4420 # step if asked to resolve
4421 4421 if ms[f] == mergemod.MERGE_RECORD_DRIVER_RESOLVED:
4422 4422 exact = m.exact(f)
4423 4423 if mark:
4424 4424 if exact:
4425 4425 ui.warn(_('not marking %s as it is driver-resolved\n')
4426 4426 % f)
4427 4427 elif unmark:
4428 4428 if exact:
4429 4429 ui.warn(_('not unmarking %s as it is driver-resolved\n')
4430 4430 % f)
4431 4431 else:
4432 4432 runconclude = True
4433 4433 continue
4434 4434
4435 4435 # path conflicts must be resolved manually
4436 4436 if ms[f] in (mergemod.MERGE_RECORD_UNRESOLVED_PATH,
4437 4437 mergemod.MERGE_RECORD_RESOLVED_PATH):
4438 4438 if mark:
4439 4439 ms.mark(f, mergemod.MERGE_RECORD_RESOLVED_PATH)
4440 4440 elif unmark:
4441 4441 ms.mark(f, mergemod.MERGE_RECORD_UNRESOLVED_PATH)
4442 4442 elif ms[f] == mergemod.MERGE_RECORD_UNRESOLVED_PATH:
4443 4443 ui.warn(_('%s: path conflict must be resolved manually\n')
4444 4444 % f)
4445 4445 continue
4446 4446
4447 4447 if mark:
4448 4448 ms.mark(f, mergemod.MERGE_RECORD_RESOLVED)
4449 4449 elif unmark:
4450 4450 ms.mark(f, mergemod.MERGE_RECORD_UNRESOLVED)
4451 4451 else:
4452 4452 # backup pre-resolve (merge uses .orig for its own purposes)
4453 4453 a = repo.wjoin(f)
4454 4454 try:
4455 4455 util.copyfile(a, a + ".resolve")
4456 4456 except (IOError, OSError) as inst:
4457 4457 if inst.errno != errno.ENOENT:
4458 4458 raise
4459 4459
4460 4460 try:
4461 4461 # preresolve file
4462 4462 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
4463 4463 'resolve')
4464 4464 complete, r = ms.preresolve(f, wctx)
4465 4465 if not complete:
4466 4466 tocomplete.append(f)
4467 4467 elif r:
4468 4468 ret = 1
4469 4469 finally:
4470 4470 ui.setconfig('ui', 'forcemerge', '', 'resolve')
4471 4471 ms.commit()
4472 4472
4473 4473 # replace filemerge's .orig file with our resolve file, but only
4474 4474 # for merges that are complete
4475 4475 if complete:
4476 4476 try:
4477 4477 util.rename(a + ".resolve",
4478 4478 scmutil.origpath(ui, repo, a))
4479 4479 except OSError as inst:
4480 4480 if inst.errno != errno.ENOENT:
4481 4481 raise
4482 4482
4483 4483 for f in tocomplete:
4484 4484 try:
4485 4485 # resolve file
4486 4486 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
4487 4487 'resolve')
4488 4488 r = ms.resolve(f, wctx)
4489 4489 if r:
4490 4490 ret = 1
4491 4491 finally:
4492 4492 ui.setconfig('ui', 'forcemerge', '', 'resolve')
4493 4493 ms.commit()
4494 4494
4495 4495 # replace filemerge's .orig file with our resolve file
4496 4496 a = repo.wjoin(f)
4497 4497 try:
4498 4498 util.rename(a + ".resolve", scmutil.origpath(ui, repo, a))
4499 4499 except OSError as inst:
4500 4500 if inst.errno != errno.ENOENT:
4501 4501 raise
4502 4502
4503 4503 ms.commit()
4504 4504 ms.recordactions()
4505 4505
4506 4506 if not didwork and pats:
4507 4507 hint = None
4508 4508 if not any([p for p in pats if p.find(':') >= 0]):
4509 4509 pats = ['path:%s' % p for p in pats]
4510 4510 m = scmutil.match(wctx, pats, opts)
4511 4511 for f in ms:
4512 4512 if not m(f):
4513 4513 continue
4514 4514 flags = ''.join(['-%s ' % o[0:1] for o in flaglist
4515 4515 if opts.get(o)])
4516 4516 hint = _("(try: hg resolve %s%s)\n") % (
4517 4517 flags,
4518 4518 ' '.join(pats))
4519 4519 break
4520 4520 ui.warn(_("arguments do not match paths that need resolving\n"))
4521 4521 if hint:
4522 4522 ui.warn(hint)
4523 4523 elif ms.mergedriver and ms.mdstate() != 's':
4524 4524 # run conclude step when either a driver-resolved file is requested
4525 4525 # or there are no driver-resolved files
4526 4526 # we can't use 'ret' to determine whether any files are unresolved
4527 4527 # because we might not have tried to resolve some
4528 4528 if ((runconclude or not list(ms.driverresolved()))
4529 4529 and not list(ms.unresolved())):
4530 4530 proceed = mergemod.driverconclude(repo, ms, wctx)
4531 4531 ms.commit()
4532 4532 if not proceed:
4533 4533 return 1
4534 4534
4535 4535 # Nudge users into finishing an unfinished operation
4536 4536 unresolvedf = list(ms.unresolved())
4537 4537 driverresolvedf = list(ms.driverresolved())
4538 4538 if not unresolvedf and not driverresolvedf:
4539 4539 ui.status(_('(no more unresolved files)\n'))
4540 4540 cmdutil.checkafterresolved(repo)
4541 4541 elif not unresolvedf:
4542 4542 ui.status(_('(no more unresolved files -- '
4543 4543 'run "hg resolve --all" to conclude)\n'))
4544 4544
4545 4545 return ret
4546 4546
4547 4547 @command('revert',
4548 4548 [('a', 'all', None, _('revert all changes when no arguments given')),
4549 4549 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4550 4550 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
4551 4551 ('C', 'no-backup', None, _('do not save backup copies of files')),
4552 4552 ('i', 'interactive', None, _('interactively select the changes')),
4553 4553 ] + walkopts + dryrunopts,
4554 4554 _('[OPTION]... [-r REV] [NAME]...'))
4555 4555 def revert(ui, repo, *pats, **opts):
4556 4556 """restore files to their checkout state
4557 4557
4558 4558 .. note::
4559 4559
4560 4560 To check out earlier revisions, you should use :hg:`update REV`.
4561 4561 To cancel an uncommitted merge (and lose your changes),
4562 4562 use :hg:`merge --abort`.
4563 4563
4564 4564 With no revision specified, revert the specified files or directories
4565 4565 to the contents they had in the parent of the working directory.
4566 4566 This restores the contents of files to an unmodified
4567 4567 state and unschedules adds, removes, copies, and renames. If the
4568 4568 working directory has two parents, you must explicitly specify a
4569 4569 revision.
4570 4570
4571 4571 Using the -r/--rev or -d/--date options, revert the given files or
4572 4572 directories to their states as of a specific revision. Because
4573 4573 revert does not change the working directory parents, this will
4574 4574 cause these files to appear modified. This can be helpful to "back
4575 4575 out" some or all of an earlier change. See :hg:`backout` for a
4576 4576 related method.
4577 4577
4578 4578 Modified files are saved with a .orig suffix before reverting.
4579 4579 To disable these backups, use --no-backup. It is possible to store
4580 4580 the backup files in a custom directory relative to the root of the
4581 4581 repository by setting the ``ui.origbackuppath`` configuration
4582 4582 option.
4583 4583
4584 4584 See :hg:`help dates` for a list of formats valid for -d/--date.
4585 4585
4586 4586 See :hg:`help backout` for a way to reverse the effect of an
4587 4587 earlier changeset.
4588 4588
4589 4589 Returns 0 on success.
4590 4590 """
4591 4591
4592 4592 opts = pycompat.byteskwargs(opts)
4593 4593 if opts.get("date"):
4594 4594 if opts.get("rev"):
4595 4595 raise error.Abort(_("you can't specify a revision and a date"))
4596 4596 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
4597 4597
4598 4598 parent, p2 = repo.dirstate.parents()
4599 4599 if not opts.get('rev') and p2 != nullid:
4600 4600 # revert after merge is a trap for new users (issue2915)
4601 4601 raise error.Abort(_('uncommitted merge with no revision specified'),
4602 4602 hint=_("use 'hg update' or see 'hg help revert'"))
4603 4603
4604 4604 rev = opts.get('rev')
4605 4605 if rev:
4606 4606 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
4607 4607 ctx = scmutil.revsingle(repo, rev)
4608 4608
4609 4609 if (not (pats or opts.get('include') or opts.get('exclude') or
4610 4610 opts.get('all') or opts.get('interactive'))):
4611 4611 msg = _("no files or directories specified")
4612 4612 if p2 != nullid:
4613 4613 hint = _("uncommitted merge, use --all to discard all changes,"
4614 4614 " or 'hg update -C .' to abort the merge")
4615 4615 raise error.Abort(msg, hint=hint)
4616 4616 dirty = any(repo.status())
4617 4617 node = ctx.node()
4618 4618 if node != parent:
4619 4619 if dirty:
4620 4620 hint = _("uncommitted changes, use --all to discard all"
4621 4621 " changes, or 'hg update %s' to update") % ctx.rev()
4622 4622 else:
4623 4623 hint = _("use --all to revert all files,"
4624 4624 " or 'hg update %s' to update") % ctx.rev()
4625 4625 elif dirty:
4626 4626 hint = _("uncommitted changes, use --all to discard all changes")
4627 4627 else:
4628 4628 hint = _("use --all to revert all files")
4629 4629 raise error.Abort(msg, hint=hint)
4630 4630
4631 4631 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats,
4632 4632 **pycompat.strkwargs(opts))
4633 4633
4634 4634 @command('rollback', dryrunopts +
4635 4635 [('f', 'force', False, _('ignore safety measures'))])
4636 4636 def rollback(ui, repo, **opts):
4637 4637 """roll back the last transaction (DANGEROUS) (DEPRECATED)
4638 4638
4639 4639 Please use :hg:`commit --amend` instead of rollback to correct
4640 4640 mistakes in the last commit.
4641 4641
4642 4642 This command should be used with care. There is only one level of
4643 4643 rollback, and there is no way to undo a rollback. It will also
4644 4644 restore the dirstate at the time of the last transaction, losing
4645 4645 any dirstate changes since that time. This command does not alter
4646 4646 the working directory.
4647 4647
4648 4648 Transactions are used to encapsulate the effects of all commands
4649 4649 that create new changesets or propagate existing changesets into a
4650 4650 repository.
4651 4651
4652 4652 .. container:: verbose
4653 4653
4654 4654 For example, the following commands are transactional, and their
4655 4655 effects can be rolled back:
4656 4656
4657 4657 - commit
4658 4658 - import
4659 4659 - pull
4660 4660 - push (with this repository as the destination)
4661 4661 - unbundle
4662 4662
4663 4663 To avoid permanent data loss, rollback will refuse to rollback a
4664 4664 commit transaction if it isn't checked out. Use --force to
4665 4665 override this protection.
4666 4666
4667 4667 The rollback command can be entirely disabled by setting the
4668 4668 ``ui.rollback`` configuration setting to false. If you're here
4669 4669 because you want to use rollback and it's disabled, you can
4670 4670 re-enable the command by setting ``ui.rollback`` to true.
4671 4671
4672 4672 This command is not intended for use on public repositories. Once
4673 4673 changes are visible for pull by other users, rolling a transaction
4674 4674 back locally is ineffective (someone else may already have pulled
4675 4675 the changes). Furthermore, a race is possible with readers of the
4676 4676 repository; for example an in-progress pull from the repository
4677 4677 may fail if a rollback is performed.
4678 4678
4679 4679 Returns 0 on success, 1 if no rollback data is available.
4680 4680 """
4681 4681 if not ui.configbool('ui', 'rollback'):
4682 4682 raise error.Abort(_('rollback is disabled because it is unsafe'),
4683 4683 hint=('see `hg help -v rollback` for information'))
4684 4684 return repo.rollback(dryrun=opts.get(r'dry_run'),
4685 4685 force=opts.get(r'force'))
4686 4686
4687 4687 @command('root', [], cmdtype=readonly)
4688 4688 def root(ui, repo):
4689 4689 """print the root (top) of the current working directory
4690 4690
4691 4691 Print the root directory of the current repository.
4692 4692
4693 4693 Returns 0 on success.
4694 4694 """
4695 4695 ui.write(repo.root + "\n")
4696 4696
4697 4697 @command('^serve',
4698 4698 [('A', 'accesslog', '', _('name of access log file to write to'),
4699 4699 _('FILE')),
4700 4700 ('d', 'daemon', None, _('run server in background')),
4701 4701 ('', 'daemon-postexec', [], _('used internally by daemon mode')),
4702 4702 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
4703 4703 # use string type, then we can check if something was passed
4704 4704 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
4705 4705 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
4706 4706 _('ADDR')),
4707 4707 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
4708 4708 _('PREFIX')),
4709 4709 ('n', 'name', '',
4710 4710 _('name to show in web pages (default: working directory)'), _('NAME')),
4711 4711 ('', 'web-conf', '',
4712 4712 _("name of the hgweb config file (see 'hg help hgweb')"), _('FILE')),
4713 4713 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
4714 4714 _('FILE')),
4715 4715 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
4716 4716 ('', 'stdio', None, _('for remote clients (ADVANCED)')),
4717 4717 ('', 'cmdserver', '', _('for remote clients (ADVANCED)'), _('MODE')),
4718 4718 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
4719 4719 ('', 'style', '', _('template style to use'), _('STYLE')),
4720 4720 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
4721 4721 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))]
4722 4722 + subrepoopts,
4723 4723 _('[OPTION]...'),
4724 4724 optionalrepo=True)
4725 4725 def serve(ui, repo, **opts):
4726 4726 """start stand-alone webserver
4727 4727
4728 4728 Start a local HTTP repository browser and pull server. You can use
4729 4729 this for ad-hoc sharing and browsing of repositories. It is
4730 4730 recommended to use a real web server to serve a repository for
4731 4731 longer periods of time.
4732 4732
4733 4733 Please note that the server does not implement access control.
4734 4734 This means that, by default, anybody can read from the server and
4735 4735 nobody can write to it by default. Set the ``web.allow-push``
4736 4736 option to ``*`` to allow everybody to push to the server. You
4737 4737 should use a real web server if you need to authenticate users.
4738 4738
4739 4739 By default, the server logs accesses to stdout and errors to
4740 4740 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
4741 4741 files.
4742 4742
4743 4743 To have the server choose a free port number to listen on, specify
4744 4744 a port number of 0; in this case, the server will print the port
4745 4745 number it uses.
4746 4746
4747 4747 Returns 0 on success.
4748 4748 """
4749 4749
4750 4750 opts = pycompat.byteskwargs(opts)
4751 4751 if opts["stdio"] and opts["cmdserver"]:
4752 4752 raise error.Abort(_("cannot use --stdio with --cmdserver"))
4753 4753
4754 4754 if opts["stdio"]:
4755 4755 if repo is None:
4756 4756 raise error.RepoError(_("there is no Mercurial repository here"
4757 4757 " (.hg not found)"))
4758 4758 s = wireprotoserver.sshserver(ui, repo)
4759 4759 s.serve_forever()
4760 4760
4761 4761 service = server.createservice(ui, repo, opts)
4762 4762 return server.runservice(opts, initfn=service.init, runfn=service.run)
4763 4763
4764 4764 @command('^status|st',
4765 4765 [('A', 'all', None, _('show status of all files')),
4766 4766 ('m', 'modified', None, _('show only modified files')),
4767 4767 ('a', 'added', None, _('show only added files')),
4768 4768 ('r', 'removed', None, _('show only removed files')),
4769 4769 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
4770 4770 ('c', 'clean', None, _('show only files without changes')),
4771 4771 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
4772 4772 ('i', 'ignored', None, _('show only ignored files')),
4773 4773 ('n', 'no-status', None, _('hide status prefix')),
4774 4774 ('t', 'terse', '', _('show the terse output (EXPERIMENTAL)')),
4775 4775 ('C', 'copies', None, _('show source of copied files')),
4776 4776 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
4777 4777 ('', 'rev', [], _('show difference from revision'), _('REV')),
4778 4778 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
4779 4779 ] + walkopts + subrepoopts + formatteropts,
4780 4780 _('[OPTION]... [FILE]...'),
4781 4781 inferrepo=True, cmdtype=readonly)
4782 4782 def status(ui, repo, *pats, **opts):
4783 4783 """show changed files in the working directory
4784 4784
4785 4785 Show status of files in the repository. If names are given, only
4786 4786 files that match are shown. Files that are clean or ignored or
4787 4787 the source of a copy/move operation, are not listed unless
4788 4788 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
4789 4789 Unless options described with "show only ..." are given, the
4790 4790 options -mardu are used.
4791 4791
4792 4792 Option -q/--quiet hides untracked (unknown and ignored) files
4793 4793 unless explicitly requested with -u/--unknown or -i/--ignored.
4794 4794
4795 4795 .. note::
4796 4796
4797 4797 :hg:`status` may appear to disagree with diff if permissions have
4798 4798 changed or a merge has occurred. The standard diff format does
4799 4799 not report permission changes and diff only reports changes
4800 4800 relative to one merge parent.
4801 4801
4802 4802 If one revision is given, it is used as the base revision.
4803 4803 If two revisions are given, the differences between them are
4804 4804 shown. The --change option can also be used as a shortcut to list
4805 4805 the changed files of a revision from its first parent.
4806 4806
4807 4807 The codes used to show the status of files are::
4808 4808
4809 4809 M = modified
4810 4810 A = added
4811 4811 R = removed
4812 4812 C = clean
4813 4813 ! = missing (deleted by non-hg command, but still tracked)
4814 4814 ? = not tracked
4815 4815 I = ignored
4816 4816 = origin of the previous file (with --copies)
4817 4817
4818 4818 .. container:: verbose
4819 4819
4820 4820 The -t/--terse option abbreviates the output by showing only the directory
4821 4821 name if all the files in it share the same status. The option takes an
4822 4822 argument indicating the statuses to abbreviate: 'm' for 'modified', 'a'
4823 4823 for 'added', 'r' for 'removed', 'd' for 'deleted', 'u' for 'unknown', 'i'
4824 4824 for 'ignored' and 'c' for clean.
4825 4825
4826 4826 It abbreviates only those statuses which are passed. Note that clean and
4827 4827 ignored files are not displayed with '--terse ic' unless the -c/--clean
4828 4828 and -i/--ignored options are also used.
4829 4829
4830 4830 The -v/--verbose option shows information when the repository is in an
4831 4831 unfinished merge, shelve, rebase state etc. You can have this behavior
4832 4832 turned on by default by enabling the ``commands.status.verbose`` option.
4833 4833
4834 4834 You can skip displaying some of these states by setting
4835 4835 ``commands.status.skipstates`` to one or more of: 'bisect', 'graft',
4836 4836 'histedit', 'merge', 'rebase', or 'unshelve'.
4837 4837
4838 4838 Examples:
4839 4839
4840 4840 - show changes in the working directory relative to a
4841 4841 changeset::
4842 4842
4843 4843 hg status --rev 9353
4844 4844
4845 4845 - show changes in the working directory relative to the
4846 4846 current directory (see :hg:`help patterns` for more information)::
4847 4847
4848 4848 hg status re:
4849 4849
4850 4850 - show all changes including copies in an existing changeset::
4851 4851
4852 4852 hg status --copies --change 9353
4853 4853
4854 4854 - get a NUL separated list of added files, suitable for xargs::
4855 4855
4856 4856 hg status -an0
4857 4857
4858 4858 - show more information about the repository status, abbreviating
4859 4859 added, removed, modified, deleted, and untracked paths::
4860 4860
4861 4861 hg status -v -t mardu
4862 4862
4863 4863 Returns 0 on success.
4864 4864
4865 4865 """
4866 4866
4867 4867 opts = pycompat.byteskwargs(opts)
4868 4868 revs = opts.get('rev')
4869 4869 change = opts.get('change')
4870 4870 terse = opts.get('terse')
4871 4871
4872 4872 if revs and change:
4873 4873 msg = _('cannot specify --rev and --change at the same time')
4874 4874 raise error.Abort(msg)
4875 4875 elif revs and terse:
4876 4876 msg = _('cannot use --terse with --rev')
4877 4877 raise error.Abort(msg)
4878 4878 elif change:
4879 4879 repo = scmutil.unhidehashlikerevs(repo, [change], 'nowarn')
4880 4880 ctx2 = scmutil.revsingle(repo, change, None)
4881 4881 ctx1 = ctx2.p1()
4882 4882 else:
4883 4883 repo = scmutil.unhidehashlikerevs(repo, revs, 'nowarn')
4884 4884 ctx1, ctx2 = scmutil.revpair(repo, revs)
4885 4885
4886 4886 if pats or ui.configbool('commands', 'status.relative'):
4887 4887 cwd = repo.getcwd()
4888 4888 else:
4889 4889 cwd = ''
4890 4890
4891 4891 if opts.get('print0'):
4892 4892 end = '\0'
4893 4893 else:
4894 4894 end = '\n'
4895 4895 copy = {}
4896 4896 states = 'modified added removed deleted unknown ignored clean'.split()
4897 4897 show = [k for k in states if opts.get(k)]
4898 4898 if opts.get('all'):
4899 4899 show += ui.quiet and (states[:4] + ['clean']) or states
4900 4900
4901 4901 if not show:
4902 4902 if ui.quiet:
4903 4903 show = states[:4]
4904 4904 else:
4905 4905 show = states[:5]
4906 4906
4907 4907 m = scmutil.match(ctx2, pats, opts)
4908 4908 if terse:
4909 4909 # we need to compute clean and unknown to terse
4910 4910 stat = repo.status(ctx1.node(), ctx2.node(), m,
4911 4911 'ignored' in show or 'i' in terse,
4912 4912 True, True, opts.get('subrepos'))
4913 4913
4914 4914 stat = cmdutil.tersedir(stat, terse)
4915 4915 else:
4916 4916 stat = repo.status(ctx1.node(), ctx2.node(), m,
4917 4917 'ignored' in show, 'clean' in show,
4918 4918 'unknown' in show, opts.get('subrepos'))
4919 4919
4920 4920 changestates = zip(states, pycompat.iterbytestr('MAR!?IC'), stat)
4921 4921
4922 4922 if (opts.get('all') or opts.get('copies')
4923 4923 or ui.configbool('ui', 'statuscopies')) and not opts.get('no_status'):
4924 4924 copy = copies.pathcopies(ctx1, ctx2, m)
4925 4925
4926 4926 ui.pager('status')
4927 4927 fm = ui.formatter('status', opts)
4928 4928 fmt = '%s' + end
4929 4929 showchar = not opts.get('no_status')
4930 4930
4931 4931 for state, char, files in changestates:
4932 4932 if state in show:
4933 4933 label = 'status.' + state
4934 4934 for f in files:
4935 4935 fm.startitem()
4936 4936 fm.condwrite(showchar, 'status', '%s ', char, label=label)
4937 4937 fm.write('path', fmt, repo.pathto(f, cwd), label=label)
4938 4938 if f in copy:
4939 4939 fm.write("copy", ' %s' + end, repo.pathto(copy[f], cwd),
4940 4940 label='status.copied')
4941 4941
4942 4942 if ((ui.verbose or ui.configbool('commands', 'status.verbose'))
4943 4943 and not ui.plain()):
4944 4944 cmdutil.morestatus(repo, fm)
4945 4945 fm.end()
4946 4946
4947 4947 @command('^summary|sum',
4948 4948 [('', 'remote', None, _('check for push and pull'))],
4949 4949 '[--remote]', cmdtype=readonly)
4950 4950 def summary(ui, repo, **opts):
4951 4951 """summarize working directory state
4952 4952
4953 4953 This generates a brief summary of the working directory state,
4954 4954 including parents, branch, commit status, phase and available updates.
4955 4955
4956 4956 With the --remote option, this will check the default paths for
4957 4957 incoming and outgoing changes. This can be time-consuming.
4958 4958
4959 4959 Returns 0 on success.
4960 4960 """
4961 4961
4962 4962 opts = pycompat.byteskwargs(opts)
4963 4963 ui.pager('summary')
4964 4964 ctx = repo[None]
4965 4965 parents = ctx.parents()
4966 4966 pnode = parents[0].node()
4967 4967 marks = []
4968 4968
4969 4969 ms = None
4970 4970 try:
4971 4971 ms = mergemod.mergestate.read(repo)
4972 4972 except error.UnsupportedMergeRecords as e:
4973 4973 s = ' '.join(e.recordtypes)
4974 4974 ui.warn(
4975 4975 _('warning: merge state has unsupported record types: %s\n') % s)
4976 4976 unresolved = []
4977 4977 else:
4978 4978 unresolved = list(ms.unresolved())
4979 4979
4980 4980 for p in parents:
4981 4981 # label with log.changeset (instead of log.parent) since this
4982 4982 # shows a working directory parent *changeset*:
4983 4983 # i18n: column positioning for "hg summary"
4984 4984 ui.write(_('parent: %d:%s ') % (p.rev(), p),
4985 4985 label=logcmdutil.changesetlabels(p))
4986 4986 ui.write(' '.join(p.tags()), label='log.tag')
4987 4987 if p.bookmarks():
4988 4988 marks.extend(p.bookmarks())
4989 4989 if p.rev() == -1:
4990 4990 if not len(repo):
4991 4991 ui.write(_(' (empty repository)'))
4992 4992 else:
4993 4993 ui.write(_(' (no revision checked out)'))
4994 4994 if p.obsolete():
4995 4995 ui.write(_(' (obsolete)'))
4996 4996 if p.isunstable():
4997 4997 instabilities = (ui.label(instability, 'trouble.%s' % instability)
4998 4998 for instability in p.instabilities())
4999 4999 ui.write(' ('
5000 5000 + ', '.join(instabilities)
5001 5001 + ')')
5002 5002 ui.write('\n')
5003 5003 if p.description():
5004 5004 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
5005 5005 label='log.summary')
5006 5006
5007 5007 branch = ctx.branch()
5008 5008 bheads = repo.branchheads(branch)
5009 5009 # i18n: column positioning for "hg summary"
5010 5010 m = _('branch: %s\n') % branch
5011 5011 if branch != 'default':
5012 5012 ui.write(m, label='log.branch')
5013 5013 else:
5014 5014 ui.status(m, label='log.branch')
5015 5015
5016 5016 if marks:
5017 5017 active = repo._activebookmark
5018 5018 # i18n: column positioning for "hg summary"
5019 5019 ui.write(_('bookmarks:'), label='log.bookmark')
5020 5020 if active is not None:
5021 5021 if active in marks:
5022 5022 ui.write(' *' + active, label=bookmarks.activebookmarklabel)
5023 5023 marks.remove(active)
5024 5024 else:
5025 5025 ui.write(' [%s]' % active, label=bookmarks.activebookmarklabel)
5026 5026 for m in marks:
5027 5027 ui.write(' ' + m, label='log.bookmark')
5028 5028 ui.write('\n', label='log.bookmark')
5029 5029
5030 5030 status = repo.status(unknown=True)
5031 5031
5032 5032 c = repo.dirstate.copies()
5033 5033 copied, renamed = [], []
5034 5034 for d, s in c.iteritems():
5035 5035 if s in status.removed:
5036 5036 status.removed.remove(s)
5037 5037 renamed.append(d)
5038 5038 else:
5039 5039 copied.append(d)
5040 5040 if d in status.added:
5041 5041 status.added.remove(d)
5042 5042
5043 5043 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
5044 5044
5045 5045 labels = [(ui.label(_('%d modified'), 'status.modified'), status.modified),
5046 5046 (ui.label(_('%d added'), 'status.added'), status.added),
5047 5047 (ui.label(_('%d removed'), 'status.removed'), status.removed),
5048 5048 (ui.label(_('%d renamed'), 'status.copied'), renamed),
5049 5049 (ui.label(_('%d copied'), 'status.copied'), copied),
5050 5050 (ui.label(_('%d deleted'), 'status.deleted'), status.deleted),
5051 5051 (ui.label(_('%d unknown'), 'status.unknown'), status.unknown),
5052 5052 (ui.label(_('%d unresolved'), 'resolve.unresolved'), unresolved),
5053 5053 (ui.label(_('%d subrepos'), 'status.modified'), subs)]
5054 5054 t = []
5055 5055 for l, s in labels:
5056 5056 if s:
5057 5057 t.append(l % len(s))
5058 5058
5059 5059 t = ', '.join(t)
5060 5060 cleanworkdir = False
5061 5061
5062 5062 if repo.vfs.exists('graftstate'):
5063 5063 t += _(' (graft in progress)')
5064 5064 if repo.vfs.exists('updatestate'):
5065 5065 t += _(' (interrupted update)')
5066 5066 elif len(parents) > 1:
5067 5067 t += _(' (merge)')
5068 5068 elif branch != parents[0].branch():
5069 5069 t += _(' (new branch)')
5070 5070 elif (parents[0].closesbranch() and
5071 5071 pnode in repo.branchheads(branch, closed=True)):
5072 5072 t += _(' (head closed)')
5073 5073 elif not (status.modified or status.added or status.removed or renamed or
5074 5074 copied or subs):
5075 5075 t += _(' (clean)')
5076 5076 cleanworkdir = True
5077 5077 elif pnode not in bheads:
5078 5078 t += _(' (new branch head)')
5079 5079
5080 5080 if parents:
5081 5081 pendingphase = max(p.phase() for p in parents)
5082 5082 else:
5083 5083 pendingphase = phases.public
5084 5084
5085 5085 if pendingphase > phases.newcommitphase(ui):
5086 5086 t += ' (%s)' % phases.phasenames[pendingphase]
5087 5087
5088 5088 if cleanworkdir:
5089 5089 # i18n: column positioning for "hg summary"
5090 5090 ui.status(_('commit: %s\n') % t.strip())
5091 5091 else:
5092 5092 # i18n: column positioning for "hg summary"
5093 5093 ui.write(_('commit: %s\n') % t.strip())
5094 5094
5095 5095 # all ancestors of branch heads - all ancestors of parent = new csets
5096 5096 new = len(repo.changelog.findmissing([pctx.node() for pctx in parents],
5097 5097 bheads))
5098 5098
5099 5099 if new == 0:
5100 5100 # i18n: column positioning for "hg summary"
5101 5101 ui.status(_('update: (current)\n'))
5102 5102 elif pnode not in bheads:
5103 5103 # i18n: column positioning for "hg summary"
5104 5104 ui.write(_('update: %d new changesets (update)\n') % new)
5105 5105 else:
5106 5106 # i18n: column positioning for "hg summary"
5107 5107 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
5108 5108 (new, len(bheads)))
5109 5109
5110 5110 t = []
5111 5111 draft = len(repo.revs('draft()'))
5112 5112 if draft:
5113 5113 t.append(_('%d draft') % draft)
5114 5114 secret = len(repo.revs('secret()'))
5115 5115 if secret:
5116 5116 t.append(_('%d secret') % secret)
5117 5117
5118 5118 if draft or secret:
5119 5119 ui.status(_('phases: %s\n') % ', '.join(t))
5120 5120
5121 5121 if obsolete.isenabled(repo, obsolete.createmarkersopt):
5122 5122 for trouble in ("orphan", "contentdivergent", "phasedivergent"):
5123 5123 numtrouble = len(repo.revs(trouble + "()"))
5124 5124 # We write all the possibilities to ease translation
5125 5125 troublemsg = {
5126 5126 "orphan": _("orphan: %d changesets"),
5127 5127 "contentdivergent": _("content-divergent: %d changesets"),
5128 5128 "phasedivergent": _("phase-divergent: %d changesets"),
5129 5129 }
5130 5130 if numtrouble > 0:
5131 5131 ui.status(troublemsg[trouble] % numtrouble + "\n")
5132 5132
5133 5133 cmdutil.summaryhooks(ui, repo)
5134 5134
5135 5135 if opts.get('remote'):
5136 5136 needsincoming, needsoutgoing = True, True
5137 5137 else:
5138 5138 needsincoming, needsoutgoing = False, False
5139 5139 for i, o in cmdutil.summaryremotehooks(ui, repo, opts, None):
5140 5140 if i:
5141 5141 needsincoming = True
5142 5142 if o:
5143 5143 needsoutgoing = True
5144 5144 if not needsincoming and not needsoutgoing:
5145 5145 return
5146 5146
5147 5147 def getincoming():
5148 5148 source, branches = hg.parseurl(ui.expandpath('default'))
5149 5149 sbranch = branches[0]
5150 5150 try:
5151 5151 other = hg.peer(repo, {}, source)
5152 5152 except error.RepoError:
5153 5153 if opts.get('remote'):
5154 5154 raise
5155 5155 return source, sbranch, None, None, None
5156 5156 revs, checkout = hg.addbranchrevs(repo, other, branches, None)
5157 5157 if revs:
5158 5158 revs = [other.lookup(rev) for rev in revs]
5159 5159 ui.debug('comparing with %s\n' % util.hidepassword(source))
5160 5160 repo.ui.pushbuffer()
5161 5161 commoninc = discovery.findcommonincoming(repo, other, heads=revs)
5162 5162 repo.ui.popbuffer()
5163 5163 return source, sbranch, other, commoninc, commoninc[1]
5164 5164
5165 5165 if needsincoming:
5166 5166 source, sbranch, sother, commoninc, incoming = getincoming()
5167 5167 else:
5168 5168 source = sbranch = sother = commoninc = incoming = None
5169 5169
5170 5170 def getoutgoing():
5171 5171 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5172 5172 dbranch = branches[0]
5173 5173 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5174 5174 if source != dest:
5175 5175 try:
5176 5176 dother = hg.peer(repo, {}, dest)
5177 5177 except error.RepoError:
5178 5178 if opts.get('remote'):
5179 5179 raise
5180 5180 return dest, dbranch, None, None
5181 5181 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5182 5182 elif sother is None:
5183 5183 # there is no explicit destination peer, but source one is invalid
5184 5184 return dest, dbranch, None, None
5185 5185 else:
5186 5186 dother = sother
5187 5187 if (source != dest or (sbranch is not None and sbranch != dbranch)):
5188 5188 common = None
5189 5189 else:
5190 5190 common = commoninc
5191 5191 if revs:
5192 5192 revs = [repo.lookup(rev) for rev in revs]
5193 5193 repo.ui.pushbuffer()
5194 5194 outgoing = discovery.findcommonoutgoing(repo, dother, onlyheads=revs,
5195 5195 commoninc=common)
5196 5196 repo.ui.popbuffer()
5197 5197 return dest, dbranch, dother, outgoing
5198 5198
5199 5199 if needsoutgoing:
5200 5200 dest, dbranch, dother, outgoing = getoutgoing()
5201 5201 else:
5202 5202 dest = dbranch = dother = outgoing = None
5203 5203
5204 5204 if opts.get('remote'):
5205 5205 t = []
5206 5206 if incoming:
5207 5207 t.append(_('1 or more incoming'))
5208 5208 o = outgoing.missing
5209 5209 if o:
5210 5210 t.append(_('%d outgoing') % len(o))
5211 5211 other = dother or sother
5212 5212 if 'bookmarks' in other.listkeys('namespaces'):
5213 5213 counts = bookmarks.summary(repo, other)
5214 5214 if counts[0] > 0:
5215 5215 t.append(_('%d incoming bookmarks') % counts[0])
5216 5216 if counts[1] > 0:
5217 5217 t.append(_('%d outgoing bookmarks') % counts[1])
5218 5218
5219 5219 if t:
5220 5220 # i18n: column positioning for "hg summary"
5221 5221 ui.write(_('remote: %s\n') % (', '.join(t)))
5222 5222 else:
5223 5223 # i18n: column positioning for "hg summary"
5224 5224 ui.status(_('remote: (synced)\n'))
5225 5225
5226 5226 cmdutil.summaryremotehooks(ui, repo, opts,
5227 5227 ((source, sbranch, sother, commoninc),
5228 5228 (dest, dbranch, dother, outgoing)))
5229 5229
5230 5230 @command('tag',
5231 5231 [('f', 'force', None, _('force tag')),
5232 5232 ('l', 'local', None, _('make the tag local')),
5233 5233 ('r', 'rev', '', _('revision to tag'), _('REV')),
5234 5234 ('', 'remove', None, _('remove a tag')),
5235 5235 # -l/--local is already there, commitopts cannot be used
5236 5236 ('e', 'edit', None, _('invoke editor on commit messages')),
5237 5237 ('m', 'message', '', _('use text as commit message'), _('TEXT')),
5238 5238 ] + commitopts2,
5239 5239 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
5240 5240 def tag(ui, repo, name1, *names, **opts):
5241 5241 """add one or more tags for the current or given revision
5242 5242
5243 5243 Name a particular revision using <name>.
5244 5244
5245 5245 Tags are used to name particular revisions of the repository and are
5246 5246 very useful to compare different revisions, to go back to significant
5247 5247 earlier versions or to mark branch points as releases, etc. Changing
5248 5248 an existing tag is normally disallowed; use -f/--force to override.
5249 5249
5250 5250 If no revision is given, the parent of the working directory is
5251 5251 used.
5252 5252
5253 5253 To facilitate version control, distribution, and merging of tags,
5254 5254 they are stored as a file named ".hgtags" which is managed similarly
5255 5255 to other project files and can be hand-edited if necessary. This
5256 5256 also means that tagging creates a new commit. The file
5257 5257 ".hg/localtags" is used for local tags (not shared among
5258 5258 repositories).
5259 5259
5260 5260 Tag commits are usually made at the head of a branch. If the parent
5261 5261 of the working directory is not a branch head, :hg:`tag` aborts; use
5262 5262 -f/--force to force the tag commit to be based on a non-head
5263 5263 changeset.
5264 5264
5265 5265 See :hg:`help dates` for a list of formats valid for -d/--date.
5266 5266
5267 5267 Since tag names have priority over branch names during revision
5268 5268 lookup, using an existing branch name as a tag name is discouraged.
5269 5269
5270 5270 Returns 0 on success.
5271 5271 """
5272 5272 opts = pycompat.byteskwargs(opts)
5273 5273 wlock = lock = None
5274 5274 try:
5275 5275 wlock = repo.wlock()
5276 5276 lock = repo.lock()
5277 5277 rev_ = "."
5278 5278 names = [t.strip() for t in (name1,) + names]
5279 5279 if len(names) != len(set(names)):
5280 5280 raise error.Abort(_('tag names must be unique'))
5281 5281 for n in names:
5282 5282 scmutil.checknewlabel(repo, n, 'tag')
5283 5283 if not n:
5284 5284 raise error.Abort(_('tag names cannot consist entirely of '
5285 5285 'whitespace'))
5286 5286 if opts.get('rev') and opts.get('remove'):
5287 5287 raise error.Abort(_("--rev and --remove are incompatible"))
5288 5288 if opts.get('rev'):
5289 5289 rev_ = opts['rev']
5290 5290 message = opts.get('message')
5291 5291 if opts.get('remove'):
5292 5292 if opts.get('local'):
5293 5293 expectedtype = 'local'
5294 5294 else:
5295 5295 expectedtype = 'global'
5296 5296
5297 5297 for n in names:
5298 5298 if not repo.tagtype(n):
5299 5299 raise error.Abort(_("tag '%s' does not exist") % n)
5300 5300 if repo.tagtype(n) != expectedtype:
5301 5301 if expectedtype == 'global':
5302 5302 raise error.Abort(_("tag '%s' is not a global tag") % n)
5303 5303 else:
5304 5304 raise error.Abort(_("tag '%s' is not a local tag") % n)
5305 5305 rev_ = 'null'
5306 5306 if not message:
5307 5307 # we don't translate commit messages
5308 5308 message = 'Removed tag %s' % ', '.join(names)
5309 5309 elif not opts.get('force'):
5310 5310 for n in names:
5311 5311 if n in repo.tags():
5312 5312 raise error.Abort(_("tag '%s' already exists "
5313 5313 "(use -f to force)") % n)
5314 5314 if not opts.get('local'):
5315 5315 p1, p2 = repo.dirstate.parents()
5316 5316 if p2 != nullid:
5317 5317 raise error.Abort(_('uncommitted merge'))
5318 5318 bheads = repo.branchheads()
5319 5319 if not opts.get('force') and bheads and p1 not in bheads:
5320 5320 raise error.Abort(_('working directory is not at a branch head '
5321 5321 '(use -f to force)'))
5322 5322 node = scmutil.revsingle(repo, rev_).node()
5323 5323
5324 5324 if not message:
5325 5325 # we don't translate commit messages
5326 5326 message = ('Added tag %s for changeset %s' %
5327 5327 (', '.join(names), short(node)))
5328 5328
5329 5329 date = opts.get('date')
5330 5330 if date:
5331 5331 date = dateutil.parsedate(date)
5332 5332
5333 5333 if opts.get('remove'):
5334 5334 editform = 'tag.remove'
5335 5335 else:
5336 5336 editform = 'tag.add'
5337 5337 editor = cmdutil.getcommiteditor(editform=editform,
5338 5338 **pycompat.strkwargs(opts))
5339 5339
5340 5340 # don't allow tagging the null rev
5341 5341 if (not opts.get('remove') and
5342 5342 scmutil.revsingle(repo, rev_).rev() == nullrev):
5343 5343 raise error.Abort(_("cannot tag null revision"))
5344 5344
5345 5345 tagsmod.tag(repo, names, node, message, opts.get('local'),
5346 5346 opts.get('user'), date, editor=editor)
5347 5347 finally:
5348 5348 release(lock, wlock)
5349 5349
5350 5350 @command('tags', formatteropts, '', cmdtype=readonly)
5351 5351 def tags(ui, repo, **opts):
5352 5352 """list repository tags
5353 5353
5354 5354 This lists both regular and local tags. When the -v/--verbose
5355 5355 switch is used, a third column "local" is printed for local tags.
5356 5356 When the -q/--quiet switch is used, only the tag name is printed.
5357 5357
5358 5358 Returns 0 on success.
5359 5359 """
5360 5360
5361 5361 opts = pycompat.byteskwargs(opts)
5362 5362 ui.pager('tags')
5363 5363 fm = ui.formatter('tags', opts)
5364 5364 hexfunc = fm.hexfunc
5365 5365 tagtype = ""
5366 5366
5367 5367 for t, n in reversed(repo.tagslist()):
5368 5368 hn = hexfunc(n)
5369 5369 label = 'tags.normal'
5370 5370 tagtype = ''
5371 5371 if repo.tagtype(t) == 'local':
5372 5372 label = 'tags.local'
5373 5373 tagtype = 'local'
5374 5374
5375 5375 fm.startitem()
5376 5376 fm.write('tag', '%s', t, label=label)
5377 5377 fmt = " " * (30 - encoding.colwidth(t)) + ' %5d:%s'
5378 5378 fm.condwrite(not ui.quiet, 'rev node', fmt,
5379 5379 repo.changelog.rev(n), hn, label=label)
5380 5380 fm.condwrite(ui.verbose and tagtype, 'type', ' %s',
5381 5381 tagtype, label=label)
5382 5382 fm.plain('\n')
5383 5383 fm.end()
5384 5384
5385 5385 @command('tip',
5386 5386 [('p', 'patch', None, _('show patch')),
5387 5387 ('g', 'git', None, _('use git extended diff format')),
5388 5388 ] + templateopts,
5389 5389 _('[-p] [-g]'))
5390 5390 def tip(ui, repo, **opts):
5391 5391 """show the tip revision (DEPRECATED)
5392 5392
5393 5393 The tip revision (usually just called the tip) is the changeset
5394 5394 most recently added to the repository (and therefore the most
5395 5395 recently changed head).
5396 5396
5397 5397 If you have just made a commit, that commit will be the tip. If
5398 5398 you have just pulled changes from another repository, the tip of
5399 5399 that repository becomes the current tip. The "tip" tag is special
5400 5400 and cannot be renamed or assigned to a different changeset.
5401 5401
5402 5402 This command is deprecated, please use :hg:`heads` instead.
5403 5403
5404 5404 Returns 0 on success.
5405 5405 """
5406 5406 opts = pycompat.byteskwargs(opts)
5407 5407 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
5408 5408 displayer.show(repo['tip'])
5409 5409 displayer.close()
5410 5410
5411 5411 @command('unbundle',
5412 5412 [('u', 'update', None,
5413 5413 _('update to new branch head if changesets were unbundled'))],
5414 5414 _('[-u] FILE...'))
5415 5415 def unbundle(ui, repo, fname1, *fnames, **opts):
5416 5416 """apply one or more bundle files
5417 5417
5418 5418 Apply one or more bundle files generated by :hg:`bundle`.
5419 5419
5420 5420 Returns 0 on success, 1 if an update has unresolved files.
5421 5421 """
5422 5422 fnames = (fname1,) + fnames
5423 5423
5424 5424 with repo.lock():
5425 5425 for fname in fnames:
5426 5426 f = hg.openpath(ui, fname)
5427 5427 gen = exchange.readbundle(ui, f, fname)
5428 5428 if isinstance(gen, streamclone.streamcloneapplier):
5429 5429 raise error.Abort(
5430 5430 _('packed bundles cannot be applied with '
5431 5431 '"hg unbundle"'),
5432 5432 hint=_('use "hg debugapplystreamclonebundle"'))
5433 5433 url = 'bundle:' + fname
5434 5434 try:
5435 5435 txnname = 'unbundle'
5436 5436 if not isinstance(gen, bundle2.unbundle20):
5437 5437 txnname = 'unbundle\n%s' % util.hidepassword(url)
5438 5438 with repo.transaction(txnname) as tr:
5439 5439 op = bundle2.applybundle(repo, gen, tr, source='unbundle',
5440 5440 url=url)
5441 5441 except error.BundleUnknownFeatureError as exc:
5442 5442 raise error.Abort(
5443 5443 _('%s: unknown bundle feature, %s') % (fname, exc),
5444 5444 hint=_("see https://mercurial-scm.org/"
5445 5445 "wiki/BundleFeature for more "
5446 5446 "information"))
5447 5447 modheads = bundle2.combinechangegroupresults(op)
5448 5448
5449 5449 return postincoming(ui, repo, modheads, opts.get(r'update'), None, None)
5450 5450
5451 5451 @command('^update|up|checkout|co',
5452 5452 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
5453 5453 ('c', 'check', None, _('require clean working directory')),
5454 5454 ('m', 'merge', None, _('merge uncommitted changes')),
5455 5455 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5456 5456 ('r', 'rev', '', _('revision'), _('REV'))
5457 5457 ] + mergetoolopts,
5458 5458 _('[-C|-c|-m] [-d DATE] [[-r] REV]'))
5459 5459 def update(ui, repo, node=None, **opts):
5460 5460 """update working directory (or switch revisions)
5461 5461
5462 5462 Update the repository's working directory to the specified
5463 5463 changeset. If no changeset is specified, update to the tip of the
5464 5464 current named branch and move the active bookmark (see :hg:`help
5465 5465 bookmarks`).
5466 5466
5467 5467 Update sets the working directory's parent revision to the specified
5468 5468 changeset (see :hg:`help parents`).
5469 5469
5470 5470 If the changeset is not a descendant or ancestor of the working
5471 5471 directory's parent and there are uncommitted changes, the update is
5472 5472 aborted. With the -c/--check option, the working directory is checked
5473 5473 for uncommitted changes; if none are found, the working directory is
5474 5474 updated to the specified changeset.
5475 5475
5476 5476 .. container:: verbose
5477 5477
5478 5478 The -C/--clean, -c/--check, and -m/--merge options control what
5479 5479 happens if the working directory contains uncommitted changes.
5480 5480 At most of one of them can be specified.
5481 5481
5482 5482 1. If no option is specified, and if
5483 5483 the requested changeset is an ancestor or descendant of
5484 5484 the working directory's parent, the uncommitted changes
5485 5485 are merged into the requested changeset and the merged
5486 5486 result is left uncommitted. If the requested changeset is
5487 5487 not an ancestor or descendant (that is, it is on another
5488 5488 branch), the update is aborted and the uncommitted changes
5489 5489 are preserved.
5490 5490
5491 5491 2. With the -m/--merge option, the update is allowed even if the
5492 5492 requested changeset is not an ancestor or descendant of
5493 5493 the working directory's parent.
5494 5494
5495 5495 3. With the -c/--check option, the update is aborted and the
5496 5496 uncommitted changes are preserved.
5497 5497
5498 5498 4. With the -C/--clean option, uncommitted changes are discarded and
5499 5499 the working directory is updated to the requested changeset.
5500 5500
5501 5501 To cancel an uncommitted merge (and lose your changes), use
5502 5502 :hg:`merge --abort`.
5503 5503
5504 5504 Use null as the changeset to remove the working directory (like
5505 5505 :hg:`clone -U`).
5506 5506
5507 5507 If you want to revert just one file to an older revision, use
5508 5508 :hg:`revert [-r REV] NAME`.
5509 5509
5510 5510 See :hg:`help dates` for a list of formats valid for -d/--date.
5511 5511
5512 5512 Returns 0 on success, 1 if there are unresolved files.
5513 5513 """
5514 5514 rev = opts.get(r'rev')
5515 5515 date = opts.get(r'date')
5516 5516 clean = opts.get(r'clean')
5517 5517 check = opts.get(r'check')
5518 5518 merge = opts.get(r'merge')
5519 5519 if rev and node:
5520 5520 raise error.Abort(_("please specify just one revision"))
5521 5521
5522 5522 if ui.configbool('commands', 'update.requiredest'):
5523 5523 if not node and not rev and not date:
5524 5524 raise error.Abort(_('you must specify a destination'),
5525 5525 hint=_('for example: hg update ".::"'))
5526 5526
5527 5527 if rev is None or rev == '':
5528 5528 rev = node
5529 5529
5530 5530 if date and rev is not None:
5531 5531 raise error.Abort(_("you can't specify a revision and a date"))
5532 5532
5533 5533 if len([x for x in (clean, check, merge) if x]) > 1:
5534 5534 raise error.Abort(_("can only specify one of -C/--clean, -c/--check, "
5535 5535 "or -m/--merge"))
5536 5536
5537 5537 updatecheck = None
5538 5538 if check:
5539 5539 updatecheck = 'abort'
5540 5540 elif merge:
5541 5541 updatecheck = 'none'
5542 5542
5543 5543 with repo.wlock():
5544 5544 cmdutil.clearunfinished(repo)
5545 5545
5546 5546 if date:
5547 5547 rev = cmdutil.finddate(ui, repo, date)
5548 5548
5549 5549 # if we defined a bookmark, we have to remember the original name
5550 5550 brev = rev
5551 5551 if rev:
5552 5552 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
5553 5553 ctx = scmutil.revsingle(repo, rev, rev)
5554 5554 rev = ctx.rev()
5555 5555 if ctx.hidden():
5556 5556 ctxstr = ctx.hex()[:12]
5557 5557 ui.warn(_("updating to a hidden changeset %s\n") % ctxstr)
5558 5558
5559 5559 if ctx.obsolete():
5560 5560 obsfatemsg = obsutil._getfilteredreason(repo, ctxstr, ctx)
5561 5561 ui.warn("(%s)\n" % obsfatemsg)
5562 5562
5563 5563 repo.ui.setconfig('ui', 'forcemerge', opts.get(r'tool'), 'update')
5564 5564
5565 5565 return hg.updatetotally(ui, repo, rev, brev, clean=clean,
5566 5566 updatecheck=updatecheck)
5567 5567
5568 5568 @command('verify', [])
5569 5569 def verify(ui, repo):
5570 5570 """verify the integrity of the repository
5571 5571
5572 5572 Verify the integrity of the current repository.
5573 5573
5574 5574 This will perform an extensive check of the repository's
5575 5575 integrity, validating the hashes and checksums of each entry in
5576 5576 the changelog, manifest, and tracked files, as well as the
5577 5577 integrity of their crosslinks and indices.
5578 5578
5579 5579 Please see https://mercurial-scm.org/wiki/RepositoryCorruption
5580 5580 for more information about recovery from corruption of the
5581 5581 repository.
5582 5582
5583 5583 Returns 0 on success, 1 if errors are encountered.
5584 5584 """
5585 5585 return hg.verify(repo)
5586 5586
5587 5587 @command('version', [] + formatteropts, norepo=True, cmdtype=readonly)
5588 5588 def version_(ui, **opts):
5589 5589 """output version and copyright information"""
5590 5590 opts = pycompat.byteskwargs(opts)
5591 5591 if ui.verbose:
5592 5592 ui.pager('version')
5593 5593 fm = ui.formatter("version", opts)
5594 5594 fm.startitem()
5595 5595 fm.write("ver", _("Mercurial Distributed SCM (version %s)\n"),
5596 5596 util.version())
5597 5597 license = _(
5598 5598 "(see https://mercurial-scm.org for more information)\n"
5599 5599 "\nCopyright (C) 2005-2018 Matt Mackall and others\n"
5600 5600 "This is free software; see the source for copying conditions. "
5601 5601 "There is NO\nwarranty; "
5602 5602 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5603 5603 )
5604 5604 if not ui.quiet:
5605 5605 fm.plain(license)
5606 5606
5607 5607 if ui.verbose:
5608 5608 fm.plain(_("\nEnabled extensions:\n\n"))
5609 5609 # format names and versions into columns
5610 5610 names = []
5611 5611 vers = []
5612 5612 isinternals = []
5613 5613 for name, module in extensions.extensions():
5614 5614 names.append(name)
5615 5615 vers.append(extensions.moduleversion(module) or None)
5616 5616 isinternals.append(extensions.ismoduleinternal(module))
5617 5617 fn = fm.nested("extensions")
5618 5618 if names:
5619 5619 namefmt = " %%-%ds " % max(len(n) for n in names)
5620 5620 places = [_("external"), _("internal")]
5621 5621 for n, v, p in zip(names, vers, isinternals):
5622 5622 fn.startitem()
5623 5623 fn.condwrite(ui.verbose, "name", namefmt, n)
5624 5624 if ui.verbose:
5625 5625 fn.plain("%s " % places[p])
5626 5626 fn.data(bundled=p)
5627 5627 fn.condwrite(ui.verbose and v, "ver", "%s", v)
5628 5628 if ui.verbose:
5629 5629 fn.plain("\n")
5630 5630 fn.end()
5631 5631 fm.end()
5632 5632
5633 5633 def loadcmdtable(ui, name, cmdtable):
5634 5634 """Load command functions from specified cmdtable
5635 5635 """
5636 5636 overrides = [cmd for cmd in cmdtable if cmd in table]
5637 5637 if overrides:
5638 5638 ui.warn(_("extension '%s' overrides commands: %s\n")
5639 5639 % (name, " ".join(overrides)))
5640 5640 table.update(cmdtable)
@@ -1,1142 +1,1143 b''
1 1 # hg.py - repository classes for mercurial
2 2 #
3 3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 4 # Copyright 2006 Vadim Gelfer <vadim.gelfer@gmail.com>
5 5 #
6 6 # This software may be used and distributed according to the terms of the
7 7 # GNU General Public License version 2 or any later version.
8 8
9 9 from __future__ import absolute_import
10 10
11 11 import errno
12 12 import hashlib
13 13 import os
14 14 import shutil
15 15 import stat
16 16
17 17 from .i18n import _
18 18 from .node import (
19 19 nullid,
20 20 )
21 21
22 22 from . import (
23 23 bookmarks,
24 24 bundlerepo,
25 25 cacheutil,
26 26 cmdutil,
27 27 destutil,
28 28 discovery,
29 29 error,
30 30 exchange,
31 31 extensions,
32 32 httppeer,
33 33 localrepo,
34 34 lock,
35 35 logcmdutil,
36 36 logexchange,
37 37 merge as mergemod,
38 38 node,
39 39 phases,
40 40 scmutil,
41 41 sshpeer,
42 42 statichttprepo,
43 43 ui as uimod,
44 44 unionrepo,
45 45 url,
46 46 util,
47 47 verify as verifymod,
48 48 vfs as vfsmod,
49 49 )
50 50
51 51 from .utils import (
52 52 stringutil,
53 53 )
54 54
55 55 release = lock.release
56 56
57 57 # shared features
58 58 sharedbookmarks = 'bookmarks'
59 59
60 60 def _local(path):
61 61 path = util.expandpath(util.urllocalpath(path))
62 62 return (os.path.isfile(path) and bundlerepo or localrepo)
63 63
64 64 def addbranchrevs(lrepo, other, branches, revs):
65 65 peer = other.peer() # a courtesy to callers using a localrepo for other
66 66 hashbranch, branches = branches
67 67 if not hashbranch and not branches:
68 68 x = revs or None
69 69 if util.safehasattr(revs, 'first'):
70 70 y = revs.first()
71 71 elif revs:
72 72 y = revs[0]
73 73 else:
74 74 y = None
75 75 return x, y
76 76 if revs:
77 77 revs = list(revs)
78 78 else:
79 79 revs = []
80 80
81 81 if not peer.capable('branchmap'):
82 82 if branches:
83 83 raise error.Abort(_("remote branch lookup not supported"))
84 84 revs.append(hashbranch)
85 85 return revs, revs[0]
86 86 branchmap = peer.branchmap()
87 87
88 88 def primary(branch):
89 89 if branch == '.':
90 90 if not lrepo:
91 91 raise error.Abort(_("dirstate branch not accessible"))
92 92 branch = lrepo.dirstate.branch()
93 93 if branch in branchmap:
94 94 revs.extend(node.hex(r) for r in reversed(branchmap[branch]))
95 95 return True
96 96 else:
97 97 return False
98 98
99 99 for branch in branches:
100 100 if not primary(branch):
101 101 raise error.RepoLookupError(_("unknown branch '%s'") % branch)
102 102 if hashbranch:
103 103 if not primary(hashbranch):
104 104 revs.append(hashbranch)
105 105 return revs, revs[0]
106 106
107 107 def parseurl(path, branches=None):
108 108 '''parse url#branch, returning (url, (branch, branches))'''
109 109
110 110 u = util.url(path)
111 111 branch = None
112 112 if u.fragment:
113 113 branch = u.fragment
114 114 u.fragment = None
115 115 return bytes(u), (branch, branches or [])
116 116
117 117 schemes = {
118 118 'bundle': bundlerepo,
119 119 'union': unionrepo,
120 120 'file': _local,
121 121 'http': httppeer,
122 122 'https': httppeer,
123 123 'ssh': sshpeer,
124 124 'static-http': statichttprepo,
125 125 }
126 126
127 127 def _peerlookup(path):
128 128 u = util.url(path)
129 129 scheme = u.scheme or 'file'
130 130 thing = schemes.get(scheme) or schemes['file']
131 131 try:
132 132 return thing(path)
133 133 except TypeError:
134 134 # we can't test callable(thing) because 'thing' can be an unloaded
135 135 # module that implements __call__
136 136 if not util.safehasattr(thing, 'instance'):
137 137 raise
138 138 return thing
139 139
140 140 def islocal(repo):
141 141 '''return true if repo (or path pointing to repo) is local'''
142 142 if isinstance(repo, bytes):
143 143 try:
144 144 return _peerlookup(repo).islocal(repo)
145 145 except AttributeError:
146 146 return False
147 147 return repo.local()
148 148
149 149 def openpath(ui, path):
150 150 '''open path with open if local, url.open if remote'''
151 151 pathurl = util.url(path, parsequery=False, parsefragment=False)
152 152 if pathurl.islocal():
153 153 return util.posixfile(pathurl.localpath(), 'rb')
154 154 else:
155 155 return url.open(ui, path)
156 156
157 157 # a list of (ui, repo) functions called for wire peer initialization
158 158 wirepeersetupfuncs = []
159 159
160 160 def _peerorrepo(ui, path, create=False, presetupfuncs=None):
161 161 """return a repository object for the specified path"""
162 162 obj = _peerlookup(path).instance(ui, path, create)
163 163 ui = getattr(obj, "ui", ui)
164 164 for f in presetupfuncs or []:
165 165 f(ui, obj)
166 166 for name, module in extensions.extensions(ui):
167 167 hook = getattr(module, 'reposetup', None)
168 168 if hook:
169 169 hook(ui, obj)
170 170 if not obj.local():
171 171 for f in wirepeersetupfuncs:
172 172 f(ui, obj)
173 173 return obj
174 174
175 175 def repository(ui, path='', create=False, presetupfuncs=None):
176 176 """return a repository object for the specified path"""
177 177 peer = _peerorrepo(ui, path, create, presetupfuncs=presetupfuncs)
178 178 repo = peer.local()
179 179 if not repo:
180 180 raise error.Abort(_("repository '%s' is not local") %
181 181 (path or peer.url()))
182 182 return repo.filtered('visible')
183 183
184 184 def peer(uiorrepo, opts, path, create=False):
185 185 '''return a repository peer for the specified path'''
186 186 rui = remoteui(uiorrepo, opts)
187 187 return _peerorrepo(rui, path, create).peer()
188 188
189 189 def defaultdest(source):
190 190 '''return default destination of clone if none is given
191 191
192 192 >>> defaultdest(b'foo')
193 193 'foo'
194 194 >>> defaultdest(b'/foo/bar')
195 195 'bar'
196 196 >>> defaultdest(b'/')
197 197 ''
198 198 >>> defaultdest(b'')
199 199 ''
200 200 >>> defaultdest(b'http://example.org/')
201 201 ''
202 202 >>> defaultdest(b'http://example.org/foo/')
203 203 'foo'
204 204 '''
205 205 path = util.url(source).path
206 206 if not path:
207 207 return ''
208 208 return os.path.basename(os.path.normpath(path))
209 209
210 210 def sharedreposource(repo):
211 211 """Returns repository object for source repository of a shared repo.
212 212
213 213 If repo is not a shared repository, returns None.
214 214 """
215 215 if repo.sharedpath == repo.path:
216 216 return None
217 217
218 218 if util.safehasattr(repo, 'srcrepo') and repo.srcrepo:
219 219 return repo.srcrepo
220 220
221 221 # the sharedpath always ends in the .hg; we want the path to the repo
222 222 source = repo.vfs.split(repo.sharedpath)[0]
223 223 srcurl, branches = parseurl(source)
224 224 srcrepo = repository(repo.ui, srcurl)
225 225 repo.srcrepo = srcrepo
226 226 return srcrepo
227 227
228 228 def share(ui, source, dest=None, update=True, bookmarks=True, defaultpath=None,
229 229 relative=False):
230 230 '''create a shared repository'''
231 231
232 232 if not islocal(source):
233 233 raise error.Abort(_('can only share local repositories'))
234 234
235 235 if not dest:
236 236 dest = defaultdest(source)
237 237 else:
238 238 dest = ui.expandpath(dest)
239 239
240 240 if isinstance(source, bytes):
241 241 origsource = ui.expandpath(source)
242 242 source, branches = parseurl(origsource)
243 243 srcrepo = repository(ui, source)
244 244 rev, checkout = addbranchrevs(srcrepo, srcrepo, branches, None)
245 245 else:
246 246 srcrepo = source.local()
247 247 origsource = source = srcrepo.url()
248 248 checkout = None
249 249
250 250 sharedpath = srcrepo.sharedpath # if our source is already sharing
251 251
252 252 destwvfs = vfsmod.vfs(dest, realpath=True)
253 253 destvfs = vfsmod.vfs(os.path.join(destwvfs.base, '.hg'), realpath=True)
254 254
255 255 if destvfs.lexists():
256 256 raise error.Abort(_('destination already exists'))
257 257
258 258 if not destwvfs.isdir():
259 259 destwvfs.mkdir()
260 260 destvfs.makedir()
261 261
262 262 requirements = ''
263 263 try:
264 264 requirements = srcrepo.vfs.read('requires')
265 265 except IOError as inst:
266 266 if inst.errno != errno.ENOENT:
267 267 raise
268 268
269 269 if relative:
270 270 try:
271 271 sharedpath = os.path.relpath(sharedpath, destvfs.base)
272 272 requirements += 'relshared\n'
273 273 except (IOError, ValueError) as e:
274 274 # ValueError is raised on Windows if the drive letters differ on
275 275 # each path
276 276 raise error.Abort(_('cannot calculate relative path'),
277 277 hint=stringutil.forcebytestr(e))
278 278 else:
279 279 requirements += 'shared\n'
280 280
281 281 destvfs.write('requires', requirements)
282 282 destvfs.write('sharedpath', sharedpath)
283 283
284 284 r = repository(ui, destwvfs.base)
285 285 postshare(srcrepo, r, bookmarks=bookmarks, defaultpath=defaultpath)
286 286 _postshareupdate(r, update, checkout=checkout)
287 287 return r
288 288
289 289 def unshare(ui, repo):
290 290 """convert a shared repository to a normal one
291 291
292 292 Copy the store data to the repo and remove the sharedpath data.
293 293 """
294 294
295 295 destlock = lock = None
296 296 lock = repo.lock()
297 297 try:
298 298 # we use locks here because if we race with commit, we
299 299 # can end up with extra data in the cloned revlogs that's
300 300 # not pointed to by changesets, thus causing verify to
301 301 # fail
302 302
303 303 destlock = copystore(ui, repo, repo.path)
304 304
305 305 sharefile = repo.vfs.join('sharedpath')
306 306 util.rename(sharefile, sharefile + '.old')
307 307
308 308 repo.requirements.discard('shared')
309 309 repo.requirements.discard('relshared')
310 310 repo._writerequirements()
311 311 finally:
312 312 destlock and destlock.release()
313 313 lock and lock.release()
314 314
315 315 # update store, spath, svfs and sjoin of repo
316 316 repo.unfiltered().__init__(repo.baseui, repo.root)
317 317
318 318 # TODO: figure out how to access subrepos that exist, but were previously
319 319 # removed from .hgsub
320 320 c = repo['.']
321 321 subs = c.substate
322 322 for s in sorted(subs):
323 323 c.sub(s).unshare()
324 324
325 325 def postshare(sourcerepo, destrepo, bookmarks=True, defaultpath=None):
326 326 """Called after a new shared repo is created.
327 327
328 328 The new repo only has a requirements file and pointer to the source.
329 329 This function configures additional shared data.
330 330
331 331 Extensions can wrap this function and write additional entries to
332 332 destrepo/.hg/shared to indicate additional pieces of data to be shared.
333 333 """
334 334 default = defaultpath or sourcerepo.ui.config('paths', 'default')
335 335 if default:
336 336 template = ('[paths]\n'
337 337 'default = %s\n')
338 338 destrepo.vfs.write('hgrc', util.tonativeeol(template % default))
339 339
340 340 with destrepo.wlock():
341 341 if bookmarks:
342 342 destrepo.vfs.write('shared', sharedbookmarks + '\n')
343 343
344 344 def _postshareupdate(repo, update, checkout=None):
345 345 """Maybe perform a working directory update after a shared repo is created.
346 346
347 347 ``update`` can be a boolean or a revision to update to.
348 348 """
349 349 if not update:
350 350 return
351 351
352 352 repo.ui.status(_("updating working directory\n"))
353 353 if update is not True:
354 354 checkout = update
355 355 for test in (checkout, 'default', 'tip'):
356 356 if test is None:
357 357 continue
358 358 try:
359 359 uprev = repo.lookup(test)
360 360 break
361 361 except error.RepoLookupError:
362 362 continue
363 363 _update(repo, uprev)
364 364
365 365 def copystore(ui, srcrepo, destpath):
366 366 '''copy files from store of srcrepo in destpath
367 367
368 368 returns destlock
369 369 '''
370 370 destlock = None
371 371 try:
372 372 hardlink = None
373 373 num = 0
374 374 closetopic = [None]
375 375 def prog(topic, pos):
376 376 if pos is None:
377 377 closetopic[0] = topic
378 378 else:
379 379 ui.progress(topic, pos + num)
380 380 srcpublishing = srcrepo.publishing()
381 381 srcvfs = vfsmod.vfs(srcrepo.sharedpath)
382 382 dstvfs = vfsmod.vfs(destpath)
383 383 for f in srcrepo.store.copylist():
384 384 if srcpublishing and f.endswith('phaseroots'):
385 385 continue
386 386 dstbase = os.path.dirname(f)
387 387 if dstbase and not dstvfs.exists(dstbase):
388 388 dstvfs.mkdir(dstbase)
389 389 if srcvfs.exists(f):
390 390 if f.endswith('data'):
391 391 # 'dstbase' may be empty (e.g. revlog format 0)
392 392 lockfile = os.path.join(dstbase, "lock")
393 393 # lock to avoid premature writing to the target
394 394 destlock = lock.lock(dstvfs, lockfile)
395 395 hardlink, n = util.copyfiles(srcvfs.join(f), dstvfs.join(f),
396 396 hardlink, progress=prog)
397 397 num += n
398 398 if hardlink:
399 399 ui.debug("linked %d files\n" % num)
400 400 if closetopic[0]:
401 401 ui.progress(closetopic[0], None)
402 402 else:
403 403 ui.debug("copied %d files\n" % num)
404 404 if closetopic[0]:
405 405 ui.progress(closetopic[0], None)
406 406 return destlock
407 407 except: # re-raises
408 408 release(destlock)
409 409 raise
410 410
411 411 def clonewithshare(ui, peeropts, sharepath, source, srcpeer, dest, pull=False,
412 412 rev=None, update=True, stream=False):
413 413 """Perform a clone using a shared repo.
414 414
415 415 The store for the repository will be located at <sharepath>/.hg. The
416 416 specified revisions will be cloned or pulled from "source". A shared repo
417 417 will be created at "dest" and a working copy will be created if "update" is
418 418 True.
419 419 """
420 420 revs = None
421 421 if rev:
422 422 if not srcpeer.capable('lookup'):
423 423 raise error.Abort(_("src repository does not support "
424 424 "revision lookup and so doesn't "
425 425 "support clone by revision"))
426 426 revs = [srcpeer.lookup(r) for r in rev]
427 427
428 428 # Obtain a lock before checking for or cloning the pooled repo otherwise
429 429 # 2 clients may race creating or populating it.
430 430 pooldir = os.path.dirname(sharepath)
431 431 # lock class requires the directory to exist.
432 432 try:
433 433 util.makedir(pooldir, False)
434 434 except OSError as e:
435 435 if e.errno != errno.EEXIST:
436 436 raise
437 437
438 438 poolvfs = vfsmod.vfs(pooldir)
439 439 basename = os.path.basename(sharepath)
440 440
441 441 with lock.lock(poolvfs, '%s.lock' % basename):
442 442 if os.path.exists(sharepath):
443 443 ui.status(_('(sharing from existing pooled repository %s)\n') %
444 444 basename)
445 445 else:
446 446 ui.status(_('(sharing from new pooled repository %s)\n') % basename)
447 447 # Always use pull mode because hardlinks in share mode don't work
448 448 # well. Never update because working copies aren't necessary in
449 449 # share mode.
450 450 clone(ui, peeropts, source, dest=sharepath, pull=True,
451 rev=rev, update=False, stream=stream)
451 revs=rev, update=False, stream=stream)
452 452
453 453 # Resolve the value to put in [paths] section for the source.
454 454 if islocal(source):
455 455 defaultpath = os.path.abspath(util.urllocalpath(source))
456 456 else:
457 457 defaultpath = source
458 458
459 459 sharerepo = repository(ui, path=sharepath)
460 460 share(ui, sharerepo, dest=dest, update=False, bookmarks=False,
461 461 defaultpath=defaultpath)
462 462
463 463 # We need to perform a pull against the dest repo to fetch bookmarks
464 464 # and other non-store data that isn't shared by default. In the case of
465 465 # non-existing shared repo, this means we pull from the remote twice. This
466 466 # is a bit weird. But at the time it was implemented, there wasn't an easy
467 467 # way to pull just non-changegroup data.
468 468 destrepo = repository(ui, path=dest)
469 469 exchange.pull(destrepo, srcpeer, heads=revs)
470 470
471 471 _postshareupdate(destrepo, update)
472 472
473 473 return srcpeer, peer(ui, peeropts, dest)
474 474
475 475 # Recomputing branch cache might be slow on big repos,
476 476 # so just copy it
477 477 def _copycache(srcrepo, dstcachedir, fname):
478 478 """copy a cache from srcrepo to destcachedir (if it exists)"""
479 479 srcbranchcache = srcrepo.vfs.join('cache/%s' % fname)
480 480 dstbranchcache = os.path.join(dstcachedir, fname)
481 481 if os.path.exists(srcbranchcache):
482 482 if not os.path.exists(dstcachedir):
483 483 os.mkdir(dstcachedir)
484 484 util.copyfile(srcbranchcache, dstbranchcache)
485 485
486 def clone(ui, peeropts, source, dest=None, pull=False, rev=None,
486 def clone(ui, peeropts, source, dest=None, pull=False, revs=None,
487 487 update=True, stream=False, branch=None, shareopts=None):
488 488 """Make a copy of an existing repository.
489 489
490 490 Create a copy of an existing repository in a new directory. The
491 491 source and destination are URLs, as passed to the repository
492 492 function. Returns a pair of repository peers, the source and
493 493 newly created destination.
494 494
495 495 The location of the source is added to the new repository's
496 496 .hg/hgrc file, as the default to be used for future pulls and
497 497 pushes.
498 498
499 499 If an exception is raised, the partly cloned/updated destination
500 500 repository will be deleted.
501 501
502 502 Arguments:
503 503
504 504 source: repository object or URL
505 505
506 506 dest: URL of destination repository to create (defaults to base
507 507 name of source repository)
508 508
509 509 pull: always pull from source repository, even in local case or if the
510 510 server prefers streaming
511 511
512 512 stream: stream raw data uncompressed from repository (fast over
513 513 LAN, slow over WAN)
514 514
515 rev: revision to clone up to (implies pull=True)
515 revs: revision to clone up to (implies pull=True)
516 516
517 517 update: update working directory after clone completes, if
518 518 destination is local repository (True means update to default rev,
519 519 anything else is treated as a revision)
520 520
521 521 branch: branches to clone
522 522
523 523 shareopts: dict of options to control auto sharing behavior. The "pool" key
524 524 activates auto sharing mode and defines the directory for stores. The
525 525 "mode" key determines how to construct the directory name of the shared
526 526 repository. "identity" means the name is derived from the node of the first
527 527 changeset in the repository. "remote" means the name is derived from the
528 528 remote's path/URL. Defaults to "identity."
529 529 """
530 530
531 531 if isinstance(source, bytes):
532 532 origsource = ui.expandpath(source)
533 533 source, branches = parseurl(origsource, branch)
534 534 srcpeer = peer(ui, peeropts, source)
535 535 else:
536 536 srcpeer = source.peer() # in case we were called with a localrepo
537 537 branches = (None, branch or [])
538 538 origsource = source = srcpeer.url()
539 rev, checkout = addbranchrevs(srcpeer, srcpeer, branches, rev)
539 revs, checkout = addbranchrevs(srcpeer, srcpeer, branches, revs)
540 540
541 541 if dest is None:
542 542 dest = defaultdest(source)
543 543 if dest:
544 544 ui.status(_("destination directory: %s\n") % dest)
545 545 else:
546 546 dest = ui.expandpath(dest)
547 547
548 548 dest = util.urllocalpath(dest)
549 549 source = util.urllocalpath(source)
550 550
551 551 if not dest:
552 552 raise error.Abort(_("empty destination path is not valid"))
553 553
554 554 destvfs = vfsmod.vfs(dest, expandpath=True)
555 555 if destvfs.lexists():
556 556 if not destvfs.isdir():
557 557 raise error.Abort(_("destination '%s' already exists") % dest)
558 558 elif destvfs.listdir():
559 559 raise error.Abort(_("destination '%s' is not empty") % dest)
560 560
561 561 shareopts = shareopts or {}
562 562 sharepool = shareopts.get('pool')
563 563 sharenamemode = shareopts.get('mode')
564 564 if sharepool and islocal(dest):
565 565 sharepath = None
566 566 if sharenamemode == 'identity':
567 567 # Resolve the name from the initial changeset in the remote
568 568 # repository. This returns nullid when the remote is empty. It
569 569 # raises RepoLookupError if revision 0 is filtered or otherwise
570 570 # not available. If we fail to resolve, sharing is not enabled.
571 571 try:
572 572 rootnode = srcpeer.lookup('0')
573 573 if rootnode != node.nullid:
574 574 sharepath = os.path.join(sharepool, node.hex(rootnode))
575 575 else:
576 576 ui.status(_('(not using pooled storage: '
577 577 'remote appears to be empty)\n'))
578 578 except error.RepoLookupError:
579 579 ui.status(_('(not using pooled storage: '
580 580 'unable to resolve identity of remote)\n'))
581 581 elif sharenamemode == 'remote':
582 582 sharepath = os.path.join(
583 583 sharepool, node.hex(hashlib.sha1(source).digest()))
584 584 else:
585 585 raise error.Abort(_('unknown share naming mode: %s') %
586 586 sharenamemode)
587 587
588 588 if sharepath:
589 589 return clonewithshare(ui, peeropts, sharepath, source, srcpeer,
590 dest, pull=pull, rev=rev, update=update,
590 dest, pull=pull, rev=revs, update=update,
591 591 stream=stream)
592 592
593 593 srclock = destlock = cleandir = None
594 594 srcrepo = srcpeer.local()
595 595 try:
596 596 abspath = origsource
597 597 if islocal(origsource):
598 598 abspath = os.path.abspath(util.urllocalpath(origsource))
599 599
600 600 if islocal(dest):
601 601 cleandir = dest
602 602
603 603 copy = False
604 604 if (srcrepo and srcrepo.cancopy() and islocal(dest)
605 605 and not phases.hassecret(srcrepo)):
606 copy = not pull and not rev
606 copy = not pull and not revs
607 607
608 608 if copy:
609 609 try:
610 610 # we use a lock here because if we race with commit, we
611 611 # can end up with extra data in the cloned revlogs that's
612 612 # not pointed to by changesets, thus causing verify to
613 613 # fail
614 614 srclock = srcrepo.lock(wait=False)
615 615 except error.LockError:
616 616 copy = False
617 617
618 618 if copy:
619 619 srcrepo.hook('preoutgoing', throw=True, source='clone')
620 620 hgdir = os.path.realpath(os.path.join(dest, ".hg"))
621 621 if not os.path.exists(dest):
622 622 os.mkdir(dest)
623 623 else:
624 624 # only clean up directories we create ourselves
625 625 cleandir = hgdir
626 626 try:
627 627 destpath = hgdir
628 628 util.makedir(destpath, notindexed=True)
629 629 except OSError as inst:
630 630 if inst.errno == errno.EEXIST:
631 631 cleandir = None
632 632 raise error.Abort(_("destination '%s' already exists")
633 633 % dest)
634 634 raise
635 635
636 636 destlock = copystore(ui, srcrepo, destpath)
637 637 # copy bookmarks over
638 638 srcbookmarks = srcrepo.vfs.join('bookmarks')
639 639 dstbookmarks = os.path.join(destpath, 'bookmarks')
640 640 if os.path.exists(srcbookmarks):
641 641 util.copyfile(srcbookmarks, dstbookmarks)
642 642
643 643 dstcachedir = os.path.join(destpath, 'cache')
644 644 for cache in cacheutil.cachetocopy(srcrepo):
645 645 _copycache(srcrepo, dstcachedir, cache)
646 646
647 647 # we need to re-init the repo after manually copying the data
648 648 # into it
649 649 destpeer = peer(srcrepo, peeropts, dest)
650 650 srcrepo.hook('outgoing', source='clone',
651 651 node=node.hex(node.nullid))
652 652 else:
653 653 try:
654 654 destpeer = peer(srcrepo or ui, peeropts, dest, create=True)
655 655 # only pass ui when no srcrepo
656 656 except OSError as inst:
657 657 if inst.errno == errno.EEXIST:
658 658 cleandir = None
659 659 raise error.Abort(_("destination '%s' already exists")
660 660 % dest)
661 661 raise
662 662
663 revs = None
664 if rev:
663 if revs:
665 664 if not srcpeer.capable('lookup'):
666 665 raise error.Abort(_("src repository does not support "
667 666 "revision lookup and so doesn't "
668 667 "support clone by revision"))
669 revs = [srcpeer.lookup(r) for r in rev]
668 revs = [srcpeer.lookup(r) for r in revs]
670 669 checkout = revs[0]
670 else:
671 revs = None
671 672 local = destpeer.local()
672 673 if local:
673 674 u = util.url(abspath)
674 675 defaulturl = bytes(u)
675 676 local.ui.setconfig('paths', 'default', defaulturl, 'clone')
676 677 if not stream:
677 678 if pull:
678 679 stream = False
679 680 else:
680 681 stream = None
681 682 # internal config: ui.quietbookmarkmove
682 683 overrides = {('ui', 'quietbookmarkmove'): True}
683 684 with local.ui.configoverride(overrides, 'clone'):
684 685 exchange.pull(local, srcpeer, revs,
685 686 streamclonerequested=stream)
686 687 elif srcrepo:
687 688 exchange.push(srcrepo, destpeer, revs=revs,
688 689 bookmarks=srcrepo._bookmarks.keys())
689 690 else:
690 691 raise error.Abort(_("clone from remote to remote not supported")
691 692 )
692 693
693 694 cleandir = None
694 695
695 696 destrepo = destpeer.local()
696 697 if destrepo:
697 698 template = uimod.samplehgrcs['cloned']
698 699 u = util.url(abspath)
699 700 u.passwd = None
700 701 defaulturl = bytes(u)
701 702 destrepo.vfs.write('hgrc', util.tonativeeol(template % defaulturl))
702 703 destrepo.ui.setconfig('paths', 'default', defaulturl, 'clone')
703 704
704 705 if ui.configbool('experimental', 'remotenames'):
705 706 logexchange.pullremotenames(destrepo, srcpeer)
706 707
707 708 if update:
708 709 if update is not True:
709 710 checkout = srcpeer.lookup(update)
710 711 uprev = None
711 712 status = None
712 713 if checkout is not None:
713 714 try:
714 715 uprev = destrepo.lookup(checkout)
715 716 except error.RepoLookupError:
716 717 if update is not True:
717 718 try:
718 719 uprev = destrepo.lookup(update)
719 720 except error.RepoLookupError:
720 721 pass
721 722 if uprev is None:
722 723 try:
723 724 uprev = destrepo._bookmarks['@']
724 725 update = '@'
725 726 bn = destrepo[uprev].branch()
726 727 if bn == 'default':
727 728 status = _("updating to bookmark @\n")
728 729 else:
729 730 status = (_("updating to bookmark @ on branch %s\n")
730 731 % bn)
731 732 except KeyError:
732 733 try:
733 734 uprev = destrepo.branchtip('default')
734 735 except error.RepoLookupError:
735 736 uprev = destrepo.lookup('tip')
736 737 if not status:
737 738 bn = destrepo[uprev].branch()
738 739 status = _("updating to branch %s\n") % bn
739 740 destrepo.ui.status(status)
740 741 _update(destrepo, uprev)
741 742 if update in destrepo._bookmarks:
742 743 bookmarks.activate(destrepo, update)
743 744 finally:
744 745 release(srclock, destlock)
745 746 if cleandir is not None:
746 747 shutil.rmtree(cleandir, True)
747 748 if srcpeer is not None:
748 749 srcpeer.close()
749 750 return srcpeer, destpeer
750 751
751 752 def _showstats(repo, stats, quietempty=False):
752 753 if quietempty and stats.isempty():
753 754 return
754 755 repo.ui.status(_("%d files updated, %d files merged, "
755 756 "%d files removed, %d files unresolved\n") % (
756 757 stats.updatedcount, stats.mergedcount,
757 758 stats.removedcount, stats.unresolvedcount))
758 759
759 760 def updaterepo(repo, node, overwrite, updatecheck=None):
760 761 """Update the working directory to node.
761 762
762 763 When overwrite is set, changes are clobbered, merged else
763 764
764 765 returns stats (see pydoc mercurial.merge.applyupdates)"""
765 766 return mergemod.update(repo, node, False, overwrite,
766 767 labels=['working copy', 'destination'],
767 768 updatecheck=updatecheck)
768 769
769 770 def update(repo, node, quietempty=False, updatecheck=None):
770 771 """update the working directory to node"""
771 772 stats = updaterepo(repo, node, False, updatecheck=updatecheck)
772 773 _showstats(repo, stats, quietempty)
773 774 if stats.unresolvedcount:
774 775 repo.ui.status(_("use 'hg resolve' to retry unresolved file merges\n"))
775 776 return stats.unresolvedcount > 0
776 777
777 778 # naming conflict in clone()
778 779 _update = update
779 780
780 781 def clean(repo, node, show_stats=True, quietempty=False):
781 782 """forcibly switch the working directory to node, clobbering changes"""
782 783 stats = updaterepo(repo, node, True)
783 784 repo.vfs.unlinkpath('graftstate', ignoremissing=True)
784 785 if show_stats:
785 786 _showstats(repo, stats, quietempty)
786 787 return stats.unresolvedcount > 0
787 788
788 789 # naming conflict in updatetotally()
789 790 _clean = clean
790 791
791 792 def updatetotally(ui, repo, checkout, brev, clean=False, updatecheck=None):
792 793 """Update the working directory with extra care for non-file components
793 794
794 795 This takes care of non-file components below:
795 796
796 797 :bookmark: might be advanced or (in)activated
797 798
798 799 This takes arguments below:
799 800
800 801 :checkout: to which revision the working directory is updated
801 802 :brev: a name, which might be a bookmark to be activated after updating
802 803 :clean: whether changes in the working directory can be discarded
803 804 :updatecheck: how to deal with a dirty working directory
804 805
805 806 Valid values for updatecheck are (None => linear):
806 807
807 808 * abort: abort if the working directory is dirty
808 809 * none: don't check (merge working directory changes into destination)
809 810 * linear: check that update is linear before merging working directory
810 811 changes into destination
811 812 * noconflict: check that the update does not result in file merges
812 813
813 814 This returns whether conflict is detected at updating or not.
814 815 """
815 816 if updatecheck is None:
816 817 updatecheck = ui.config('commands', 'update.check')
817 818 if updatecheck not in ('abort', 'none', 'linear', 'noconflict'):
818 819 # If not configured, or invalid value configured
819 820 updatecheck = 'linear'
820 821 with repo.wlock():
821 822 movemarkfrom = None
822 823 warndest = False
823 824 if checkout is None:
824 825 updata = destutil.destupdate(repo, clean=clean)
825 826 checkout, movemarkfrom, brev = updata
826 827 warndest = True
827 828
828 829 if clean:
829 830 ret = _clean(repo, checkout)
830 831 else:
831 832 if updatecheck == 'abort':
832 833 cmdutil.bailifchanged(repo, merge=False)
833 834 updatecheck = 'none'
834 835 ret = _update(repo, checkout, updatecheck=updatecheck)
835 836
836 837 if not ret and movemarkfrom:
837 838 if movemarkfrom == repo['.'].node():
838 839 pass # no-op update
839 840 elif bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
840 841 b = ui.label(repo._activebookmark, 'bookmarks.active')
841 842 ui.status(_("updating bookmark %s\n") % b)
842 843 else:
843 844 # this can happen with a non-linear update
844 845 b = ui.label(repo._activebookmark, 'bookmarks')
845 846 ui.status(_("(leaving bookmark %s)\n") % b)
846 847 bookmarks.deactivate(repo)
847 848 elif brev in repo._bookmarks:
848 849 if brev != repo._activebookmark:
849 850 b = ui.label(brev, 'bookmarks.active')
850 851 ui.status(_("(activating bookmark %s)\n") % b)
851 852 bookmarks.activate(repo, brev)
852 853 elif brev:
853 854 if repo._activebookmark:
854 855 b = ui.label(repo._activebookmark, 'bookmarks')
855 856 ui.status(_("(leaving bookmark %s)\n") % b)
856 857 bookmarks.deactivate(repo)
857 858
858 859 if warndest:
859 860 destutil.statusotherdests(ui, repo)
860 861
861 862 return ret
862 863
863 864 def merge(repo, node, force=None, remind=True, mergeforce=False, labels=None,
864 865 abort=False):
865 866 """Branch merge with node, resolving changes. Return true if any
866 867 unresolved conflicts."""
867 868 if not abort:
868 869 stats = mergemod.update(repo, node, True, force, mergeforce=mergeforce,
869 870 labels=labels)
870 871 else:
871 872 ms = mergemod.mergestate.read(repo)
872 873 if ms.active():
873 874 # there were conflicts
874 875 node = ms.localctx.hex()
875 876 else:
876 877 # there were no conficts, mergestate was not stored
877 878 node = repo['.'].hex()
878 879
879 880 repo.ui.status(_("aborting the merge, updating back to"
880 881 " %s\n") % node[:12])
881 882 stats = mergemod.update(repo, node, branchmerge=False, force=True,
882 883 labels=labels)
883 884
884 885 _showstats(repo, stats)
885 886 if stats.unresolvedcount:
886 887 repo.ui.status(_("use 'hg resolve' to retry unresolved file merges "
887 888 "or 'hg merge --abort' to abandon\n"))
888 889 elif remind and not abort:
889 890 repo.ui.status(_("(branch merge, don't forget to commit)\n"))
890 891 return stats.unresolvedcount > 0
891 892
892 893 def _incoming(displaychlist, subreporecurse, ui, repo, source,
893 894 opts, buffered=False):
894 895 """
895 896 Helper for incoming / gincoming.
896 897 displaychlist gets called with
897 898 (remoterepo, incomingchangesetlist, displayer) parameters,
898 899 and is supposed to contain only code that can't be unified.
899 900 """
900 901 source, branches = parseurl(ui.expandpath(source), opts.get('branch'))
901 902 other = peer(repo, opts, source)
902 903 ui.status(_('comparing with %s\n') % util.hidepassword(source))
903 904 revs, checkout = addbranchrevs(repo, other, branches, opts.get('rev'))
904 905
905 906 if revs:
906 907 revs = [other.lookup(rev) for rev in revs]
907 908 other, chlist, cleanupfn = bundlerepo.getremotechanges(ui, repo, other,
908 909 revs, opts["bundle"], opts["force"])
909 910 try:
910 911 if not chlist:
911 912 ui.status(_("no changes found\n"))
912 913 return subreporecurse()
913 914 ui.pager('incoming')
914 915 displayer = logcmdutil.changesetdisplayer(ui, other, opts,
915 916 buffered=buffered)
916 917 displaychlist(other, chlist, displayer)
917 918 displayer.close()
918 919 finally:
919 920 cleanupfn()
920 921 subreporecurse()
921 922 return 0 # exit code is zero since we found incoming changes
922 923
923 924 def incoming(ui, repo, source, opts):
924 925 def subreporecurse():
925 926 ret = 1
926 927 if opts.get('subrepos'):
927 928 ctx = repo[None]
928 929 for subpath in sorted(ctx.substate):
929 930 sub = ctx.sub(subpath)
930 931 ret = min(ret, sub.incoming(ui, source, opts))
931 932 return ret
932 933
933 934 def display(other, chlist, displayer):
934 935 limit = logcmdutil.getlimit(opts)
935 936 if opts.get('newest_first'):
936 937 chlist.reverse()
937 938 count = 0
938 939 for n in chlist:
939 940 if limit is not None and count >= limit:
940 941 break
941 942 parents = [p for p in other.changelog.parents(n) if p != nullid]
942 943 if opts.get('no_merges') and len(parents) == 2:
943 944 continue
944 945 count += 1
945 946 displayer.show(other[n])
946 947 return _incoming(display, subreporecurse, ui, repo, source, opts)
947 948
948 949 def _outgoing(ui, repo, dest, opts):
949 950 path = ui.paths.getpath(dest, default=('default-push', 'default'))
950 951 if not path:
951 952 raise error.Abort(_('default repository not configured!'),
952 953 hint=_("see 'hg help config.paths'"))
953 954 dest = path.pushloc or path.loc
954 955 branches = path.branch, opts.get('branch') or []
955 956
956 957 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
957 958 revs, checkout = addbranchrevs(repo, repo, branches, opts.get('rev'))
958 959 if revs:
959 960 revs = [repo.lookup(rev) for rev in scmutil.revrange(repo, revs)]
960 961
961 962 other = peer(repo, opts, dest)
962 963 outgoing = discovery.findcommonoutgoing(repo, other, revs,
963 964 force=opts.get('force'))
964 965 o = outgoing.missing
965 966 if not o:
966 967 scmutil.nochangesfound(repo.ui, repo, outgoing.excluded)
967 968 return o, other
968 969
969 970 def outgoing(ui, repo, dest, opts):
970 971 def recurse():
971 972 ret = 1
972 973 if opts.get('subrepos'):
973 974 ctx = repo[None]
974 975 for subpath in sorted(ctx.substate):
975 976 sub = ctx.sub(subpath)
976 977 ret = min(ret, sub.outgoing(ui, dest, opts))
977 978 return ret
978 979
979 980 limit = logcmdutil.getlimit(opts)
980 981 o, other = _outgoing(ui, repo, dest, opts)
981 982 if not o:
982 983 cmdutil.outgoinghooks(ui, repo, other, opts, o)
983 984 return recurse()
984 985
985 986 if opts.get('newest_first'):
986 987 o.reverse()
987 988 ui.pager('outgoing')
988 989 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
989 990 count = 0
990 991 for n in o:
991 992 if limit is not None and count >= limit:
992 993 break
993 994 parents = [p for p in repo.changelog.parents(n) if p != nullid]
994 995 if opts.get('no_merges') and len(parents) == 2:
995 996 continue
996 997 count += 1
997 998 displayer.show(repo[n])
998 999 displayer.close()
999 1000 cmdutil.outgoinghooks(ui, repo, other, opts, o)
1000 1001 recurse()
1001 1002 return 0 # exit code is zero since we found outgoing changes
1002 1003
1003 1004 def verify(repo):
1004 1005 """verify the consistency of a repository"""
1005 1006 ret = verifymod.verify(repo)
1006 1007
1007 1008 # Broken subrepo references in hidden csets don't seem worth worrying about,
1008 1009 # since they can't be pushed/pulled, and --hidden can be used if they are a
1009 1010 # concern.
1010 1011
1011 1012 # pathto() is needed for -R case
1012 1013 revs = repo.revs("filelog(%s)",
1013 1014 util.pathto(repo.root, repo.getcwd(), '.hgsubstate'))
1014 1015
1015 1016 if revs:
1016 1017 repo.ui.status(_('checking subrepo links\n'))
1017 1018 for rev in revs:
1018 1019 ctx = repo[rev]
1019 1020 try:
1020 1021 for subpath in ctx.substate:
1021 1022 try:
1022 1023 ret = (ctx.sub(subpath, allowcreate=False).verify()
1023 1024 or ret)
1024 1025 except error.RepoError as e:
1025 1026 repo.ui.warn(('%s: %s\n') % (rev, e))
1026 1027 except Exception:
1027 1028 repo.ui.warn(_('.hgsubstate is corrupt in revision %s\n') %
1028 1029 node.short(ctx.node()))
1029 1030
1030 1031 return ret
1031 1032
1032 1033 def remoteui(src, opts):
1033 1034 'build a remote ui from ui or repo and opts'
1034 1035 if util.safehasattr(src, 'baseui'): # looks like a repository
1035 1036 dst = src.baseui.copy() # drop repo-specific config
1036 1037 src = src.ui # copy target options from repo
1037 1038 else: # assume it's a global ui object
1038 1039 dst = src.copy() # keep all global options
1039 1040
1040 1041 # copy ssh-specific options
1041 1042 for o in 'ssh', 'remotecmd':
1042 1043 v = opts.get(o) or src.config('ui', o)
1043 1044 if v:
1044 1045 dst.setconfig("ui", o, v, 'copied')
1045 1046
1046 1047 # copy bundle-specific options
1047 1048 r = src.config('bundle', 'mainreporoot')
1048 1049 if r:
1049 1050 dst.setconfig('bundle', 'mainreporoot', r, 'copied')
1050 1051
1051 1052 # copy selected local settings to the remote ui
1052 1053 for sect in ('auth', 'hostfingerprints', 'hostsecurity', 'http_proxy'):
1053 1054 for key, val in src.configitems(sect):
1054 1055 dst.setconfig(sect, key, val, 'copied')
1055 1056 v = src.config('web', 'cacerts')
1056 1057 if v:
1057 1058 dst.setconfig('web', 'cacerts', util.expandpath(v), 'copied')
1058 1059
1059 1060 return dst
1060 1061
1061 1062 # Files of interest
1062 1063 # Used to check if the repository has changed looking at mtime and size of
1063 1064 # these files.
1064 1065 foi = [('spath', '00changelog.i'),
1065 1066 ('spath', 'phaseroots'), # ! phase can change content at the same size
1066 1067 ('spath', 'obsstore'),
1067 1068 ('path', 'bookmarks'), # ! bookmark can change content at the same size
1068 1069 ]
1069 1070
1070 1071 class cachedlocalrepo(object):
1071 1072 """Holds a localrepository that can be cached and reused."""
1072 1073
1073 1074 def __init__(self, repo):
1074 1075 """Create a new cached repo from an existing repo.
1075 1076
1076 1077 We assume the passed in repo was recently created. If the
1077 1078 repo has changed between when it was created and when it was
1078 1079 turned into a cache, it may not refresh properly.
1079 1080 """
1080 1081 assert isinstance(repo, localrepo.localrepository)
1081 1082 self._repo = repo
1082 1083 self._state, self.mtime = self._repostate()
1083 1084 self._filtername = repo.filtername
1084 1085
1085 1086 def fetch(self):
1086 1087 """Refresh (if necessary) and return a repository.
1087 1088
1088 1089 If the cached instance is out of date, it will be recreated
1089 1090 automatically and returned.
1090 1091
1091 1092 Returns a tuple of the repo and a boolean indicating whether a new
1092 1093 repo instance was created.
1093 1094 """
1094 1095 # We compare the mtimes and sizes of some well-known files to
1095 1096 # determine if the repo changed. This is not precise, as mtimes
1096 1097 # are susceptible to clock skew and imprecise filesystems and
1097 1098 # file content can change while maintaining the same size.
1098 1099
1099 1100 state, mtime = self._repostate()
1100 1101 if state == self._state:
1101 1102 return self._repo, False
1102 1103
1103 1104 repo = repository(self._repo.baseui, self._repo.url())
1104 1105 if self._filtername:
1105 1106 self._repo = repo.filtered(self._filtername)
1106 1107 else:
1107 1108 self._repo = repo.unfiltered()
1108 1109 self._state = state
1109 1110 self.mtime = mtime
1110 1111
1111 1112 return self._repo, True
1112 1113
1113 1114 def _repostate(self):
1114 1115 state = []
1115 1116 maxmtime = -1
1116 1117 for attr, fname in foi:
1117 1118 prefix = getattr(self._repo, attr)
1118 1119 p = os.path.join(prefix, fname)
1119 1120 try:
1120 1121 st = os.stat(p)
1121 1122 except OSError:
1122 1123 st = os.stat(prefix)
1123 1124 state.append((st[stat.ST_MTIME], st.st_size))
1124 1125 maxmtime = max(maxmtime, st[stat.ST_MTIME])
1125 1126
1126 1127 return tuple(state), maxmtime
1127 1128
1128 1129 def copy(self):
1129 1130 """Obtain a copy of this class instance.
1130 1131
1131 1132 A new localrepository instance is obtained. The new instance should be
1132 1133 completely independent of the original.
1133 1134 """
1134 1135 repo = repository(self._repo.baseui, self._repo.origroot)
1135 1136 if self._filtername:
1136 1137 repo = repo.filtered(self._filtername)
1137 1138 else:
1138 1139 repo = repo.unfiltered()
1139 1140 c = cachedlocalrepo(repo)
1140 1141 c._state = self._state
1141 1142 c.mtime = self.mtime
1142 1143 return c
General Comments 0
You need to be logged in to leave comments. Login now