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