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