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