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