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