##// END OF EJS Templates
cmdutil: say that `graft --stop` stops the graft instead of aborting...
Pulkit Goyal -
r38331:47f5454a default
parent child Browse files
Show More
@@ -1,3262 +1,3262 b''
1 1 # cmdutil.py - help for command processing in mercurial
2 2 #
3 3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 from __future__ import absolute_import
9 9
10 10 import errno
11 11 import os
12 12 import re
13 13
14 14 from .i18n import _
15 15 from .node import (
16 16 hex,
17 17 nullid,
18 18 nullrev,
19 19 short,
20 20 )
21 21
22 22 from . import (
23 23 bookmarks,
24 24 changelog,
25 25 copies,
26 26 crecord as crecordmod,
27 27 dirstateguard,
28 28 encoding,
29 29 error,
30 30 formatter,
31 31 logcmdutil,
32 32 match as matchmod,
33 33 merge as mergemod,
34 34 mergeutil,
35 35 obsolete,
36 36 patch,
37 37 pathutil,
38 38 pycompat,
39 39 revlog,
40 40 rewriteutil,
41 41 scmutil,
42 42 smartset,
43 43 subrepoutil,
44 44 templatekw,
45 45 templater,
46 46 util,
47 47 vfs as vfsmod,
48 48 )
49 49
50 50 from .utils import (
51 51 dateutil,
52 52 stringutil,
53 53 )
54 54
55 55 stringio = util.stringio
56 56
57 57 # templates of common command options
58 58
59 59 dryrunopts = [
60 60 ('n', 'dry-run', None,
61 61 _('do not perform actions, just print output')),
62 62 ]
63 63
64 64 remoteopts = [
65 65 ('e', 'ssh', '',
66 66 _('specify ssh command to use'), _('CMD')),
67 67 ('', 'remotecmd', '',
68 68 _('specify hg command to run on the remote side'), _('CMD')),
69 69 ('', 'insecure', None,
70 70 _('do not verify server certificate (ignoring web.cacerts config)')),
71 71 ]
72 72
73 73 walkopts = [
74 74 ('I', 'include', [],
75 75 _('include names matching the given patterns'), _('PATTERN')),
76 76 ('X', 'exclude', [],
77 77 _('exclude names matching the given patterns'), _('PATTERN')),
78 78 ]
79 79
80 80 commitopts = [
81 81 ('m', 'message', '',
82 82 _('use text as commit message'), _('TEXT')),
83 83 ('l', 'logfile', '',
84 84 _('read commit message from file'), _('FILE')),
85 85 ]
86 86
87 87 commitopts2 = [
88 88 ('d', 'date', '',
89 89 _('record the specified date as commit date'), _('DATE')),
90 90 ('u', 'user', '',
91 91 _('record the specified user as committer'), _('USER')),
92 92 ]
93 93
94 94 # hidden for now
95 95 formatteropts = [
96 96 ('T', 'template', '',
97 97 _('display with template (EXPERIMENTAL)'), _('TEMPLATE')),
98 98 ]
99 99
100 100 templateopts = [
101 101 ('', 'style', '',
102 102 _('display using template map file (DEPRECATED)'), _('STYLE')),
103 103 ('T', 'template', '',
104 104 _('display with template'), _('TEMPLATE')),
105 105 ]
106 106
107 107 logopts = [
108 108 ('p', 'patch', None, _('show patch')),
109 109 ('g', 'git', None, _('use git extended diff format')),
110 110 ('l', 'limit', '',
111 111 _('limit number of changes displayed'), _('NUM')),
112 112 ('M', 'no-merges', None, _('do not show merges')),
113 113 ('', 'stat', None, _('output diffstat-style summary of changes')),
114 114 ('G', 'graph', None, _("show the revision DAG")),
115 115 ] + templateopts
116 116
117 117 diffopts = [
118 118 ('a', 'text', None, _('treat all files as text')),
119 119 ('g', 'git', None, _('use git extended diff format')),
120 120 ('', 'binary', None, _('generate binary diffs in git mode (default)')),
121 121 ('', 'nodates', None, _('omit dates from diff headers'))
122 122 ]
123 123
124 124 diffwsopts = [
125 125 ('w', 'ignore-all-space', None,
126 126 _('ignore white space when comparing lines')),
127 127 ('b', 'ignore-space-change', None,
128 128 _('ignore changes in the amount of white space')),
129 129 ('B', 'ignore-blank-lines', None,
130 130 _('ignore changes whose lines are all blank')),
131 131 ('Z', 'ignore-space-at-eol', None,
132 132 _('ignore changes in whitespace at EOL')),
133 133 ]
134 134
135 135 diffopts2 = [
136 136 ('', 'noprefix', None, _('omit a/ and b/ prefixes from filenames')),
137 137 ('p', 'show-function', None, _('show which function each change is in')),
138 138 ('', 'reverse', None, _('produce a diff that undoes the changes')),
139 139 ] + diffwsopts + [
140 140 ('U', 'unified', '',
141 141 _('number of lines of context to show'), _('NUM')),
142 142 ('', 'stat', None, _('output diffstat-style summary of changes')),
143 143 ('', 'root', '', _('produce diffs relative to subdirectory'), _('DIR')),
144 144 ]
145 145
146 146 mergetoolopts = [
147 147 ('t', 'tool', '', _('specify merge tool')),
148 148 ]
149 149
150 150 similarityopts = [
151 151 ('s', 'similarity', '',
152 152 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
153 153 ]
154 154
155 155 subrepoopts = [
156 156 ('S', 'subrepos', None,
157 157 _('recurse into subrepositories'))
158 158 ]
159 159
160 160 debugrevlogopts = [
161 161 ('c', 'changelog', False, _('open changelog')),
162 162 ('m', 'manifest', False, _('open manifest')),
163 163 ('', 'dir', '', _('open directory manifest')),
164 164 ]
165 165
166 166 # special string such that everything below this line will be ingored in the
167 167 # editor text
168 168 _linebelow = "^HG: ------------------------ >8 ------------------------$"
169 169
170 170 def ishunk(x):
171 171 hunkclasses = (crecordmod.uihunk, patch.recordhunk)
172 172 return isinstance(x, hunkclasses)
173 173
174 174 def newandmodified(chunks, originalchunks):
175 175 newlyaddedandmodifiedfiles = set()
176 176 for chunk in chunks:
177 177 if ishunk(chunk) and chunk.header.isnewfile() and chunk not in \
178 178 originalchunks:
179 179 newlyaddedandmodifiedfiles.add(chunk.header.filename())
180 180 return newlyaddedandmodifiedfiles
181 181
182 182 def parsealiases(cmd):
183 183 return cmd.lstrip("^").split("|")
184 184
185 185 def setupwrapcolorwrite(ui):
186 186 # wrap ui.write so diff output can be labeled/colorized
187 187 def wrapwrite(orig, *args, **kw):
188 188 label = kw.pop(r'label', '')
189 189 for chunk, l in patch.difflabel(lambda: args):
190 190 orig(chunk, label=label + l)
191 191
192 192 oldwrite = ui.write
193 193 def wrap(*args, **kwargs):
194 194 return wrapwrite(oldwrite, *args, **kwargs)
195 195 setattr(ui, 'write', wrap)
196 196 return oldwrite
197 197
198 198 def filterchunks(ui, originalhunks, usecurses, testfile, operation=None):
199 199 try:
200 200 if usecurses:
201 201 if testfile:
202 202 recordfn = crecordmod.testdecorator(
203 203 testfile, crecordmod.testchunkselector)
204 204 else:
205 205 recordfn = crecordmod.chunkselector
206 206
207 207 return crecordmod.filterpatch(ui, originalhunks, recordfn,
208 208 operation)
209 209 except crecordmod.fallbackerror as e:
210 210 ui.warn('%s\n' % e.message)
211 211 ui.warn(_('falling back to text mode\n'))
212 212
213 213 return patch.filterpatch(ui, originalhunks, operation)
214 214
215 215 def recordfilter(ui, originalhunks, operation=None):
216 216 """ Prompts the user to filter the originalhunks and return a list of
217 217 selected hunks.
218 218 *operation* is used for to build ui messages to indicate the user what
219 219 kind of filtering they are doing: reverting, committing, shelving, etc.
220 220 (see patch.filterpatch).
221 221 """
222 222 usecurses = crecordmod.checkcurses(ui)
223 223 testfile = ui.config('experimental', 'crecordtest')
224 224 oldwrite = setupwrapcolorwrite(ui)
225 225 try:
226 226 newchunks, newopts = filterchunks(ui, originalhunks, usecurses,
227 227 testfile, operation)
228 228 finally:
229 229 ui.write = oldwrite
230 230 return newchunks, newopts
231 231
232 232 def dorecord(ui, repo, commitfunc, cmdsuggest, backupall,
233 233 filterfn, *pats, **opts):
234 234 opts = pycompat.byteskwargs(opts)
235 235 if not ui.interactive():
236 236 if cmdsuggest:
237 237 msg = _('running non-interactively, use %s instead') % cmdsuggest
238 238 else:
239 239 msg = _('running non-interactively')
240 240 raise error.Abort(msg)
241 241
242 242 # make sure username is set before going interactive
243 243 if not opts.get('user'):
244 244 ui.username() # raise exception, username not provided
245 245
246 246 def recordfunc(ui, repo, message, match, opts):
247 247 """This is generic record driver.
248 248
249 249 Its job is to interactively filter local changes, and
250 250 accordingly prepare working directory into a state in which the
251 251 job can be delegated to a non-interactive commit command such as
252 252 'commit' or 'qrefresh'.
253 253
254 254 After the actual job is done by non-interactive command, the
255 255 working directory is restored to its original state.
256 256
257 257 In the end we'll record interesting changes, and everything else
258 258 will be left in place, so the user can continue working.
259 259 """
260 260
261 261 checkunfinished(repo, commit=True)
262 262 wctx = repo[None]
263 263 merge = len(wctx.parents()) > 1
264 264 if merge:
265 265 raise error.Abort(_('cannot partially commit a merge '
266 266 '(use "hg commit" instead)'))
267 267
268 268 def fail(f, msg):
269 269 raise error.Abort('%s: %s' % (f, msg))
270 270
271 271 force = opts.get('force')
272 272 if not force:
273 273 vdirs = []
274 274 match.explicitdir = vdirs.append
275 275 match.bad = fail
276 276
277 277 status = repo.status(match=match)
278 278 if not force:
279 279 repo.checkcommitpatterns(wctx, vdirs, match, status, fail)
280 280 diffopts = patch.difffeatureopts(ui, opts=opts, whitespace=True)
281 281 diffopts.nodates = True
282 282 diffopts.git = True
283 283 diffopts.showfunc = True
284 284 originaldiff = patch.diff(repo, changes=status, opts=diffopts)
285 285 originalchunks = patch.parsepatch(originaldiff)
286 286
287 287 # 1. filter patch, since we are intending to apply subset of it
288 288 try:
289 289 chunks, newopts = filterfn(ui, originalchunks)
290 290 except error.PatchError as err:
291 291 raise error.Abort(_('error parsing patch: %s') % err)
292 292 opts.update(newopts)
293 293
294 294 # We need to keep a backup of files that have been newly added and
295 295 # modified during the recording process because there is a previous
296 296 # version without the edit in the workdir
297 297 newlyaddedandmodifiedfiles = newandmodified(chunks, originalchunks)
298 298 contenders = set()
299 299 for h in chunks:
300 300 try:
301 301 contenders.update(set(h.files()))
302 302 except AttributeError:
303 303 pass
304 304
305 305 changed = status.modified + status.added + status.removed
306 306 newfiles = [f for f in changed if f in contenders]
307 307 if not newfiles:
308 308 ui.status(_('no changes to record\n'))
309 309 return 0
310 310
311 311 modified = set(status.modified)
312 312
313 313 # 2. backup changed files, so we can restore them in the end
314 314
315 315 if backupall:
316 316 tobackup = changed
317 317 else:
318 318 tobackup = [f for f in newfiles if f in modified or f in \
319 319 newlyaddedandmodifiedfiles]
320 320 backups = {}
321 321 if tobackup:
322 322 backupdir = repo.vfs.join('record-backups')
323 323 try:
324 324 os.mkdir(backupdir)
325 325 except OSError as err:
326 326 if err.errno != errno.EEXIST:
327 327 raise
328 328 try:
329 329 # backup continues
330 330 for f in tobackup:
331 331 fd, tmpname = pycompat.mkstemp(prefix=f.replace('/', '_') + '.',
332 332 dir=backupdir)
333 333 os.close(fd)
334 334 ui.debug('backup %r as %r\n' % (f, tmpname))
335 335 util.copyfile(repo.wjoin(f), tmpname, copystat=True)
336 336 backups[f] = tmpname
337 337
338 338 fp = stringio()
339 339 for c in chunks:
340 340 fname = c.filename()
341 341 if fname in backups:
342 342 c.write(fp)
343 343 dopatch = fp.tell()
344 344 fp.seek(0)
345 345
346 346 # 2.5 optionally review / modify patch in text editor
347 347 if opts.get('review', False):
348 348 patchtext = (crecordmod.diffhelptext
349 349 + crecordmod.patchhelptext
350 350 + fp.read())
351 351 reviewedpatch = ui.edit(patchtext, "",
352 352 action="diff",
353 353 repopath=repo.path)
354 354 fp.truncate(0)
355 355 fp.write(reviewedpatch)
356 356 fp.seek(0)
357 357
358 358 [os.unlink(repo.wjoin(c)) for c in newlyaddedandmodifiedfiles]
359 359 # 3a. apply filtered patch to clean repo (clean)
360 360 if backups:
361 361 # Equivalent to hg.revert
362 362 m = scmutil.matchfiles(repo, backups.keys())
363 363 mergemod.update(repo, repo.dirstate.p1(),
364 364 False, True, matcher=m)
365 365
366 366 # 3b. (apply)
367 367 if dopatch:
368 368 try:
369 369 ui.debug('applying patch\n')
370 370 ui.debug(fp.getvalue())
371 371 patch.internalpatch(ui, repo, fp, 1, eolmode=None)
372 372 except error.PatchError as err:
373 373 raise error.Abort(pycompat.bytestr(err))
374 374 del fp
375 375
376 376 # 4. We prepared working directory according to filtered
377 377 # patch. Now is the time to delegate the job to
378 378 # commit/qrefresh or the like!
379 379
380 380 # Make all of the pathnames absolute.
381 381 newfiles = [repo.wjoin(nf) for nf in newfiles]
382 382 return commitfunc(ui, repo, *newfiles, **pycompat.strkwargs(opts))
383 383 finally:
384 384 # 5. finally restore backed-up files
385 385 try:
386 386 dirstate = repo.dirstate
387 387 for realname, tmpname in backups.iteritems():
388 388 ui.debug('restoring %r to %r\n' % (tmpname, realname))
389 389
390 390 if dirstate[realname] == 'n':
391 391 # without normallookup, restoring timestamp
392 392 # may cause partially committed files
393 393 # to be treated as unmodified
394 394 dirstate.normallookup(realname)
395 395
396 396 # copystat=True here and above are a hack to trick any
397 397 # editors that have f open that we haven't modified them.
398 398 #
399 399 # Also note that this racy as an editor could notice the
400 400 # file's mtime before we've finished writing it.
401 401 util.copyfile(tmpname, repo.wjoin(realname), copystat=True)
402 402 os.unlink(tmpname)
403 403 if tobackup:
404 404 os.rmdir(backupdir)
405 405 except OSError:
406 406 pass
407 407
408 408 def recordinwlock(ui, repo, message, match, opts):
409 409 with repo.wlock():
410 410 return recordfunc(ui, repo, message, match, opts)
411 411
412 412 return commit(ui, repo, recordinwlock, pats, opts)
413 413
414 414 class dirnode(object):
415 415 """
416 416 Represent a directory in user working copy with information required for
417 417 the purpose of tersing its status.
418 418
419 419 path is the path to the directory, without a trailing '/'
420 420
421 421 statuses is a set of statuses of all files in this directory (this includes
422 422 all the files in all the subdirectories too)
423 423
424 424 files is a list of files which are direct child of this directory
425 425
426 426 subdirs is a dictionary of sub-directory name as the key and it's own
427 427 dirnode object as the value
428 428 """
429 429
430 430 def __init__(self, dirpath):
431 431 self.path = dirpath
432 432 self.statuses = set([])
433 433 self.files = []
434 434 self.subdirs = {}
435 435
436 436 def _addfileindir(self, filename, status):
437 437 """Add a file in this directory as a direct child."""
438 438 self.files.append((filename, status))
439 439
440 440 def addfile(self, filename, status):
441 441 """
442 442 Add a file to this directory or to its direct parent directory.
443 443
444 444 If the file is not direct child of this directory, we traverse to the
445 445 directory of which this file is a direct child of and add the file
446 446 there.
447 447 """
448 448
449 449 # the filename contains a path separator, it means it's not the direct
450 450 # child of this directory
451 451 if '/' in filename:
452 452 subdir, filep = filename.split('/', 1)
453 453
454 454 # does the dirnode object for subdir exists
455 455 if subdir not in self.subdirs:
456 456 subdirpath = pathutil.join(self.path, subdir)
457 457 self.subdirs[subdir] = dirnode(subdirpath)
458 458
459 459 # try adding the file in subdir
460 460 self.subdirs[subdir].addfile(filep, status)
461 461
462 462 else:
463 463 self._addfileindir(filename, status)
464 464
465 465 if status not in self.statuses:
466 466 self.statuses.add(status)
467 467
468 468 def iterfilepaths(self):
469 469 """Yield (status, path) for files directly under this directory."""
470 470 for f, st in self.files:
471 471 yield st, pathutil.join(self.path, f)
472 472
473 473 def tersewalk(self, terseargs):
474 474 """
475 475 Yield (status, path) obtained by processing the status of this
476 476 dirnode.
477 477
478 478 terseargs is the string of arguments passed by the user with `--terse`
479 479 flag.
480 480
481 481 Following are the cases which can happen:
482 482
483 483 1) All the files in the directory (including all the files in its
484 484 subdirectories) share the same status and the user has asked us to terse
485 485 that status. -> yield (status, dirpath). dirpath will end in '/'.
486 486
487 487 2) Otherwise, we do following:
488 488
489 489 a) Yield (status, filepath) for all the files which are in this
490 490 directory (only the ones in this directory, not the subdirs)
491 491
492 492 b) Recurse the function on all the subdirectories of this
493 493 directory
494 494 """
495 495
496 496 if len(self.statuses) == 1:
497 497 onlyst = self.statuses.pop()
498 498
499 499 # Making sure we terse only when the status abbreviation is
500 500 # passed as terse argument
501 501 if onlyst in terseargs:
502 502 yield onlyst, self.path + '/'
503 503 return
504 504
505 505 # add the files to status list
506 506 for st, fpath in self.iterfilepaths():
507 507 yield st, fpath
508 508
509 509 #recurse on the subdirs
510 510 for dirobj in self.subdirs.values():
511 511 for st, fpath in dirobj.tersewalk(terseargs):
512 512 yield st, fpath
513 513
514 514 def tersedir(statuslist, terseargs):
515 515 """
516 516 Terse the status if all the files in a directory shares the same status.
517 517
518 518 statuslist is scmutil.status() object which contains a list of files for
519 519 each status.
520 520 terseargs is string which is passed by the user as the argument to `--terse`
521 521 flag.
522 522
523 523 The function makes a tree of objects of dirnode class, and at each node it
524 524 stores the information required to know whether we can terse a certain
525 525 directory or not.
526 526 """
527 527 # the order matters here as that is used to produce final list
528 528 allst = ('m', 'a', 'r', 'd', 'u', 'i', 'c')
529 529
530 530 # checking the argument validity
531 531 for s in pycompat.bytestr(terseargs):
532 532 if s not in allst:
533 533 raise error.Abort(_("'%s' not recognized") % s)
534 534
535 535 # creating a dirnode object for the root of the repo
536 536 rootobj = dirnode('')
537 537 pstatus = ('modified', 'added', 'deleted', 'clean', 'unknown',
538 538 'ignored', 'removed')
539 539
540 540 tersedict = {}
541 541 for attrname in pstatus:
542 542 statuschar = attrname[0:1]
543 543 for f in getattr(statuslist, attrname):
544 544 rootobj.addfile(f, statuschar)
545 545 tersedict[statuschar] = []
546 546
547 547 # we won't be tersing the root dir, so add files in it
548 548 for st, fpath in rootobj.iterfilepaths():
549 549 tersedict[st].append(fpath)
550 550
551 551 # process each sub-directory and build tersedict
552 552 for subdir in rootobj.subdirs.values():
553 553 for st, f in subdir.tersewalk(terseargs):
554 554 tersedict[st].append(f)
555 555
556 556 tersedlist = []
557 557 for st in allst:
558 558 tersedict[st].sort()
559 559 tersedlist.append(tersedict[st])
560 560
561 561 return tersedlist
562 562
563 563 def _commentlines(raw):
564 564 '''Surround lineswith a comment char and a new line'''
565 565 lines = raw.splitlines()
566 566 commentedlines = ['# %s' % line for line in lines]
567 567 return '\n'.join(commentedlines) + '\n'
568 568
569 569 def _conflictsmsg(repo):
570 570 mergestate = mergemod.mergestate.read(repo)
571 571 if not mergestate.active():
572 572 return
573 573
574 574 m = scmutil.match(repo[None])
575 575 unresolvedlist = [f for f in mergestate.unresolved() if m(f)]
576 576 if unresolvedlist:
577 577 mergeliststr = '\n'.join(
578 578 [' %s' % util.pathto(repo.root, pycompat.getcwd(), path)
579 579 for path in unresolvedlist])
580 580 msg = _('''Unresolved merge conflicts:
581 581
582 582 %s
583 583
584 584 To mark files as resolved: hg resolve --mark FILE''') % mergeliststr
585 585 else:
586 586 msg = _('No unresolved merge conflicts.')
587 587
588 588 return _commentlines(msg)
589 589
590 590 def _helpmessage(continuecmd, abortcmd):
591 591 msg = _('To continue: %s\n'
592 592 'To abort: %s') % (continuecmd, abortcmd)
593 593 return _commentlines(msg)
594 594
595 595 def _rebasemsg():
596 596 return _helpmessage('hg rebase --continue', 'hg rebase --abort')
597 597
598 598 def _histeditmsg():
599 599 return _helpmessage('hg histedit --continue', 'hg histedit --abort')
600 600
601 601 def _unshelvemsg():
602 602 return _helpmessage('hg unshelve --continue', 'hg unshelve --abort')
603 603
604 604 def _updatecleanmsg(dest=None):
605 605 warning = _('warning: this will discard uncommitted changes')
606 606 return 'hg update --clean %s (%s)' % (dest or '.', warning)
607 607
608 608 def _graftmsg():
609 609 # tweakdefaults requires `update` to have a rev hence the `.`
610 610 return _helpmessage('hg graft --continue', _updatecleanmsg())
611 611
612 612 def _mergemsg():
613 613 # tweakdefaults requires `update` to have a rev hence the `.`
614 614 return _helpmessage('hg commit', _updatecleanmsg())
615 615
616 616 def _bisectmsg():
617 617 msg = _('To mark the changeset good: hg bisect --good\n'
618 618 'To mark the changeset bad: hg bisect --bad\n'
619 619 'To abort: hg bisect --reset\n')
620 620 return _commentlines(msg)
621 621
622 622 def fileexistspredicate(filename):
623 623 return lambda repo: repo.vfs.exists(filename)
624 624
625 625 def _mergepredicate(repo):
626 626 return len(repo[None].parents()) > 1
627 627
628 628 STATES = (
629 629 # (state, predicate to detect states, helpful message function)
630 630 ('histedit', fileexistspredicate('histedit-state'), _histeditmsg),
631 631 ('bisect', fileexistspredicate('bisect.state'), _bisectmsg),
632 632 ('graft', fileexistspredicate('graftstate'), _graftmsg),
633 633 ('unshelve', fileexistspredicate('unshelverebasestate'), _unshelvemsg),
634 634 ('rebase', fileexistspredicate('rebasestate'), _rebasemsg),
635 635 # The merge state is part of a list that will be iterated over.
636 636 # They need to be last because some of the other unfinished states may also
637 637 # be in a merge or update state (eg. rebase, histedit, graft, etc).
638 638 # We want those to have priority.
639 639 ('merge', _mergepredicate, _mergemsg),
640 640 )
641 641
642 642 def _getrepostate(repo):
643 643 # experimental config: commands.status.skipstates
644 644 skip = set(repo.ui.configlist('commands', 'status.skipstates'))
645 645 for state, statedetectionpredicate, msgfn in STATES:
646 646 if state in skip:
647 647 continue
648 648 if statedetectionpredicate(repo):
649 649 return (state, statedetectionpredicate, msgfn)
650 650
651 651 def morestatus(repo, fm):
652 652 statetuple = _getrepostate(repo)
653 653 label = 'status.morestatus'
654 654 if statetuple:
655 655 fm.startitem()
656 656 state, statedetectionpredicate, helpfulmsg = statetuple
657 657 statemsg = _('The repository is in an unfinished *%s* state.') % state
658 658 fm.write('statemsg', '%s\n', _commentlines(statemsg), label=label)
659 659 conmsg = _conflictsmsg(repo)
660 660 if conmsg:
661 661 fm.write('conflictsmsg', '%s\n', conmsg, label=label)
662 662 if helpfulmsg:
663 663 helpmsg = helpfulmsg()
664 664 fm.write('helpmsg', '%s\n', helpmsg, label=label)
665 665
666 666 def findpossible(cmd, table, strict=False):
667 667 """
668 668 Return cmd -> (aliases, command table entry)
669 669 for each matching command.
670 670 Return debug commands (or their aliases) only if no normal command matches.
671 671 """
672 672 choice = {}
673 673 debugchoice = {}
674 674
675 675 if cmd in table:
676 676 # short-circuit exact matches, "log" alias beats "^log|history"
677 677 keys = [cmd]
678 678 else:
679 679 keys = table.keys()
680 680
681 681 allcmds = []
682 682 for e in keys:
683 683 aliases = parsealiases(e)
684 684 allcmds.extend(aliases)
685 685 found = None
686 686 if cmd in aliases:
687 687 found = cmd
688 688 elif not strict:
689 689 for a in aliases:
690 690 if a.startswith(cmd):
691 691 found = a
692 692 break
693 693 if found is not None:
694 694 if aliases[0].startswith("debug") or found.startswith("debug"):
695 695 debugchoice[found] = (aliases, table[e])
696 696 else:
697 697 choice[found] = (aliases, table[e])
698 698
699 699 if not choice and debugchoice:
700 700 choice = debugchoice
701 701
702 702 return choice, allcmds
703 703
704 704 def findcmd(cmd, table, strict=True):
705 705 """Return (aliases, command table entry) for command string."""
706 706 choice, allcmds = findpossible(cmd, table, strict)
707 707
708 708 if cmd in choice:
709 709 return choice[cmd]
710 710
711 711 if len(choice) > 1:
712 712 clist = sorted(choice)
713 713 raise error.AmbiguousCommand(cmd, clist)
714 714
715 715 if choice:
716 716 return list(choice.values())[0]
717 717
718 718 raise error.UnknownCommand(cmd, allcmds)
719 719
720 720 def changebranch(ui, repo, revs, label):
721 721 """ Change the branch name of given revs to label """
722 722
723 723 with repo.wlock(), repo.lock(), repo.transaction('branches'):
724 724 # abort in case of uncommitted merge or dirty wdir
725 725 bailifchanged(repo)
726 726 revs = scmutil.revrange(repo, revs)
727 727 if not revs:
728 728 raise error.Abort("empty revision set")
729 729 roots = repo.revs('roots(%ld)', revs)
730 730 if len(roots) > 1:
731 731 raise error.Abort(_("cannot change branch of non-linear revisions"))
732 732 rewriteutil.precheck(repo, revs, 'change branch of')
733 733
734 734 root = repo[roots.first()]
735 735 if not root.p1().branch() == label and label in repo.branchmap():
736 736 raise error.Abort(_("a branch of the same name already exists"))
737 737
738 738 if repo.revs('merge() and %ld', revs):
739 739 raise error.Abort(_("cannot change branch of a merge commit"))
740 740 if repo.revs('obsolete() and %ld', revs):
741 741 raise error.Abort(_("cannot change branch of a obsolete changeset"))
742 742
743 743 # make sure only topological heads
744 744 if repo.revs('heads(%ld) - head()', revs):
745 745 raise error.Abort(_("cannot change branch in middle of a stack"))
746 746
747 747 replacements = {}
748 748 # avoid import cycle mercurial.cmdutil -> mercurial.context ->
749 749 # mercurial.subrepo -> mercurial.cmdutil
750 750 from . import context
751 751 for rev in revs:
752 752 ctx = repo[rev]
753 753 oldbranch = ctx.branch()
754 754 # check if ctx has same branch
755 755 if oldbranch == label:
756 756 continue
757 757
758 758 def filectxfn(repo, newctx, path):
759 759 try:
760 760 return ctx[path]
761 761 except error.ManifestLookupError:
762 762 return None
763 763
764 764 ui.debug("changing branch of '%s' from '%s' to '%s'\n"
765 765 % (hex(ctx.node()), oldbranch, label))
766 766 extra = ctx.extra()
767 767 extra['branch_change'] = hex(ctx.node())
768 768 # While changing branch of set of linear commits, make sure that
769 769 # we base our commits on new parent rather than old parent which
770 770 # was obsoleted while changing the branch
771 771 p1 = ctx.p1().node()
772 772 p2 = ctx.p2().node()
773 773 if p1 in replacements:
774 774 p1 = replacements[p1][0]
775 775 if p2 in replacements:
776 776 p2 = replacements[p2][0]
777 777
778 778 mc = context.memctx(repo, (p1, p2),
779 779 ctx.description(),
780 780 ctx.files(),
781 781 filectxfn,
782 782 user=ctx.user(),
783 783 date=ctx.date(),
784 784 extra=extra,
785 785 branch=label)
786 786
787 787 commitphase = ctx.phase()
788 788 overrides = {('phases', 'new-commit'): commitphase}
789 789 with repo.ui.configoverride(overrides, 'branch-change'):
790 790 newnode = repo.commitctx(mc)
791 791
792 792 replacements[ctx.node()] = (newnode,)
793 793 ui.debug('new node id is %s\n' % hex(newnode))
794 794
795 795 # create obsmarkers and move bookmarks
796 796 scmutil.cleanupnodes(repo, replacements, 'branch-change')
797 797
798 798 # move the working copy too
799 799 wctx = repo[None]
800 800 # in-progress merge is a bit too complex for now.
801 801 if len(wctx.parents()) == 1:
802 802 newid = replacements.get(wctx.p1().node())
803 803 if newid is not None:
804 804 # avoid import cycle mercurial.cmdutil -> mercurial.hg ->
805 805 # mercurial.cmdutil
806 806 from . import hg
807 807 hg.update(repo, newid[0], quietempty=True)
808 808
809 809 ui.status(_("changed branch on %d changesets\n") % len(replacements))
810 810
811 811 def findrepo(p):
812 812 while not os.path.isdir(os.path.join(p, ".hg")):
813 813 oldp, p = p, os.path.dirname(p)
814 814 if p == oldp:
815 815 return None
816 816
817 817 return p
818 818
819 819 def bailifchanged(repo, merge=True, hint=None):
820 820 """ enforce the precondition that working directory must be clean.
821 821
822 822 'merge' can be set to false if a pending uncommitted merge should be
823 823 ignored (such as when 'update --check' runs).
824 824
825 825 'hint' is the usual hint given to Abort exception.
826 826 """
827 827
828 828 if merge and repo.dirstate.p2() != nullid:
829 829 raise error.Abort(_('outstanding uncommitted merge'), hint=hint)
830 830 modified, added, removed, deleted = repo.status()[:4]
831 831 if modified or added or removed or deleted:
832 832 raise error.Abort(_('uncommitted changes'), hint=hint)
833 833 ctx = repo[None]
834 834 for s in sorted(ctx.substate):
835 835 ctx.sub(s).bailifchanged(hint=hint)
836 836
837 837 def logmessage(ui, opts):
838 838 """ get the log message according to -m and -l option """
839 839 message = opts.get('message')
840 840 logfile = opts.get('logfile')
841 841
842 842 if message and logfile:
843 843 raise error.Abort(_('options --message and --logfile are mutually '
844 844 'exclusive'))
845 845 if not message and logfile:
846 846 try:
847 847 if isstdiofilename(logfile):
848 848 message = ui.fin.read()
849 849 else:
850 850 message = '\n'.join(util.readfile(logfile).splitlines())
851 851 except IOError as inst:
852 852 raise error.Abort(_("can't read commit message '%s': %s") %
853 853 (logfile, encoding.strtolocal(inst.strerror)))
854 854 return message
855 855
856 856 def mergeeditform(ctxorbool, baseformname):
857 857 """return appropriate editform name (referencing a committemplate)
858 858
859 859 'ctxorbool' is either a ctx to be committed, or a bool indicating whether
860 860 merging is committed.
861 861
862 862 This returns baseformname with '.merge' appended if it is a merge,
863 863 otherwise '.normal' is appended.
864 864 """
865 865 if isinstance(ctxorbool, bool):
866 866 if ctxorbool:
867 867 return baseformname + ".merge"
868 868 elif 1 < len(ctxorbool.parents()):
869 869 return baseformname + ".merge"
870 870
871 871 return baseformname + ".normal"
872 872
873 873 def getcommiteditor(edit=False, finishdesc=None, extramsg=None,
874 874 editform='', **opts):
875 875 """get appropriate commit message editor according to '--edit' option
876 876
877 877 'finishdesc' is a function to be called with edited commit message
878 878 (= 'description' of the new changeset) just after editing, but
879 879 before checking empty-ness. It should return actual text to be
880 880 stored into history. This allows to change description before
881 881 storing.
882 882
883 883 'extramsg' is a extra message to be shown in the editor instead of
884 884 'Leave message empty to abort commit' line. 'HG: ' prefix and EOL
885 885 is automatically added.
886 886
887 887 'editform' is a dot-separated list of names, to distinguish
888 888 the purpose of commit text editing.
889 889
890 890 'getcommiteditor' returns 'commitforceeditor' regardless of
891 891 'edit', if one of 'finishdesc' or 'extramsg' is specified, because
892 892 they are specific for usage in MQ.
893 893 """
894 894 if edit or finishdesc or extramsg:
895 895 return lambda r, c, s: commitforceeditor(r, c, s,
896 896 finishdesc=finishdesc,
897 897 extramsg=extramsg,
898 898 editform=editform)
899 899 elif editform:
900 900 return lambda r, c, s: commiteditor(r, c, s, editform=editform)
901 901 else:
902 902 return commiteditor
903 903
904 904 def _escapecommandtemplate(tmpl):
905 905 parts = []
906 906 for typ, start, end in templater.scantemplate(tmpl, raw=True):
907 907 if typ == b'string':
908 908 parts.append(stringutil.escapestr(tmpl[start:end]))
909 909 else:
910 910 parts.append(tmpl[start:end])
911 911 return b''.join(parts)
912 912
913 913 def rendercommandtemplate(ui, tmpl, props):
914 914 r"""Expand a literal template 'tmpl' in a way suitable for command line
915 915
916 916 '\' in outermost string is not taken as an escape character because it
917 917 is a directory separator on Windows.
918 918
919 919 >>> from . import ui as uimod
920 920 >>> ui = uimod.ui()
921 921 >>> rendercommandtemplate(ui, b'c:\\{path}', {b'path': b'foo'})
922 922 'c:\\foo'
923 923 >>> rendercommandtemplate(ui, b'{"c:\\{path}"}', {'path': b'foo'})
924 924 'c:{path}'
925 925 """
926 926 if not tmpl:
927 927 return tmpl
928 928 t = formatter.maketemplater(ui, _escapecommandtemplate(tmpl))
929 929 return t.renderdefault(props)
930 930
931 931 def rendertemplate(ctx, tmpl, props=None):
932 932 """Expand a literal template 'tmpl' byte-string against one changeset
933 933
934 934 Each props item must be a stringify-able value or a callable returning
935 935 such value, i.e. no bare list nor dict should be passed.
936 936 """
937 937 repo = ctx.repo()
938 938 tres = formatter.templateresources(repo.ui, repo)
939 939 t = formatter.maketemplater(repo.ui, tmpl, defaults=templatekw.keywords,
940 940 resources=tres)
941 941 mapping = {'ctx': ctx}
942 942 if props:
943 943 mapping.update(props)
944 944 return t.renderdefault(mapping)
945 945
946 946 def _buildfntemplate(pat, total=None, seqno=None, revwidth=None, pathname=None):
947 947 r"""Convert old-style filename format string to template string
948 948
949 949 >>> _buildfntemplate(b'foo-%b-%n.patch', seqno=0)
950 950 'foo-{reporoot|basename}-{seqno}.patch'
951 951 >>> _buildfntemplate(b'%R{tags % "{tag}"}%H')
952 952 '{rev}{tags % "{tag}"}{node}'
953 953
954 954 '\' in outermost strings has to be escaped because it is a directory
955 955 separator on Windows:
956 956
957 957 >>> _buildfntemplate(b'c:\\tmp\\%R\\%n.patch', seqno=0)
958 958 'c:\\\\tmp\\\\{rev}\\\\{seqno}.patch'
959 959 >>> _buildfntemplate(b'\\\\foo\\bar.patch')
960 960 '\\\\\\\\foo\\\\bar.patch'
961 961 >>> _buildfntemplate(b'\\{tags % "{tag}"}')
962 962 '\\\\{tags % "{tag}"}'
963 963
964 964 but inner strings follow the template rules (i.e. '\' is taken as an
965 965 escape character):
966 966
967 967 >>> _buildfntemplate(br'{"c:\tmp"}', seqno=0)
968 968 '{"c:\\tmp"}'
969 969 """
970 970 expander = {
971 971 b'H': b'{node}',
972 972 b'R': b'{rev}',
973 973 b'h': b'{node|short}',
974 974 b'm': br'{sub(r"[^\w]", "_", desc|firstline)}',
975 975 b'r': b'{if(revwidth, pad(rev, revwidth, "0", left=True), rev)}',
976 976 b'%': b'%',
977 977 b'b': b'{reporoot|basename}',
978 978 }
979 979 if total is not None:
980 980 expander[b'N'] = b'{total}'
981 981 if seqno is not None:
982 982 expander[b'n'] = b'{seqno}'
983 983 if total is not None and seqno is not None:
984 984 expander[b'n'] = b'{pad(seqno, total|stringify|count, "0", left=True)}'
985 985 if pathname is not None:
986 986 expander[b's'] = b'{pathname|basename}'
987 987 expander[b'd'] = b'{if(pathname|dirname, pathname|dirname, ".")}'
988 988 expander[b'p'] = b'{pathname}'
989 989
990 990 newname = []
991 991 for typ, start, end in templater.scantemplate(pat, raw=True):
992 992 if typ != b'string':
993 993 newname.append(pat[start:end])
994 994 continue
995 995 i = start
996 996 while i < end:
997 997 n = pat.find(b'%', i, end)
998 998 if n < 0:
999 999 newname.append(stringutil.escapestr(pat[i:end]))
1000 1000 break
1001 1001 newname.append(stringutil.escapestr(pat[i:n]))
1002 1002 if n + 2 > end:
1003 1003 raise error.Abort(_("incomplete format spec in output "
1004 1004 "filename"))
1005 1005 c = pat[n + 1:n + 2]
1006 1006 i = n + 2
1007 1007 try:
1008 1008 newname.append(expander[c])
1009 1009 except KeyError:
1010 1010 raise error.Abort(_("invalid format spec '%%%s' in output "
1011 1011 "filename") % c)
1012 1012 return ''.join(newname)
1013 1013
1014 1014 def makefilename(ctx, pat, **props):
1015 1015 if not pat:
1016 1016 return pat
1017 1017 tmpl = _buildfntemplate(pat, **props)
1018 1018 # BUG: alias expansion shouldn't be made against template fragments
1019 1019 # rewritten from %-format strings, but we have no easy way to partially
1020 1020 # disable the expansion.
1021 1021 return rendertemplate(ctx, tmpl, pycompat.byteskwargs(props))
1022 1022
1023 1023 def isstdiofilename(pat):
1024 1024 """True if the given pat looks like a filename denoting stdin/stdout"""
1025 1025 return not pat or pat == '-'
1026 1026
1027 1027 class _unclosablefile(object):
1028 1028 def __init__(self, fp):
1029 1029 self._fp = fp
1030 1030
1031 1031 def close(self):
1032 1032 pass
1033 1033
1034 1034 def __iter__(self):
1035 1035 return iter(self._fp)
1036 1036
1037 1037 def __getattr__(self, attr):
1038 1038 return getattr(self._fp, attr)
1039 1039
1040 1040 def __enter__(self):
1041 1041 return self
1042 1042
1043 1043 def __exit__(self, exc_type, exc_value, exc_tb):
1044 1044 pass
1045 1045
1046 1046 def makefileobj(ctx, pat, mode='wb', **props):
1047 1047 writable = mode not in ('r', 'rb')
1048 1048
1049 1049 if isstdiofilename(pat):
1050 1050 repo = ctx.repo()
1051 1051 if writable:
1052 1052 fp = repo.ui.fout
1053 1053 else:
1054 1054 fp = repo.ui.fin
1055 1055 return _unclosablefile(fp)
1056 1056 fn = makefilename(ctx, pat, **props)
1057 1057 return open(fn, mode)
1058 1058
1059 1059 def openrevlog(repo, cmd, file_, opts):
1060 1060 """opens the changelog, manifest, a filelog or a given revlog"""
1061 1061 cl = opts['changelog']
1062 1062 mf = opts['manifest']
1063 1063 dir = opts['dir']
1064 1064 msg = None
1065 1065 if cl and mf:
1066 1066 msg = _('cannot specify --changelog and --manifest at the same time')
1067 1067 elif cl and dir:
1068 1068 msg = _('cannot specify --changelog and --dir at the same time')
1069 1069 elif cl or mf or dir:
1070 1070 if file_:
1071 1071 msg = _('cannot specify filename with --changelog or --manifest')
1072 1072 elif not repo:
1073 1073 msg = _('cannot specify --changelog or --manifest or --dir '
1074 1074 'without a repository')
1075 1075 if msg:
1076 1076 raise error.Abort(msg)
1077 1077
1078 1078 r = None
1079 1079 if repo:
1080 1080 if cl:
1081 1081 r = repo.unfiltered().changelog
1082 1082 elif dir:
1083 1083 if 'treemanifest' not in repo.requirements:
1084 1084 raise error.Abort(_("--dir can only be used on repos with "
1085 1085 "treemanifest enabled"))
1086 1086 if not dir.endswith('/'):
1087 1087 dir = dir + '/'
1088 1088 dirlog = repo.manifestlog._revlog.dirlog(dir)
1089 1089 if len(dirlog):
1090 1090 r = dirlog
1091 1091 elif mf:
1092 1092 r = repo.manifestlog._revlog
1093 1093 elif file_:
1094 1094 filelog = repo.file(file_)
1095 1095 if len(filelog):
1096 1096 r = filelog
1097 1097 if not r:
1098 1098 if not file_:
1099 1099 raise error.CommandError(cmd, _('invalid arguments'))
1100 1100 if not os.path.isfile(file_):
1101 1101 raise error.Abort(_("revlog '%s' not found") % file_)
1102 1102 r = revlog.revlog(vfsmod.vfs(pycompat.getcwd(), audit=False),
1103 1103 file_[:-2] + ".i")
1104 1104 return r
1105 1105
1106 1106 def copy(ui, repo, pats, opts, rename=False):
1107 1107 # called with the repo lock held
1108 1108 #
1109 1109 # hgsep => pathname that uses "/" to separate directories
1110 1110 # ossep => pathname that uses os.sep to separate directories
1111 1111 cwd = repo.getcwd()
1112 1112 targets = {}
1113 1113 after = opts.get("after")
1114 1114 dryrun = opts.get("dry_run")
1115 1115 wctx = repo[None]
1116 1116
1117 1117 def walkpat(pat):
1118 1118 srcs = []
1119 1119 if after:
1120 1120 badstates = '?'
1121 1121 else:
1122 1122 badstates = '?r'
1123 1123 m = scmutil.match(wctx, [pat], opts, globbed=True)
1124 1124 for abs in wctx.walk(m):
1125 1125 state = repo.dirstate[abs]
1126 1126 rel = m.rel(abs)
1127 1127 exact = m.exact(abs)
1128 1128 if state in badstates:
1129 1129 if exact and state == '?':
1130 1130 ui.warn(_('%s: not copying - file is not managed\n') % rel)
1131 1131 if exact and state == 'r':
1132 1132 ui.warn(_('%s: not copying - file has been marked for'
1133 1133 ' remove\n') % rel)
1134 1134 continue
1135 1135 # abs: hgsep
1136 1136 # rel: ossep
1137 1137 srcs.append((abs, rel, exact))
1138 1138 return srcs
1139 1139
1140 1140 # abssrc: hgsep
1141 1141 # relsrc: ossep
1142 1142 # otarget: ossep
1143 1143 def copyfile(abssrc, relsrc, otarget, exact):
1144 1144 abstarget = pathutil.canonpath(repo.root, cwd, otarget)
1145 1145 if '/' in abstarget:
1146 1146 # We cannot normalize abstarget itself, this would prevent
1147 1147 # case only renames, like a => A.
1148 1148 abspath, absname = abstarget.rsplit('/', 1)
1149 1149 abstarget = repo.dirstate.normalize(abspath) + '/' + absname
1150 1150 reltarget = repo.pathto(abstarget, cwd)
1151 1151 target = repo.wjoin(abstarget)
1152 1152 src = repo.wjoin(abssrc)
1153 1153 state = repo.dirstate[abstarget]
1154 1154
1155 1155 scmutil.checkportable(ui, abstarget)
1156 1156
1157 1157 # check for collisions
1158 1158 prevsrc = targets.get(abstarget)
1159 1159 if prevsrc is not None:
1160 1160 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
1161 1161 (reltarget, repo.pathto(abssrc, cwd),
1162 1162 repo.pathto(prevsrc, cwd)))
1163 1163 return
1164 1164
1165 1165 # check for overwrites
1166 1166 exists = os.path.lexists(target)
1167 1167 samefile = False
1168 1168 if exists and abssrc != abstarget:
1169 1169 if (repo.dirstate.normalize(abssrc) ==
1170 1170 repo.dirstate.normalize(abstarget)):
1171 1171 if not rename:
1172 1172 ui.warn(_("%s: can't copy - same file\n") % reltarget)
1173 1173 return
1174 1174 exists = False
1175 1175 samefile = True
1176 1176
1177 1177 if not after and exists or after and state in 'mn':
1178 1178 if not opts['force']:
1179 1179 if state in 'mn':
1180 1180 msg = _('%s: not overwriting - file already committed\n')
1181 1181 if after:
1182 1182 flags = '--after --force'
1183 1183 else:
1184 1184 flags = '--force'
1185 1185 if rename:
1186 1186 hint = _('(hg rename %s to replace the file by '
1187 1187 'recording a rename)\n') % flags
1188 1188 else:
1189 1189 hint = _('(hg copy %s to replace the file by '
1190 1190 'recording a copy)\n') % flags
1191 1191 else:
1192 1192 msg = _('%s: not overwriting - file exists\n')
1193 1193 if rename:
1194 1194 hint = _('(hg rename --after to record the rename)\n')
1195 1195 else:
1196 1196 hint = _('(hg copy --after to record the copy)\n')
1197 1197 ui.warn(msg % reltarget)
1198 1198 ui.warn(hint)
1199 1199 return
1200 1200
1201 1201 if after:
1202 1202 if not exists:
1203 1203 if rename:
1204 1204 ui.warn(_('%s: not recording move - %s does not exist\n') %
1205 1205 (relsrc, reltarget))
1206 1206 else:
1207 1207 ui.warn(_('%s: not recording copy - %s does not exist\n') %
1208 1208 (relsrc, reltarget))
1209 1209 return
1210 1210 elif not dryrun:
1211 1211 try:
1212 1212 if exists:
1213 1213 os.unlink(target)
1214 1214 targetdir = os.path.dirname(target) or '.'
1215 1215 if not os.path.isdir(targetdir):
1216 1216 os.makedirs(targetdir)
1217 1217 if samefile:
1218 1218 tmp = target + "~hgrename"
1219 1219 os.rename(src, tmp)
1220 1220 os.rename(tmp, target)
1221 1221 else:
1222 1222 # Preserve stat info on renames, not on copies; this matches
1223 1223 # Linux CLI behavior.
1224 1224 util.copyfile(src, target, copystat=rename)
1225 1225 srcexists = True
1226 1226 except IOError as inst:
1227 1227 if inst.errno == errno.ENOENT:
1228 1228 ui.warn(_('%s: deleted in working directory\n') % relsrc)
1229 1229 srcexists = False
1230 1230 else:
1231 1231 ui.warn(_('%s: cannot copy - %s\n') %
1232 1232 (relsrc, encoding.strtolocal(inst.strerror)))
1233 1233 return True # report a failure
1234 1234
1235 1235 if ui.verbose or not exact:
1236 1236 if rename:
1237 1237 ui.status(_('moving %s to %s\n') % (relsrc, reltarget))
1238 1238 else:
1239 1239 ui.status(_('copying %s to %s\n') % (relsrc, reltarget))
1240 1240
1241 1241 targets[abstarget] = abssrc
1242 1242
1243 1243 # fix up dirstate
1244 1244 scmutil.dirstatecopy(ui, repo, wctx, abssrc, abstarget,
1245 1245 dryrun=dryrun, cwd=cwd)
1246 1246 if rename and not dryrun:
1247 1247 if not after and srcexists and not samefile:
1248 1248 repo.wvfs.unlinkpath(abssrc)
1249 1249 wctx.forget([abssrc])
1250 1250
1251 1251 # pat: ossep
1252 1252 # dest ossep
1253 1253 # srcs: list of (hgsep, hgsep, ossep, bool)
1254 1254 # return: function that takes hgsep and returns ossep
1255 1255 def targetpathfn(pat, dest, srcs):
1256 1256 if os.path.isdir(pat):
1257 1257 abspfx = pathutil.canonpath(repo.root, cwd, pat)
1258 1258 abspfx = util.localpath(abspfx)
1259 1259 if destdirexists:
1260 1260 striplen = len(os.path.split(abspfx)[0])
1261 1261 else:
1262 1262 striplen = len(abspfx)
1263 1263 if striplen:
1264 1264 striplen += len(pycompat.ossep)
1265 1265 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
1266 1266 elif destdirexists:
1267 1267 res = lambda p: os.path.join(dest,
1268 1268 os.path.basename(util.localpath(p)))
1269 1269 else:
1270 1270 res = lambda p: dest
1271 1271 return res
1272 1272
1273 1273 # pat: ossep
1274 1274 # dest ossep
1275 1275 # srcs: list of (hgsep, hgsep, ossep, bool)
1276 1276 # return: function that takes hgsep and returns ossep
1277 1277 def targetpathafterfn(pat, dest, srcs):
1278 1278 if matchmod.patkind(pat):
1279 1279 # a mercurial pattern
1280 1280 res = lambda p: os.path.join(dest,
1281 1281 os.path.basename(util.localpath(p)))
1282 1282 else:
1283 1283 abspfx = pathutil.canonpath(repo.root, cwd, pat)
1284 1284 if len(abspfx) < len(srcs[0][0]):
1285 1285 # A directory. Either the target path contains the last
1286 1286 # component of the source path or it does not.
1287 1287 def evalpath(striplen):
1288 1288 score = 0
1289 1289 for s in srcs:
1290 1290 t = os.path.join(dest, util.localpath(s[0])[striplen:])
1291 1291 if os.path.lexists(t):
1292 1292 score += 1
1293 1293 return score
1294 1294
1295 1295 abspfx = util.localpath(abspfx)
1296 1296 striplen = len(abspfx)
1297 1297 if striplen:
1298 1298 striplen += len(pycompat.ossep)
1299 1299 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
1300 1300 score = evalpath(striplen)
1301 1301 striplen1 = len(os.path.split(abspfx)[0])
1302 1302 if striplen1:
1303 1303 striplen1 += len(pycompat.ossep)
1304 1304 if evalpath(striplen1) > score:
1305 1305 striplen = striplen1
1306 1306 res = lambda p: os.path.join(dest,
1307 1307 util.localpath(p)[striplen:])
1308 1308 else:
1309 1309 # a file
1310 1310 if destdirexists:
1311 1311 res = lambda p: os.path.join(dest,
1312 1312 os.path.basename(util.localpath(p)))
1313 1313 else:
1314 1314 res = lambda p: dest
1315 1315 return res
1316 1316
1317 1317 pats = scmutil.expandpats(pats)
1318 1318 if not pats:
1319 1319 raise error.Abort(_('no source or destination specified'))
1320 1320 if len(pats) == 1:
1321 1321 raise error.Abort(_('no destination specified'))
1322 1322 dest = pats.pop()
1323 1323 destdirexists = os.path.isdir(dest) and not os.path.islink(dest)
1324 1324 if not destdirexists:
1325 1325 if len(pats) > 1 or matchmod.patkind(pats[0]):
1326 1326 raise error.Abort(_('with multiple sources, destination must be an '
1327 1327 'existing directory'))
1328 1328 if util.endswithsep(dest):
1329 1329 raise error.Abort(_('destination %s is not a directory') % dest)
1330 1330
1331 1331 tfn = targetpathfn
1332 1332 if after:
1333 1333 tfn = targetpathafterfn
1334 1334 copylist = []
1335 1335 for pat in pats:
1336 1336 srcs = walkpat(pat)
1337 1337 if not srcs:
1338 1338 continue
1339 1339 copylist.append((tfn(pat, dest, srcs), srcs))
1340 1340 if not copylist:
1341 1341 raise error.Abort(_('no files to copy'))
1342 1342
1343 1343 errors = 0
1344 1344 for targetpath, srcs in copylist:
1345 1345 for abssrc, relsrc, exact in srcs:
1346 1346 if copyfile(abssrc, relsrc, targetpath(abssrc), exact):
1347 1347 errors += 1
1348 1348
1349 1349 if errors:
1350 1350 ui.warn(_('(consider using --after)\n'))
1351 1351
1352 1352 return errors != 0
1353 1353
1354 1354 ## facility to let extension process additional data into an import patch
1355 1355 # list of identifier to be executed in order
1356 1356 extrapreimport = [] # run before commit
1357 1357 extrapostimport = [] # run after commit
1358 1358 # mapping from identifier to actual import function
1359 1359 #
1360 1360 # 'preimport' are run before the commit is made and are provided the following
1361 1361 # arguments:
1362 1362 # - repo: the localrepository instance,
1363 1363 # - patchdata: data extracted from patch header (cf m.patch.patchheadermap),
1364 1364 # - extra: the future extra dictionary of the changeset, please mutate it,
1365 1365 # - opts: the import options.
1366 1366 # XXX ideally, we would just pass an ctx ready to be computed, that would allow
1367 1367 # mutation of in memory commit and more. Feel free to rework the code to get
1368 1368 # there.
1369 1369 extrapreimportmap = {}
1370 1370 # 'postimport' are run after the commit is made and are provided the following
1371 1371 # argument:
1372 1372 # - ctx: the changectx created by import.
1373 1373 extrapostimportmap = {}
1374 1374
1375 1375 def tryimportone(ui, repo, patchdata, parents, opts, msgs, updatefunc):
1376 1376 """Utility function used by commands.import to import a single patch
1377 1377
1378 1378 This function is explicitly defined here to help the evolve extension to
1379 1379 wrap this part of the import logic.
1380 1380
1381 1381 The API is currently a bit ugly because it a simple code translation from
1382 1382 the import command. Feel free to make it better.
1383 1383
1384 1384 :patchdata: a dictionary containing parsed patch data (such as from
1385 1385 ``patch.extract()``)
1386 1386 :parents: nodes that will be parent of the created commit
1387 1387 :opts: the full dict of option passed to the import command
1388 1388 :msgs: list to save commit message to.
1389 1389 (used in case we need to save it when failing)
1390 1390 :updatefunc: a function that update a repo to a given node
1391 1391 updatefunc(<repo>, <node>)
1392 1392 """
1393 1393 # avoid cycle context -> subrepo -> cmdutil
1394 1394 from . import context
1395 1395
1396 1396 tmpname = patchdata.get('filename')
1397 1397 message = patchdata.get('message')
1398 1398 user = opts.get('user') or patchdata.get('user')
1399 1399 date = opts.get('date') or patchdata.get('date')
1400 1400 branch = patchdata.get('branch')
1401 1401 nodeid = patchdata.get('nodeid')
1402 1402 p1 = patchdata.get('p1')
1403 1403 p2 = patchdata.get('p2')
1404 1404
1405 1405 nocommit = opts.get('no_commit')
1406 1406 importbranch = opts.get('import_branch')
1407 1407 update = not opts.get('bypass')
1408 1408 strip = opts["strip"]
1409 1409 prefix = opts["prefix"]
1410 1410 sim = float(opts.get('similarity') or 0)
1411 1411
1412 1412 if not tmpname:
1413 1413 return None, None, False
1414 1414
1415 1415 rejects = False
1416 1416
1417 1417 cmdline_message = logmessage(ui, opts)
1418 1418 if cmdline_message:
1419 1419 # pickup the cmdline msg
1420 1420 message = cmdline_message
1421 1421 elif message:
1422 1422 # pickup the patch msg
1423 1423 message = message.strip()
1424 1424 else:
1425 1425 # launch the editor
1426 1426 message = None
1427 1427 ui.debug('message:\n%s\n' % (message or ''))
1428 1428
1429 1429 if len(parents) == 1:
1430 1430 parents.append(repo[nullid])
1431 1431 if opts.get('exact'):
1432 1432 if not nodeid or not p1:
1433 1433 raise error.Abort(_('not a Mercurial patch'))
1434 1434 p1 = repo[p1]
1435 1435 p2 = repo[p2 or nullid]
1436 1436 elif p2:
1437 1437 try:
1438 1438 p1 = repo[p1]
1439 1439 p2 = repo[p2]
1440 1440 # Without any options, consider p2 only if the
1441 1441 # patch is being applied on top of the recorded
1442 1442 # first parent.
1443 1443 if p1 != parents[0]:
1444 1444 p1 = parents[0]
1445 1445 p2 = repo[nullid]
1446 1446 except error.RepoError:
1447 1447 p1, p2 = parents
1448 1448 if p2.node() == nullid:
1449 1449 ui.warn(_("warning: import the patch as a normal revision\n"
1450 1450 "(use --exact to import the patch as a merge)\n"))
1451 1451 else:
1452 1452 p1, p2 = parents
1453 1453
1454 1454 n = None
1455 1455 if update:
1456 1456 if p1 != parents[0]:
1457 1457 updatefunc(repo, p1.node())
1458 1458 if p2 != parents[1]:
1459 1459 repo.setparents(p1.node(), p2.node())
1460 1460
1461 1461 if opts.get('exact') or importbranch:
1462 1462 repo.dirstate.setbranch(branch or 'default')
1463 1463
1464 1464 partial = opts.get('partial', False)
1465 1465 files = set()
1466 1466 try:
1467 1467 patch.patch(ui, repo, tmpname, strip=strip, prefix=prefix,
1468 1468 files=files, eolmode=None, similarity=sim / 100.0)
1469 1469 except error.PatchError as e:
1470 1470 if not partial:
1471 1471 raise error.Abort(pycompat.bytestr(e))
1472 1472 if partial:
1473 1473 rejects = True
1474 1474
1475 1475 files = list(files)
1476 1476 if nocommit:
1477 1477 if message:
1478 1478 msgs.append(message)
1479 1479 else:
1480 1480 if opts.get('exact') or p2:
1481 1481 # If you got here, you either use --force and know what
1482 1482 # you are doing or used --exact or a merge patch while
1483 1483 # being updated to its first parent.
1484 1484 m = None
1485 1485 else:
1486 1486 m = scmutil.matchfiles(repo, files or [])
1487 1487 editform = mergeeditform(repo[None], 'import.normal')
1488 1488 if opts.get('exact'):
1489 1489 editor = None
1490 1490 else:
1491 1491 editor = getcommiteditor(editform=editform,
1492 1492 **pycompat.strkwargs(opts))
1493 1493 extra = {}
1494 1494 for idfunc in extrapreimport:
1495 1495 extrapreimportmap[idfunc](repo, patchdata, extra, opts)
1496 1496 overrides = {}
1497 1497 if partial:
1498 1498 overrides[('ui', 'allowemptycommit')] = True
1499 1499 with repo.ui.configoverride(overrides, 'import'):
1500 1500 n = repo.commit(message, user,
1501 1501 date, match=m,
1502 1502 editor=editor, extra=extra)
1503 1503 for idfunc in extrapostimport:
1504 1504 extrapostimportmap[idfunc](repo[n])
1505 1505 else:
1506 1506 if opts.get('exact') or importbranch:
1507 1507 branch = branch or 'default'
1508 1508 else:
1509 1509 branch = p1.branch()
1510 1510 store = patch.filestore()
1511 1511 try:
1512 1512 files = set()
1513 1513 try:
1514 1514 patch.patchrepo(ui, repo, p1, store, tmpname, strip, prefix,
1515 1515 files, eolmode=None)
1516 1516 except error.PatchError as e:
1517 1517 raise error.Abort(stringutil.forcebytestr(e))
1518 1518 if opts.get('exact'):
1519 1519 editor = None
1520 1520 else:
1521 1521 editor = getcommiteditor(editform='import.bypass')
1522 1522 memctx = context.memctx(repo, (p1.node(), p2.node()),
1523 1523 message,
1524 1524 files=files,
1525 1525 filectxfn=store,
1526 1526 user=user,
1527 1527 date=date,
1528 1528 branch=branch,
1529 1529 editor=editor)
1530 1530 n = memctx.commit()
1531 1531 finally:
1532 1532 store.close()
1533 1533 if opts.get('exact') and nocommit:
1534 1534 # --exact with --no-commit is still useful in that it does merge
1535 1535 # and branch bits
1536 1536 ui.warn(_("warning: can't check exact import with --no-commit\n"))
1537 1537 elif opts.get('exact') and (not n or hex(n) != nodeid):
1538 1538 raise error.Abort(_('patch is damaged or loses information'))
1539 1539 msg = _('applied to working directory')
1540 1540 if n:
1541 1541 # i18n: refers to a short changeset id
1542 1542 msg = _('created %s') % short(n)
1543 1543 return msg, n, rejects
1544 1544
1545 1545 # facility to let extensions include additional data in an exported patch
1546 1546 # list of identifiers to be executed in order
1547 1547 extraexport = []
1548 1548 # mapping from identifier to actual export function
1549 1549 # function as to return a string to be added to the header or None
1550 1550 # it is given two arguments (sequencenumber, changectx)
1551 1551 extraexportmap = {}
1552 1552
1553 1553 def _exportsingle(repo, ctx, fm, match, switch_parent, seqno, diffopts):
1554 1554 node = scmutil.binnode(ctx)
1555 1555 parents = [p.node() for p in ctx.parents() if p]
1556 1556 branch = ctx.branch()
1557 1557 if switch_parent:
1558 1558 parents.reverse()
1559 1559
1560 1560 if parents:
1561 1561 prev = parents[0]
1562 1562 else:
1563 1563 prev = nullid
1564 1564
1565 1565 fm.context(ctx=ctx)
1566 1566 fm.plain('# HG changeset patch\n')
1567 1567 fm.write('user', '# User %s\n', ctx.user())
1568 1568 fm.plain('# Date %d %d\n' % ctx.date())
1569 1569 fm.write('date', '# %s\n', fm.formatdate(ctx.date()))
1570 1570 fm.condwrite(branch and branch != 'default',
1571 1571 'branch', '# Branch %s\n', branch)
1572 1572 fm.write('node', '# Node ID %s\n', hex(node))
1573 1573 fm.plain('# Parent %s\n' % hex(prev))
1574 1574 if len(parents) > 1:
1575 1575 fm.plain('# Parent %s\n' % hex(parents[1]))
1576 1576 fm.data(parents=fm.formatlist(pycompat.maplist(hex, parents), name='node'))
1577 1577
1578 1578 # TODO: redesign extraexportmap function to support formatter
1579 1579 for headerid in extraexport:
1580 1580 header = extraexportmap[headerid](seqno, ctx)
1581 1581 if header is not None:
1582 1582 fm.plain('# %s\n' % header)
1583 1583
1584 1584 fm.write('desc', '%s\n', ctx.description().rstrip())
1585 1585 fm.plain('\n')
1586 1586
1587 1587 if fm.isplain():
1588 1588 chunkiter = patch.diffui(repo, prev, node, match, opts=diffopts)
1589 1589 for chunk, label in chunkiter:
1590 1590 fm.plain(chunk, label=label)
1591 1591 else:
1592 1592 chunkiter = patch.diff(repo, prev, node, match, opts=diffopts)
1593 1593 # TODO: make it structured?
1594 1594 fm.data(diff=b''.join(chunkiter))
1595 1595
1596 1596 def _exportfile(repo, revs, fm, dest, switch_parent, diffopts, match):
1597 1597 """Export changesets to stdout or a single file"""
1598 1598 for seqno, rev in enumerate(revs, 1):
1599 1599 ctx = repo[rev]
1600 1600 if not dest.startswith('<'):
1601 1601 repo.ui.note("%s\n" % dest)
1602 1602 fm.startitem()
1603 1603 _exportsingle(repo, ctx, fm, match, switch_parent, seqno, diffopts)
1604 1604
1605 1605 def _exportfntemplate(repo, revs, basefm, fntemplate, switch_parent, diffopts,
1606 1606 match):
1607 1607 """Export changesets to possibly multiple files"""
1608 1608 total = len(revs)
1609 1609 revwidth = max(len(str(rev)) for rev in revs)
1610 1610 filemap = util.sortdict() # filename: [(seqno, rev), ...]
1611 1611
1612 1612 for seqno, rev in enumerate(revs, 1):
1613 1613 ctx = repo[rev]
1614 1614 dest = makefilename(ctx, fntemplate,
1615 1615 total=total, seqno=seqno, revwidth=revwidth)
1616 1616 filemap.setdefault(dest, []).append((seqno, rev))
1617 1617
1618 1618 for dest in filemap:
1619 1619 with formatter.maybereopen(basefm, dest) as fm:
1620 1620 repo.ui.note("%s\n" % dest)
1621 1621 for seqno, rev in filemap[dest]:
1622 1622 fm.startitem()
1623 1623 ctx = repo[rev]
1624 1624 _exportsingle(repo, ctx, fm, match, switch_parent, seqno,
1625 1625 diffopts)
1626 1626
1627 1627 def export(repo, revs, basefm, fntemplate='hg-%h.patch', switch_parent=False,
1628 1628 opts=None, match=None):
1629 1629 '''export changesets as hg patches
1630 1630
1631 1631 Args:
1632 1632 repo: The repository from which we're exporting revisions.
1633 1633 revs: A list of revisions to export as revision numbers.
1634 1634 basefm: A formatter to which patches should be written.
1635 1635 fntemplate: An optional string to use for generating patch file names.
1636 1636 switch_parent: If True, show diffs against second parent when not nullid.
1637 1637 Default is false, which always shows diff against p1.
1638 1638 opts: diff options to use for generating the patch.
1639 1639 match: If specified, only export changes to files matching this matcher.
1640 1640
1641 1641 Returns:
1642 1642 Nothing.
1643 1643
1644 1644 Side Effect:
1645 1645 "HG Changeset Patch" data is emitted to one of the following
1646 1646 destinations:
1647 1647 fntemplate specified: Each rev is written to a unique file named using
1648 1648 the given template.
1649 1649 Otherwise: All revs will be written to basefm.
1650 1650 '''
1651 1651 scmutil.prefetchfiles(repo, revs, match)
1652 1652
1653 1653 if not fntemplate:
1654 1654 _exportfile(repo, revs, basefm, '<unnamed>', switch_parent, opts, match)
1655 1655 else:
1656 1656 _exportfntemplate(repo, revs, basefm, fntemplate, switch_parent, opts,
1657 1657 match)
1658 1658
1659 1659 def exportfile(repo, revs, fp, switch_parent=False, opts=None, match=None):
1660 1660 """Export changesets to the given file stream"""
1661 1661 scmutil.prefetchfiles(repo, revs, match)
1662 1662
1663 1663 dest = getattr(fp, 'name', '<unnamed>')
1664 1664 with formatter.formatter(repo.ui, fp, 'export', {}) as fm:
1665 1665 _exportfile(repo, revs, fm, dest, switch_parent, opts, match)
1666 1666
1667 1667 def showmarker(fm, marker, index=None):
1668 1668 """utility function to display obsolescence marker in a readable way
1669 1669
1670 1670 To be used by debug function."""
1671 1671 if index is not None:
1672 1672 fm.write('index', '%i ', index)
1673 1673 fm.write('prednode', '%s ', hex(marker.prednode()))
1674 1674 succs = marker.succnodes()
1675 1675 fm.condwrite(succs, 'succnodes', '%s ',
1676 1676 fm.formatlist(map(hex, succs), name='node'))
1677 1677 fm.write('flag', '%X ', marker.flags())
1678 1678 parents = marker.parentnodes()
1679 1679 if parents is not None:
1680 1680 fm.write('parentnodes', '{%s} ',
1681 1681 fm.formatlist(map(hex, parents), name='node', sep=', '))
1682 1682 fm.write('date', '(%s) ', fm.formatdate(marker.date()))
1683 1683 meta = marker.metadata().copy()
1684 1684 meta.pop('date', None)
1685 1685 smeta = util.rapply(pycompat.maybebytestr, meta)
1686 1686 fm.write('metadata', '{%s}', fm.formatdict(smeta, fmt='%r: %r', sep=', '))
1687 1687 fm.plain('\n')
1688 1688
1689 1689 def finddate(ui, repo, date):
1690 1690 """Find the tipmost changeset that matches the given date spec"""
1691 1691
1692 1692 df = dateutil.matchdate(date)
1693 1693 m = scmutil.matchall(repo)
1694 1694 results = {}
1695 1695
1696 1696 def prep(ctx, fns):
1697 1697 d = ctx.date()
1698 1698 if df(d[0]):
1699 1699 results[ctx.rev()] = d
1700 1700
1701 1701 for ctx in walkchangerevs(repo, m, {'rev': None}, prep):
1702 1702 rev = ctx.rev()
1703 1703 if rev in results:
1704 1704 ui.status(_("found revision %s from %s\n") %
1705 1705 (rev, dateutil.datestr(results[rev])))
1706 1706 return '%d' % rev
1707 1707
1708 1708 raise error.Abort(_("revision matching date not found"))
1709 1709
1710 1710 def increasingwindows(windowsize=8, sizelimit=512):
1711 1711 while True:
1712 1712 yield windowsize
1713 1713 if windowsize < sizelimit:
1714 1714 windowsize *= 2
1715 1715
1716 1716 def _walkrevs(repo, opts):
1717 1717 # Default --rev value depends on --follow but --follow behavior
1718 1718 # depends on revisions resolved from --rev...
1719 1719 follow = opts.get('follow') or opts.get('follow_first')
1720 1720 if opts.get('rev'):
1721 1721 revs = scmutil.revrange(repo, opts['rev'])
1722 1722 elif follow and repo.dirstate.p1() == nullid:
1723 1723 revs = smartset.baseset()
1724 1724 elif follow:
1725 1725 revs = repo.revs('reverse(:.)')
1726 1726 else:
1727 1727 revs = smartset.spanset(repo)
1728 1728 revs.reverse()
1729 1729 return revs
1730 1730
1731 1731 class FileWalkError(Exception):
1732 1732 pass
1733 1733
1734 1734 def walkfilerevs(repo, match, follow, revs, fncache):
1735 1735 '''Walks the file history for the matched files.
1736 1736
1737 1737 Returns the changeset revs that are involved in the file history.
1738 1738
1739 1739 Throws FileWalkError if the file history can't be walked using
1740 1740 filelogs alone.
1741 1741 '''
1742 1742 wanted = set()
1743 1743 copies = []
1744 1744 minrev, maxrev = min(revs), max(revs)
1745 1745 def filerevgen(filelog, last):
1746 1746 """
1747 1747 Only files, no patterns. Check the history of each file.
1748 1748
1749 1749 Examines filelog entries within minrev, maxrev linkrev range
1750 1750 Returns an iterator yielding (linkrev, parentlinkrevs, copied)
1751 1751 tuples in backwards order
1752 1752 """
1753 1753 cl_count = len(repo)
1754 1754 revs = []
1755 1755 for j in xrange(0, last + 1):
1756 1756 linkrev = filelog.linkrev(j)
1757 1757 if linkrev < minrev:
1758 1758 continue
1759 1759 # only yield rev for which we have the changelog, it can
1760 1760 # happen while doing "hg log" during a pull or commit
1761 1761 if linkrev >= cl_count:
1762 1762 break
1763 1763
1764 1764 parentlinkrevs = []
1765 1765 for p in filelog.parentrevs(j):
1766 1766 if p != nullrev:
1767 1767 parentlinkrevs.append(filelog.linkrev(p))
1768 1768 n = filelog.node(j)
1769 1769 revs.append((linkrev, parentlinkrevs,
1770 1770 follow and filelog.renamed(n)))
1771 1771
1772 1772 return reversed(revs)
1773 1773 def iterfiles():
1774 1774 pctx = repo['.']
1775 1775 for filename in match.files():
1776 1776 if follow:
1777 1777 if filename not in pctx:
1778 1778 raise error.Abort(_('cannot follow file not in parent '
1779 1779 'revision: "%s"') % filename)
1780 1780 yield filename, pctx[filename].filenode()
1781 1781 else:
1782 1782 yield filename, None
1783 1783 for filename_node in copies:
1784 1784 yield filename_node
1785 1785
1786 1786 for file_, node in iterfiles():
1787 1787 filelog = repo.file(file_)
1788 1788 if not len(filelog):
1789 1789 if node is None:
1790 1790 # A zero count may be a directory or deleted file, so
1791 1791 # try to find matching entries on the slow path.
1792 1792 if follow:
1793 1793 raise error.Abort(
1794 1794 _('cannot follow nonexistent file: "%s"') % file_)
1795 1795 raise FileWalkError("Cannot walk via filelog")
1796 1796 else:
1797 1797 continue
1798 1798
1799 1799 if node is None:
1800 1800 last = len(filelog) - 1
1801 1801 else:
1802 1802 last = filelog.rev(node)
1803 1803
1804 1804 # keep track of all ancestors of the file
1805 1805 ancestors = {filelog.linkrev(last)}
1806 1806
1807 1807 # iterate from latest to oldest revision
1808 1808 for rev, flparentlinkrevs, copied in filerevgen(filelog, last):
1809 1809 if not follow:
1810 1810 if rev > maxrev:
1811 1811 continue
1812 1812 else:
1813 1813 # Note that last might not be the first interesting
1814 1814 # rev to us:
1815 1815 # if the file has been changed after maxrev, we'll
1816 1816 # have linkrev(last) > maxrev, and we still need
1817 1817 # to explore the file graph
1818 1818 if rev not in ancestors:
1819 1819 continue
1820 1820 # XXX insert 1327 fix here
1821 1821 if flparentlinkrevs:
1822 1822 ancestors.update(flparentlinkrevs)
1823 1823
1824 1824 fncache.setdefault(rev, []).append(file_)
1825 1825 wanted.add(rev)
1826 1826 if copied:
1827 1827 copies.append(copied)
1828 1828
1829 1829 return wanted
1830 1830
1831 1831 class _followfilter(object):
1832 1832 def __init__(self, repo, onlyfirst=False):
1833 1833 self.repo = repo
1834 1834 self.startrev = nullrev
1835 1835 self.roots = set()
1836 1836 self.onlyfirst = onlyfirst
1837 1837
1838 1838 def match(self, rev):
1839 1839 def realparents(rev):
1840 1840 if self.onlyfirst:
1841 1841 return self.repo.changelog.parentrevs(rev)[0:1]
1842 1842 else:
1843 1843 return filter(lambda x: x != nullrev,
1844 1844 self.repo.changelog.parentrevs(rev))
1845 1845
1846 1846 if self.startrev == nullrev:
1847 1847 self.startrev = rev
1848 1848 return True
1849 1849
1850 1850 if rev > self.startrev:
1851 1851 # forward: all descendants
1852 1852 if not self.roots:
1853 1853 self.roots.add(self.startrev)
1854 1854 for parent in realparents(rev):
1855 1855 if parent in self.roots:
1856 1856 self.roots.add(rev)
1857 1857 return True
1858 1858 else:
1859 1859 # backwards: all parents
1860 1860 if not self.roots:
1861 1861 self.roots.update(realparents(self.startrev))
1862 1862 if rev in self.roots:
1863 1863 self.roots.remove(rev)
1864 1864 self.roots.update(realparents(rev))
1865 1865 return True
1866 1866
1867 1867 return False
1868 1868
1869 1869 def walkchangerevs(repo, match, opts, prepare):
1870 1870 '''Iterate over files and the revs in which they changed.
1871 1871
1872 1872 Callers most commonly need to iterate backwards over the history
1873 1873 in which they are interested. Doing so has awful (quadratic-looking)
1874 1874 performance, so we use iterators in a "windowed" way.
1875 1875
1876 1876 We walk a window of revisions in the desired order. Within the
1877 1877 window, we first walk forwards to gather data, then in the desired
1878 1878 order (usually backwards) to display it.
1879 1879
1880 1880 This function returns an iterator yielding contexts. Before
1881 1881 yielding each context, the iterator will first call the prepare
1882 1882 function on each context in the window in forward order.'''
1883 1883
1884 1884 follow = opts.get('follow') or opts.get('follow_first')
1885 1885 revs = _walkrevs(repo, opts)
1886 1886 if not revs:
1887 1887 return []
1888 1888 wanted = set()
1889 1889 slowpath = match.anypats() or (not match.always() and opts.get('removed'))
1890 1890 fncache = {}
1891 1891 change = repo.__getitem__
1892 1892
1893 1893 # First step is to fill wanted, the set of revisions that we want to yield.
1894 1894 # When it does not induce extra cost, we also fill fncache for revisions in
1895 1895 # wanted: a cache of filenames that were changed (ctx.files()) and that
1896 1896 # match the file filtering conditions.
1897 1897
1898 1898 if match.always():
1899 1899 # No files, no patterns. Display all revs.
1900 1900 wanted = revs
1901 1901 elif not slowpath:
1902 1902 # We only have to read through the filelog to find wanted revisions
1903 1903
1904 1904 try:
1905 1905 wanted = walkfilerevs(repo, match, follow, revs, fncache)
1906 1906 except FileWalkError:
1907 1907 slowpath = True
1908 1908
1909 1909 # We decided to fall back to the slowpath because at least one
1910 1910 # of the paths was not a file. Check to see if at least one of them
1911 1911 # existed in history, otherwise simply return
1912 1912 for path in match.files():
1913 1913 if path == '.' or path in repo.store:
1914 1914 break
1915 1915 else:
1916 1916 return []
1917 1917
1918 1918 if slowpath:
1919 1919 # We have to read the changelog to match filenames against
1920 1920 # changed files
1921 1921
1922 1922 if follow:
1923 1923 raise error.Abort(_('can only follow copies/renames for explicit '
1924 1924 'filenames'))
1925 1925
1926 1926 # The slow path checks files modified in every changeset.
1927 1927 # This is really slow on large repos, so compute the set lazily.
1928 1928 class lazywantedset(object):
1929 1929 def __init__(self):
1930 1930 self.set = set()
1931 1931 self.revs = set(revs)
1932 1932
1933 1933 # No need to worry about locality here because it will be accessed
1934 1934 # in the same order as the increasing window below.
1935 1935 def __contains__(self, value):
1936 1936 if value in self.set:
1937 1937 return True
1938 1938 elif not value in self.revs:
1939 1939 return False
1940 1940 else:
1941 1941 self.revs.discard(value)
1942 1942 ctx = change(value)
1943 1943 matches = [f for f in ctx.files() if match(f)]
1944 1944 if matches:
1945 1945 fncache[value] = matches
1946 1946 self.set.add(value)
1947 1947 return True
1948 1948 return False
1949 1949
1950 1950 def discard(self, value):
1951 1951 self.revs.discard(value)
1952 1952 self.set.discard(value)
1953 1953
1954 1954 wanted = lazywantedset()
1955 1955
1956 1956 # it might be worthwhile to do this in the iterator if the rev range
1957 1957 # is descending and the prune args are all within that range
1958 1958 for rev in opts.get('prune', ()):
1959 1959 rev = repo[rev].rev()
1960 1960 ff = _followfilter(repo)
1961 1961 stop = min(revs[0], revs[-1])
1962 1962 for x in xrange(rev, stop - 1, -1):
1963 1963 if ff.match(x):
1964 1964 wanted = wanted - [x]
1965 1965
1966 1966 # Now that wanted is correctly initialized, we can iterate over the
1967 1967 # revision range, yielding only revisions in wanted.
1968 1968 def iterate():
1969 1969 if follow and match.always():
1970 1970 ff = _followfilter(repo, onlyfirst=opts.get('follow_first'))
1971 1971 def want(rev):
1972 1972 return ff.match(rev) and rev in wanted
1973 1973 else:
1974 1974 def want(rev):
1975 1975 return rev in wanted
1976 1976
1977 1977 it = iter(revs)
1978 1978 stopiteration = False
1979 1979 for windowsize in increasingwindows():
1980 1980 nrevs = []
1981 1981 for i in xrange(windowsize):
1982 1982 rev = next(it, None)
1983 1983 if rev is None:
1984 1984 stopiteration = True
1985 1985 break
1986 1986 elif want(rev):
1987 1987 nrevs.append(rev)
1988 1988 for rev in sorted(nrevs):
1989 1989 fns = fncache.get(rev)
1990 1990 ctx = change(rev)
1991 1991 if not fns:
1992 1992 def fns_generator():
1993 1993 for f in ctx.files():
1994 1994 if match(f):
1995 1995 yield f
1996 1996 fns = fns_generator()
1997 1997 prepare(ctx, fns)
1998 1998 for rev in nrevs:
1999 1999 yield change(rev)
2000 2000
2001 2001 if stopiteration:
2002 2002 break
2003 2003
2004 2004 return iterate()
2005 2005
2006 2006 def add(ui, repo, match, prefix, explicitonly, **opts):
2007 2007 join = lambda f: os.path.join(prefix, f)
2008 2008 bad = []
2009 2009
2010 2010 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2011 2011 names = []
2012 2012 wctx = repo[None]
2013 2013 cca = None
2014 2014 abort, warn = scmutil.checkportabilityalert(ui)
2015 2015 if abort or warn:
2016 2016 cca = scmutil.casecollisionauditor(ui, abort, repo.dirstate)
2017 2017
2018 2018 badmatch = matchmod.badmatch(match, badfn)
2019 2019 dirstate = repo.dirstate
2020 2020 # We don't want to just call wctx.walk here, since it would return a lot of
2021 2021 # clean files, which we aren't interested in and takes time.
2022 2022 for f in sorted(dirstate.walk(badmatch, subrepos=sorted(wctx.substate),
2023 2023 unknown=True, ignored=False, full=False)):
2024 2024 exact = match.exact(f)
2025 2025 if exact or not explicitonly and f not in wctx and repo.wvfs.lexists(f):
2026 2026 if cca:
2027 2027 cca(f)
2028 2028 names.append(f)
2029 2029 if ui.verbose or not exact:
2030 2030 ui.status(_('adding %s\n') % match.rel(f))
2031 2031
2032 2032 for subpath in sorted(wctx.substate):
2033 2033 sub = wctx.sub(subpath)
2034 2034 try:
2035 2035 submatch = matchmod.subdirmatcher(subpath, match)
2036 2036 if opts.get(r'subrepos'):
2037 2037 bad.extend(sub.add(ui, submatch, prefix, False, **opts))
2038 2038 else:
2039 2039 bad.extend(sub.add(ui, submatch, prefix, True, **opts))
2040 2040 except error.LookupError:
2041 2041 ui.status(_("skipping missing subrepository: %s\n")
2042 2042 % join(subpath))
2043 2043
2044 2044 if not opts.get(r'dry_run'):
2045 2045 rejected = wctx.add(names, prefix)
2046 2046 bad.extend(f for f in rejected if f in match.files())
2047 2047 return bad
2048 2048
2049 2049 def addwebdirpath(repo, serverpath, webconf):
2050 2050 webconf[serverpath] = repo.root
2051 2051 repo.ui.debug('adding %s = %s\n' % (serverpath, repo.root))
2052 2052
2053 2053 for r in repo.revs('filelog("path:.hgsub")'):
2054 2054 ctx = repo[r]
2055 2055 for subpath in ctx.substate:
2056 2056 ctx.sub(subpath).addwebdirpath(serverpath, webconf)
2057 2057
2058 2058 def forget(ui, repo, match, prefix, explicitonly, dryrun, interactive):
2059 2059 if dryrun and interactive:
2060 2060 raise error.Abort(_("cannot specify both --dry-run and --interactive"))
2061 2061 join = lambda f: os.path.join(prefix, f)
2062 2062 bad = []
2063 2063 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2064 2064 wctx = repo[None]
2065 2065 forgot = []
2066 2066
2067 2067 s = repo.status(match=matchmod.badmatch(match, badfn), clean=True)
2068 2068 forget = sorted(s.modified + s.added + s.deleted + s.clean)
2069 2069 if explicitonly:
2070 2070 forget = [f for f in forget if match.exact(f)]
2071 2071
2072 2072 for subpath in sorted(wctx.substate):
2073 2073 sub = wctx.sub(subpath)
2074 2074 try:
2075 2075 submatch = matchmod.subdirmatcher(subpath, match)
2076 2076 subbad, subforgot = sub.forget(submatch, prefix, dryrun=dryrun,
2077 2077 interactive=interactive)
2078 2078 bad.extend([subpath + '/' + f for f in subbad])
2079 2079 forgot.extend([subpath + '/' + f for f in subforgot])
2080 2080 except error.LookupError:
2081 2081 ui.status(_("skipping missing subrepository: %s\n")
2082 2082 % join(subpath))
2083 2083
2084 2084 if not explicitonly:
2085 2085 for f in match.files():
2086 2086 if f not in repo.dirstate and not repo.wvfs.isdir(f):
2087 2087 if f not in forgot:
2088 2088 if repo.wvfs.exists(f):
2089 2089 # Don't complain if the exact case match wasn't given.
2090 2090 # But don't do this until after checking 'forgot', so
2091 2091 # that subrepo files aren't normalized, and this op is
2092 2092 # purely from data cached by the status walk above.
2093 2093 if repo.dirstate.normalize(f) in repo.dirstate:
2094 2094 continue
2095 2095 ui.warn(_('not removing %s: '
2096 2096 'file is already untracked\n')
2097 2097 % match.rel(f))
2098 2098 bad.append(f)
2099 2099
2100 2100 if interactive:
2101 2101 responses = _('[Ynsa?]'
2102 2102 '$$ &Yes, forget this file'
2103 2103 '$$ &No, skip this file'
2104 2104 '$$ &Skip remaining files'
2105 2105 '$$ Include &all remaining files'
2106 2106 '$$ &? (display help)')
2107 2107 for filename in forget[:]:
2108 2108 r = ui.promptchoice(_('forget %s %s') % (filename, responses))
2109 2109 if r == 4: # ?
2110 2110 while r == 4:
2111 2111 for c, t in ui.extractchoices(responses)[1]:
2112 2112 ui.write('%s - %s\n' % (c, encoding.lower(t)))
2113 2113 r = ui.promptchoice(_('forget %s %s') % (filename,
2114 2114 responses))
2115 2115 if r == 0: # yes
2116 2116 continue
2117 2117 elif r == 1: # no
2118 2118 forget.remove(filename)
2119 2119 elif r == 2: # Skip
2120 2120 fnindex = forget.index(filename)
2121 2121 del forget[fnindex:]
2122 2122 break
2123 2123 elif r == 3: # All
2124 2124 break
2125 2125
2126 2126 for f in forget:
2127 2127 if ui.verbose or not match.exact(f) or interactive:
2128 2128 ui.status(_('removing %s\n') % match.rel(f))
2129 2129
2130 2130 if not dryrun:
2131 2131 rejected = wctx.forget(forget, prefix)
2132 2132 bad.extend(f for f in rejected if f in match.files())
2133 2133 forgot.extend(f for f in forget if f not in rejected)
2134 2134 return bad, forgot
2135 2135
2136 2136 def files(ui, ctx, m, fm, fmt, subrepos):
2137 2137 ret = 1
2138 2138
2139 2139 for f in ctx.matches(m):
2140 2140 fm.startitem()
2141 2141 if ui.verbose:
2142 2142 fc = ctx[f]
2143 2143 fm.write('size flags', '% 10d % 1s ', fc.size(), fc.flags())
2144 2144 fm.data(abspath=f)
2145 2145 fm.write('path', fmt, m.rel(f))
2146 2146 ret = 0
2147 2147
2148 2148 for subpath in sorted(ctx.substate):
2149 2149 submatch = matchmod.subdirmatcher(subpath, m)
2150 2150 if (subrepos or m.exact(subpath) or any(submatch.files())):
2151 2151 sub = ctx.sub(subpath)
2152 2152 try:
2153 2153 recurse = m.exact(subpath) or subrepos
2154 2154 if sub.printfiles(ui, submatch, fm, fmt, recurse) == 0:
2155 2155 ret = 0
2156 2156 except error.LookupError:
2157 2157 ui.status(_("skipping missing subrepository: %s\n")
2158 2158 % m.abs(subpath))
2159 2159
2160 2160 return ret
2161 2161
2162 2162 def remove(ui, repo, m, prefix, after, force, subrepos, dryrun, warnings=None):
2163 2163 join = lambda f: os.path.join(prefix, f)
2164 2164 ret = 0
2165 2165 s = repo.status(match=m, clean=True)
2166 2166 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
2167 2167
2168 2168 wctx = repo[None]
2169 2169
2170 2170 if warnings is None:
2171 2171 warnings = []
2172 2172 warn = True
2173 2173 else:
2174 2174 warn = False
2175 2175
2176 2176 subs = sorted(wctx.substate)
2177 2177 total = len(subs)
2178 2178 count = 0
2179 2179 for subpath in subs:
2180 2180 count += 1
2181 2181 submatch = matchmod.subdirmatcher(subpath, m)
2182 2182 if subrepos or m.exact(subpath) or any(submatch.files()):
2183 2183 ui.progress(_('searching'), count, total=total, unit=_('subrepos'))
2184 2184 sub = wctx.sub(subpath)
2185 2185 try:
2186 2186 if sub.removefiles(submatch, prefix, after, force, subrepos,
2187 2187 dryrun, warnings):
2188 2188 ret = 1
2189 2189 except error.LookupError:
2190 2190 warnings.append(_("skipping missing subrepository: %s\n")
2191 2191 % join(subpath))
2192 2192 ui.progress(_('searching'), None)
2193 2193
2194 2194 # warn about failure to delete explicit files/dirs
2195 2195 deleteddirs = util.dirs(deleted)
2196 2196 files = m.files()
2197 2197 total = len(files)
2198 2198 count = 0
2199 2199 for f in files:
2200 2200 def insubrepo():
2201 2201 for subpath in wctx.substate:
2202 2202 if f.startswith(subpath + '/'):
2203 2203 return True
2204 2204 return False
2205 2205
2206 2206 count += 1
2207 2207 ui.progress(_('deleting'), count, total=total, unit=_('files'))
2208 2208 isdir = f in deleteddirs or wctx.hasdir(f)
2209 2209 if (f in repo.dirstate or isdir or f == '.'
2210 2210 or insubrepo() or f in subs):
2211 2211 continue
2212 2212
2213 2213 if repo.wvfs.exists(f):
2214 2214 if repo.wvfs.isdir(f):
2215 2215 warnings.append(_('not removing %s: no tracked files\n')
2216 2216 % m.rel(f))
2217 2217 else:
2218 2218 warnings.append(_('not removing %s: file is untracked\n')
2219 2219 % m.rel(f))
2220 2220 # missing files will generate a warning elsewhere
2221 2221 ret = 1
2222 2222 ui.progress(_('deleting'), None)
2223 2223
2224 2224 if force:
2225 2225 list = modified + deleted + clean + added
2226 2226 elif after:
2227 2227 list = deleted
2228 2228 remaining = modified + added + clean
2229 2229 total = len(remaining)
2230 2230 count = 0
2231 2231 for f in remaining:
2232 2232 count += 1
2233 2233 ui.progress(_('skipping'), count, total=total, unit=_('files'))
2234 2234 if ui.verbose or (f in files):
2235 2235 warnings.append(_('not removing %s: file still exists\n')
2236 2236 % m.rel(f))
2237 2237 ret = 1
2238 2238 ui.progress(_('skipping'), None)
2239 2239 else:
2240 2240 list = deleted + clean
2241 2241 total = len(modified) + len(added)
2242 2242 count = 0
2243 2243 for f in modified:
2244 2244 count += 1
2245 2245 ui.progress(_('skipping'), count, total=total, unit=_('files'))
2246 2246 warnings.append(_('not removing %s: file is modified (use -f'
2247 2247 ' to force removal)\n') % m.rel(f))
2248 2248 ret = 1
2249 2249 for f in added:
2250 2250 count += 1
2251 2251 ui.progress(_('skipping'), count, total=total, unit=_('files'))
2252 2252 warnings.append(_("not removing %s: file has been marked for add"
2253 2253 " (use 'hg forget' to undo add)\n") % m.rel(f))
2254 2254 ret = 1
2255 2255 ui.progress(_('skipping'), None)
2256 2256
2257 2257 list = sorted(list)
2258 2258 total = len(list)
2259 2259 count = 0
2260 2260 for f in list:
2261 2261 count += 1
2262 2262 if ui.verbose or not m.exact(f):
2263 2263 ui.progress(_('deleting'), count, total=total, unit=_('files'))
2264 2264 ui.status(_('removing %s\n') % m.rel(f))
2265 2265 ui.progress(_('deleting'), None)
2266 2266
2267 2267 if not dryrun:
2268 2268 with repo.wlock():
2269 2269 if not after:
2270 2270 for f in list:
2271 2271 if f in added:
2272 2272 continue # we never unlink added files on remove
2273 2273 repo.wvfs.unlinkpath(f, ignoremissing=True)
2274 2274 repo[None].forget(list)
2275 2275
2276 2276 if warn:
2277 2277 for warning in warnings:
2278 2278 ui.warn(warning)
2279 2279
2280 2280 return ret
2281 2281
2282 2282 def _updatecatformatter(fm, ctx, matcher, path, decode):
2283 2283 """Hook for adding data to the formatter used by ``hg cat``.
2284 2284
2285 2285 Extensions (e.g., lfs) can wrap this to inject keywords/data, but must call
2286 2286 this method first."""
2287 2287 data = ctx[path].data()
2288 2288 if decode:
2289 2289 data = ctx.repo().wwritedata(path, data)
2290 2290 fm.startitem()
2291 2291 fm.write('data', '%s', data)
2292 2292 fm.data(abspath=path, path=matcher.rel(path))
2293 2293
2294 2294 def cat(ui, repo, ctx, matcher, basefm, fntemplate, prefix, **opts):
2295 2295 err = 1
2296 2296 opts = pycompat.byteskwargs(opts)
2297 2297
2298 2298 def write(path):
2299 2299 filename = None
2300 2300 if fntemplate:
2301 2301 filename = makefilename(ctx, fntemplate,
2302 2302 pathname=os.path.join(prefix, path))
2303 2303 # attempt to create the directory if it does not already exist
2304 2304 try:
2305 2305 os.makedirs(os.path.dirname(filename))
2306 2306 except OSError:
2307 2307 pass
2308 2308 with formatter.maybereopen(basefm, filename) as fm:
2309 2309 _updatecatformatter(fm, ctx, matcher, path, opts.get('decode'))
2310 2310
2311 2311 # Automation often uses hg cat on single files, so special case it
2312 2312 # for performance to avoid the cost of parsing the manifest.
2313 2313 if len(matcher.files()) == 1 and not matcher.anypats():
2314 2314 file = matcher.files()[0]
2315 2315 mfl = repo.manifestlog
2316 2316 mfnode = ctx.manifestnode()
2317 2317 try:
2318 2318 if mfnode and mfl[mfnode].find(file)[0]:
2319 2319 scmutil.prefetchfiles(repo, [ctx.rev()], matcher)
2320 2320 write(file)
2321 2321 return 0
2322 2322 except KeyError:
2323 2323 pass
2324 2324
2325 2325 scmutil.prefetchfiles(repo, [ctx.rev()], matcher)
2326 2326
2327 2327 for abs in ctx.walk(matcher):
2328 2328 write(abs)
2329 2329 err = 0
2330 2330
2331 2331 for subpath in sorted(ctx.substate):
2332 2332 sub = ctx.sub(subpath)
2333 2333 try:
2334 2334 submatch = matchmod.subdirmatcher(subpath, matcher)
2335 2335
2336 2336 if not sub.cat(submatch, basefm, fntemplate,
2337 2337 os.path.join(prefix, sub._path),
2338 2338 **pycompat.strkwargs(opts)):
2339 2339 err = 0
2340 2340 except error.RepoLookupError:
2341 2341 ui.status(_("skipping missing subrepository: %s\n")
2342 2342 % os.path.join(prefix, subpath))
2343 2343
2344 2344 return err
2345 2345
2346 2346 def commit(ui, repo, commitfunc, pats, opts):
2347 2347 '''commit the specified files or all outstanding changes'''
2348 2348 date = opts.get('date')
2349 2349 if date:
2350 2350 opts['date'] = dateutil.parsedate(date)
2351 2351 message = logmessage(ui, opts)
2352 2352 matcher = scmutil.match(repo[None], pats, opts)
2353 2353
2354 2354 dsguard = None
2355 2355 # extract addremove carefully -- this function can be called from a command
2356 2356 # that doesn't support addremove
2357 2357 if opts.get('addremove'):
2358 2358 dsguard = dirstateguard.dirstateguard(repo, 'commit')
2359 2359 with dsguard or util.nullcontextmanager():
2360 2360 if dsguard:
2361 2361 if scmutil.addremove(repo, matcher, "", opts) != 0:
2362 2362 raise error.Abort(
2363 2363 _("failed to mark all new/missing files as added/removed"))
2364 2364
2365 2365 return commitfunc(ui, repo, message, matcher, opts)
2366 2366
2367 2367 def samefile(f, ctx1, ctx2):
2368 2368 if f in ctx1.manifest():
2369 2369 a = ctx1.filectx(f)
2370 2370 if f in ctx2.manifest():
2371 2371 b = ctx2.filectx(f)
2372 2372 return (not a.cmp(b)
2373 2373 and a.flags() == b.flags())
2374 2374 else:
2375 2375 return False
2376 2376 else:
2377 2377 return f not in ctx2.manifest()
2378 2378
2379 2379 def amend(ui, repo, old, extra, pats, opts):
2380 2380 # avoid cycle context -> subrepo -> cmdutil
2381 2381 from . import context
2382 2382
2383 2383 # amend will reuse the existing user if not specified, but the obsolete
2384 2384 # marker creation requires that the current user's name is specified.
2385 2385 if obsolete.isenabled(repo, obsolete.createmarkersopt):
2386 2386 ui.username() # raise exception if username not set
2387 2387
2388 2388 ui.note(_('amending changeset %s\n') % old)
2389 2389 base = old.p1()
2390 2390
2391 2391 with repo.wlock(), repo.lock(), repo.transaction('amend'):
2392 2392 # Participating changesets:
2393 2393 #
2394 2394 # wctx o - workingctx that contains changes from working copy
2395 2395 # | to go into amending commit
2396 2396 # |
2397 2397 # old o - changeset to amend
2398 2398 # |
2399 2399 # base o - first parent of the changeset to amend
2400 2400 wctx = repo[None]
2401 2401
2402 2402 # Copy to avoid mutating input
2403 2403 extra = extra.copy()
2404 2404 # Update extra dict from amended commit (e.g. to preserve graft
2405 2405 # source)
2406 2406 extra.update(old.extra())
2407 2407
2408 2408 # Also update it from the from the wctx
2409 2409 extra.update(wctx.extra())
2410 2410
2411 2411 user = opts.get('user') or old.user()
2412 2412 date = opts.get('date') or old.date()
2413 2413
2414 2414 # Parse the date to allow comparison between date and old.date()
2415 2415 date = dateutil.parsedate(date)
2416 2416
2417 2417 if len(old.parents()) > 1:
2418 2418 # ctx.files() isn't reliable for merges, so fall back to the
2419 2419 # slower repo.status() method
2420 2420 files = set([fn for st in repo.status(base, old)[:3]
2421 2421 for fn in st])
2422 2422 else:
2423 2423 files = set(old.files())
2424 2424
2425 2425 # add/remove the files to the working copy if the "addremove" option
2426 2426 # was specified.
2427 2427 matcher = scmutil.match(wctx, pats, opts)
2428 2428 if (opts.get('addremove')
2429 2429 and scmutil.addremove(repo, matcher, "", opts)):
2430 2430 raise error.Abort(
2431 2431 _("failed to mark all new/missing files as added/removed"))
2432 2432
2433 2433 # Check subrepos. This depends on in-place wctx._status update in
2434 2434 # subrepo.precommit(). To minimize the risk of this hack, we do
2435 2435 # nothing if .hgsub does not exist.
2436 2436 if '.hgsub' in wctx or '.hgsub' in old:
2437 2437 subs, commitsubs, newsubstate = subrepoutil.precommit(
2438 2438 ui, wctx, wctx._status, matcher)
2439 2439 # amend should abort if commitsubrepos is enabled
2440 2440 assert not commitsubs
2441 2441 if subs:
2442 2442 subrepoutil.writestate(repo, newsubstate)
2443 2443
2444 2444 ms = mergemod.mergestate.read(repo)
2445 2445 mergeutil.checkunresolved(ms)
2446 2446
2447 2447 filestoamend = set(f for f in wctx.files() if matcher(f))
2448 2448
2449 2449 changes = (len(filestoamend) > 0)
2450 2450 if changes:
2451 2451 # Recompute copies (avoid recording a -> b -> a)
2452 2452 copied = copies.pathcopies(base, wctx, matcher)
2453 2453 if old.p2:
2454 2454 copied.update(copies.pathcopies(old.p2(), wctx, matcher))
2455 2455
2456 2456 # Prune files which were reverted by the updates: if old
2457 2457 # introduced file X and the file was renamed in the working
2458 2458 # copy, then those two files are the same and
2459 2459 # we can discard X from our list of files. Likewise if X
2460 2460 # was removed, it's no longer relevant. If X is missing (aka
2461 2461 # deleted), old X must be preserved.
2462 2462 files.update(filestoamend)
2463 2463 files = [f for f in files if (not samefile(f, wctx, base)
2464 2464 or f in wctx.deleted())]
2465 2465
2466 2466 def filectxfn(repo, ctx_, path):
2467 2467 try:
2468 2468 # If the file being considered is not amongst the files
2469 2469 # to be amended, we should return the file context from the
2470 2470 # old changeset. This avoids issues when only some files in
2471 2471 # the working copy are being amended but there are also
2472 2472 # changes to other files from the old changeset.
2473 2473 if path not in filestoamend:
2474 2474 return old.filectx(path)
2475 2475
2476 2476 # Return None for removed files.
2477 2477 if path in wctx.removed():
2478 2478 return None
2479 2479
2480 2480 fctx = wctx[path]
2481 2481 flags = fctx.flags()
2482 2482 mctx = context.memfilectx(repo, ctx_,
2483 2483 fctx.path(), fctx.data(),
2484 2484 islink='l' in flags,
2485 2485 isexec='x' in flags,
2486 2486 copied=copied.get(path))
2487 2487 return mctx
2488 2488 except KeyError:
2489 2489 return None
2490 2490 else:
2491 2491 ui.note(_('copying changeset %s to %s\n') % (old, base))
2492 2492
2493 2493 # Use version of files as in the old cset
2494 2494 def filectxfn(repo, ctx_, path):
2495 2495 try:
2496 2496 return old.filectx(path)
2497 2497 except KeyError:
2498 2498 return None
2499 2499
2500 2500 # See if we got a message from -m or -l, if not, open the editor with
2501 2501 # the message of the changeset to amend.
2502 2502 message = logmessage(ui, opts)
2503 2503
2504 2504 editform = mergeeditform(old, 'commit.amend')
2505 2505 editor = getcommiteditor(editform=editform,
2506 2506 **pycompat.strkwargs(opts))
2507 2507
2508 2508 if not message:
2509 2509 editor = getcommiteditor(edit=True, editform=editform)
2510 2510 message = old.description()
2511 2511
2512 2512 pureextra = extra.copy()
2513 2513 extra['amend_source'] = old.hex()
2514 2514
2515 2515 new = context.memctx(repo,
2516 2516 parents=[base.node(), old.p2().node()],
2517 2517 text=message,
2518 2518 files=files,
2519 2519 filectxfn=filectxfn,
2520 2520 user=user,
2521 2521 date=date,
2522 2522 extra=extra,
2523 2523 editor=editor)
2524 2524
2525 2525 newdesc = changelog.stripdesc(new.description())
2526 2526 if ((not changes)
2527 2527 and newdesc == old.description()
2528 2528 and user == old.user()
2529 2529 and date == old.date()
2530 2530 and pureextra == old.extra()):
2531 2531 # nothing changed. continuing here would create a new node
2532 2532 # anyway because of the amend_source noise.
2533 2533 #
2534 2534 # This not what we expect from amend.
2535 2535 return old.node()
2536 2536
2537 2537 if opts.get('secret'):
2538 2538 commitphase = 'secret'
2539 2539 else:
2540 2540 commitphase = old.phase()
2541 2541 overrides = {('phases', 'new-commit'): commitphase}
2542 2542 with ui.configoverride(overrides, 'amend'):
2543 2543 newid = repo.commitctx(new)
2544 2544
2545 2545 # Reroute the working copy parent to the new changeset
2546 2546 repo.setparents(newid, nullid)
2547 2547 mapping = {old.node(): (newid,)}
2548 2548 obsmetadata = None
2549 2549 if opts.get('note'):
2550 2550 obsmetadata = {'note': opts['note']}
2551 2551 scmutil.cleanupnodes(repo, mapping, 'amend', metadata=obsmetadata)
2552 2552
2553 2553 # Fixing the dirstate because localrepo.commitctx does not update
2554 2554 # it. This is rather convenient because we did not need to update
2555 2555 # the dirstate for all the files in the new commit which commitctx
2556 2556 # could have done if it updated the dirstate. Now, we can
2557 2557 # selectively update the dirstate only for the amended files.
2558 2558 dirstate = repo.dirstate
2559 2559
2560 2560 # Update the state of the files which were added and
2561 2561 # and modified in the amend to "normal" in the dirstate.
2562 2562 normalfiles = set(wctx.modified() + wctx.added()) & filestoamend
2563 2563 for f in normalfiles:
2564 2564 dirstate.normal(f)
2565 2565
2566 2566 # Update the state of files which were removed in the amend
2567 2567 # to "removed" in the dirstate.
2568 2568 removedfiles = set(wctx.removed()) & filestoamend
2569 2569 for f in removedfiles:
2570 2570 dirstate.drop(f)
2571 2571
2572 2572 return newid
2573 2573
2574 2574 def commiteditor(repo, ctx, subs, editform=''):
2575 2575 if ctx.description():
2576 2576 return ctx.description()
2577 2577 return commitforceeditor(repo, ctx, subs, editform=editform,
2578 2578 unchangedmessagedetection=True)
2579 2579
2580 2580 def commitforceeditor(repo, ctx, subs, finishdesc=None, extramsg=None,
2581 2581 editform='', unchangedmessagedetection=False):
2582 2582 if not extramsg:
2583 2583 extramsg = _("Leave message empty to abort commit.")
2584 2584
2585 2585 forms = [e for e in editform.split('.') if e]
2586 2586 forms.insert(0, 'changeset')
2587 2587 templatetext = None
2588 2588 while forms:
2589 2589 ref = '.'.join(forms)
2590 2590 if repo.ui.config('committemplate', ref):
2591 2591 templatetext = committext = buildcommittemplate(
2592 2592 repo, ctx, subs, extramsg, ref)
2593 2593 break
2594 2594 forms.pop()
2595 2595 else:
2596 2596 committext = buildcommittext(repo, ctx, subs, extramsg)
2597 2597
2598 2598 # run editor in the repository root
2599 2599 olddir = pycompat.getcwd()
2600 2600 os.chdir(repo.root)
2601 2601
2602 2602 # make in-memory changes visible to external process
2603 2603 tr = repo.currenttransaction()
2604 2604 repo.dirstate.write(tr)
2605 2605 pending = tr and tr.writepending() and repo.root
2606 2606
2607 2607 editortext = repo.ui.edit(committext, ctx.user(), ctx.extra(),
2608 2608 editform=editform, pending=pending,
2609 2609 repopath=repo.path, action='commit')
2610 2610 text = editortext
2611 2611
2612 2612 # strip away anything below this special string (used for editors that want
2613 2613 # to display the diff)
2614 2614 stripbelow = re.search(_linebelow, text, flags=re.MULTILINE)
2615 2615 if stripbelow:
2616 2616 text = text[:stripbelow.start()]
2617 2617
2618 2618 text = re.sub("(?m)^HG:.*(\n|$)", "", text)
2619 2619 os.chdir(olddir)
2620 2620
2621 2621 if finishdesc:
2622 2622 text = finishdesc(text)
2623 2623 if not text.strip():
2624 2624 raise error.Abort(_("empty commit message"))
2625 2625 if unchangedmessagedetection and editortext == templatetext:
2626 2626 raise error.Abort(_("commit message unchanged"))
2627 2627
2628 2628 return text
2629 2629
2630 2630 def buildcommittemplate(repo, ctx, subs, extramsg, ref):
2631 2631 ui = repo.ui
2632 2632 spec = formatter.templatespec(ref, None, None)
2633 2633 t = logcmdutil.changesettemplater(ui, repo, spec)
2634 2634 t.t.cache.update((k, templater.unquotestring(v))
2635 2635 for k, v in repo.ui.configitems('committemplate'))
2636 2636
2637 2637 if not extramsg:
2638 2638 extramsg = '' # ensure that extramsg is string
2639 2639
2640 2640 ui.pushbuffer()
2641 2641 t.show(ctx, extramsg=extramsg)
2642 2642 return ui.popbuffer()
2643 2643
2644 2644 def hgprefix(msg):
2645 2645 return "\n".join(["HG: %s" % a for a in msg.split("\n") if a])
2646 2646
2647 2647 def buildcommittext(repo, ctx, subs, extramsg):
2648 2648 edittext = []
2649 2649 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
2650 2650 if ctx.description():
2651 2651 edittext.append(ctx.description())
2652 2652 edittext.append("")
2653 2653 edittext.append("") # Empty line between message and comments.
2654 2654 edittext.append(hgprefix(_("Enter commit message."
2655 2655 " Lines beginning with 'HG:' are removed.")))
2656 2656 edittext.append(hgprefix(extramsg))
2657 2657 edittext.append("HG: --")
2658 2658 edittext.append(hgprefix(_("user: %s") % ctx.user()))
2659 2659 if ctx.p2():
2660 2660 edittext.append(hgprefix(_("branch merge")))
2661 2661 if ctx.branch():
2662 2662 edittext.append(hgprefix(_("branch '%s'") % ctx.branch()))
2663 2663 if bookmarks.isactivewdirparent(repo):
2664 2664 edittext.append(hgprefix(_("bookmark '%s'") % repo._activebookmark))
2665 2665 edittext.extend([hgprefix(_("subrepo %s") % s) for s in subs])
2666 2666 edittext.extend([hgprefix(_("added %s") % f) for f in added])
2667 2667 edittext.extend([hgprefix(_("changed %s") % f) for f in modified])
2668 2668 edittext.extend([hgprefix(_("removed %s") % f) for f in removed])
2669 2669 if not added and not modified and not removed:
2670 2670 edittext.append(hgprefix(_("no files changed")))
2671 2671 edittext.append("")
2672 2672
2673 2673 return "\n".join(edittext)
2674 2674
2675 2675 def commitstatus(repo, node, branch, bheads=None, opts=None):
2676 2676 if opts is None:
2677 2677 opts = {}
2678 2678 ctx = repo[node]
2679 2679 parents = ctx.parents()
2680 2680
2681 2681 if (not opts.get('amend') and bheads and node not in bheads and not
2682 2682 [x for x in parents if x.node() in bheads and x.branch() == branch]):
2683 2683 repo.ui.status(_('created new head\n'))
2684 2684 # The message is not printed for initial roots. For the other
2685 2685 # changesets, it is printed in the following situations:
2686 2686 #
2687 2687 # Par column: for the 2 parents with ...
2688 2688 # N: null or no parent
2689 2689 # B: parent is on another named branch
2690 2690 # C: parent is a regular non head changeset
2691 2691 # H: parent was a branch head of the current branch
2692 2692 # Msg column: whether we print "created new head" message
2693 2693 # In the following, it is assumed that there already exists some
2694 2694 # initial branch heads of the current branch, otherwise nothing is
2695 2695 # printed anyway.
2696 2696 #
2697 2697 # Par Msg Comment
2698 2698 # N N y additional topo root
2699 2699 #
2700 2700 # B N y additional branch root
2701 2701 # C N y additional topo head
2702 2702 # H N n usual case
2703 2703 #
2704 2704 # B B y weird additional branch root
2705 2705 # C B y branch merge
2706 2706 # H B n merge with named branch
2707 2707 #
2708 2708 # C C y additional head from merge
2709 2709 # C H n merge with a head
2710 2710 #
2711 2711 # H H n head merge: head count decreases
2712 2712
2713 2713 if not opts.get('close_branch'):
2714 2714 for r in parents:
2715 2715 if r.closesbranch() and r.branch() == branch:
2716 2716 repo.ui.status(_('reopening closed branch head %d\n') % r.rev())
2717 2717
2718 2718 if repo.ui.debugflag:
2719 2719 repo.ui.write(_('committed changeset %d:%s\n') % (ctx.rev(), ctx.hex()))
2720 2720 elif repo.ui.verbose:
2721 2721 repo.ui.write(_('committed changeset %d:%s\n') % (ctx.rev(), ctx))
2722 2722
2723 2723 def postcommitstatus(repo, pats, opts):
2724 2724 return repo.status(match=scmutil.match(repo[None], pats, opts))
2725 2725
2726 2726 def revert(ui, repo, ctx, parents, *pats, **opts):
2727 2727 opts = pycompat.byteskwargs(opts)
2728 2728 parent, p2 = parents
2729 2729 node = ctx.node()
2730 2730
2731 2731 mf = ctx.manifest()
2732 2732 if node == p2:
2733 2733 parent = p2
2734 2734
2735 2735 # need all matching names in dirstate and manifest of target rev,
2736 2736 # so have to walk both. do not print errors if files exist in one
2737 2737 # but not other. in both cases, filesets should be evaluated against
2738 2738 # workingctx to get consistent result (issue4497). this means 'set:**'
2739 2739 # cannot be used to select missing files from target rev.
2740 2740
2741 2741 # `names` is a mapping for all elements in working copy and target revision
2742 2742 # The mapping is in the form:
2743 2743 # <asb path in repo> -> (<path from CWD>, <exactly specified by matcher?>)
2744 2744 names = {}
2745 2745
2746 2746 with repo.wlock():
2747 2747 ## filling of the `names` mapping
2748 2748 # walk dirstate to fill `names`
2749 2749
2750 2750 interactive = opts.get('interactive', False)
2751 2751 wctx = repo[None]
2752 2752 m = scmutil.match(wctx, pats, opts)
2753 2753
2754 2754 # we'll need this later
2755 2755 targetsubs = sorted(s for s in wctx.substate if m(s))
2756 2756
2757 2757 if not m.always():
2758 2758 matcher = matchmod.badmatch(m, lambda x, y: False)
2759 2759 for abs in wctx.walk(matcher):
2760 2760 names[abs] = m.rel(abs), m.exact(abs)
2761 2761
2762 2762 # walk target manifest to fill `names`
2763 2763
2764 2764 def badfn(path, msg):
2765 2765 if path in names:
2766 2766 return
2767 2767 if path in ctx.substate:
2768 2768 return
2769 2769 path_ = path + '/'
2770 2770 for f in names:
2771 2771 if f.startswith(path_):
2772 2772 return
2773 2773 ui.warn("%s: %s\n" % (m.rel(path), msg))
2774 2774
2775 2775 for abs in ctx.walk(matchmod.badmatch(m, badfn)):
2776 2776 if abs not in names:
2777 2777 names[abs] = m.rel(abs), m.exact(abs)
2778 2778
2779 2779 # Find status of all file in `names`.
2780 2780 m = scmutil.matchfiles(repo, names)
2781 2781
2782 2782 changes = repo.status(node1=node, match=m,
2783 2783 unknown=True, ignored=True, clean=True)
2784 2784 else:
2785 2785 changes = repo.status(node1=node, match=m)
2786 2786 for kind in changes:
2787 2787 for abs in kind:
2788 2788 names[abs] = m.rel(abs), m.exact(abs)
2789 2789
2790 2790 m = scmutil.matchfiles(repo, names)
2791 2791
2792 2792 modified = set(changes.modified)
2793 2793 added = set(changes.added)
2794 2794 removed = set(changes.removed)
2795 2795 _deleted = set(changes.deleted)
2796 2796 unknown = set(changes.unknown)
2797 2797 unknown.update(changes.ignored)
2798 2798 clean = set(changes.clean)
2799 2799 modadded = set()
2800 2800
2801 2801 # We need to account for the state of the file in the dirstate,
2802 2802 # even when we revert against something else than parent. This will
2803 2803 # slightly alter the behavior of revert (doing back up or not, delete
2804 2804 # or just forget etc).
2805 2805 if parent == node:
2806 2806 dsmodified = modified
2807 2807 dsadded = added
2808 2808 dsremoved = removed
2809 2809 # store all local modifications, useful later for rename detection
2810 2810 localchanges = dsmodified | dsadded
2811 2811 modified, added, removed = set(), set(), set()
2812 2812 else:
2813 2813 changes = repo.status(node1=parent, match=m)
2814 2814 dsmodified = set(changes.modified)
2815 2815 dsadded = set(changes.added)
2816 2816 dsremoved = set(changes.removed)
2817 2817 # store all local modifications, useful later for rename detection
2818 2818 localchanges = dsmodified | dsadded
2819 2819
2820 2820 # only take into account for removes between wc and target
2821 2821 clean |= dsremoved - removed
2822 2822 dsremoved &= removed
2823 2823 # distinct between dirstate remove and other
2824 2824 removed -= dsremoved
2825 2825
2826 2826 modadded = added & dsmodified
2827 2827 added -= modadded
2828 2828
2829 2829 # tell newly modified apart.
2830 2830 dsmodified &= modified
2831 2831 dsmodified |= modified & dsadded # dirstate added may need backup
2832 2832 modified -= dsmodified
2833 2833
2834 2834 # We need to wait for some post-processing to update this set
2835 2835 # before making the distinction. The dirstate will be used for
2836 2836 # that purpose.
2837 2837 dsadded = added
2838 2838
2839 2839 # in case of merge, files that are actually added can be reported as
2840 2840 # modified, we need to post process the result
2841 2841 if p2 != nullid:
2842 2842 mergeadd = set(dsmodified)
2843 2843 for path in dsmodified:
2844 2844 if path in mf:
2845 2845 mergeadd.remove(path)
2846 2846 dsadded |= mergeadd
2847 2847 dsmodified -= mergeadd
2848 2848
2849 2849 # if f is a rename, update `names` to also revert the source
2850 2850 cwd = repo.getcwd()
2851 2851 for f in localchanges:
2852 2852 src = repo.dirstate.copied(f)
2853 2853 # XXX should we check for rename down to target node?
2854 2854 if src and src not in names and repo.dirstate[src] == 'r':
2855 2855 dsremoved.add(src)
2856 2856 names[src] = (repo.pathto(src, cwd), True)
2857 2857
2858 2858 # determine the exact nature of the deleted changesets
2859 2859 deladded = set(_deleted)
2860 2860 for path in _deleted:
2861 2861 if path in mf:
2862 2862 deladded.remove(path)
2863 2863 deleted = _deleted - deladded
2864 2864
2865 2865 # distinguish between file to forget and the other
2866 2866 added = set()
2867 2867 for abs in dsadded:
2868 2868 if repo.dirstate[abs] != 'a':
2869 2869 added.add(abs)
2870 2870 dsadded -= added
2871 2871
2872 2872 for abs in deladded:
2873 2873 if repo.dirstate[abs] == 'a':
2874 2874 dsadded.add(abs)
2875 2875 deladded -= dsadded
2876 2876
2877 2877 # For files marked as removed, we check if an unknown file is present at
2878 2878 # the same path. If a such file exists it may need to be backed up.
2879 2879 # Making the distinction at this stage helps have simpler backup
2880 2880 # logic.
2881 2881 removunk = set()
2882 2882 for abs in removed:
2883 2883 target = repo.wjoin(abs)
2884 2884 if os.path.lexists(target):
2885 2885 removunk.add(abs)
2886 2886 removed -= removunk
2887 2887
2888 2888 dsremovunk = set()
2889 2889 for abs in dsremoved:
2890 2890 target = repo.wjoin(abs)
2891 2891 if os.path.lexists(target):
2892 2892 dsremovunk.add(abs)
2893 2893 dsremoved -= dsremovunk
2894 2894
2895 2895 # action to be actually performed by revert
2896 2896 # (<list of file>, message>) tuple
2897 2897 actions = {'revert': ([], _('reverting %s\n')),
2898 2898 'add': ([], _('adding %s\n')),
2899 2899 'remove': ([], _('removing %s\n')),
2900 2900 'drop': ([], _('removing %s\n')),
2901 2901 'forget': ([], _('forgetting %s\n')),
2902 2902 'undelete': ([], _('undeleting %s\n')),
2903 2903 'noop': (None, _('no changes needed to %s\n')),
2904 2904 'unknown': (None, _('file not managed: %s\n')),
2905 2905 }
2906 2906
2907 2907 # "constant" that convey the backup strategy.
2908 2908 # All set to `discard` if `no-backup` is set do avoid checking
2909 2909 # no_backup lower in the code.
2910 2910 # These values are ordered for comparison purposes
2911 2911 backupinteractive = 3 # do backup if interactively modified
2912 2912 backup = 2 # unconditionally do backup
2913 2913 check = 1 # check if the existing file differs from target
2914 2914 discard = 0 # never do backup
2915 2915 if opts.get('no_backup'):
2916 2916 backupinteractive = backup = check = discard
2917 2917 if interactive:
2918 2918 dsmodifiedbackup = backupinteractive
2919 2919 else:
2920 2920 dsmodifiedbackup = backup
2921 2921 tobackup = set()
2922 2922
2923 2923 backupanddel = actions['remove']
2924 2924 if not opts.get('no_backup'):
2925 2925 backupanddel = actions['drop']
2926 2926
2927 2927 disptable = (
2928 2928 # dispatch table:
2929 2929 # file state
2930 2930 # action
2931 2931 # make backup
2932 2932
2933 2933 ## Sets that results that will change file on disk
2934 2934 # Modified compared to target, no local change
2935 2935 (modified, actions['revert'], discard),
2936 2936 # Modified compared to target, but local file is deleted
2937 2937 (deleted, actions['revert'], discard),
2938 2938 # Modified compared to target, local change
2939 2939 (dsmodified, actions['revert'], dsmodifiedbackup),
2940 2940 # Added since target
2941 2941 (added, actions['remove'], discard),
2942 2942 # Added in working directory
2943 2943 (dsadded, actions['forget'], discard),
2944 2944 # Added since target, have local modification
2945 2945 (modadded, backupanddel, backup),
2946 2946 # Added since target but file is missing in working directory
2947 2947 (deladded, actions['drop'], discard),
2948 2948 # Removed since target, before working copy parent
2949 2949 (removed, actions['add'], discard),
2950 2950 # Same as `removed` but an unknown file exists at the same path
2951 2951 (removunk, actions['add'], check),
2952 2952 # Removed since targe, marked as such in working copy parent
2953 2953 (dsremoved, actions['undelete'], discard),
2954 2954 # Same as `dsremoved` but an unknown file exists at the same path
2955 2955 (dsremovunk, actions['undelete'], check),
2956 2956 ## the following sets does not result in any file changes
2957 2957 # File with no modification
2958 2958 (clean, actions['noop'], discard),
2959 2959 # Existing file, not tracked anywhere
2960 2960 (unknown, actions['unknown'], discard),
2961 2961 )
2962 2962
2963 2963 for abs, (rel, exact) in sorted(names.items()):
2964 2964 # target file to be touch on disk (relative to cwd)
2965 2965 target = repo.wjoin(abs)
2966 2966 # search the entry in the dispatch table.
2967 2967 # if the file is in any of these sets, it was touched in the working
2968 2968 # directory parent and we are sure it needs to be reverted.
2969 2969 for table, (xlist, msg), dobackup in disptable:
2970 2970 if abs not in table:
2971 2971 continue
2972 2972 if xlist is not None:
2973 2973 xlist.append(abs)
2974 2974 if dobackup:
2975 2975 # If in interactive mode, don't automatically create
2976 2976 # .orig files (issue4793)
2977 2977 if dobackup == backupinteractive:
2978 2978 tobackup.add(abs)
2979 2979 elif (backup <= dobackup or wctx[abs].cmp(ctx[abs])):
2980 2980 bakname = scmutil.origpath(ui, repo, rel)
2981 2981 ui.note(_('saving current version of %s as %s\n') %
2982 2982 (rel, bakname))
2983 2983 if not opts.get('dry_run'):
2984 2984 if interactive:
2985 2985 util.copyfile(target, bakname)
2986 2986 else:
2987 2987 util.rename(target, bakname)
2988 2988 if ui.verbose or not exact:
2989 2989 if not isinstance(msg, bytes):
2990 2990 msg = msg(abs)
2991 2991 ui.status(msg % rel)
2992 2992 elif exact:
2993 2993 ui.warn(msg % rel)
2994 2994 break
2995 2995
2996 2996 if not opts.get('dry_run'):
2997 2997 needdata = ('revert', 'add', 'undelete')
2998 2998 oplist = [actions[name][0] for name in needdata]
2999 2999 prefetch = scmutil.prefetchfiles
3000 3000 matchfiles = scmutil.matchfiles
3001 3001 prefetch(repo, [ctx.rev()],
3002 3002 matchfiles(repo,
3003 3003 [f for sublist in oplist for f in sublist]))
3004 3004 _performrevert(repo, parents, ctx, actions, interactive, tobackup)
3005 3005
3006 3006 if targetsubs:
3007 3007 # Revert the subrepos on the revert list
3008 3008 for sub in targetsubs:
3009 3009 try:
3010 3010 wctx.sub(sub).revert(ctx.substate[sub], *pats,
3011 3011 **pycompat.strkwargs(opts))
3012 3012 except KeyError:
3013 3013 raise error.Abort("subrepository '%s' does not exist in %s!"
3014 3014 % (sub, short(ctx.node())))
3015 3015
3016 3016 def _performrevert(repo, parents, ctx, actions, interactive=False,
3017 3017 tobackup=None):
3018 3018 """function that actually perform all the actions computed for revert
3019 3019
3020 3020 This is an independent function to let extension to plug in and react to
3021 3021 the imminent revert.
3022 3022
3023 3023 Make sure you have the working directory locked when calling this function.
3024 3024 """
3025 3025 parent, p2 = parents
3026 3026 node = ctx.node()
3027 3027 excluded_files = []
3028 3028
3029 3029 def checkout(f):
3030 3030 fc = ctx[f]
3031 3031 repo.wwrite(f, fc.data(), fc.flags())
3032 3032
3033 3033 def doremove(f):
3034 3034 try:
3035 3035 repo.wvfs.unlinkpath(f)
3036 3036 except OSError:
3037 3037 pass
3038 3038 repo.dirstate.remove(f)
3039 3039
3040 3040 audit_path = pathutil.pathauditor(repo.root, cached=True)
3041 3041 for f in actions['forget'][0]:
3042 3042 if interactive:
3043 3043 choice = repo.ui.promptchoice(
3044 3044 _("forget added file %s (Yn)?$$ &Yes $$ &No") % f)
3045 3045 if choice == 0:
3046 3046 repo.dirstate.drop(f)
3047 3047 else:
3048 3048 excluded_files.append(f)
3049 3049 else:
3050 3050 repo.dirstate.drop(f)
3051 3051 for f in actions['remove'][0]:
3052 3052 audit_path(f)
3053 3053 if interactive:
3054 3054 choice = repo.ui.promptchoice(
3055 3055 _("remove added file %s (Yn)?$$ &Yes $$ &No") % f)
3056 3056 if choice == 0:
3057 3057 doremove(f)
3058 3058 else:
3059 3059 excluded_files.append(f)
3060 3060 else:
3061 3061 doremove(f)
3062 3062 for f in actions['drop'][0]:
3063 3063 audit_path(f)
3064 3064 repo.dirstate.remove(f)
3065 3065
3066 3066 normal = None
3067 3067 if node == parent:
3068 3068 # We're reverting to our parent. If possible, we'd like status
3069 3069 # to report the file as clean. We have to use normallookup for
3070 3070 # merges to avoid losing information about merged/dirty files.
3071 3071 if p2 != nullid:
3072 3072 normal = repo.dirstate.normallookup
3073 3073 else:
3074 3074 normal = repo.dirstate.normal
3075 3075
3076 3076 newlyaddedandmodifiedfiles = set()
3077 3077 if interactive:
3078 3078 # Prompt the user for changes to revert
3079 3079 torevert = [f for f in actions['revert'][0] if f not in excluded_files]
3080 3080 m = scmutil.matchfiles(repo, torevert)
3081 3081 diffopts = patch.difffeatureopts(repo.ui, whitespace=True)
3082 3082 diffopts.nodates = True
3083 3083 diffopts.git = True
3084 3084 operation = 'discard'
3085 3085 reversehunks = True
3086 3086 if node != parent:
3087 3087 operation = 'apply'
3088 3088 reversehunks = False
3089 3089 if reversehunks:
3090 3090 diff = patch.diff(repo, ctx.node(), None, m, opts=diffopts)
3091 3091 else:
3092 3092 diff = patch.diff(repo, None, ctx.node(), m, opts=diffopts)
3093 3093 originalchunks = patch.parsepatch(diff)
3094 3094
3095 3095 try:
3096 3096
3097 3097 chunks, opts = recordfilter(repo.ui, originalchunks,
3098 3098 operation=operation)
3099 3099 if reversehunks:
3100 3100 chunks = patch.reversehunks(chunks)
3101 3101
3102 3102 except error.PatchError as err:
3103 3103 raise error.Abort(_('error parsing patch: %s') % err)
3104 3104
3105 3105 newlyaddedandmodifiedfiles = newandmodified(chunks, originalchunks)
3106 3106 if tobackup is None:
3107 3107 tobackup = set()
3108 3108 # Apply changes
3109 3109 fp = stringio()
3110 3110 for c in chunks:
3111 3111 # Create a backup file only if this hunk should be backed up
3112 3112 if ishunk(c) and c.header.filename() in tobackup:
3113 3113 abs = c.header.filename()
3114 3114 target = repo.wjoin(abs)
3115 3115 bakname = scmutil.origpath(repo.ui, repo, m.rel(abs))
3116 3116 util.copyfile(target, bakname)
3117 3117 tobackup.remove(abs)
3118 3118 c.write(fp)
3119 3119 dopatch = fp.tell()
3120 3120 fp.seek(0)
3121 3121 if dopatch:
3122 3122 try:
3123 3123 patch.internalpatch(repo.ui, repo, fp, 1, eolmode=None)
3124 3124 except error.PatchError as err:
3125 3125 raise error.Abort(pycompat.bytestr(err))
3126 3126 del fp
3127 3127 else:
3128 3128 for f in actions['revert'][0]:
3129 3129 checkout(f)
3130 3130 if normal:
3131 3131 normal(f)
3132 3132
3133 3133 for f in actions['add'][0]:
3134 3134 # Don't checkout modified files, they are already created by the diff
3135 3135 if f not in newlyaddedandmodifiedfiles:
3136 3136 checkout(f)
3137 3137 repo.dirstate.add(f)
3138 3138
3139 3139 normal = repo.dirstate.normallookup
3140 3140 if node == parent and p2 == nullid:
3141 3141 normal = repo.dirstate.normal
3142 3142 for f in actions['undelete'][0]:
3143 3143 checkout(f)
3144 3144 normal(f)
3145 3145
3146 3146 copied = copies.pathcopies(repo[parent], ctx)
3147 3147
3148 3148 for f in actions['add'][0] + actions['undelete'][0] + actions['revert'][0]:
3149 3149 if f in copied:
3150 3150 repo.dirstate.copy(copied[f], f)
3151 3151
3152 3152 # a list of (ui, repo, otherpeer, opts, missing) functions called by
3153 3153 # commands.outgoing. "missing" is "missing" of the result of
3154 3154 # "findcommonoutgoing()"
3155 3155 outgoinghooks = util.hooks()
3156 3156
3157 3157 # a list of (ui, repo) functions called by commands.summary
3158 3158 summaryhooks = util.hooks()
3159 3159
3160 3160 # a list of (ui, repo, opts, changes) functions called by commands.summary.
3161 3161 #
3162 3162 # functions should return tuple of booleans below, if 'changes' is None:
3163 3163 # (whether-incomings-are-needed, whether-outgoings-are-needed)
3164 3164 #
3165 3165 # otherwise, 'changes' is a tuple of tuples below:
3166 3166 # - (sourceurl, sourcebranch, sourcepeer, incoming)
3167 3167 # - (desturl, destbranch, destpeer, outgoing)
3168 3168 summaryremotehooks = util.hooks()
3169 3169
3170 3170 # A list of state files kept by multistep operations like graft.
3171 3171 # Since graft cannot be aborted, it is considered 'clearable' by update.
3172 3172 # note: bisect is intentionally excluded
3173 3173 # (state file, clearable, allowcommit, error, hint)
3174 3174 unfinishedstates = [
3175 3175 ('graftstate', True, False, _('graft in progress'),
3176 _("use 'hg graft --continue' or 'hg graft --stop' to abort")),
3176 _("use 'hg graft --continue' or 'hg graft --stop' to stop")),
3177 3177 ('updatestate', True, False, _('last update was interrupted'),
3178 3178 _("use 'hg update' to get a consistent checkout"))
3179 3179 ]
3180 3180
3181 3181 def checkunfinished(repo, commit=False):
3182 3182 '''Look for an unfinished multistep operation, like graft, and abort
3183 3183 if found. It's probably good to check this right before
3184 3184 bailifchanged().
3185 3185 '''
3186 3186 # Check for non-clearable states first, so things like rebase will take
3187 3187 # precedence over update.
3188 3188 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3189 3189 if clearable or (commit and allowcommit):
3190 3190 continue
3191 3191 if repo.vfs.exists(f):
3192 3192 raise error.Abort(msg, hint=hint)
3193 3193
3194 3194 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3195 3195 if not clearable or (commit and allowcommit):
3196 3196 continue
3197 3197 if repo.vfs.exists(f):
3198 3198 raise error.Abort(msg, hint=hint)
3199 3199
3200 3200 def clearunfinished(repo):
3201 3201 '''Check for unfinished operations (as above), and clear the ones
3202 3202 that are clearable.
3203 3203 '''
3204 3204 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3205 3205 if not clearable and repo.vfs.exists(f):
3206 3206 raise error.Abort(msg, hint=hint)
3207 3207 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3208 3208 if clearable and repo.vfs.exists(f):
3209 3209 util.unlink(repo.vfs.join(f))
3210 3210
3211 3211 afterresolvedstates = [
3212 3212 ('graftstate',
3213 3213 _('hg graft --continue')),
3214 3214 ]
3215 3215
3216 3216 def howtocontinue(repo):
3217 3217 '''Check for an unfinished operation and return the command to finish
3218 3218 it.
3219 3219
3220 3220 afterresolvedstates tuples define a .hg/{file} and the corresponding
3221 3221 command needed to finish it.
3222 3222
3223 3223 Returns a (msg, warning) tuple. 'msg' is a string and 'warning' is
3224 3224 a boolean.
3225 3225 '''
3226 3226 contmsg = _("continue: %s")
3227 3227 for f, msg in afterresolvedstates:
3228 3228 if repo.vfs.exists(f):
3229 3229 return contmsg % msg, True
3230 3230 if repo[None].dirty(missing=True, merge=False, branch=False):
3231 3231 return contmsg % _("hg commit"), False
3232 3232 return None, None
3233 3233
3234 3234 def checkafterresolved(repo):
3235 3235 '''Inform the user about the next action after completing hg resolve
3236 3236
3237 3237 If there's a matching afterresolvedstates, howtocontinue will yield
3238 3238 repo.ui.warn as the reporter.
3239 3239
3240 3240 Otherwise, it will yield repo.ui.note.
3241 3241 '''
3242 3242 msg, warning = howtocontinue(repo)
3243 3243 if msg is not None:
3244 3244 if warning:
3245 3245 repo.ui.warn("%s\n" % msg)
3246 3246 else:
3247 3247 repo.ui.note("%s\n" % msg)
3248 3248
3249 3249 def wrongtooltocontinue(repo, task):
3250 3250 '''Raise an abort suggesting how to properly continue if there is an
3251 3251 active task.
3252 3252
3253 3253 Uses howtocontinue() to find the active task.
3254 3254
3255 3255 If there's no task (repo.ui.note for 'hg commit'), it does not offer
3256 3256 a hint.
3257 3257 '''
3258 3258 after = howtocontinue(repo)
3259 3259 hint = None
3260 3260 if after[1]:
3261 3261 hint = after[0]
3262 3262 raise error.Abort(_('no %s in progress') % task, hint=hint)
@@ -1,1672 +1,1672 b''
1 1 $ cat >> $HGRCPATH <<EOF
2 2 > [extdiff]
3 3 > # for portability:
4 4 > pdiff = sh "$RUNTESTDIR/pdiff"
5 5 > EOF
6 6
7 7 Create a repo with some stuff in it:
8 8
9 9 $ hg init a
10 10 $ cd a
11 11 $ echo a > a
12 12 $ echo a > d
13 13 $ echo a > e
14 14 $ hg ci -qAm0
15 15 $ echo b > a
16 16 $ hg ci -m1 -u bar
17 17 $ hg mv a b
18 18 $ hg ci -m2
19 19 $ hg cp b c
20 20 $ hg ci -m3 -u baz
21 21 $ echo b > d
22 22 $ echo f > e
23 23 $ hg ci -m4
24 24 $ hg up -q 3
25 25 $ echo b > e
26 26 $ hg branch -q stable
27 27 $ hg ci -m5
28 28 $ hg merge -q default --tool internal:local
29 29 $ hg branch -q default
30 30 $ hg ci -m6
31 31 $ hg phase --public 3
32 32 $ hg phase --force --secret 6
33 33
34 34 $ hg log -G --template '{author}@{rev}.{phase}: {desc}\n'
35 35 @ test@6.secret: 6
36 36 |\
37 37 | o test@5.draft: 5
38 38 | |
39 39 o | test@4.draft: 4
40 40 |/
41 41 o baz@3.public: 3
42 42 |
43 43 o test@2.public: 2
44 44 |
45 45 o bar@1.public: 1
46 46 |
47 47 o test@0.public: 0
48 48
49 49 Can't continue without starting:
50 50
51 51 $ hg rm -q e
52 52 $ hg graft --continue
53 53 abort: no graft in progress
54 54 [255]
55 55 $ hg revert -r . -q e
56 56
57 57 Need to specify a rev:
58 58
59 59 $ hg graft
60 60 abort: no revisions specified
61 61 [255]
62 62
63 63 Can't graft ancestor:
64 64
65 65 $ hg graft 1 2
66 66 skipping ancestor revision 1:5d205f8b35b6
67 67 skipping ancestor revision 2:5c095ad7e90f
68 68 [255]
69 69
70 70 Specify revisions with -r:
71 71
72 72 $ hg graft -r 1 -r 2
73 73 skipping ancestor revision 1:5d205f8b35b6
74 74 skipping ancestor revision 2:5c095ad7e90f
75 75 [255]
76 76
77 77 $ hg graft -r 1 2
78 78 warning: inconsistent use of --rev might give unexpected revision ordering!
79 79 skipping ancestor revision 2:5c095ad7e90f
80 80 skipping ancestor revision 1:5d205f8b35b6
81 81 [255]
82 82
83 83 Can't graft with dirty wd:
84 84
85 85 $ hg up -q 0
86 86 $ echo foo > a
87 87 $ hg graft 1
88 88 abort: uncommitted changes
89 89 [255]
90 90 $ hg revert a
91 91
92 92 Graft a rename:
93 93 (this also tests that editor is invoked if '--edit' is specified)
94 94
95 95 $ hg status --rev "2^1" --rev 2
96 96 A b
97 97 R a
98 98 $ HGEDITOR=cat hg graft 2 -u foo --edit
99 99 grafting 2:5c095ad7e90f "2"
100 100 merging a and b to b
101 101 2
102 102
103 103
104 104 HG: Enter commit message. Lines beginning with 'HG:' are removed.
105 105 HG: Leave message empty to abort commit.
106 106 HG: --
107 107 HG: user: foo
108 108 HG: branch 'default'
109 109 HG: added b
110 110 HG: removed a
111 111 $ hg export tip --git
112 112 # HG changeset patch
113 113 # User foo
114 114 # Date 0 0
115 115 # Thu Jan 01 00:00:00 1970 +0000
116 116 # Node ID ef0ef43d49e79e81ddafdc7997401ba0041efc82
117 117 # Parent 68795b066622ca79a25816a662041d8f78f3cd9e
118 118 2
119 119
120 120 diff --git a/a b/b
121 121 rename from a
122 122 rename to b
123 123
124 124 Look for extra:source
125 125
126 126 $ hg log --debug -r tip
127 127 changeset: 7:ef0ef43d49e79e81ddafdc7997401ba0041efc82
128 128 tag: tip
129 129 phase: draft
130 130 parent: 0:68795b066622ca79a25816a662041d8f78f3cd9e
131 131 parent: -1:0000000000000000000000000000000000000000
132 132 manifest: 7:e59b6b228f9cbf9903d5e9abf996e083a1f533eb
133 133 user: foo
134 134 date: Thu Jan 01 00:00:00 1970 +0000
135 135 files+: b
136 136 files-: a
137 137 extra: branch=default
138 138 extra: source=5c095ad7e90f871700f02dd1fa5012cb4498a2d4
139 139 description:
140 140 2
141 141
142 142
143 143
144 144 Graft out of order, skipping a merge and a duplicate
145 145 (this also tests that editor is not invoked if '--edit' is not specified)
146 146
147 147 $ hg graft 1 5 4 3 'merge()' 2 -n
148 148 skipping ungraftable merge revision 6
149 149 skipping revision 2:5c095ad7e90f (already grafted to 7:ef0ef43d49e7)
150 150 grafting 1:5d205f8b35b6 "1"
151 151 grafting 5:97f8bfe72746 "5"
152 152 grafting 4:9c233e8e184d "4"
153 153 grafting 3:4c60f11aa304 "3"
154 154
155 155 $ HGEDITOR=cat hg graft 1 5 'merge()' 2 --debug
156 156 skipping ungraftable merge revision 6
157 157 scanning for duplicate grafts
158 158 skipping revision 2:5c095ad7e90f (already grafted to 7:ef0ef43d49e7)
159 159 grafting 1:5d205f8b35b6 "1"
160 160 searching for copies back to rev 1
161 161 unmatched files in local:
162 162 b
163 163 all copies found (* = to merge, ! = divergent, % = renamed and deleted):
164 164 src: 'a' -> dst: 'b' *
165 165 checking for directory renames
166 166 resolving manifests
167 167 branchmerge: True, force: True, partial: False
168 168 ancestor: 68795b066622, local: ef0ef43d49e7+, remote: 5d205f8b35b6
169 169 preserving b for resolve of b
170 170 starting 4 threads for background file closing (?)
171 171 b: local copied/moved from a -> m (premerge)
172 172 picked tool ':merge' for b (binary False symlink False changedelete False)
173 173 merging b and a to b
174 174 my b@ef0ef43d49e7+ other a@5d205f8b35b6 ancestor a@68795b066622
175 175 premerge successful
176 176 committing files:
177 177 b
178 178 committing manifest
179 179 committing changelog
180 180 updating the branch cache
181 181 grafting 5:97f8bfe72746 "5"
182 182 searching for copies back to rev 1
183 183 unmatched files in other (from topological common ancestor):
184 184 c
185 185 resolving manifests
186 186 branchmerge: True, force: True, partial: False
187 187 ancestor: 4c60f11aa304, local: 6b9e5368ca4e+, remote: 97f8bfe72746
188 188 e: remote is newer -> g
189 189 getting e
190 190 committing files:
191 191 e
192 192 committing manifest
193 193 committing changelog
194 194 updating the branch cache
195 195 $ HGEDITOR=cat hg graft 4 3 --log --debug
196 196 scanning for duplicate grafts
197 197 grafting 4:9c233e8e184d "4"
198 198 searching for copies back to rev 1
199 199 unmatched files in other (from topological common ancestor):
200 200 c
201 201 resolving manifests
202 202 branchmerge: True, force: True, partial: False
203 203 ancestor: 4c60f11aa304, local: 1905859650ec+, remote: 9c233e8e184d
204 204 preserving e for resolve of e
205 205 d: remote is newer -> g
206 206 getting d
207 207 e: versions differ -> m (premerge)
208 208 picked tool ':merge' for e (binary False symlink False changedelete False)
209 209 merging e
210 210 my e@1905859650ec+ other e@9c233e8e184d ancestor e@4c60f11aa304
211 211 e: versions differ -> m (merge)
212 212 picked tool ':merge' for e (binary False symlink False changedelete False)
213 213 my e@1905859650ec+ other e@9c233e8e184d ancestor e@4c60f11aa304
214 214 warning: conflicts while merging e! (edit, then use 'hg resolve --mark')
215 215 abort: unresolved conflicts, can't continue
216 216 (use 'hg resolve' and 'hg graft --continue')
217 217 [255]
218 218
219 219 Summary should mention graft:
220 220
221 221 $ hg summary |grep graft
222 222 commit: 2 modified, 2 unknown, 1 unresolved (graft in progress)
223 223
224 224 Using status to get more context
225 225
226 226 $ hg status --verbose
227 227 M d
228 228 M e
229 229 ? a.orig
230 230 ? e.orig
231 231 # The repository is in an unfinished *graft* state.
232 232
233 233 # Unresolved merge conflicts:
234 234 #
235 235 # e
236 236 #
237 237 # To mark files as resolved: hg resolve --mark FILE
238 238
239 239 # To continue: hg graft --continue
240 240 # To abort: hg update --clean . (warning: this will discard uncommitted changes)
241 241
242 242
243 243 Commit while interrupted should fail:
244 244
245 245 $ hg ci -m 'commit interrupted graft'
246 246 abort: graft in progress
247 (use 'hg graft --continue' or 'hg graft --stop' to abort)
247 (use 'hg graft --continue' or 'hg graft --stop' to stop)
248 248 [255]
249 249
250 250 Abort the graft and try committing:
251 251
252 252 $ hg up -C .
253 253 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
254 254 $ echo c >> e
255 255 $ hg ci -mtest
256 256
257 257 $ hg strip . --config extensions.strip=
258 258 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
259 259 saved backup bundle to $TESTTMP/a/.hg/strip-backup/*-backup.hg (glob)
260 260
261 261 Graft again:
262 262
263 263 $ hg graft 1 5 4 3 'merge()' 2
264 264 skipping ungraftable merge revision 6
265 265 skipping revision 2:5c095ad7e90f (already grafted to 7:ef0ef43d49e7)
266 266 skipping revision 1:5d205f8b35b6 (already grafted to 8:6b9e5368ca4e)
267 267 skipping revision 5:97f8bfe72746 (already grafted to 9:1905859650ec)
268 268 grafting 4:9c233e8e184d "4"
269 269 merging e
270 270 warning: conflicts while merging e! (edit, then use 'hg resolve --mark')
271 271 abort: unresolved conflicts, can't continue
272 272 (use 'hg resolve' and 'hg graft --continue')
273 273 [255]
274 274
275 275 Continue without resolve should fail:
276 276
277 277 $ hg graft -c
278 278 grafting 4:9c233e8e184d "4"
279 279 abort: unresolved merge conflicts (see 'hg help resolve')
280 280 [255]
281 281
282 282 Fix up:
283 283
284 284 $ echo b > e
285 285 $ hg resolve -m e
286 286 (no more unresolved files)
287 287 continue: hg graft --continue
288 288
289 289 Continue with a revision should fail:
290 290
291 291 $ hg graft -c 6
292 292 abort: can't specify --continue and revisions
293 293 [255]
294 294
295 295 $ hg graft -c -r 6
296 296 abort: can't specify --continue and revisions
297 297 [255]
298 298
299 299 Continue for real, clobber usernames
300 300
301 301 $ hg graft -c -U
302 302 grafting 4:9c233e8e184d "4"
303 303 grafting 3:4c60f11aa304 "3"
304 304
305 305 Compare with original:
306 306
307 307 $ hg diff -r 6
308 308 $ hg status --rev 0:. -C
309 309 M d
310 310 M e
311 311 A b
312 312 a
313 313 A c
314 314 a
315 315 R a
316 316
317 317 View graph:
318 318
319 319 $ hg log -G --template '{author}@{rev}.{phase}: {desc}\n'
320 320 @ test@11.draft: 3
321 321 |
322 322 o test@10.draft: 4
323 323 |
324 324 o test@9.draft: 5
325 325 |
326 326 o bar@8.draft: 1
327 327 |
328 328 o foo@7.draft: 2
329 329 |
330 330 | o test@6.secret: 6
331 331 | |\
332 332 | | o test@5.draft: 5
333 333 | | |
334 334 | o | test@4.draft: 4
335 335 | |/
336 336 | o baz@3.public: 3
337 337 | |
338 338 | o test@2.public: 2
339 339 | |
340 340 | o bar@1.public: 1
341 341 |/
342 342 o test@0.public: 0
343 343
344 344 Graft again onto another branch should preserve the original source
345 345 $ hg up -q 0
346 346 $ echo 'g'>g
347 347 $ hg add g
348 348 $ hg ci -m 7
349 349 created new head
350 350 $ hg graft 7
351 351 grafting 7:ef0ef43d49e7 "2"
352 352
353 353 $ hg log -r 7 --template '{rev}:{node}\n'
354 354 7:ef0ef43d49e79e81ddafdc7997401ba0041efc82
355 355 $ hg log -r 2 --template '{rev}:{node}\n'
356 356 2:5c095ad7e90f871700f02dd1fa5012cb4498a2d4
357 357
358 358 $ hg log --debug -r tip
359 359 changeset: 13:7a4785234d87ec1aa420ed6b11afe40fa73e12a9
360 360 tag: tip
361 361 phase: draft
362 362 parent: 12:b592ea63bb0c19a6c5c44685ee29a2284f9f1b8f
363 363 parent: -1:0000000000000000000000000000000000000000
364 364 manifest: 13:dc313617b8c32457c0d589e0dbbedfe71f3cd637
365 365 user: foo
366 366 date: Thu Jan 01 00:00:00 1970 +0000
367 367 files+: b
368 368 files-: a
369 369 extra: branch=default
370 370 extra: intermediate-source=ef0ef43d49e79e81ddafdc7997401ba0041efc82
371 371 extra: source=5c095ad7e90f871700f02dd1fa5012cb4498a2d4
372 372 description:
373 373 2
374 374
375 375
376 376 Disallow grafting an already grafted cset onto its original branch
377 377 $ hg up -q 6
378 378 $ hg graft 7
379 379 skipping already grafted revision 7:ef0ef43d49e7 (was grafted from 2:5c095ad7e90f)
380 380 [255]
381 381
382 382 $ hg pdiff --config extensions.extdiff= --patch -r 2 -r 13
383 383 --- */hg-5c095ad7e90f.patch * (glob)
384 384 +++ */hg-7a4785234d87.patch * (glob)
385 385 @@ -1,18 +1,18 @@
386 386 # HG changeset patch
387 387 -# User test
388 388 +# User foo
389 389 # Date 0 0
390 390 # Thu Jan 01 00:00:00 1970 +0000
391 391 -# Node ID 5c095ad7e90f871700f02dd1fa5012cb4498a2d4
392 392 -# Parent 5d205f8b35b66bc36375c9534ffd3237730e8f04
393 393 +# Node ID 7a4785234d87ec1aa420ed6b11afe40fa73e12a9
394 394 +# Parent b592ea63bb0c19a6c5c44685ee29a2284f9f1b8f
395 395 2
396 396
397 397 -diff -r 5d205f8b35b6 -r 5c095ad7e90f a
398 398 +diff -r b592ea63bb0c -r 7a4785234d87 a
399 399 --- a/a Thu Jan 01 00:00:00 1970 +0000
400 400 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
401 401 @@ -1,1 +0,0 @@
402 402 --b
403 403 -diff -r 5d205f8b35b6 -r 5c095ad7e90f b
404 404 +-a
405 405 +diff -r b592ea63bb0c -r 7a4785234d87 b
406 406 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
407 407 +++ b/b Thu Jan 01 00:00:00 1970 +0000
408 408 @@ -0,0 +1,1 @@
409 409 -+b
410 410 ++a
411 411 [1]
412 412
413 413 $ hg pdiff --config extensions.extdiff= --patch -r 2 -r 13 -X .
414 414 --- */hg-5c095ad7e90f.patch * (glob)
415 415 +++ */hg-7a4785234d87.patch * (glob)
416 416 @@ -1,8 +1,8 @@
417 417 # HG changeset patch
418 418 -# User test
419 419 +# User foo
420 420 # Date 0 0
421 421 # Thu Jan 01 00:00:00 1970 +0000
422 422 -# Node ID 5c095ad7e90f871700f02dd1fa5012cb4498a2d4
423 423 -# Parent 5d205f8b35b66bc36375c9534ffd3237730e8f04
424 424 +# Node ID 7a4785234d87ec1aa420ed6b11afe40fa73e12a9
425 425 +# Parent b592ea63bb0c19a6c5c44685ee29a2284f9f1b8f
426 426 2
427 427
428 428 [1]
429 429
430 430 Disallow grafting already grafted csets with the same origin onto each other
431 431 $ hg up -q 13
432 432 $ hg graft 2
433 433 skipping revision 2:5c095ad7e90f (already grafted to 13:7a4785234d87)
434 434 [255]
435 435 $ hg graft 7
436 436 skipping already grafted revision 7:ef0ef43d49e7 (13:7a4785234d87 also has origin 2:5c095ad7e90f)
437 437 [255]
438 438
439 439 $ hg up -q 7
440 440 $ hg graft 2
441 441 skipping revision 2:5c095ad7e90f (already grafted to 7:ef0ef43d49e7)
442 442 [255]
443 443 $ hg graft tip
444 444 skipping already grafted revision 13:7a4785234d87 (7:ef0ef43d49e7 also has origin 2:5c095ad7e90f)
445 445 [255]
446 446
447 447 Graft with --log
448 448
449 449 $ hg up -Cq 1
450 450 $ hg graft 3 --log -u foo
451 451 grafting 3:4c60f11aa304 "3"
452 452 warning: can't find ancestor for 'c' copied from 'b'!
453 453 $ hg log --template '{rev}:{node|short} {parents} {desc}\n' -r tip
454 454 14:0c921c65ef1e 1:5d205f8b35b6 3
455 455 (grafted from 4c60f11aa304a54ae1c199feb94e7fc771e51ed8)
456 456
457 457 Resolve conflicted graft
458 458 $ hg up -q 0
459 459 $ echo b > a
460 460 $ hg ci -m 8
461 461 created new head
462 462 $ echo c > a
463 463 $ hg ci -m 9
464 464 $ hg graft 1 --tool internal:fail
465 465 grafting 1:5d205f8b35b6 "1"
466 466 abort: unresolved conflicts, can't continue
467 467 (use 'hg resolve' and 'hg graft --continue')
468 468 [255]
469 469 $ hg resolve --all
470 470 merging a
471 471 warning: conflicts while merging a! (edit, then use 'hg resolve --mark')
472 472 [1]
473 473 $ cat a
474 474 <<<<<<< local: aaa4406d4f0a - test: 9
475 475 c
476 476 =======
477 477 b
478 478 >>>>>>> graft: 5d205f8b35b6 - bar: 1
479 479 $ echo b > a
480 480 $ hg resolve -m a
481 481 (no more unresolved files)
482 482 continue: hg graft --continue
483 483 $ hg graft -c
484 484 grafting 1:5d205f8b35b6 "1"
485 485 $ hg export tip --git
486 486 # HG changeset patch
487 487 # User bar
488 488 # Date 0 0
489 489 # Thu Jan 01 00:00:00 1970 +0000
490 490 # Node ID f67661df0c4804d301f064f332b57e7d5ddaf2be
491 491 # Parent aaa4406d4f0ae9befd6e58c82ec63706460cbca6
492 492 1
493 493
494 494 diff --git a/a b/a
495 495 --- a/a
496 496 +++ b/a
497 497 @@ -1,1 +1,1 @@
498 498 -c
499 499 +b
500 500
501 501 Resolve conflicted graft with rename
502 502 $ echo c > a
503 503 $ hg ci -m 10
504 504 $ hg graft 2 --tool internal:fail
505 505 grafting 2:5c095ad7e90f "2"
506 506 abort: unresolved conflicts, can't continue
507 507 (use 'hg resolve' and 'hg graft --continue')
508 508 [255]
509 509 $ hg resolve --all
510 510 merging a and b to b
511 511 (no more unresolved files)
512 512 continue: hg graft --continue
513 513 $ hg graft -c
514 514 grafting 2:5c095ad7e90f "2"
515 515 $ hg export tip --git
516 516 # HG changeset patch
517 517 # User test
518 518 # Date 0 0
519 519 # Thu Jan 01 00:00:00 1970 +0000
520 520 # Node ID 9627f653b421c61fc1ea4c4e366745070fa3d2bc
521 521 # Parent ee295f490a40b97f3d18dd4c4f1c8936c233b612
522 522 2
523 523
524 524 diff --git a/a b/b
525 525 rename from a
526 526 rename to b
527 527
528 528 Test simple origin(), with and without args
529 529 $ hg log -r 'origin()'
530 530 changeset: 1:5d205f8b35b6
531 531 user: bar
532 532 date: Thu Jan 01 00:00:00 1970 +0000
533 533 summary: 1
534 534
535 535 changeset: 2:5c095ad7e90f
536 536 user: test
537 537 date: Thu Jan 01 00:00:00 1970 +0000
538 538 summary: 2
539 539
540 540 changeset: 3:4c60f11aa304
541 541 user: baz
542 542 date: Thu Jan 01 00:00:00 1970 +0000
543 543 summary: 3
544 544
545 545 changeset: 4:9c233e8e184d
546 546 user: test
547 547 date: Thu Jan 01 00:00:00 1970 +0000
548 548 summary: 4
549 549
550 550 changeset: 5:97f8bfe72746
551 551 branch: stable
552 552 parent: 3:4c60f11aa304
553 553 user: test
554 554 date: Thu Jan 01 00:00:00 1970 +0000
555 555 summary: 5
556 556
557 557 $ hg log -r 'origin(7)'
558 558 changeset: 2:5c095ad7e90f
559 559 user: test
560 560 date: Thu Jan 01 00:00:00 1970 +0000
561 561 summary: 2
562 562
563 563 Now transplant a graft to test following through copies
564 564 $ hg up -q 0
565 565 $ hg branch -q dev
566 566 $ hg ci -qm "dev branch"
567 567 $ hg --config extensions.transplant= transplant -q 7
568 568 $ hg log -r 'origin(.)'
569 569 changeset: 2:5c095ad7e90f
570 570 user: test
571 571 date: Thu Jan 01 00:00:00 1970 +0000
572 572 summary: 2
573 573
574 574 Test that the graft and transplant markers in extra are converted, allowing
575 575 origin() to still work. Note that these recheck the immediately preceeding two
576 576 tests.
577 577 $ hg --quiet --config extensions.convert= --config convert.hg.saverev=True convert . ../converted
578 578
579 579 The graft case
580 580 $ hg -R ../converted log -r 7 --template "{rev}: {node}\n{join(extras, '\n')}\n"
581 581 7: 7ae846e9111fc8f57745634250c7b9ac0a60689b
582 582 branch=default
583 583 convert_revision=ef0ef43d49e79e81ddafdc7997401ba0041efc82
584 584 source=e0213322b2c1a5d5d236c74e79666441bee67a7d
585 585 $ hg -R ../converted log -r 'origin(7)'
586 586 changeset: 2:e0213322b2c1
587 587 user: test
588 588 date: Thu Jan 01 00:00:00 1970 +0000
589 589 summary: 2
590 590
591 591 Test that template correctly expands more than one 'extra' (issue4362), and that
592 592 'intermediate-source' is converted.
593 593 $ hg -R ../converted log -r 13 --template "{extras % ' Extra: {extra}\n'}"
594 594 Extra: branch=default
595 595 Extra: convert_revision=7a4785234d87ec1aa420ed6b11afe40fa73e12a9
596 596 Extra: intermediate-source=7ae846e9111fc8f57745634250c7b9ac0a60689b
597 597 Extra: source=e0213322b2c1a5d5d236c74e79666441bee67a7d
598 598
599 599 The transplant case
600 600 $ hg -R ../converted log -r tip --template "{rev}: {node}\n{join(extras, '\n')}\n"
601 601 21: fbb6c5cc81002f2b4b49c9d731404688bcae5ade
602 602 branch=dev
603 603 convert_revision=7e61b508e709a11d28194a5359bc3532d910af21
604 604 transplant_source=z\xe8F\xe9\x11\x1f\xc8\xf5wEcBP\xc7\xb9\xac\n`h\x9b
605 605 $ hg -R ../converted log -r 'origin(tip)'
606 606 changeset: 2:e0213322b2c1
607 607 user: test
608 608 date: Thu Jan 01 00:00:00 1970 +0000
609 609 summary: 2
610 610
611 611
612 612 Test simple destination
613 613 $ hg log -r 'destination()'
614 614 changeset: 7:ef0ef43d49e7
615 615 parent: 0:68795b066622
616 616 user: foo
617 617 date: Thu Jan 01 00:00:00 1970 +0000
618 618 summary: 2
619 619
620 620 changeset: 8:6b9e5368ca4e
621 621 user: bar
622 622 date: Thu Jan 01 00:00:00 1970 +0000
623 623 summary: 1
624 624
625 625 changeset: 9:1905859650ec
626 626 user: test
627 627 date: Thu Jan 01 00:00:00 1970 +0000
628 628 summary: 5
629 629
630 630 changeset: 10:52dc0b4c6907
631 631 user: test
632 632 date: Thu Jan 01 00:00:00 1970 +0000
633 633 summary: 4
634 634
635 635 changeset: 11:882b35362a6b
636 636 user: test
637 637 date: Thu Jan 01 00:00:00 1970 +0000
638 638 summary: 3
639 639
640 640 changeset: 13:7a4785234d87
641 641 user: foo
642 642 date: Thu Jan 01 00:00:00 1970 +0000
643 643 summary: 2
644 644
645 645 changeset: 14:0c921c65ef1e
646 646 parent: 1:5d205f8b35b6
647 647 user: foo
648 648 date: Thu Jan 01 00:00:00 1970 +0000
649 649 summary: 3
650 650
651 651 changeset: 17:f67661df0c48
652 652 user: bar
653 653 date: Thu Jan 01 00:00:00 1970 +0000
654 654 summary: 1
655 655
656 656 changeset: 19:9627f653b421
657 657 user: test
658 658 date: Thu Jan 01 00:00:00 1970 +0000
659 659 summary: 2
660 660
661 661 changeset: 21:7e61b508e709
662 662 branch: dev
663 663 tag: tip
664 664 user: foo
665 665 date: Thu Jan 01 00:00:00 1970 +0000
666 666 summary: 2
667 667
668 668 $ hg log -r 'destination(2)'
669 669 changeset: 7:ef0ef43d49e7
670 670 parent: 0:68795b066622
671 671 user: foo
672 672 date: Thu Jan 01 00:00:00 1970 +0000
673 673 summary: 2
674 674
675 675 changeset: 13:7a4785234d87
676 676 user: foo
677 677 date: Thu Jan 01 00:00:00 1970 +0000
678 678 summary: 2
679 679
680 680 changeset: 19:9627f653b421
681 681 user: test
682 682 date: Thu Jan 01 00:00:00 1970 +0000
683 683 summary: 2
684 684
685 685 changeset: 21:7e61b508e709
686 686 branch: dev
687 687 tag: tip
688 688 user: foo
689 689 date: Thu Jan 01 00:00:00 1970 +0000
690 690 summary: 2
691 691
692 692 Transplants of grafts can find a destination...
693 693 $ hg log -r 'destination(7)'
694 694 changeset: 21:7e61b508e709
695 695 branch: dev
696 696 tag: tip
697 697 user: foo
698 698 date: Thu Jan 01 00:00:00 1970 +0000
699 699 summary: 2
700 700
701 701 ... grafts of grafts unfortunately can't
702 702 $ hg graft -q 13
703 703 warning: can't find ancestor for 'b' copied from 'a'!
704 704 $ hg log -r 'destination(13)'
705 705 All copies of a cset
706 706 $ hg log -r 'origin(13) or destination(origin(13))'
707 707 changeset: 2:5c095ad7e90f
708 708 user: test
709 709 date: Thu Jan 01 00:00:00 1970 +0000
710 710 summary: 2
711 711
712 712 changeset: 7:ef0ef43d49e7
713 713 parent: 0:68795b066622
714 714 user: foo
715 715 date: Thu Jan 01 00:00:00 1970 +0000
716 716 summary: 2
717 717
718 718 changeset: 13:7a4785234d87
719 719 user: foo
720 720 date: Thu Jan 01 00:00:00 1970 +0000
721 721 summary: 2
722 722
723 723 changeset: 19:9627f653b421
724 724 user: test
725 725 date: Thu Jan 01 00:00:00 1970 +0000
726 726 summary: 2
727 727
728 728 changeset: 21:7e61b508e709
729 729 branch: dev
730 730 user: foo
731 731 date: Thu Jan 01 00:00:00 1970 +0000
732 732 summary: 2
733 733
734 734 changeset: 22:d1cb6591fa4b
735 735 branch: dev
736 736 tag: tip
737 737 user: foo
738 738 date: Thu Jan 01 00:00:00 1970 +0000
739 739 summary: 2
740 740
741 741
742 742 graft works on complex revset
743 743
744 744 $ hg graft 'origin(13) or destination(origin(13))'
745 745 skipping ancestor revision 21:7e61b508e709
746 746 skipping ancestor revision 22:d1cb6591fa4b
747 747 skipping revision 2:5c095ad7e90f (already grafted to 22:d1cb6591fa4b)
748 748 grafting 7:ef0ef43d49e7 "2"
749 749 warning: can't find ancestor for 'b' copied from 'a'!
750 750 grafting 13:7a4785234d87 "2"
751 751 warning: can't find ancestor for 'b' copied from 'a'!
752 752 grafting 19:9627f653b421 "2"
753 753 merging b
754 754 warning: can't find ancestor for 'b' copied from 'a'!
755 755
756 756 graft with --force (still doesn't graft merges)
757 757
758 758 $ hg graft 19 0 6
759 759 skipping ungraftable merge revision 6
760 760 skipping ancestor revision 0:68795b066622
761 761 skipping already grafted revision 19:9627f653b421 (22:d1cb6591fa4b also has origin 2:5c095ad7e90f)
762 762 [255]
763 763 $ hg graft 19 0 6 --force
764 764 skipping ungraftable merge revision 6
765 765 grafting 19:9627f653b421 "2"
766 766 merging b
767 767 warning: can't find ancestor for 'b' copied from 'a'!
768 768 grafting 0:68795b066622 "0"
769 769
770 770 graft --force after backout
771 771
772 772 $ echo abc > a
773 773 $ hg ci -m 28
774 774 $ hg backout 28
775 775 reverting a
776 776 changeset 29:53177ba928f6 backs out changeset 28:50a516bb8b57
777 777 $ hg graft 28
778 778 skipping ancestor revision 28:50a516bb8b57
779 779 [255]
780 780 $ hg graft 28 --force
781 781 grafting 28:50a516bb8b57 "28"
782 782 merging a
783 783 $ cat a
784 784 abc
785 785
786 786 graft --continue after --force
787 787
788 788 $ echo def > a
789 789 $ hg ci -m 31
790 790 $ hg graft 28 --force --tool internal:fail
791 791 grafting 28:50a516bb8b57 "28"
792 792 abort: unresolved conflicts, can't continue
793 793 (use 'hg resolve' and 'hg graft --continue')
794 794 [255]
795 795 $ hg resolve --all
796 796 merging a
797 797 warning: conflicts while merging a! (edit, then use 'hg resolve --mark')
798 798 [1]
799 799 $ echo abc > a
800 800 $ hg resolve -m a
801 801 (no more unresolved files)
802 802 continue: hg graft --continue
803 803 $ hg graft -c
804 804 grafting 28:50a516bb8b57 "28"
805 805 $ cat a
806 806 abc
807 807
808 808 Continue testing same origin policy, using revision numbers from test above
809 809 but do some destructive editing of the repo:
810 810
811 811 $ hg up -qC 7
812 812 $ hg tag -l -r 13 tmp
813 813 $ hg --config extensions.strip= strip 2
814 814 saved backup bundle to $TESTTMP/a/.hg/strip-backup/5c095ad7e90f-d323a1e4-backup.hg
815 815 $ hg graft tmp
816 816 skipping already grafted revision 8:7a4785234d87 (2:ef0ef43d49e7 also has unknown origin 5c095ad7e90f)
817 817 [255]
818 818
819 819 Empty graft
820 820
821 821 $ hg up -qr 26
822 822 $ hg tag -f something
823 823 $ hg graft -qr 27
824 824 $ hg graft -f 27
825 825 grafting 27:ed6c7e54e319 "28"
826 826 note: graft of 27:ed6c7e54e319 created no changes to commit
827 827
828 828 $ cd ..
829 829
830 830 Graft to duplicate a commit
831 831
832 832 $ hg init graftsibling
833 833 $ cd graftsibling
834 834 $ touch a
835 835 $ hg commit -qAm a
836 836 $ touch b
837 837 $ hg commit -qAm b
838 838 $ hg log -G -T '{rev}\n'
839 839 @ 1
840 840 |
841 841 o 0
842 842
843 843 $ hg up -q 0
844 844 $ hg graft -r 1
845 845 grafting 1:0e067c57feba "b" (tip)
846 846 $ hg log -G -T '{rev}\n'
847 847 @ 2
848 848 |
849 849 | o 1
850 850 |/
851 851 o 0
852 852
853 853 Graft to duplicate a commit twice
854 854
855 855 $ hg up -q 0
856 856 $ hg graft -r 2
857 857 grafting 2:044ec77f6389 "b" (tip)
858 858 $ hg log -G -T '{rev}\n'
859 859 @ 3
860 860 |
861 861 | o 2
862 862 |/
863 863 | o 1
864 864 |/
865 865 o 0
866 866
867 867 Graft from behind a move or rename
868 868 ==================================
869 869
870 870 NOTE: This is affected by issue5343, and will need updating when it's fixed
871 871
872 872 Possible cases during a regular graft (when ca is between cta and c2):
873 873
874 874 name | c1<-cta | cta<->ca | ca->c2
875 875 A.0 | | |
876 876 A.1 | X | |
877 877 A.2 | | X |
878 878 A.3 | | | X
879 879 A.4 | X | X |
880 880 A.5 | X | | X
881 881 A.6 | | X | X
882 882 A.7 | X | X | X
883 883
884 884 A.0 is trivial, and doesn't need copy tracking.
885 885 For A.1, a forward rename is recorded in the c1 pass, to be followed later.
886 886 In A.2, the rename is recorded in the c2 pass and followed backwards.
887 887 A.3 is recorded in the c2 pass as a forward rename to be duplicated on target.
888 888 In A.4, both passes of checkcopies record incomplete renames, which are
889 889 then joined in mergecopies to record a rename to be followed.
890 890 In A.5 and A.7, the c1 pass records an incomplete rename, while the c2 pass
891 891 records an incomplete divergence. The incomplete rename is then joined to the
892 892 appropriate side of the incomplete divergence, and the result is recorded as a
893 893 divergence. The code doesn't distinguish at all between these two cases, since
894 894 the end result of them is the same: an incomplete divergence joined with an
895 895 incomplete rename into a divergence.
896 896 Finally, A.6 records a divergence entirely in the c2 pass.
897 897
898 898 A.4 has a degenerate case a<-b<-a->a, where checkcopies isn't needed at all.
899 899 A.5 has a special case a<-b<-b->a, which is treated like a<-b->a in a merge.
900 900 A.6 has a special case a<-a<-b->a. Here, checkcopies will find a spurious
901 901 incomplete divergence, which is in fact complete. This is handled later in
902 902 mergecopies.
903 903 A.7 has 4 special cases: a<-b<-a->b (the "ping-pong" case), a<-b<-c->b,
904 904 a<-b<-a->c and a<-b<-c->a. Of these, only the "ping-pong" case is interesting,
905 905 the others are fairly trivial (a<-b<-c->b and a<-b<-a->c proceed like the base
906 906 case, a<-b<-c->a is treated the same as a<-b<-b->a).
907 907
908 908 f5a therefore tests the "ping-pong" rename case, where a file is renamed to the
909 909 same name on both branches, then the rename is backed out on one branch, and
910 910 the backout is grafted to the other branch. This creates a challenging rename
911 911 sequence of a<-b<-a->b in the graft target, topological CA, graft CA and graft
912 912 source, respectively. Since rename detection will run on the c1 side for such a
913 913 sequence (as for technical reasons, we split the c1 and c2 sides not at the
914 914 graft CA, but rather at the topological CA), it will pick up a false rename,
915 915 and cause a spurious merge conflict. This false rename is always exactly the
916 916 reverse of the true rename that would be detected on the c2 side, so we can
917 917 correct for it by detecting this condition and reversing as necessary.
918 918
919 919 First, set up the repository with commits to be grafted
920 920
921 921 $ hg init ../graftmove
922 922 $ cd ../graftmove
923 923 $ echo c1a > f1a
924 924 $ echo c2a > f2a
925 925 $ echo c3a > f3a
926 926 $ echo c4a > f4a
927 927 $ echo c5a > f5a
928 928 $ hg ci -qAm A0
929 929 $ hg mv f1a f1b
930 930 $ hg mv f3a f3b
931 931 $ hg mv f5a f5b
932 932 $ hg ci -qAm B0
933 933 $ echo c1c > f1b
934 934 $ hg mv f2a f2c
935 935 $ hg mv f5b f5a
936 936 $ echo c5c > f5a
937 937 $ hg ci -qAm C0
938 938 $ hg mv f3b f3d
939 939 $ echo c4d > f4a
940 940 $ hg ci -qAm D0
941 941 $ hg log -G
942 942 @ changeset: 3:b69f5839d2d9
943 943 | tag: tip
944 944 | user: test
945 945 | date: Thu Jan 01 00:00:00 1970 +0000
946 946 | summary: D0
947 947 |
948 948 o changeset: 2:f58c7e2b28fa
949 949 | user: test
950 950 | date: Thu Jan 01 00:00:00 1970 +0000
951 951 | summary: C0
952 952 |
953 953 o changeset: 1:3d7bba921b5d
954 954 | user: test
955 955 | date: Thu Jan 01 00:00:00 1970 +0000
956 956 | summary: B0
957 957 |
958 958 o changeset: 0:11f7a1b56675
959 959 user: test
960 960 date: Thu Jan 01 00:00:00 1970 +0000
961 961 summary: A0
962 962
963 963
964 964 Test the cases A.2 (f1x), A.3 (f2x) and a special case of A.6 (f5x) where the
965 965 two renames actually converge to the same name (thus no actual divergence).
966 966
967 967 $ hg up -q 'desc("A0")'
968 968 $ HGEDITOR="echo C1 >" hg graft -r 'desc("C0")' --edit
969 969 grafting 2:f58c7e2b28fa "C0"
970 970 merging f1a and f1b to f1a
971 971 merging f5a
972 972 warning: can't find ancestor for 'f5a' copied from 'f5b'!
973 973 $ hg status --change .
974 974 M f1a
975 975 M f5a
976 976 A f2c
977 977 R f2a
978 978 $ hg cat f1a
979 979 c1c
980 980 $ hg cat f1b
981 981 f1b: no such file in rev c9763722f9bd
982 982 [1]
983 983
984 984 Test the cases A.0 (f4x) and A.6 (f3x)
985 985
986 986 $ HGEDITOR="echo D1 >" hg graft -r 'desc("D0")' --edit
987 987 grafting 3:b69f5839d2d9 "D0"
988 988 note: possible conflict - f3b was renamed multiple times to:
989 989 f3d
990 990 f3a
991 991 warning: can't find ancestor for 'f3d' copied from 'f3b'!
992 992
993 993 Set up the repository for some further tests
994 994
995 995 $ hg up -q "min(desc("A0"))"
996 996 $ hg mv f1a f1e
997 997 $ echo c2e > f2a
998 998 $ hg mv f3a f3e
999 999 $ hg mv f4a f4e
1000 1000 $ hg mv f5a f5b
1001 1001 $ hg ci -qAm "E0"
1002 1002 $ hg log -G
1003 1003 @ changeset: 6:6bd1736cab86
1004 1004 | tag: tip
1005 1005 | parent: 0:11f7a1b56675
1006 1006 | user: test
1007 1007 | date: Thu Jan 01 00:00:00 1970 +0000
1008 1008 | summary: E0
1009 1009 |
1010 1010 | o changeset: 5:560daee679da
1011 1011 | | user: test
1012 1012 | | date: Thu Jan 01 00:00:00 1970 +0000
1013 1013 | | summary: D1
1014 1014 | |
1015 1015 | o changeset: 4:c9763722f9bd
1016 1016 |/ parent: 0:11f7a1b56675
1017 1017 | user: test
1018 1018 | date: Thu Jan 01 00:00:00 1970 +0000
1019 1019 | summary: C1
1020 1020 |
1021 1021 | o changeset: 3:b69f5839d2d9
1022 1022 | | user: test
1023 1023 | | date: Thu Jan 01 00:00:00 1970 +0000
1024 1024 | | summary: D0
1025 1025 | |
1026 1026 | o changeset: 2:f58c7e2b28fa
1027 1027 | | user: test
1028 1028 | | date: Thu Jan 01 00:00:00 1970 +0000
1029 1029 | | summary: C0
1030 1030 | |
1031 1031 | o changeset: 1:3d7bba921b5d
1032 1032 |/ user: test
1033 1033 | date: Thu Jan 01 00:00:00 1970 +0000
1034 1034 | summary: B0
1035 1035 |
1036 1036 o changeset: 0:11f7a1b56675
1037 1037 user: test
1038 1038 date: Thu Jan 01 00:00:00 1970 +0000
1039 1039 summary: A0
1040 1040
1041 1041
1042 1042 Test the cases A.4 (f1x), the "ping-pong" special case of A.7 (f5x),
1043 1043 and A.3 with a local content change to be preserved (f2x).
1044 1044
1045 1045 $ HGEDITOR="echo C2 >" hg graft -r 'desc("C0")' --edit
1046 1046 grafting 2:f58c7e2b28fa "C0"
1047 1047 merging f1e and f1b to f1e
1048 1048 merging f2a and f2c to f2c
1049 1049 merging f5b and f5a to f5a
1050 1050
1051 1051 Test the cases A.1 (f4x) and A.7 (f3x).
1052 1052
1053 1053 $ HGEDITOR="echo D2 >" hg graft -r 'desc("D0")' --edit
1054 1054 grafting 3:b69f5839d2d9 "D0"
1055 1055 note: possible conflict - f3b was renamed multiple times to:
1056 1056 f3e
1057 1057 f3d
1058 1058 merging f4e and f4a to f4e
1059 1059 warning: can't find ancestor for 'f3d' copied from 'f3b'!
1060 1060
1061 1061 Check the results of the grafts tested
1062 1062
1063 1063 $ hg log -CGv --patch --git
1064 1064 @ changeset: 8:93ee502e8b0a
1065 1065 | tag: tip
1066 1066 | user: test
1067 1067 | date: Thu Jan 01 00:00:00 1970 +0000
1068 1068 | files: f3d f4e
1069 1069 | description:
1070 1070 | D2
1071 1071 |
1072 1072 |
1073 1073 | diff --git a/f3d b/f3d
1074 1074 | new file mode 100644
1075 1075 | --- /dev/null
1076 1076 | +++ b/f3d
1077 1077 | @@ -0,0 +1,1 @@
1078 1078 | +c3a
1079 1079 | diff --git a/f4e b/f4e
1080 1080 | --- a/f4e
1081 1081 | +++ b/f4e
1082 1082 | @@ -1,1 +1,1 @@
1083 1083 | -c4a
1084 1084 | +c4d
1085 1085 |
1086 1086 o changeset: 7:539cf145f496
1087 1087 | user: test
1088 1088 | date: Thu Jan 01 00:00:00 1970 +0000
1089 1089 | files: f1e f2a f2c f5a f5b
1090 1090 | copies: f2c (f2a) f5a (f5b)
1091 1091 | description:
1092 1092 | C2
1093 1093 |
1094 1094 |
1095 1095 | diff --git a/f1e b/f1e
1096 1096 | --- a/f1e
1097 1097 | +++ b/f1e
1098 1098 | @@ -1,1 +1,1 @@
1099 1099 | -c1a
1100 1100 | +c1c
1101 1101 | diff --git a/f2a b/f2c
1102 1102 | rename from f2a
1103 1103 | rename to f2c
1104 1104 | diff --git a/f5b b/f5a
1105 1105 | rename from f5b
1106 1106 | rename to f5a
1107 1107 | --- a/f5b
1108 1108 | +++ b/f5a
1109 1109 | @@ -1,1 +1,1 @@
1110 1110 | -c5a
1111 1111 | +c5c
1112 1112 |
1113 1113 o changeset: 6:6bd1736cab86
1114 1114 | parent: 0:11f7a1b56675
1115 1115 | user: test
1116 1116 | date: Thu Jan 01 00:00:00 1970 +0000
1117 1117 | files: f1a f1e f2a f3a f3e f4a f4e f5a f5b
1118 1118 | copies: f1e (f1a) f3e (f3a) f4e (f4a) f5b (f5a)
1119 1119 | description:
1120 1120 | E0
1121 1121 |
1122 1122 |
1123 1123 | diff --git a/f1a b/f1e
1124 1124 | rename from f1a
1125 1125 | rename to f1e
1126 1126 | diff --git a/f2a b/f2a
1127 1127 | --- a/f2a
1128 1128 | +++ b/f2a
1129 1129 | @@ -1,1 +1,1 @@
1130 1130 | -c2a
1131 1131 | +c2e
1132 1132 | diff --git a/f3a b/f3e
1133 1133 | rename from f3a
1134 1134 | rename to f3e
1135 1135 | diff --git a/f4a b/f4e
1136 1136 | rename from f4a
1137 1137 | rename to f4e
1138 1138 | diff --git a/f5a b/f5b
1139 1139 | rename from f5a
1140 1140 | rename to f5b
1141 1141 |
1142 1142 | o changeset: 5:560daee679da
1143 1143 | | user: test
1144 1144 | | date: Thu Jan 01 00:00:00 1970 +0000
1145 1145 | | files: f3d f4a
1146 1146 | | description:
1147 1147 | | D1
1148 1148 | |
1149 1149 | |
1150 1150 | | diff --git a/f3d b/f3d
1151 1151 | | new file mode 100644
1152 1152 | | --- /dev/null
1153 1153 | | +++ b/f3d
1154 1154 | | @@ -0,0 +1,1 @@
1155 1155 | | +c3a
1156 1156 | | diff --git a/f4a b/f4a
1157 1157 | | --- a/f4a
1158 1158 | | +++ b/f4a
1159 1159 | | @@ -1,1 +1,1 @@
1160 1160 | | -c4a
1161 1161 | | +c4d
1162 1162 | |
1163 1163 | o changeset: 4:c9763722f9bd
1164 1164 |/ parent: 0:11f7a1b56675
1165 1165 | user: test
1166 1166 | date: Thu Jan 01 00:00:00 1970 +0000
1167 1167 | files: f1a f2a f2c f5a
1168 1168 | copies: f2c (f2a)
1169 1169 | description:
1170 1170 | C1
1171 1171 |
1172 1172 |
1173 1173 | diff --git a/f1a b/f1a
1174 1174 | --- a/f1a
1175 1175 | +++ b/f1a
1176 1176 | @@ -1,1 +1,1 @@
1177 1177 | -c1a
1178 1178 | +c1c
1179 1179 | diff --git a/f2a b/f2c
1180 1180 | rename from f2a
1181 1181 | rename to f2c
1182 1182 | diff --git a/f5a b/f5a
1183 1183 | --- a/f5a
1184 1184 | +++ b/f5a
1185 1185 | @@ -1,1 +1,1 @@
1186 1186 | -c5a
1187 1187 | +c5c
1188 1188 |
1189 1189 | o changeset: 3:b69f5839d2d9
1190 1190 | | user: test
1191 1191 | | date: Thu Jan 01 00:00:00 1970 +0000
1192 1192 | | files: f3b f3d f4a
1193 1193 | | copies: f3d (f3b)
1194 1194 | | description:
1195 1195 | | D0
1196 1196 | |
1197 1197 | |
1198 1198 | | diff --git a/f3b b/f3d
1199 1199 | | rename from f3b
1200 1200 | | rename to f3d
1201 1201 | | diff --git a/f4a b/f4a
1202 1202 | | --- a/f4a
1203 1203 | | +++ b/f4a
1204 1204 | | @@ -1,1 +1,1 @@
1205 1205 | | -c4a
1206 1206 | | +c4d
1207 1207 | |
1208 1208 | o changeset: 2:f58c7e2b28fa
1209 1209 | | user: test
1210 1210 | | date: Thu Jan 01 00:00:00 1970 +0000
1211 1211 | | files: f1b f2a f2c f5a f5b
1212 1212 | | copies: f2c (f2a) f5a (f5b)
1213 1213 | | description:
1214 1214 | | C0
1215 1215 | |
1216 1216 | |
1217 1217 | | diff --git a/f1b b/f1b
1218 1218 | | --- a/f1b
1219 1219 | | +++ b/f1b
1220 1220 | | @@ -1,1 +1,1 @@
1221 1221 | | -c1a
1222 1222 | | +c1c
1223 1223 | | diff --git a/f2a b/f2c
1224 1224 | | rename from f2a
1225 1225 | | rename to f2c
1226 1226 | | diff --git a/f5b b/f5a
1227 1227 | | rename from f5b
1228 1228 | | rename to f5a
1229 1229 | | --- a/f5b
1230 1230 | | +++ b/f5a
1231 1231 | | @@ -1,1 +1,1 @@
1232 1232 | | -c5a
1233 1233 | | +c5c
1234 1234 | |
1235 1235 | o changeset: 1:3d7bba921b5d
1236 1236 |/ user: test
1237 1237 | date: Thu Jan 01 00:00:00 1970 +0000
1238 1238 | files: f1a f1b f3a f3b f5a f5b
1239 1239 | copies: f1b (f1a) f3b (f3a) f5b (f5a)
1240 1240 | description:
1241 1241 | B0
1242 1242 |
1243 1243 |
1244 1244 | diff --git a/f1a b/f1b
1245 1245 | rename from f1a
1246 1246 | rename to f1b
1247 1247 | diff --git a/f3a b/f3b
1248 1248 | rename from f3a
1249 1249 | rename to f3b
1250 1250 | diff --git a/f5a b/f5b
1251 1251 | rename from f5a
1252 1252 | rename to f5b
1253 1253 |
1254 1254 o changeset: 0:11f7a1b56675
1255 1255 user: test
1256 1256 date: Thu Jan 01 00:00:00 1970 +0000
1257 1257 files: f1a f2a f3a f4a f5a
1258 1258 description:
1259 1259 A0
1260 1260
1261 1261
1262 1262 diff --git a/f1a b/f1a
1263 1263 new file mode 100644
1264 1264 --- /dev/null
1265 1265 +++ b/f1a
1266 1266 @@ -0,0 +1,1 @@
1267 1267 +c1a
1268 1268 diff --git a/f2a b/f2a
1269 1269 new file mode 100644
1270 1270 --- /dev/null
1271 1271 +++ b/f2a
1272 1272 @@ -0,0 +1,1 @@
1273 1273 +c2a
1274 1274 diff --git a/f3a b/f3a
1275 1275 new file mode 100644
1276 1276 --- /dev/null
1277 1277 +++ b/f3a
1278 1278 @@ -0,0 +1,1 @@
1279 1279 +c3a
1280 1280 diff --git a/f4a b/f4a
1281 1281 new file mode 100644
1282 1282 --- /dev/null
1283 1283 +++ b/f4a
1284 1284 @@ -0,0 +1,1 @@
1285 1285 +c4a
1286 1286 diff --git a/f5a b/f5a
1287 1287 new file mode 100644
1288 1288 --- /dev/null
1289 1289 +++ b/f5a
1290 1290 @@ -0,0 +1,1 @@
1291 1291 +c5a
1292 1292
1293 1293 $ hg cat f2c
1294 1294 c2e
1295 1295
1296 1296 Check superfluous filemerge of files renamed in the past but untouched by graft
1297 1297
1298 1298 $ echo a > a
1299 1299 $ hg ci -qAma
1300 1300 $ hg mv a b
1301 1301 $ echo b > b
1302 1302 $ hg ci -qAmb
1303 1303 $ echo c > c
1304 1304 $ hg ci -qAmc
1305 1305 $ hg up -q .~2
1306 1306 $ hg graft tip -qt:fail
1307 1307
1308 1308 $ cd ..
1309 1309
1310 1310 Graft a change into a new file previously grafted into a renamed directory
1311 1311
1312 1312 $ hg init dirmovenewfile
1313 1313 $ cd dirmovenewfile
1314 1314 $ mkdir a
1315 1315 $ echo a > a/a
1316 1316 $ hg ci -qAma
1317 1317 $ echo x > a/x
1318 1318 $ hg ci -qAmx
1319 1319 $ hg up -q 0
1320 1320 $ hg mv -q a b
1321 1321 $ hg ci -qAmb
1322 1322 $ hg graft -q 1 # a/x grafted as b/x, but no copy information recorded
1323 1323 $ hg up -q 1
1324 1324 $ echo y > a/x
1325 1325 $ hg ci -qAmy
1326 1326 $ hg up -q 3
1327 1327 $ hg graft -q 4
1328 1328 $ hg status --change .
1329 1329 M b/x
1330 1330
1331 1331 Prepare for test of skipped changesets and how merges can influence it:
1332 1332
1333 1333 $ hg merge -q -r 1 --tool :local
1334 1334 $ hg ci -m m
1335 1335 $ echo xx >> b/x
1336 1336 $ hg ci -m xx
1337 1337
1338 1338 $ hg log -G -T '{rev} {desc|firstline}'
1339 1339 @ 7 xx
1340 1340 |
1341 1341 o 6 m
1342 1342 |\
1343 1343 | o 5 y
1344 1344 | |
1345 1345 +---o 4 y
1346 1346 | |
1347 1347 | o 3 x
1348 1348 | |
1349 1349 | o 2 b
1350 1350 | |
1351 1351 o | 1 x
1352 1352 |/
1353 1353 o 0 a
1354 1354
1355 1355 Grafting of plain changes correctly detects that 3 and 5 should be skipped:
1356 1356
1357 1357 $ hg up -qCr 4
1358 1358 $ hg graft --tool :local -r 2::5
1359 1359 skipping already grafted revision 3:ca093ca2f1d9 (was grafted from 1:13ec5badbf2a)
1360 1360 skipping already grafted revision 5:43e9eb70dab0 (was grafted from 4:6c9a1289e5f1)
1361 1361 grafting 2:42127f193bcd "b"
1362 1362
1363 1363 Extending the graft range to include a (skipped) merge of 3 will not prevent us from
1364 1364 also detecting that both 3 and 5 should be skipped:
1365 1365
1366 1366 $ hg up -qCr 4
1367 1367 $ hg graft --tool :local -r 2::7
1368 1368 skipping ungraftable merge revision 6
1369 1369 skipping already grafted revision 3:ca093ca2f1d9 (was grafted from 1:13ec5badbf2a)
1370 1370 skipping already grafted revision 5:43e9eb70dab0 (was grafted from 4:6c9a1289e5f1)
1371 1371 grafting 2:42127f193bcd "b"
1372 1372 grafting 7:d3c3f2b38ecc "xx"
1373 1373 note: graft of 7:d3c3f2b38ecc created no changes to commit
1374 1374
1375 1375 $ cd ..
1376 1376
1377 1377 Testing the reading of old format graftstate file with newer mercurial
1378 1378
1379 1379 $ hg init oldgraft
1380 1380 $ cd oldgraft
1381 1381 $ for ch in a b c; do echo foo > $ch; hg add $ch; hg ci -Aqm "added "$ch; done;
1382 1382 $ hg log -GT "{rev}:{node|short} {desc}\n"
1383 1383 @ 2:8be98ac1a569 added c
1384 1384 |
1385 1385 o 1:80e6d2c47cfe added b
1386 1386 |
1387 1387 o 0:f7ad41964313 added a
1388 1388
1389 1389 $ hg up 0
1390 1390 0 files updated, 0 files merged, 2 files removed, 0 files unresolved
1391 1391 $ echo bar > b
1392 1392 $ hg add b
1393 1393 $ hg ci -m "bar to b"
1394 1394 created new head
1395 1395 $ hg graft -r 1 -r 2
1396 1396 grafting 1:80e6d2c47cfe "added b"
1397 1397 merging b
1398 1398 warning: conflicts while merging b! (edit, then use 'hg resolve --mark')
1399 1399 abort: unresolved conflicts, can't continue
1400 1400 (use 'hg resolve' and 'hg graft --continue')
1401 1401 [255]
1402 1402
1403 1403 Writing the nodes in old format to graftstate
1404 1404
1405 1405 $ hg log -r 1 -r 2 -T '{node}\n' > .hg/graftstate
1406 1406 $ echo foo > b
1407 1407 $ hg resolve -m
1408 1408 (no more unresolved files)
1409 1409 continue: hg graft --continue
1410 1410 $ hg graft --continue
1411 1411 grafting 1:80e6d2c47cfe "added b"
1412 1412 grafting 2:8be98ac1a569 "added c"
1413 1413
1414 1414 Testing that --user is preserved during conflicts and value is reused while
1415 1415 running `hg graft --continue`
1416 1416
1417 1417 $ hg log -G
1418 1418 @ changeset: 5:711e9fa999f1
1419 1419 | tag: tip
1420 1420 | user: test
1421 1421 | date: Thu Jan 01 00:00:00 1970 +0000
1422 1422 | summary: added c
1423 1423 |
1424 1424 o changeset: 4:e5ad7353b408
1425 1425 | user: test
1426 1426 | date: Thu Jan 01 00:00:00 1970 +0000
1427 1427 | summary: added b
1428 1428 |
1429 1429 o changeset: 3:9e887f7a939c
1430 1430 | parent: 0:f7ad41964313
1431 1431 | user: test
1432 1432 | date: Thu Jan 01 00:00:00 1970 +0000
1433 1433 | summary: bar to b
1434 1434 |
1435 1435 | o changeset: 2:8be98ac1a569
1436 1436 | | user: test
1437 1437 | | date: Thu Jan 01 00:00:00 1970 +0000
1438 1438 | | summary: added c
1439 1439 | |
1440 1440 | o changeset: 1:80e6d2c47cfe
1441 1441 |/ user: test
1442 1442 | date: Thu Jan 01 00:00:00 1970 +0000
1443 1443 | summary: added b
1444 1444 |
1445 1445 o changeset: 0:f7ad41964313
1446 1446 user: test
1447 1447 date: Thu Jan 01 00:00:00 1970 +0000
1448 1448 summary: added a
1449 1449
1450 1450
1451 1451 $ hg up '.^^'
1452 1452 1 files updated, 0 files merged, 1 files removed, 0 files unresolved
1453 1453
1454 1454 $ hg graft -r 1 -r 2 --user batman
1455 1455 grafting 1:80e6d2c47cfe "added b"
1456 1456 merging b
1457 1457 warning: conflicts while merging b! (edit, then use 'hg resolve --mark')
1458 1458 abort: unresolved conflicts, can't continue
1459 1459 (use 'hg resolve' and 'hg graft --continue')
1460 1460 [255]
1461 1461
1462 1462 $ echo wat > b
1463 1463 $ hg resolve -m
1464 1464 (no more unresolved files)
1465 1465 continue: hg graft --continue
1466 1466
1467 1467 $ hg graft --continue
1468 1468 grafting 1:80e6d2c47cfe "added b"
1469 1469 grafting 2:8be98ac1a569 "added c"
1470 1470
1471 1471 $ hg log -Gr 3::
1472 1472 @ changeset: 7:11a36ffaacf2
1473 1473 | tag: tip
1474 1474 | user: batman
1475 1475 | date: Thu Jan 01 00:00:00 1970 +0000
1476 1476 | summary: added c
1477 1477 |
1478 1478 o changeset: 6:76803afc6511
1479 1479 | parent: 3:9e887f7a939c
1480 1480 | user: batman
1481 1481 | date: Thu Jan 01 00:00:00 1970 +0000
1482 1482 | summary: added b
1483 1483 |
1484 1484 | o changeset: 5:711e9fa999f1
1485 1485 | | user: test
1486 1486 | | date: Thu Jan 01 00:00:00 1970 +0000
1487 1487 | | summary: added c
1488 1488 | |
1489 1489 | o changeset: 4:e5ad7353b408
1490 1490 |/ user: test
1491 1491 | date: Thu Jan 01 00:00:00 1970 +0000
1492 1492 | summary: added b
1493 1493 |
1494 1494 o changeset: 3:9e887f7a939c
1495 1495 | parent: 0:f7ad41964313
1496 1496 ~ user: test
1497 1497 date: Thu Jan 01 00:00:00 1970 +0000
1498 1498 summary: bar to b
1499 1499
1500 1500 Test that --date is preserved and reused in `hg graft --continue`
1501 1501
1502 1502 $ hg up '.^^'
1503 1503 1 files updated, 0 files merged, 1 files removed, 0 files unresolved
1504 1504 $ hg graft -r 1 -r 2 --date '1234560000 120'
1505 1505 grafting 1:80e6d2c47cfe "added b"
1506 1506 merging b
1507 1507 warning: conflicts while merging b! (edit, then use 'hg resolve --mark')
1508 1508 abort: unresolved conflicts, can't continue
1509 1509 (use 'hg resolve' and 'hg graft --continue')
1510 1510 [255]
1511 1511
1512 1512 $ echo foobar > b
1513 1513 $ hg resolve -m
1514 1514 (no more unresolved files)
1515 1515 continue: hg graft --continue
1516 1516 $ hg graft --continue
1517 1517 grafting 1:80e6d2c47cfe "added b"
1518 1518 grafting 2:8be98ac1a569 "added c"
1519 1519
1520 1520 $ hg log -Gr '.^^::.'
1521 1521 @ changeset: 9:1896b76e007a
1522 1522 | tag: tip
1523 1523 | user: test
1524 1524 | date: Fri Feb 13 21:18:00 2009 -0002
1525 1525 | summary: added c
1526 1526 |
1527 1527 o changeset: 8:ce2b4f1632af
1528 1528 | parent: 3:9e887f7a939c
1529 1529 | user: test
1530 1530 | date: Fri Feb 13 21:18:00 2009 -0002
1531 1531 | summary: added b
1532 1532 |
1533 1533 o changeset: 3:9e887f7a939c
1534 1534 | parent: 0:f7ad41964313
1535 1535 ~ user: test
1536 1536 date: Thu Jan 01 00:00:00 1970 +0000
1537 1537 summary: bar to b
1538 1538
1539 1539 Test that --log is preserved and reused in `hg graft --continue`
1540 1540
1541 1541 $ hg up '.^^'
1542 1542 1 files updated, 0 files merged, 1 files removed, 0 files unresolved
1543 1543 $ hg graft -r 1 -r 2 --log
1544 1544 grafting 1:80e6d2c47cfe "added b"
1545 1545 merging b
1546 1546 warning: conflicts while merging b! (edit, then use 'hg resolve --mark')
1547 1547 abort: unresolved conflicts, can't continue
1548 1548 (use 'hg resolve' and 'hg graft --continue')
1549 1549 [255]
1550 1550
1551 1551 $ echo foobar > b
1552 1552 $ hg resolve -m
1553 1553 (no more unresolved files)
1554 1554 continue: hg graft --continue
1555 1555
1556 1556 $ hg graft --continue
1557 1557 grafting 1:80e6d2c47cfe "added b"
1558 1558 grafting 2:8be98ac1a569 "added c"
1559 1559
1560 1560 $ hg log -GT "{rev}:{node|short} {desc}" -r '.^^::.'
1561 1561 @ 11:30c1050a58b2 added c
1562 1562 | (grafted from 8be98ac1a56990c2d9ca6861041b8390af7bd6f3)
1563 1563 o 10:ec7eda2313e2 added b
1564 1564 | (grafted from 80e6d2c47cfe5b3185519568327a17a061c7efb6)
1565 1565 o 3:9e887f7a939c bar to b
1566 1566 |
1567 1567 ~
1568 1568
1569 1569 $ cd ..
1570 1570
1571 1571 Testing the --stop flag of `hg graft` which stops the interrupted graft
1572 1572
1573 1573 $ hg init stopgraft
1574 1574 $ cd stopgraft
1575 1575 $ for ch in a b c d; do echo $ch > $ch; hg add $ch; hg ci -Aqm "added "$ch; done;
1576 1576
1577 1577 $ hg log -G
1578 1578 @ changeset: 3:9150fe93bec6
1579 1579 | tag: tip
1580 1580 | user: test
1581 1581 | date: Thu Jan 01 00:00:00 1970 +0000
1582 1582 | summary: added d
1583 1583 |
1584 1584 o changeset: 2:155349b645be
1585 1585 | user: test
1586 1586 | date: Thu Jan 01 00:00:00 1970 +0000
1587 1587 | summary: added c
1588 1588 |
1589 1589 o changeset: 1:5f6d8a4bf34a
1590 1590 | user: test
1591 1591 | date: Thu Jan 01 00:00:00 1970 +0000
1592 1592 | summary: added b
1593 1593 |
1594 1594 o changeset: 0:9092f1db7931
1595 1595 user: test
1596 1596 date: Thu Jan 01 00:00:00 1970 +0000
1597 1597 summary: added a
1598 1598
1599 1599 $ hg up '.^^'
1600 1600 0 files updated, 0 files merged, 2 files removed, 0 files unresolved
1601 1601
1602 1602 $ echo foo > d
1603 1603 $ hg ci -Aqm "added foo to d"
1604 1604
1605 1605 $ hg graft --stop
1606 1606 abort: no interrupted graft found
1607 1607 [255]
1608 1608
1609 1609 $ hg graft -r 3
1610 1610 grafting 3:9150fe93bec6 "added d"
1611 1611 merging d
1612 1612 warning: conflicts while merging d! (edit, then use 'hg resolve --mark')
1613 1613 abort: unresolved conflicts, can't continue
1614 1614 (use 'hg resolve' and 'hg graft --continue')
1615 1615 [255]
1616 1616
1617 1617 $ hg graft --stop --continue
1618 1618 abort: cannot use '--continue' and '--stop' together
1619 1619 [255]
1620 1620
1621 1621 $ hg graft --stop -U
1622 1622 abort: cannot specify any other flag with '--stop'
1623 1623 [255]
1624 1624 $ hg graft --stop --rev 4
1625 1625 abort: cannot specify any other flag with '--stop'
1626 1626 [255]
1627 1627 $ hg graft --stop --log
1628 1628 abort: cannot specify any other flag with '--stop'
1629 1629 [255]
1630 1630
1631 1631 $ hg graft --stop
1632 1632 stopped the interrupted graft
1633 1633 working directory is now at a0deacecd59d
1634 1634
1635 1635 $ hg diff
1636 1636
1637 1637 $ hg log -Gr '.'
1638 1638 @ changeset: 4:a0deacecd59d
1639 1639 | tag: tip
1640 1640 ~ parent: 1:5f6d8a4bf34a
1641 1641 user: test
1642 1642 date: Thu Jan 01 00:00:00 1970 +0000
1643 1643 summary: added foo to d
1644 1644
1645 1645 $ hg graft -r 2 -r 3
1646 1646 grafting 2:155349b645be "added c"
1647 1647 grafting 3:9150fe93bec6 "added d"
1648 1648 merging d
1649 1649 warning: conflicts while merging d! (edit, then use 'hg resolve --mark')
1650 1650 abort: unresolved conflicts, can't continue
1651 1651 (use 'hg resolve' and 'hg graft --continue')
1652 1652 [255]
1653 1653
1654 1654 $ hg graft --stop
1655 1655 stopped the interrupted graft
1656 1656 working directory is now at 75b447541a9e
1657 1657
1658 1658 $ hg diff
1659 1659
1660 1660 $ hg log -G -T "{rev}:{node|short} {desc}"
1661 1661 @ 5:75b447541a9e added c
1662 1662 |
1663 1663 o 4:a0deacecd59d added foo to d
1664 1664 |
1665 1665 | o 3:9150fe93bec6 added d
1666 1666 | |
1667 1667 | o 2:155349b645be added c
1668 1668 |/
1669 1669 o 1:5f6d8a4bf34a added b
1670 1670 |
1671 1671 o 0:9092f1db7931 added a
1672 1672
General Comments 0
You need to be logged in to leave comments. Login now