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