##// END OF EJS Templates
py3: fix handling of keyword arguments in revert...
Pulkit Goyal -
r35148:3da4bd50 default
parent child Browse files
Show More
@@ -1,3978 +1,3980 b''
1 1 # cmdutil.py - help for command processing in mercurial
2 2 #
3 3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 from __future__ import absolute_import
9 9
10 10 import errno
11 11 import itertools
12 12 import os
13 13 import re
14 14 import tempfile
15 15
16 16 from .i18n import _
17 17 from .node import (
18 18 hex,
19 19 nullid,
20 20 nullrev,
21 21 short,
22 22 )
23 23
24 24 from . import (
25 25 bookmarks,
26 26 changelog,
27 27 copies,
28 28 crecord as crecordmod,
29 29 dagop,
30 30 dirstateguard,
31 31 encoding,
32 32 error,
33 33 formatter,
34 34 graphmod,
35 35 match as matchmod,
36 36 mdiff,
37 37 obsolete,
38 38 patch,
39 39 pathutil,
40 40 pycompat,
41 41 registrar,
42 42 revlog,
43 43 revset,
44 44 scmutil,
45 45 smartset,
46 46 templatekw,
47 47 templater,
48 48 util,
49 49 vfs as vfsmod,
50 50 )
51 51 stringio = util.stringio
52 52
53 53 # templates of common command options
54 54
55 55 dryrunopts = [
56 56 ('n', 'dry-run', None,
57 57 _('do not perform actions, just print output')),
58 58 ]
59 59
60 60 remoteopts = [
61 61 ('e', 'ssh', '',
62 62 _('specify ssh command to use'), _('CMD')),
63 63 ('', 'remotecmd', '',
64 64 _('specify hg command to run on the remote side'), _('CMD')),
65 65 ('', 'insecure', None,
66 66 _('do not verify server certificate (ignoring web.cacerts config)')),
67 67 ]
68 68
69 69 walkopts = [
70 70 ('I', 'include', [],
71 71 _('include names matching the given patterns'), _('PATTERN')),
72 72 ('X', 'exclude', [],
73 73 _('exclude names matching the given patterns'), _('PATTERN')),
74 74 ]
75 75
76 76 commitopts = [
77 77 ('m', 'message', '',
78 78 _('use text as commit message'), _('TEXT')),
79 79 ('l', 'logfile', '',
80 80 _('read commit message from file'), _('FILE')),
81 81 ]
82 82
83 83 commitopts2 = [
84 84 ('d', 'date', '',
85 85 _('record the specified date as commit date'), _('DATE')),
86 86 ('u', 'user', '',
87 87 _('record the specified user as committer'), _('USER')),
88 88 ]
89 89
90 90 # hidden for now
91 91 formatteropts = [
92 92 ('T', 'template', '',
93 93 _('display with template (EXPERIMENTAL)'), _('TEMPLATE')),
94 94 ]
95 95
96 96 templateopts = [
97 97 ('', 'style', '',
98 98 _('display using template map file (DEPRECATED)'), _('STYLE')),
99 99 ('T', 'template', '',
100 100 _('display with template'), _('TEMPLATE')),
101 101 ]
102 102
103 103 logopts = [
104 104 ('p', 'patch', None, _('show patch')),
105 105 ('g', 'git', None, _('use git extended diff format')),
106 106 ('l', 'limit', '',
107 107 _('limit number of changes displayed'), _('NUM')),
108 108 ('M', 'no-merges', None, _('do not show merges')),
109 109 ('', 'stat', None, _('output diffstat-style summary of changes')),
110 110 ('G', 'graph', None, _("show the revision DAG")),
111 111 ] + templateopts
112 112
113 113 diffopts = [
114 114 ('a', 'text', None, _('treat all files as text')),
115 115 ('g', 'git', None, _('use git extended diff format')),
116 116 ('', 'binary', None, _('generate binary diffs in git mode (default)')),
117 117 ('', 'nodates', None, _('omit dates from diff headers'))
118 118 ]
119 119
120 120 diffwsopts = [
121 121 ('w', 'ignore-all-space', None,
122 122 _('ignore white space when comparing lines')),
123 123 ('b', 'ignore-space-change', None,
124 124 _('ignore changes in the amount of white space')),
125 125 ('B', 'ignore-blank-lines', None,
126 126 _('ignore changes whose lines are all blank')),
127 127 ('Z', 'ignore-space-at-eol', None,
128 128 _('ignore changes in whitespace at EOL')),
129 129 ]
130 130
131 131 diffopts2 = [
132 132 ('', 'noprefix', None, _('omit a/ and b/ prefixes from filenames')),
133 133 ('p', 'show-function', None, _('show which function each change is in')),
134 134 ('', 'reverse', None, _('produce a diff that undoes the changes')),
135 135 ] + diffwsopts + [
136 136 ('U', 'unified', '',
137 137 _('number of lines of context to show'), _('NUM')),
138 138 ('', 'stat', None, _('output diffstat-style summary of changes')),
139 139 ('', 'root', '', _('produce diffs relative to subdirectory'), _('DIR')),
140 140 ]
141 141
142 142 mergetoolopts = [
143 143 ('t', 'tool', '', _('specify merge tool')),
144 144 ]
145 145
146 146 similarityopts = [
147 147 ('s', 'similarity', '',
148 148 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
149 149 ]
150 150
151 151 subrepoopts = [
152 152 ('S', 'subrepos', None,
153 153 _('recurse into subrepositories'))
154 154 ]
155 155
156 156 debugrevlogopts = [
157 157 ('c', 'changelog', False, _('open changelog')),
158 158 ('m', 'manifest', False, _('open manifest')),
159 159 ('', 'dir', '', _('open directory manifest')),
160 160 ]
161 161
162 162 # special string such that everything below this line will be ingored in the
163 163 # editor text
164 164 _linebelow = "^HG: ------------------------ >8 ------------------------$"
165 165
166 166 def ishunk(x):
167 167 hunkclasses = (crecordmod.uihunk, patch.recordhunk)
168 168 return isinstance(x, hunkclasses)
169 169
170 170 def newandmodified(chunks, originalchunks):
171 171 newlyaddedandmodifiedfiles = set()
172 172 for chunk in chunks:
173 173 if ishunk(chunk) and chunk.header.isnewfile() and chunk not in \
174 174 originalchunks:
175 175 newlyaddedandmodifiedfiles.add(chunk.header.filename())
176 176 return newlyaddedandmodifiedfiles
177 177
178 178 def parsealiases(cmd):
179 179 return cmd.lstrip("^").split("|")
180 180
181 181 def setupwrapcolorwrite(ui):
182 182 # wrap ui.write so diff output can be labeled/colorized
183 183 def wrapwrite(orig, *args, **kw):
184 184 label = kw.pop('label', '')
185 185 for chunk, l in patch.difflabel(lambda: args):
186 186 orig(chunk, label=label + l)
187 187
188 188 oldwrite = ui.write
189 189 def wrap(*args, **kwargs):
190 190 return wrapwrite(oldwrite, *args, **kwargs)
191 191 setattr(ui, 'write', wrap)
192 192 return oldwrite
193 193
194 194 def filterchunks(ui, originalhunks, usecurses, testfile, operation=None):
195 195 if usecurses:
196 196 if testfile:
197 197 recordfn = crecordmod.testdecorator(testfile,
198 198 crecordmod.testchunkselector)
199 199 else:
200 200 recordfn = crecordmod.chunkselector
201 201
202 202 return crecordmod.filterpatch(ui, originalhunks, recordfn, operation)
203 203
204 204 else:
205 205 return patch.filterpatch(ui, originalhunks, operation)
206 206
207 207 def recordfilter(ui, originalhunks, operation=None):
208 208 """ Prompts the user to filter the originalhunks and return a list of
209 209 selected hunks.
210 210 *operation* is used for to build ui messages to indicate the user what
211 211 kind of filtering they are doing: reverting, committing, shelving, etc.
212 212 (see patch.filterpatch).
213 213 """
214 214 usecurses = crecordmod.checkcurses(ui)
215 215 testfile = ui.config('experimental', 'crecordtest')
216 216 oldwrite = setupwrapcolorwrite(ui)
217 217 try:
218 218 newchunks, newopts = filterchunks(ui, originalhunks, usecurses,
219 219 testfile, operation)
220 220 finally:
221 221 ui.write = oldwrite
222 222 return newchunks, newopts
223 223
224 224 def dorecord(ui, repo, commitfunc, cmdsuggest, backupall,
225 225 filterfn, *pats, **opts):
226 226 from . import merge as mergemod
227 227 opts = pycompat.byteskwargs(opts)
228 228 if not ui.interactive():
229 229 if cmdsuggest:
230 230 msg = _('running non-interactively, use %s instead') % cmdsuggest
231 231 else:
232 232 msg = _('running non-interactively')
233 233 raise error.Abort(msg)
234 234
235 235 # make sure username is set before going interactive
236 236 if not opts.get('user'):
237 237 ui.username() # raise exception, username not provided
238 238
239 239 def recordfunc(ui, repo, message, match, opts):
240 240 """This is generic record driver.
241 241
242 242 Its job is to interactively filter local changes, and
243 243 accordingly prepare working directory into a state in which the
244 244 job can be delegated to a non-interactive commit command such as
245 245 'commit' or 'qrefresh'.
246 246
247 247 After the actual job is done by non-interactive command, the
248 248 working directory is restored to its original state.
249 249
250 250 In the end we'll record interesting changes, and everything else
251 251 will be left in place, so the user can continue working.
252 252 """
253 253
254 254 checkunfinished(repo, commit=True)
255 255 wctx = repo[None]
256 256 merge = len(wctx.parents()) > 1
257 257 if merge:
258 258 raise error.Abort(_('cannot partially commit a merge '
259 259 '(use "hg commit" instead)'))
260 260
261 261 def fail(f, msg):
262 262 raise error.Abort('%s: %s' % (f, msg))
263 263
264 264 force = opts.get('force')
265 265 if not force:
266 266 vdirs = []
267 267 match.explicitdir = vdirs.append
268 268 match.bad = fail
269 269
270 270 status = repo.status(match=match)
271 271 if not force:
272 272 repo.checkcommitpatterns(wctx, vdirs, match, status, fail)
273 273 diffopts = patch.difffeatureopts(ui, opts=opts, whitespace=True)
274 274 diffopts.nodates = True
275 275 diffopts.git = True
276 276 diffopts.showfunc = True
277 277 originaldiff = patch.diff(repo, changes=status, opts=diffopts)
278 278 originalchunks = patch.parsepatch(originaldiff)
279 279
280 280 # 1. filter patch, since we are intending to apply subset of it
281 281 try:
282 282 chunks, newopts = filterfn(ui, originalchunks)
283 283 except error.PatchError as err:
284 284 raise error.Abort(_('error parsing patch: %s') % err)
285 285 opts.update(newopts)
286 286
287 287 # We need to keep a backup of files that have been newly added and
288 288 # modified during the recording process because there is a previous
289 289 # version without the edit in the workdir
290 290 newlyaddedandmodifiedfiles = newandmodified(chunks, originalchunks)
291 291 contenders = set()
292 292 for h in chunks:
293 293 try:
294 294 contenders.update(set(h.files()))
295 295 except AttributeError:
296 296 pass
297 297
298 298 changed = status.modified + status.added + status.removed
299 299 newfiles = [f for f in changed if f in contenders]
300 300 if not newfiles:
301 301 ui.status(_('no changes to record\n'))
302 302 return 0
303 303
304 304 modified = set(status.modified)
305 305
306 306 # 2. backup changed files, so we can restore them in the end
307 307
308 308 if backupall:
309 309 tobackup = changed
310 310 else:
311 311 tobackup = [f for f in newfiles if f in modified or f in \
312 312 newlyaddedandmodifiedfiles]
313 313 backups = {}
314 314 if tobackup:
315 315 backupdir = repo.vfs.join('record-backups')
316 316 try:
317 317 os.mkdir(backupdir)
318 318 except OSError as err:
319 319 if err.errno != errno.EEXIST:
320 320 raise
321 321 try:
322 322 # backup continues
323 323 for f in tobackup:
324 324 fd, tmpname = tempfile.mkstemp(prefix=f.replace('/', '_')+'.',
325 325 dir=backupdir)
326 326 os.close(fd)
327 327 ui.debug('backup %r as %r\n' % (f, tmpname))
328 328 util.copyfile(repo.wjoin(f), tmpname, copystat=True)
329 329 backups[f] = tmpname
330 330
331 331 fp = stringio()
332 332 for c in chunks:
333 333 fname = c.filename()
334 334 if fname in backups:
335 335 c.write(fp)
336 336 dopatch = fp.tell()
337 337 fp.seek(0)
338 338
339 339 # 2.5 optionally review / modify patch in text editor
340 340 if opts.get('review', False):
341 341 patchtext = (crecordmod.diffhelptext
342 342 + crecordmod.patchhelptext
343 343 + fp.read())
344 344 reviewedpatch = ui.edit(patchtext, "",
345 345 action="diff",
346 346 repopath=repo.path)
347 347 fp.truncate(0)
348 348 fp.write(reviewedpatch)
349 349 fp.seek(0)
350 350
351 351 [os.unlink(repo.wjoin(c)) for c in newlyaddedandmodifiedfiles]
352 352 # 3a. apply filtered patch to clean repo (clean)
353 353 if backups:
354 354 # Equivalent to hg.revert
355 355 m = scmutil.matchfiles(repo, backups.keys())
356 356 mergemod.update(repo, repo.dirstate.p1(),
357 357 False, True, matcher=m)
358 358
359 359 # 3b. (apply)
360 360 if dopatch:
361 361 try:
362 362 ui.debug('applying patch\n')
363 363 ui.debug(fp.getvalue())
364 364 patch.internalpatch(ui, repo, fp, 1, eolmode=None)
365 365 except error.PatchError as err:
366 366 raise error.Abort(str(err))
367 367 del fp
368 368
369 369 # 4. We prepared working directory according to filtered
370 370 # patch. Now is the time to delegate the job to
371 371 # commit/qrefresh or the like!
372 372
373 373 # Make all of the pathnames absolute.
374 374 newfiles = [repo.wjoin(nf) for nf in newfiles]
375 375 return commitfunc(ui, repo, *newfiles, **opts)
376 376 finally:
377 377 # 5. finally restore backed-up files
378 378 try:
379 379 dirstate = repo.dirstate
380 380 for realname, tmpname in backups.iteritems():
381 381 ui.debug('restoring %r to %r\n' % (tmpname, realname))
382 382
383 383 if dirstate[realname] == 'n':
384 384 # without normallookup, restoring timestamp
385 385 # may cause partially committed files
386 386 # to be treated as unmodified
387 387 dirstate.normallookup(realname)
388 388
389 389 # copystat=True here and above are a hack to trick any
390 390 # editors that have f open that we haven't modified them.
391 391 #
392 392 # Also note that this racy as an editor could notice the
393 393 # file's mtime before we've finished writing it.
394 394 util.copyfile(tmpname, repo.wjoin(realname), copystat=True)
395 395 os.unlink(tmpname)
396 396 if tobackup:
397 397 os.rmdir(backupdir)
398 398 except OSError:
399 399 pass
400 400
401 401 def recordinwlock(ui, repo, message, match, opts):
402 402 with repo.wlock():
403 403 return recordfunc(ui, repo, message, match, opts)
404 404
405 405 return commit(ui, repo, recordinwlock, pats, opts)
406 406
407 407 class dirnode(object):
408 408 """
409 409 Represent a directory in user working copy with information required for
410 410 the purpose of tersing its status.
411 411
412 412 path is the path to the directory
413 413
414 414 statuses is a set of statuses of all files in this directory (this includes
415 415 all the files in all the subdirectories too)
416 416
417 417 files is a list of files which are direct child of this directory
418 418
419 419 subdirs is a dictionary of sub-directory name as the key and it's own
420 420 dirnode object as the value
421 421 """
422 422
423 423 def __init__(self, dirpath):
424 424 self.path = dirpath
425 425 self.statuses = set([])
426 426 self.files = []
427 427 self.subdirs = {}
428 428
429 429 def _addfileindir(self, filename, status):
430 430 """Add a file in this directory as a direct child."""
431 431 self.files.append((filename, status))
432 432
433 433 def addfile(self, filename, status):
434 434 """
435 435 Add a file to this directory or to its direct parent directory.
436 436
437 437 If the file is not direct child of this directory, we traverse to the
438 438 directory of which this file is a direct child of and add the file
439 439 there.
440 440 """
441 441
442 442 # the filename contains a path separator, it means it's not the direct
443 443 # child of this directory
444 444 if '/' in filename:
445 445 subdir, filep = filename.split('/', 1)
446 446
447 447 # does the dirnode object for subdir exists
448 448 if subdir not in self.subdirs:
449 449 subdirpath = os.path.join(self.path, subdir)
450 450 self.subdirs[subdir] = dirnode(subdirpath)
451 451
452 452 # try adding the file in subdir
453 453 self.subdirs[subdir].addfile(filep, status)
454 454
455 455 else:
456 456 self._addfileindir(filename, status)
457 457
458 458 if status not in self.statuses:
459 459 self.statuses.add(status)
460 460
461 461 def iterfilepaths(self):
462 462 """Yield (status, path) for files directly under this directory."""
463 463 for f, st in self.files:
464 464 yield st, os.path.join(self.path, f)
465 465
466 466 def tersewalk(self, terseargs):
467 467 """
468 468 Yield (status, path) obtained by processing the status of this
469 469 dirnode.
470 470
471 471 terseargs is the string of arguments passed by the user with `--terse`
472 472 flag.
473 473
474 474 Following are the cases which can happen:
475 475
476 476 1) All the files in the directory (including all the files in its
477 477 subdirectories) share the same status and the user has asked us to terse
478 478 that status. -> yield (status, dirpath)
479 479
480 480 2) Otherwise, we do following:
481 481
482 482 a) Yield (status, filepath) for all the files which are in this
483 483 directory (only the ones in this directory, not the subdirs)
484 484
485 485 b) Recurse the function on all the subdirectories of this
486 486 directory
487 487 """
488 488
489 489 if len(self.statuses) == 1:
490 490 onlyst = self.statuses.pop()
491 491
492 492 # Making sure we terse only when the status abbreviation is
493 493 # passed as terse argument
494 494 if onlyst in terseargs:
495 495 yield onlyst, self.path + pycompat.ossep
496 496 return
497 497
498 498 # add the files to status list
499 499 for st, fpath in self.iterfilepaths():
500 500 yield st, fpath
501 501
502 502 #recurse on the subdirs
503 503 for dirobj in self.subdirs.values():
504 504 for st, fpath in dirobj.tersewalk(terseargs):
505 505 yield st, fpath
506 506
507 507 def tersedir(statuslist, terseargs):
508 508 """
509 509 Terse the status if all the files in a directory shares the same status.
510 510
511 511 statuslist is scmutil.status() object which contains a list of files for
512 512 each status.
513 513 terseargs is string which is passed by the user as the argument to `--terse`
514 514 flag.
515 515
516 516 The function makes a tree of objects of dirnode class, and at each node it
517 517 stores the information required to know whether we can terse a certain
518 518 directory or not.
519 519 """
520 520 # the order matters here as that is used to produce final list
521 521 allst = ('m', 'a', 'r', 'd', 'u', 'i', 'c')
522 522
523 523 # checking the argument validity
524 524 for s in pycompat.bytestr(terseargs):
525 525 if s not in allst:
526 526 raise error.Abort(_("'%s' not recognized") % s)
527 527
528 528 # creating a dirnode object for the root of the repo
529 529 rootobj = dirnode('')
530 530 pstatus = ('modified', 'added', 'deleted', 'clean', 'unknown',
531 531 'ignored', 'removed')
532 532
533 533 tersedict = {}
534 534 for attrname in pstatus:
535 535 statuschar = attrname[0:1]
536 536 for f in getattr(statuslist, attrname):
537 537 rootobj.addfile(f, statuschar)
538 538 tersedict[statuschar] = []
539 539
540 540 # we won't be tersing the root dir, so add files in it
541 541 for st, fpath in rootobj.iterfilepaths():
542 542 tersedict[st].append(fpath)
543 543
544 544 # process each sub-directory and build tersedict
545 545 for subdir in rootobj.subdirs.values():
546 546 for st, f in subdir.tersewalk(terseargs):
547 547 tersedict[st].append(f)
548 548
549 549 tersedlist = []
550 550 for st in allst:
551 551 tersedict[st].sort()
552 552 tersedlist.append(tersedict[st])
553 553
554 554 return tersedlist
555 555
556 556 def _commentlines(raw):
557 557 '''Surround lineswith a comment char and a new line'''
558 558 lines = raw.splitlines()
559 559 commentedlines = ['# %s' % line for line in lines]
560 560 return '\n'.join(commentedlines) + '\n'
561 561
562 562 def _conflictsmsg(repo):
563 563 # avoid merge cycle
564 564 from . import merge as mergemod
565 565 mergestate = mergemod.mergestate.read(repo)
566 566 if not mergestate.active():
567 567 return
568 568
569 569 m = scmutil.match(repo[None])
570 570 unresolvedlist = [f for f in mergestate.unresolved() if m(f)]
571 571 if unresolvedlist:
572 572 mergeliststr = '\n'.join(
573 573 [' %s' % util.pathto(repo.root, pycompat.getcwd(), path)
574 574 for path in unresolvedlist])
575 575 msg = _('''Unresolved merge conflicts:
576 576
577 577 %s
578 578
579 579 To mark files as resolved: hg resolve --mark FILE''') % mergeliststr
580 580 else:
581 581 msg = _('No unresolved merge conflicts.')
582 582
583 583 return _commentlines(msg)
584 584
585 585 def _helpmessage(continuecmd, abortcmd):
586 586 msg = _('To continue: %s\n'
587 587 'To abort: %s') % (continuecmd, abortcmd)
588 588 return _commentlines(msg)
589 589
590 590 def _rebasemsg():
591 591 return _helpmessage('hg rebase --continue', 'hg rebase --abort')
592 592
593 593 def _histeditmsg():
594 594 return _helpmessage('hg histedit --continue', 'hg histedit --abort')
595 595
596 596 def _unshelvemsg():
597 597 return _helpmessage('hg unshelve --continue', 'hg unshelve --abort')
598 598
599 599 def _updatecleanmsg(dest=None):
600 600 warning = _('warning: this will discard uncommitted changes')
601 601 return 'hg update --clean %s (%s)' % (dest or '.', warning)
602 602
603 603 def _graftmsg():
604 604 # tweakdefaults requires `update` to have a rev hence the `.`
605 605 return _helpmessage('hg graft --continue', _updatecleanmsg())
606 606
607 607 def _mergemsg():
608 608 # tweakdefaults requires `update` to have a rev hence the `.`
609 609 return _helpmessage('hg commit', _updatecleanmsg())
610 610
611 611 def _bisectmsg():
612 612 msg = _('To mark the changeset good: hg bisect --good\n'
613 613 'To mark the changeset bad: hg bisect --bad\n'
614 614 'To abort: hg bisect --reset\n')
615 615 return _commentlines(msg)
616 616
617 617 def fileexistspredicate(filename):
618 618 return lambda repo: repo.vfs.exists(filename)
619 619
620 620 def _mergepredicate(repo):
621 621 return len(repo[None].parents()) > 1
622 622
623 623 STATES = (
624 624 # (state, predicate to detect states, helpful message function)
625 625 ('histedit', fileexistspredicate('histedit-state'), _histeditmsg),
626 626 ('bisect', fileexistspredicate('bisect.state'), _bisectmsg),
627 627 ('graft', fileexistspredicate('graftstate'), _graftmsg),
628 628 ('unshelve', fileexistspredicate('unshelverebasestate'), _unshelvemsg),
629 629 ('rebase', fileexistspredicate('rebasestate'), _rebasemsg),
630 630 # The merge state is part of a list that will be iterated over.
631 631 # They need to be last because some of the other unfinished states may also
632 632 # be in a merge or update state (eg. rebase, histedit, graft, etc).
633 633 # We want those to have priority.
634 634 ('merge', _mergepredicate, _mergemsg),
635 635 )
636 636
637 637 def _getrepostate(repo):
638 638 # experimental config: commands.status.skipstates
639 639 skip = set(repo.ui.configlist('commands', 'status.skipstates'))
640 640 for state, statedetectionpredicate, msgfn in STATES:
641 641 if state in skip:
642 642 continue
643 643 if statedetectionpredicate(repo):
644 644 return (state, statedetectionpredicate, msgfn)
645 645
646 646 def morestatus(repo, fm):
647 647 statetuple = _getrepostate(repo)
648 648 label = 'status.morestatus'
649 649 if statetuple:
650 650 fm.startitem()
651 651 state, statedetectionpredicate, helpfulmsg = statetuple
652 652 statemsg = _('The repository is in an unfinished *%s* state.') % state
653 653 fm.write('statemsg', '%s\n', _commentlines(statemsg), label=label)
654 654 conmsg = _conflictsmsg(repo)
655 655 if conmsg:
656 656 fm.write('conflictsmsg', '%s\n', conmsg, label=label)
657 657 if helpfulmsg:
658 658 helpmsg = helpfulmsg()
659 659 fm.write('helpmsg', '%s\n', helpmsg, label=label)
660 660
661 661 def findpossible(cmd, table, strict=False):
662 662 """
663 663 Return cmd -> (aliases, command table entry)
664 664 for each matching command.
665 665 Return debug commands (or their aliases) only if no normal command matches.
666 666 """
667 667 choice = {}
668 668 debugchoice = {}
669 669
670 670 if cmd in table:
671 671 # short-circuit exact matches, "log" alias beats "^log|history"
672 672 keys = [cmd]
673 673 else:
674 674 keys = table.keys()
675 675
676 676 allcmds = []
677 677 for e in keys:
678 678 aliases = parsealiases(e)
679 679 allcmds.extend(aliases)
680 680 found = None
681 681 if cmd in aliases:
682 682 found = cmd
683 683 elif not strict:
684 684 for a in aliases:
685 685 if a.startswith(cmd):
686 686 found = a
687 687 break
688 688 if found is not None:
689 689 if aliases[0].startswith("debug") or found.startswith("debug"):
690 690 debugchoice[found] = (aliases, table[e])
691 691 else:
692 692 choice[found] = (aliases, table[e])
693 693
694 694 if not choice and debugchoice:
695 695 choice = debugchoice
696 696
697 697 return choice, allcmds
698 698
699 699 def findcmd(cmd, table, strict=True):
700 700 """Return (aliases, command table entry) for command string."""
701 701 choice, allcmds = findpossible(cmd, table, strict)
702 702
703 703 if cmd in choice:
704 704 return choice[cmd]
705 705
706 706 if len(choice) > 1:
707 707 clist = sorted(choice)
708 708 raise error.AmbiguousCommand(cmd, clist)
709 709
710 710 if choice:
711 711 return list(choice.values())[0]
712 712
713 713 raise error.UnknownCommand(cmd, allcmds)
714 714
715 715 def findrepo(p):
716 716 while not os.path.isdir(os.path.join(p, ".hg")):
717 717 oldp, p = p, os.path.dirname(p)
718 718 if p == oldp:
719 719 return None
720 720
721 721 return p
722 722
723 723 def bailifchanged(repo, merge=True, hint=None):
724 724 """ enforce the precondition that working directory must be clean.
725 725
726 726 'merge' can be set to false if a pending uncommitted merge should be
727 727 ignored (such as when 'update --check' runs).
728 728
729 729 'hint' is the usual hint given to Abort exception.
730 730 """
731 731
732 732 if merge and repo.dirstate.p2() != nullid:
733 733 raise error.Abort(_('outstanding uncommitted merge'), hint=hint)
734 734 modified, added, removed, deleted = repo.status()[:4]
735 735 if modified or added or removed or deleted:
736 736 raise error.Abort(_('uncommitted changes'), hint=hint)
737 737 ctx = repo[None]
738 738 for s in sorted(ctx.substate):
739 739 ctx.sub(s).bailifchanged(hint=hint)
740 740
741 741 def logmessage(ui, opts):
742 742 """ get the log message according to -m and -l option """
743 743 message = opts.get('message')
744 744 logfile = opts.get('logfile')
745 745
746 746 if message and logfile:
747 747 raise error.Abort(_('options --message and --logfile are mutually '
748 748 'exclusive'))
749 749 if not message and logfile:
750 750 try:
751 751 if isstdiofilename(logfile):
752 752 message = ui.fin.read()
753 753 else:
754 754 message = '\n'.join(util.readfile(logfile).splitlines())
755 755 except IOError as inst:
756 756 raise error.Abort(_("can't read commit message '%s': %s") %
757 757 (logfile, encoding.strtolocal(inst.strerror)))
758 758 return message
759 759
760 760 def mergeeditform(ctxorbool, baseformname):
761 761 """return appropriate editform name (referencing a committemplate)
762 762
763 763 'ctxorbool' is either a ctx to be committed, or a bool indicating whether
764 764 merging is committed.
765 765
766 766 This returns baseformname with '.merge' appended if it is a merge,
767 767 otherwise '.normal' is appended.
768 768 """
769 769 if isinstance(ctxorbool, bool):
770 770 if ctxorbool:
771 771 return baseformname + ".merge"
772 772 elif 1 < len(ctxorbool.parents()):
773 773 return baseformname + ".merge"
774 774
775 775 return baseformname + ".normal"
776 776
777 777 def getcommiteditor(edit=False, finishdesc=None, extramsg=None,
778 778 editform='', **opts):
779 779 """get appropriate commit message editor according to '--edit' option
780 780
781 781 'finishdesc' is a function to be called with edited commit message
782 782 (= 'description' of the new changeset) just after editing, but
783 783 before checking empty-ness. It should return actual text to be
784 784 stored into history. This allows to change description before
785 785 storing.
786 786
787 787 'extramsg' is a extra message to be shown in the editor instead of
788 788 'Leave message empty to abort commit' line. 'HG: ' prefix and EOL
789 789 is automatically added.
790 790
791 791 'editform' is a dot-separated list of names, to distinguish
792 792 the purpose of commit text editing.
793 793
794 794 'getcommiteditor' returns 'commitforceeditor' regardless of
795 795 'edit', if one of 'finishdesc' or 'extramsg' is specified, because
796 796 they are specific for usage in MQ.
797 797 """
798 798 if edit or finishdesc or extramsg:
799 799 return lambda r, c, s: commitforceeditor(r, c, s,
800 800 finishdesc=finishdesc,
801 801 extramsg=extramsg,
802 802 editform=editform)
803 803 elif editform:
804 804 return lambda r, c, s: commiteditor(r, c, s, editform=editform)
805 805 else:
806 806 return commiteditor
807 807
808 808 def loglimit(opts):
809 809 """get the log limit according to option -l/--limit"""
810 810 limit = opts.get('limit')
811 811 if limit:
812 812 try:
813 813 limit = int(limit)
814 814 except ValueError:
815 815 raise error.Abort(_('limit must be a positive integer'))
816 816 if limit <= 0:
817 817 raise error.Abort(_('limit must be positive'))
818 818 else:
819 819 limit = None
820 820 return limit
821 821
822 822 def makefilename(repo, pat, node, desc=None,
823 823 total=None, seqno=None, revwidth=None, pathname=None):
824 824 node_expander = {
825 825 'H': lambda: hex(node),
826 826 'R': lambda: str(repo.changelog.rev(node)),
827 827 'h': lambda: short(node),
828 828 'm': lambda: re.sub('[^\w]', '_', str(desc))
829 829 }
830 830 expander = {
831 831 '%': lambda: '%',
832 832 'b': lambda: os.path.basename(repo.root),
833 833 }
834 834
835 835 try:
836 836 if node:
837 837 expander.update(node_expander)
838 838 if node:
839 839 expander['r'] = (lambda:
840 840 str(repo.changelog.rev(node)).zfill(revwidth or 0))
841 841 if total is not None:
842 842 expander['N'] = lambda: str(total)
843 843 if seqno is not None:
844 844 expander['n'] = lambda: str(seqno)
845 845 if total is not None and seqno is not None:
846 846 expander['n'] = lambda: str(seqno).zfill(len(str(total)))
847 847 if pathname is not None:
848 848 expander['s'] = lambda: os.path.basename(pathname)
849 849 expander['d'] = lambda: os.path.dirname(pathname) or '.'
850 850 expander['p'] = lambda: pathname
851 851
852 852 newname = []
853 853 patlen = len(pat)
854 854 i = 0
855 855 while i < patlen:
856 856 c = pat[i:i + 1]
857 857 if c == '%':
858 858 i += 1
859 859 c = pat[i:i + 1]
860 860 c = expander[c]()
861 861 newname.append(c)
862 862 i += 1
863 863 return ''.join(newname)
864 864 except KeyError as inst:
865 865 raise error.Abort(_("invalid format spec '%%%s' in output filename") %
866 866 inst.args[0])
867 867
868 868 def isstdiofilename(pat):
869 869 """True if the given pat looks like a filename denoting stdin/stdout"""
870 870 return not pat or pat == '-'
871 871
872 872 class _unclosablefile(object):
873 873 def __init__(self, fp):
874 874 self._fp = fp
875 875
876 876 def close(self):
877 877 pass
878 878
879 879 def __iter__(self):
880 880 return iter(self._fp)
881 881
882 882 def __getattr__(self, attr):
883 883 return getattr(self._fp, attr)
884 884
885 885 def __enter__(self):
886 886 return self
887 887
888 888 def __exit__(self, exc_type, exc_value, exc_tb):
889 889 pass
890 890
891 891 def makefileobj(repo, pat, node=None, desc=None, total=None,
892 892 seqno=None, revwidth=None, mode='wb', modemap=None,
893 893 pathname=None):
894 894
895 895 writable = mode not in ('r', 'rb')
896 896
897 897 if isstdiofilename(pat):
898 898 if writable:
899 899 fp = repo.ui.fout
900 900 else:
901 901 fp = repo.ui.fin
902 902 return _unclosablefile(fp)
903 903 fn = makefilename(repo, pat, node, desc, total, seqno, revwidth, pathname)
904 904 if modemap is not None:
905 905 mode = modemap.get(fn, mode)
906 906 if mode == 'wb':
907 907 modemap[fn] = 'ab'
908 908 return open(fn, mode)
909 909
910 910 def openrevlog(repo, cmd, file_, opts):
911 911 """opens the changelog, manifest, a filelog or a given revlog"""
912 912 cl = opts['changelog']
913 913 mf = opts['manifest']
914 914 dir = opts['dir']
915 915 msg = None
916 916 if cl and mf:
917 917 msg = _('cannot specify --changelog and --manifest at the same time')
918 918 elif cl and dir:
919 919 msg = _('cannot specify --changelog and --dir at the same time')
920 920 elif cl or mf or dir:
921 921 if file_:
922 922 msg = _('cannot specify filename with --changelog or --manifest')
923 923 elif not repo:
924 924 msg = _('cannot specify --changelog or --manifest or --dir '
925 925 'without a repository')
926 926 if msg:
927 927 raise error.Abort(msg)
928 928
929 929 r = None
930 930 if repo:
931 931 if cl:
932 932 r = repo.unfiltered().changelog
933 933 elif dir:
934 934 if 'treemanifest' not in repo.requirements:
935 935 raise error.Abort(_("--dir can only be used on repos with "
936 936 "treemanifest enabled"))
937 937 dirlog = repo.manifestlog._revlog.dirlog(dir)
938 938 if len(dirlog):
939 939 r = dirlog
940 940 elif mf:
941 941 r = repo.manifestlog._revlog
942 942 elif file_:
943 943 filelog = repo.file(file_)
944 944 if len(filelog):
945 945 r = filelog
946 946 if not r:
947 947 if not file_:
948 948 raise error.CommandError(cmd, _('invalid arguments'))
949 949 if not os.path.isfile(file_):
950 950 raise error.Abort(_("revlog '%s' not found") % file_)
951 951 r = revlog.revlog(vfsmod.vfs(pycompat.getcwd(), audit=False),
952 952 file_[:-2] + ".i")
953 953 return r
954 954
955 955 def copy(ui, repo, pats, opts, rename=False):
956 956 # called with the repo lock held
957 957 #
958 958 # hgsep => pathname that uses "/" to separate directories
959 959 # ossep => pathname that uses os.sep to separate directories
960 960 cwd = repo.getcwd()
961 961 targets = {}
962 962 after = opts.get("after")
963 963 dryrun = opts.get("dry_run")
964 964 wctx = repo[None]
965 965
966 966 def walkpat(pat):
967 967 srcs = []
968 968 if after:
969 969 badstates = '?'
970 970 else:
971 971 badstates = '?r'
972 972 m = scmutil.match(wctx, [pat], opts, globbed=True)
973 973 for abs in wctx.walk(m):
974 974 state = repo.dirstate[abs]
975 975 rel = m.rel(abs)
976 976 exact = m.exact(abs)
977 977 if state in badstates:
978 978 if exact and state == '?':
979 979 ui.warn(_('%s: not copying - file is not managed\n') % rel)
980 980 if exact and state == 'r':
981 981 ui.warn(_('%s: not copying - file has been marked for'
982 982 ' remove\n') % rel)
983 983 continue
984 984 # abs: hgsep
985 985 # rel: ossep
986 986 srcs.append((abs, rel, exact))
987 987 return srcs
988 988
989 989 # abssrc: hgsep
990 990 # relsrc: ossep
991 991 # otarget: ossep
992 992 def copyfile(abssrc, relsrc, otarget, exact):
993 993 abstarget = pathutil.canonpath(repo.root, cwd, otarget)
994 994 if '/' in abstarget:
995 995 # We cannot normalize abstarget itself, this would prevent
996 996 # case only renames, like a => A.
997 997 abspath, absname = abstarget.rsplit('/', 1)
998 998 abstarget = repo.dirstate.normalize(abspath) + '/' + absname
999 999 reltarget = repo.pathto(abstarget, cwd)
1000 1000 target = repo.wjoin(abstarget)
1001 1001 src = repo.wjoin(abssrc)
1002 1002 state = repo.dirstate[abstarget]
1003 1003
1004 1004 scmutil.checkportable(ui, abstarget)
1005 1005
1006 1006 # check for collisions
1007 1007 prevsrc = targets.get(abstarget)
1008 1008 if prevsrc is not None:
1009 1009 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
1010 1010 (reltarget, repo.pathto(abssrc, cwd),
1011 1011 repo.pathto(prevsrc, cwd)))
1012 1012 return
1013 1013
1014 1014 # check for overwrites
1015 1015 exists = os.path.lexists(target)
1016 1016 samefile = False
1017 1017 if exists and abssrc != abstarget:
1018 1018 if (repo.dirstate.normalize(abssrc) ==
1019 1019 repo.dirstate.normalize(abstarget)):
1020 1020 if not rename:
1021 1021 ui.warn(_("%s: can't copy - same file\n") % reltarget)
1022 1022 return
1023 1023 exists = False
1024 1024 samefile = True
1025 1025
1026 1026 if not after and exists or after and state in 'mn':
1027 1027 if not opts['force']:
1028 1028 if state in 'mn':
1029 1029 msg = _('%s: not overwriting - file already committed\n')
1030 1030 if after:
1031 1031 flags = '--after --force'
1032 1032 else:
1033 1033 flags = '--force'
1034 1034 if rename:
1035 1035 hint = _('(hg rename %s to replace the file by '
1036 1036 'recording a rename)\n') % flags
1037 1037 else:
1038 1038 hint = _('(hg copy %s to replace the file by '
1039 1039 'recording a copy)\n') % flags
1040 1040 else:
1041 1041 msg = _('%s: not overwriting - file exists\n')
1042 1042 if rename:
1043 1043 hint = _('(hg rename --after to record the rename)\n')
1044 1044 else:
1045 1045 hint = _('(hg copy --after to record the copy)\n')
1046 1046 ui.warn(msg % reltarget)
1047 1047 ui.warn(hint)
1048 1048 return
1049 1049
1050 1050 if after:
1051 1051 if not exists:
1052 1052 if rename:
1053 1053 ui.warn(_('%s: not recording move - %s does not exist\n') %
1054 1054 (relsrc, reltarget))
1055 1055 else:
1056 1056 ui.warn(_('%s: not recording copy - %s does not exist\n') %
1057 1057 (relsrc, reltarget))
1058 1058 return
1059 1059 elif not dryrun:
1060 1060 try:
1061 1061 if exists:
1062 1062 os.unlink(target)
1063 1063 targetdir = os.path.dirname(target) or '.'
1064 1064 if not os.path.isdir(targetdir):
1065 1065 os.makedirs(targetdir)
1066 1066 if samefile:
1067 1067 tmp = target + "~hgrename"
1068 1068 os.rename(src, tmp)
1069 1069 os.rename(tmp, target)
1070 1070 else:
1071 1071 util.copyfile(src, target)
1072 1072 srcexists = True
1073 1073 except IOError as inst:
1074 1074 if inst.errno == errno.ENOENT:
1075 1075 ui.warn(_('%s: deleted in working directory\n') % relsrc)
1076 1076 srcexists = False
1077 1077 else:
1078 1078 ui.warn(_('%s: cannot copy - %s\n') %
1079 1079 (relsrc, encoding.strtolocal(inst.strerror)))
1080 1080 return True # report a failure
1081 1081
1082 1082 if ui.verbose or not exact:
1083 1083 if rename:
1084 1084 ui.status(_('moving %s to %s\n') % (relsrc, reltarget))
1085 1085 else:
1086 1086 ui.status(_('copying %s to %s\n') % (relsrc, reltarget))
1087 1087
1088 1088 targets[abstarget] = abssrc
1089 1089
1090 1090 # fix up dirstate
1091 1091 scmutil.dirstatecopy(ui, repo, wctx, abssrc, abstarget,
1092 1092 dryrun=dryrun, cwd=cwd)
1093 1093 if rename and not dryrun:
1094 1094 if not after and srcexists and not samefile:
1095 1095 repo.wvfs.unlinkpath(abssrc)
1096 1096 wctx.forget([abssrc])
1097 1097
1098 1098 # pat: ossep
1099 1099 # dest ossep
1100 1100 # srcs: list of (hgsep, hgsep, ossep, bool)
1101 1101 # return: function that takes hgsep and returns ossep
1102 1102 def targetpathfn(pat, dest, srcs):
1103 1103 if os.path.isdir(pat):
1104 1104 abspfx = pathutil.canonpath(repo.root, cwd, pat)
1105 1105 abspfx = util.localpath(abspfx)
1106 1106 if destdirexists:
1107 1107 striplen = len(os.path.split(abspfx)[0])
1108 1108 else:
1109 1109 striplen = len(abspfx)
1110 1110 if striplen:
1111 1111 striplen += len(pycompat.ossep)
1112 1112 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
1113 1113 elif destdirexists:
1114 1114 res = lambda p: os.path.join(dest,
1115 1115 os.path.basename(util.localpath(p)))
1116 1116 else:
1117 1117 res = lambda p: dest
1118 1118 return res
1119 1119
1120 1120 # pat: ossep
1121 1121 # dest ossep
1122 1122 # srcs: list of (hgsep, hgsep, ossep, bool)
1123 1123 # return: function that takes hgsep and returns ossep
1124 1124 def targetpathafterfn(pat, dest, srcs):
1125 1125 if matchmod.patkind(pat):
1126 1126 # a mercurial pattern
1127 1127 res = lambda p: os.path.join(dest,
1128 1128 os.path.basename(util.localpath(p)))
1129 1129 else:
1130 1130 abspfx = pathutil.canonpath(repo.root, cwd, pat)
1131 1131 if len(abspfx) < len(srcs[0][0]):
1132 1132 # A directory. Either the target path contains the last
1133 1133 # component of the source path or it does not.
1134 1134 def evalpath(striplen):
1135 1135 score = 0
1136 1136 for s in srcs:
1137 1137 t = os.path.join(dest, util.localpath(s[0])[striplen:])
1138 1138 if os.path.lexists(t):
1139 1139 score += 1
1140 1140 return score
1141 1141
1142 1142 abspfx = util.localpath(abspfx)
1143 1143 striplen = len(abspfx)
1144 1144 if striplen:
1145 1145 striplen += len(pycompat.ossep)
1146 1146 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
1147 1147 score = evalpath(striplen)
1148 1148 striplen1 = len(os.path.split(abspfx)[0])
1149 1149 if striplen1:
1150 1150 striplen1 += len(pycompat.ossep)
1151 1151 if evalpath(striplen1) > score:
1152 1152 striplen = striplen1
1153 1153 res = lambda p: os.path.join(dest,
1154 1154 util.localpath(p)[striplen:])
1155 1155 else:
1156 1156 # a file
1157 1157 if destdirexists:
1158 1158 res = lambda p: os.path.join(dest,
1159 1159 os.path.basename(util.localpath(p)))
1160 1160 else:
1161 1161 res = lambda p: dest
1162 1162 return res
1163 1163
1164 1164 pats = scmutil.expandpats(pats)
1165 1165 if not pats:
1166 1166 raise error.Abort(_('no source or destination specified'))
1167 1167 if len(pats) == 1:
1168 1168 raise error.Abort(_('no destination specified'))
1169 1169 dest = pats.pop()
1170 1170 destdirexists = os.path.isdir(dest) and not os.path.islink(dest)
1171 1171 if not destdirexists:
1172 1172 if len(pats) > 1 or matchmod.patkind(pats[0]):
1173 1173 raise error.Abort(_('with multiple sources, destination must be an '
1174 1174 'existing directory'))
1175 1175 if util.endswithsep(dest):
1176 1176 raise error.Abort(_('destination %s is not a directory') % dest)
1177 1177
1178 1178 tfn = targetpathfn
1179 1179 if after:
1180 1180 tfn = targetpathafterfn
1181 1181 copylist = []
1182 1182 for pat in pats:
1183 1183 srcs = walkpat(pat)
1184 1184 if not srcs:
1185 1185 continue
1186 1186 copylist.append((tfn(pat, dest, srcs), srcs))
1187 1187 if not copylist:
1188 1188 raise error.Abort(_('no files to copy'))
1189 1189
1190 1190 errors = 0
1191 1191 for targetpath, srcs in copylist:
1192 1192 for abssrc, relsrc, exact in srcs:
1193 1193 if copyfile(abssrc, relsrc, targetpath(abssrc), exact):
1194 1194 errors += 1
1195 1195
1196 1196 if errors:
1197 1197 ui.warn(_('(consider using --after)\n'))
1198 1198
1199 1199 return errors != 0
1200 1200
1201 1201 ## facility to let extension process additional data into an import patch
1202 1202 # list of identifier to be executed in order
1203 1203 extrapreimport = [] # run before commit
1204 1204 extrapostimport = [] # run after commit
1205 1205 # mapping from identifier to actual import function
1206 1206 #
1207 1207 # 'preimport' are run before the commit is made and are provided the following
1208 1208 # arguments:
1209 1209 # - repo: the localrepository instance,
1210 1210 # - patchdata: data extracted from patch header (cf m.patch.patchheadermap),
1211 1211 # - extra: the future extra dictionary of the changeset, please mutate it,
1212 1212 # - opts: the import options.
1213 1213 # XXX ideally, we would just pass an ctx ready to be computed, that would allow
1214 1214 # mutation of in memory commit and more. Feel free to rework the code to get
1215 1215 # there.
1216 1216 extrapreimportmap = {}
1217 1217 # 'postimport' are run after the commit is made and are provided the following
1218 1218 # argument:
1219 1219 # - ctx: the changectx created by import.
1220 1220 extrapostimportmap = {}
1221 1221
1222 1222 def tryimportone(ui, repo, hunk, parents, opts, msgs, updatefunc):
1223 1223 """Utility function used by commands.import to import a single patch
1224 1224
1225 1225 This function is explicitly defined here to help the evolve extension to
1226 1226 wrap this part of the import logic.
1227 1227
1228 1228 The API is currently a bit ugly because it a simple code translation from
1229 1229 the import command. Feel free to make it better.
1230 1230
1231 1231 :hunk: a patch (as a binary string)
1232 1232 :parents: nodes that will be parent of the created commit
1233 1233 :opts: the full dict of option passed to the import command
1234 1234 :msgs: list to save commit message to.
1235 1235 (used in case we need to save it when failing)
1236 1236 :updatefunc: a function that update a repo to a given node
1237 1237 updatefunc(<repo>, <node>)
1238 1238 """
1239 1239 # avoid cycle context -> subrepo -> cmdutil
1240 1240 from . import context
1241 1241 extractdata = patch.extract(ui, hunk)
1242 1242 tmpname = extractdata.get('filename')
1243 1243 message = extractdata.get('message')
1244 1244 user = opts.get('user') or extractdata.get('user')
1245 1245 date = opts.get('date') or extractdata.get('date')
1246 1246 branch = extractdata.get('branch')
1247 1247 nodeid = extractdata.get('nodeid')
1248 1248 p1 = extractdata.get('p1')
1249 1249 p2 = extractdata.get('p2')
1250 1250
1251 1251 nocommit = opts.get('no_commit')
1252 1252 importbranch = opts.get('import_branch')
1253 1253 update = not opts.get('bypass')
1254 1254 strip = opts["strip"]
1255 1255 prefix = opts["prefix"]
1256 1256 sim = float(opts.get('similarity') or 0)
1257 1257 if not tmpname:
1258 1258 return (None, None, False)
1259 1259
1260 1260 rejects = False
1261 1261
1262 1262 try:
1263 1263 cmdline_message = logmessage(ui, opts)
1264 1264 if cmdline_message:
1265 1265 # pickup the cmdline msg
1266 1266 message = cmdline_message
1267 1267 elif message:
1268 1268 # pickup the patch msg
1269 1269 message = message.strip()
1270 1270 else:
1271 1271 # launch the editor
1272 1272 message = None
1273 1273 ui.debug('message:\n%s\n' % message)
1274 1274
1275 1275 if len(parents) == 1:
1276 1276 parents.append(repo[nullid])
1277 1277 if opts.get('exact'):
1278 1278 if not nodeid or not p1:
1279 1279 raise error.Abort(_('not a Mercurial patch'))
1280 1280 p1 = repo[p1]
1281 1281 p2 = repo[p2 or nullid]
1282 1282 elif p2:
1283 1283 try:
1284 1284 p1 = repo[p1]
1285 1285 p2 = repo[p2]
1286 1286 # Without any options, consider p2 only if the
1287 1287 # patch is being applied on top of the recorded
1288 1288 # first parent.
1289 1289 if p1 != parents[0]:
1290 1290 p1 = parents[0]
1291 1291 p2 = repo[nullid]
1292 1292 except error.RepoError:
1293 1293 p1, p2 = parents
1294 1294 if p2.node() == nullid:
1295 1295 ui.warn(_("warning: import the patch as a normal revision\n"
1296 1296 "(use --exact to import the patch as a merge)\n"))
1297 1297 else:
1298 1298 p1, p2 = parents
1299 1299
1300 1300 n = None
1301 1301 if update:
1302 1302 if p1 != parents[0]:
1303 1303 updatefunc(repo, p1.node())
1304 1304 if p2 != parents[1]:
1305 1305 repo.setparents(p1.node(), p2.node())
1306 1306
1307 1307 if opts.get('exact') or importbranch:
1308 1308 repo.dirstate.setbranch(branch or 'default')
1309 1309
1310 1310 partial = opts.get('partial', False)
1311 1311 files = set()
1312 1312 try:
1313 1313 patch.patch(ui, repo, tmpname, strip=strip, prefix=prefix,
1314 1314 files=files, eolmode=None, similarity=sim / 100.0)
1315 1315 except error.PatchError as e:
1316 1316 if not partial:
1317 1317 raise error.Abort(str(e))
1318 1318 if partial:
1319 1319 rejects = True
1320 1320
1321 1321 files = list(files)
1322 1322 if nocommit:
1323 1323 if message:
1324 1324 msgs.append(message)
1325 1325 else:
1326 1326 if opts.get('exact') or p2:
1327 1327 # If you got here, you either use --force and know what
1328 1328 # you are doing or used --exact or a merge patch while
1329 1329 # being updated to its first parent.
1330 1330 m = None
1331 1331 else:
1332 1332 m = scmutil.matchfiles(repo, files or [])
1333 1333 editform = mergeeditform(repo[None], 'import.normal')
1334 1334 if opts.get('exact'):
1335 1335 editor = None
1336 1336 else:
1337 1337 editor = getcommiteditor(editform=editform, **opts)
1338 1338 extra = {}
1339 1339 for idfunc in extrapreimport:
1340 1340 extrapreimportmap[idfunc](repo, extractdata, extra, opts)
1341 1341 overrides = {}
1342 1342 if partial:
1343 1343 overrides[('ui', 'allowemptycommit')] = True
1344 1344 with repo.ui.configoverride(overrides, 'import'):
1345 1345 n = repo.commit(message, user,
1346 1346 date, match=m,
1347 1347 editor=editor, extra=extra)
1348 1348 for idfunc in extrapostimport:
1349 1349 extrapostimportmap[idfunc](repo[n])
1350 1350 else:
1351 1351 if opts.get('exact') or importbranch:
1352 1352 branch = branch or 'default'
1353 1353 else:
1354 1354 branch = p1.branch()
1355 1355 store = patch.filestore()
1356 1356 try:
1357 1357 files = set()
1358 1358 try:
1359 1359 patch.patchrepo(ui, repo, p1, store, tmpname, strip, prefix,
1360 1360 files, eolmode=None)
1361 1361 except error.PatchError as e:
1362 1362 raise error.Abort(str(e))
1363 1363 if opts.get('exact'):
1364 1364 editor = None
1365 1365 else:
1366 1366 editor = getcommiteditor(editform='import.bypass')
1367 1367 memctx = context.memctx(repo, (p1.node(), p2.node()),
1368 1368 message,
1369 1369 files=files,
1370 1370 filectxfn=store,
1371 1371 user=user,
1372 1372 date=date,
1373 1373 branch=branch,
1374 1374 editor=editor)
1375 1375 n = memctx.commit()
1376 1376 finally:
1377 1377 store.close()
1378 1378 if opts.get('exact') and nocommit:
1379 1379 # --exact with --no-commit is still useful in that it does merge
1380 1380 # and branch bits
1381 1381 ui.warn(_("warning: can't check exact import with --no-commit\n"))
1382 1382 elif opts.get('exact') and hex(n) != nodeid:
1383 1383 raise error.Abort(_('patch is damaged or loses information'))
1384 1384 msg = _('applied to working directory')
1385 1385 if n:
1386 1386 # i18n: refers to a short changeset id
1387 1387 msg = _('created %s') % short(n)
1388 1388 return (msg, n, rejects)
1389 1389 finally:
1390 1390 os.unlink(tmpname)
1391 1391
1392 1392 # facility to let extensions include additional data in an exported patch
1393 1393 # list of identifiers to be executed in order
1394 1394 extraexport = []
1395 1395 # mapping from identifier to actual export function
1396 1396 # function as to return a string to be added to the header or None
1397 1397 # it is given two arguments (sequencenumber, changectx)
1398 1398 extraexportmap = {}
1399 1399
1400 1400 def _exportsingle(repo, ctx, match, switch_parent, rev, seqno, write, diffopts):
1401 1401 node = scmutil.binnode(ctx)
1402 1402 parents = [p.node() for p in ctx.parents() if p]
1403 1403 branch = ctx.branch()
1404 1404 if switch_parent:
1405 1405 parents.reverse()
1406 1406
1407 1407 if parents:
1408 1408 prev = parents[0]
1409 1409 else:
1410 1410 prev = nullid
1411 1411
1412 1412 write("# HG changeset patch\n")
1413 1413 write("# User %s\n" % ctx.user())
1414 1414 write("# Date %d %d\n" % ctx.date())
1415 1415 write("# %s\n" % util.datestr(ctx.date()))
1416 1416 if branch and branch != 'default':
1417 1417 write("# Branch %s\n" % branch)
1418 1418 write("# Node ID %s\n" % hex(node))
1419 1419 write("# Parent %s\n" % hex(prev))
1420 1420 if len(parents) > 1:
1421 1421 write("# Parent %s\n" % hex(parents[1]))
1422 1422
1423 1423 for headerid in extraexport:
1424 1424 header = extraexportmap[headerid](seqno, ctx)
1425 1425 if header is not None:
1426 1426 write('# %s\n' % header)
1427 1427 write(ctx.description().rstrip())
1428 1428 write("\n\n")
1429 1429
1430 1430 for chunk, label in patch.diffui(repo, prev, node, match, opts=diffopts):
1431 1431 write(chunk, label=label)
1432 1432
1433 1433 def export(repo, revs, fntemplate='hg-%h.patch', fp=None, switch_parent=False,
1434 1434 opts=None, match=None):
1435 1435 '''export changesets as hg patches
1436 1436
1437 1437 Args:
1438 1438 repo: The repository from which we're exporting revisions.
1439 1439 revs: A list of revisions to export as revision numbers.
1440 1440 fntemplate: An optional string to use for generating patch file names.
1441 1441 fp: An optional file-like object to which patches should be written.
1442 1442 switch_parent: If True, show diffs against second parent when not nullid.
1443 1443 Default is false, which always shows diff against p1.
1444 1444 opts: diff options to use for generating the patch.
1445 1445 match: If specified, only export changes to files matching this matcher.
1446 1446
1447 1447 Returns:
1448 1448 Nothing.
1449 1449
1450 1450 Side Effect:
1451 1451 "HG Changeset Patch" data is emitted to one of the following
1452 1452 destinations:
1453 1453 fp is specified: All revs are written to the specified
1454 1454 file-like object.
1455 1455 fntemplate specified: Each rev is written to a unique file named using
1456 1456 the given template.
1457 1457 Neither fp nor template specified: All revs written to repo.ui.write()
1458 1458 '''
1459 1459
1460 1460 total = len(revs)
1461 1461 revwidth = max(len(str(rev)) for rev in revs)
1462 1462 filemode = {}
1463 1463
1464 1464 write = None
1465 1465 dest = '<unnamed>'
1466 1466 if fp:
1467 1467 dest = getattr(fp, 'name', dest)
1468 1468 def write(s, **kw):
1469 1469 fp.write(s)
1470 1470 elif not fntemplate:
1471 1471 write = repo.ui.write
1472 1472
1473 1473 for seqno, rev in enumerate(revs, 1):
1474 1474 ctx = repo[rev]
1475 1475 fo = None
1476 1476 if not fp and fntemplate:
1477 1477 desc_lines = ctx.description().rstrip().split('\n')
1478 1478 desc = desc_lines[0] #Commit always has a first line.
1479 1479 fo = makefileobj(repo, fntemplate, ctx.node(), desc=desc,
1480 1480 total=total, seqno=seqno, revwidth=revwidth,
1481 1481 mode='wb', modemap=filemode)
1482 1482 dest = fo.name
1483 1483 def write(s, **kw):
1484 1484 fo.write(s)
1485 1485 if not dest.startswith('<'):
1486 1486 repo.ui.note("%s\n" % dest)
1487 1487 _exportsingle(
1488 1488 repo, ctx, match, switch_parent, rev, seqno, write, opts)
1489 1489 if fo is not None:
1490 1490 fo.close()
1491 1491
1492 1492 def diffordiffstat(ui, repo, diffopts, node1, node2, match,
1493 1493 changes=None, stat=False, fp=None, prefix='',
1494 1494 root='', listsubrepos=False, hunksfilterfn=None):
1495 1495 '''show diff or diffstat.'''
1496 1496 if fp is None:
1497 1497 write = ui.write
1498 1498 else:
1499 1499 def write(s, **kw):
1500 1500 fp.write(s)
1501 1501
1502 1502 if root:
1503 1503 relroot = pathutil.canonpath(repo.root, repo.getcwd(), root)
1504 1504 else:
1505 1505 relroot = ''
1506 1506 if relroot != '':
1507 1507 # XXX relative roots currently don't work if the root is within a
1508 1508 # subrepo
1509 1509 uirelroot = match.uipath(relroot)
1510 1510 relroot += '/'
1511 1511 for matchroot in match.files():
1512 1512 if not matchroot.startswith(relroot):
1513 1513 ui.warn(_('warning: %s not inside relative root %s\n') % (
1514 1514 match.uipath(matchroot), uirelroot))
1515 1515
1516 1516 if stat:
1517 1517 diffopts = diffopts.copy(context=0)
1518 1518 width = 80
1519 1519 if not ui.plain():
1520 1520 width = ui.termwidth()
1521 1521 chunks = patch.diff(repo, node1, node2, match, changes, diffopts,
1522 1522 prefix=prefix, relroot=relroot,
1523 1523 hunksfilterfn=hunksfilterfn)
1524 1524 for chunk, label in patch.diffstatui(util.iterlines(chunks),
1525 1525 width=width):
1526 1526 write(chunk, label=label)
1527 1527 else:
1528 1528 for chunk, label in patch.diffui(repo, node1, node2, match,
1529 1529 changes, diffopts, prefix=prefix,
1530 1530 relroot=relroot,
1531 1531 hunksfilterfn=hunksfilterfn):
1532 1532 write(chunk, label=label)
1533 1533
1534 1534 if listsubrepos:
1535 1535 ctx1 = repo[node1]
1536 1536 ctx2 = repo[node2]
1537 1537 for subpath, sub in scmutil.itersubrepos(ctx1, ctx2):
1538 1538 tempnode2 = node2
1539 1539 try:
1540 1540 if node2 is not None:
1541 1541 tempnode2 = ctx2.substate[subpath][1]
1542 1542 except KeyError:
1543 1543 # A subrepo that existed in node1 was deleted between node1 and
1544 1544 # node2 (inclusive). Thus, ctx2's substate won't contain that
1545 1545 # subpath. The best we can do is to ignore it.
1546 1546 tempnode2 = None
1547 1547 submatch = matchmod.subdirmatcher(subpath, match)
1548 1548 sub.diff(ui, diffopts, tempnode2, submatch, changes=changes,
1549 1549 stat=stat, fp=fp, prefix=prefix)
1550 1550
1551 1551 def _changesetlabels(ctx):
1552 1552 labels = ['log.changeset', 'changeset.%s' % ctx.phasestr()]
1553 1553 if ctx.obsolete():
1554 1554 labels.append('changeset.obsolete')
1555 1555 if ctx.isunstable():
1556 1556 labels.append('changeset.unstable')
1557 1557 for instability in ctx.instabilities():
1558 1558 labels.append('instability.%s' % instability)
1559 1559 return ' '.join(labels)
1560 1560
1561 1561 class changeset_printer(object):
1562 1562 '''show changeset information when templating not requested.'''
1563 1563
1564 1564 def __init__(self, ui, repo, matchfn, diffopts, buffered):
1565 1565 self.ui = ui
1566 1566 self.repo = repo
1567 1567 self.buffered = buffered
1568 1568 self.matchfn = matchfn
1569 1569 self.diffopts = diffopts
1570 1570 self.header = {}
1571 1571 self.hunk = {}
1572 1572 self.lastheader = None
1573 1573 self.footer = None
1574 1574
1575 1575 def flush(self, ctx):
1576 1576 rev = ctx.rev()
1577 1577 if rev in self.header:
1578 1578 h = self.header[rev]
1579 1579 if h != self.lastheader:
1580 1580 self.lastheader = h
1581 1581 self.ui.write(h)
1582 1582 del self.header[rev]
1583 1583 if rev in self.hunk:
1584 1584 self.ui.write(self.hunk[rev])
1585 1585 del self.hunk[rev]
1586 1586 return 1
1587 1587 return 0
1588 1588
1589 1589 def close(self):
1590 1590 if self.footer:
1591 1591 self.ui.write(self.footer)
1592 1592
1593 1593 def show(self, ctx, copies=None, matchfn=None, hunksfilterfn=None,
1594 1594 **props):
1595 1595 props = pycompat.byteskwargs(props)
1596 1596 if self.buffered:
1597 1597 self.ui.pushbuffer(labeled=True)
1598 1598 self._show(ctx, copies, matchfn, hunksfilterfn, props)
1599 1599 self.hunk[ctx.rev()] = self.ui.popbuffer()
1600 1600 else:
1601 1601 self._show(ctx, copies, matchfn, hunksfilterfn, props)
1602 1602
1603 1603 def _show(self, ctx, copies, matchfn, hunksfilterfn, props):
1604 1604 '''show a single changeset or file revision'''
1605 1605 changenode = ctx.node()
1606 1606 rev = ctx.rev()
1607 1607
1608 1608 if self.ui.quiet:
1609 1609 self.ui.write("%s\n" % scmutil.formatchangeid(ctx),
1610 1610 label='log.node')
1611 1611 return
1612 1612
1613 1613 date = util.datestr(ctx.date())
1614 1614
1615 1615 # i18n: column positioning for "hg log"
1616 1616 self.ui.write(_("changeset: %s\n") % scmutil.formatchangeid(ctx),
1617 1617 label=_changesetlabels(ctx))
1618 1618
1619 1619 # branches are shown first before any other names due to backwards
1620 1620 # compatibility
1621 1621 branch = ctx.branch()
1622 1622 # don't show the default branch name
1623 1623 if branch != 'default':
1624 1624 # i18n: column positioning for "hg log"
1625 1625 self.ui.write(_("branch: %s\n") % branch,
1626 1626 label='log.branch')
1627 1627
1628 1628 for nsname, ns in self.repo.names.iteritems():
1629 1629 # branches has special logic already handled above, so here we just
1630 1630 # skip it
1631 1631 if nsname == 'branches':
1632 1632 continue
1633 1633 # we will use the templatename as the color name since those two
1634 1634 # should be the same
1635 1635 for name in ns.names(self.repo, changenode):
1636 1636 self.ui.write(ns.logfmt % name,
1637 1637 label='log.%s' % ns.colorname)
1638 1638 if self.ui.debugflag:
1639 1639 # i18n: column positioning for "hg log"
1640 1640 self.ui.write(_("phase: %s\n") % ctx.phasestr(),
1641 1641 label='log.phase')
1642 1642 for pctx in scmutil.meaningfulparents(self.repo, ctx):
1643 1643 label = 'log.parent changeset.%s' % pctx.phasestr()
1644 1644 # i18n: column positioning for "hg log"
1645 1645 self.ui.write(_("parent: %s\n") % scmutil.formatchangeid(pctx),
1646 1646 label=label)
1647 1647
1648 1648 if self.ui.debugflag and rev is not None:
1649 1649 mnode = ctx.manifestnode()
1650 1650 mrev = self.repo.manifestlog._revlog.rev(mnode)
1651 1651 # i18n: column positioning for "hg log"
1652 1652 self.ui.write(_("manifest: %s\n")
1653 1653 % scmutil.formatrevnode(self.ui, mrev, mnode),
1654 1654 label='ui.debug log.manifest')
1655 1655 # i18n: column positioning for "hg log"
1656 1656 self.ui.write(_("user: %s\n") % ctx.user(),
1657 1657 label='log.user')
1658 1658 # i18n: column positioning for "hg log"
1659 1659 self.ui.write(_("date: %s\n") % date,
1660 1660 label='log.date')
1661 1661
1662 1662 if ctx.isunstable():
1663 1663 # i18n: column positioning for "hg log"
1664 1664 instabilities = ctx.instabilities()
1665 1665 self.ui.write(_("instability: %s\n") % ', '.join(instabilities),
1666 1666 label='log.instability')
1667 1667
1668 1668 elif ctx.obsolete():
1669 1669 self._showobsfate(ctx)
1670 1670
1671 1671 self._exthook(ctx)
1672 1672
1673 1673 if self.ui.debugflag:
1674 1674 files = ctx.p1().status(ctx)[:3]
1675 1675 for key, value in zip([# i18n: column positioning for "hg log"
1676 1676 _("files:"),
1677 1677 # i18n: column positioning for "hg log"
1678 1678 _("files+:"),
1679 1679 # i18n: column positioning for "hg log"
1680 1680 _("files-:")], files):
1681 1681 if value:
1682 1682 self.ui.write("%-12s %s\n" % (key, " ".join(value)),
1683 1683 label='ui.debug log.files')
1684 1684 elif ctx.files() and self.ui.verbose:
1685 1685 # i18n: column positioning for "hg log"
1686 1686 self.ui.write(_("files: %s\n") % " ".join(ctx.files()),
1687 1687 label='ui.note log.files')
1688 1688 if copies and self.ui.verbose:
1689 1689 copies = ['%s (%s)' % c for c in copies]
1690 1690 # i18n: column positioning for "hg log"
1691 1691 self.ui.write(_("copies: %s\n") % ' '.join(copies),
1692 1692 label='ui.note log.copies')
1693 1693
1694 1694 extra = ctx.extra()
1695 1695 if extra and self.ui.debugflag:
1696 1696 for key, value in sorted(extra.items()):
1697 1697 # i18n: column positioning for "hg log"
1698 1698 self.ui.write(_("extra: %s=%s\n")
1699 1699 % (key, util.escapestr(value)),
1700 1700 label='ui.debug log.extra')
1701 1701
1702 1702 description = ctx.description().strip()
1703 1703 if description:
1704 1704 if self.ui.verbose:
1705 1705 self.ui.write(_("description:\n"),
1706 1706 label='ui.note log.description')
1707 1707 self.ui.write(description,
1708 1708 label='ui.note log.description')
1709 1709 self.ui.write("\n\n")
1710 1710 else:
1711 1711 # i18n: column positioning for "hg log"
1712 1712 self.ui.write(_("summary: %s\n") %
1713 1713 description.splitlines()[0],
1714 1714 label='log.summary')
1715 1715 self.ui.write("\n")
1716 1716
1717 1717 self.showpatch(ctx, matchfn, hunksfilterfn=hunksfilterfn)
1718 1718
1719 1719 def _showobsfate(self, ctx):
1720 1720 obsfate = templatekw.showobsfate(repo=self.repo, ctx=ctx, ui=self.ui)
1721 1721
1722 1722 if obsfate:
1723 1723 for obsfateline in obsfate:
1724 1724 # i18n: column positioning for "hg log"
1725 1725 self.ui.write(_("obsolete: %s\n") % obsfateline,
1726 1726 label='log.obsfate')
1727 1727
1728 1728 def _exthook(self, ctx):
1729 1729 '''empty method used by extension as a hook point
1730 1730 '''
1731 1731
1732 1732 def showpatch(self, ctx, matchfn, hunksfilterfn=None):
1733 1733 if not matchfn:
1734 1734 matchfn = self.matchfn
1735 1735 if matchfn:
1736 1736 stat = self.diffopts.get('stat')
1737 1737 diff = self.diffopts.get('patch')
1738 1738 diffopts = patch.diffallopts(self.ui, self.diffopts)
1739 1739 node = ctx.node()
1740 1740 prev = ctx.p1().node()
1741 1741 if stat:
1742 1742 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1743 1743 match=matchfn, stat=True,
1744 1744 hunksfilterfn=hunksfilterfn)
1745 1745 if diff:
1746 1746 if stat:
1747 1747 self.ui.write("\n")
1748 1748 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1749 1749 match=matchfn, stat=False,
1750 1750 hunksfilterfn=hunksfilterfn)
1751 1751 self.ui.write("\n")
1752 1752
1753 1753 class jsonchangeset(changeset_printer):
1754 1754 '''format changeset information.'''
1755 1755
1756 1756 def __init__(self, ui, repo, matchfn, diffopts, buffered):
1757 1757 changeset_printer.__init__(self, ui, repo, matchfn, diffopts, buffered)
1758 1758 self.cache = {}
1759 1759 self._first = True
1760 1760
1761 1761 def close(self):
1762 1762 if not self._first:
1763 1763 self.ui.write("\n]\n")
1764 1764 else:
1765 1765 self.ui.write("[]\n")
1766 1766
1767 1767 def _show(self, ctx, copies, matchfn, hunksfilterfn, props):
1768 1768 '''show a single changeset or file revision'''
1769 1769 rev = ctx.rev()
1770 1770 if rev is None:
1771 1771 jrev = jnode = 'null'
1772 1772 else:
1773 1773 jrev = '%d' % rev
1774 1774 jnode = '"%s"' % hex(ctx.node())
1775 1775 j = encoding.jsonescape
1776 1776
1777 1777 if self._first:
1778 1778 self.ui.write("[\n {")
1779 1779 self._first = False
1780 1780 else:
1781 1781 self.ui.write(",\n {")
1782 1782
1783 1783 if self.ui.quiet:
1784 1784 self.ui.write(('\n "rev": %s') % jrev)
1785 1785 self.ui.write((',\n "node": %s') % jnode)
1786 1786 self.ui.write('\n }')
1787 1787 return
1788 1788
1789 1789 self.ui.write(('\n "rev": %s') % jrev)
1790 1790 self.ui.write((',\n "node": %s') % jnode)
1791 1791 self.ui.write((',\n "branch": "%s"') % j(ctx.branch()))
1792 1792 self.ui.write((',\n "phase": "%s"') % ctx.phasestr())
1793 1793 self.ui.write((',\n "user": "%s"') % j(ctx.user()))
1794 1794 self.ui.write((',\n "date": [%d, %d]') % ctx.date())
1795 1795 self.ui.write((',\n "desc": "%s"') % j(ctx.description()))
1796 1796
1797 1797 self.ui.write((',\n "bookmarks": [%s]') %
1798 1798 ", ".join('"%s"' % j(b) for b in ctx.bookmarks()))
1799 1799 self.ui.write((',\n "tags": [%s]') %
1800 1800 ", ".join('"%s"' % j(t) for t in ctx.tags()))
1801 1801 self.ui.write((',\n "parents": [%s]') %
1802 1802 ", ".join('"%s"' % c.hex() for c in ctx.parents()))
1803 1803
1804 1804 if self.ui.debugflag:
1805 1805 if rev is None:
1806 1806 jmanifestnode = 'null'
1807 1807 else:
1808 1808 jmanifestnode = '"%s"' % hex(ctx.manifestnode())
1809 1809 self.ui.write((',\n "manifest": %s') % jmanifestnode)
1810 1810
1811 1811 self.ui.write((',\n "extra": {%s}') %
1812 1812 ", ".join('"%s": "%s"' % (j(k), j(v))
1813 1813 for k, v in ctx.extra().items()))
1814 1814
1815 1815 files = ctx.p1().status(ctx)
1816 1816 self.ui.write((',\n "modified": [%s]') %
1817 1817 ", ".join('"%s"' % j(f) for f in files[0]))
1818 1818 self.ui.write((',\n "added": [%s]') %
1819 1819 ", ".join('"%s"' % j(f) for f in files[1]))
1820 1820 self.ui.write((',\n "removed": [%s]') %
1821 1821 ", ".join('"%s"' % j(f) for f in files[2]))
1822 1822
1823 1823 elif self.ui.verbose:
1824 1824 self.ui.write((',\n "files": [%s]') %
1825 1825 ", ".join('"%s"' % j(f) for f in ctx.files()))
1826 1826
1827 1827 if copies:
1828 1828 self.ui.write((',\n "copies": {%s}') %
1829 1829 ", ".join('"%s": "%s"' % (j(k), j(v))
1830 1830 for k, v in copies))
1831 1831
1832 1832 matchfn = self.matchfn
1833 1833 if matchfn:
1834 1834 stat = self.diffopts.get('stat')
1835 1835 diff = self.diffopts.get('patch')
1836 1836 diffopts = patch.difffeatureopts(self.ui, self.diffopts, git=True)
1837 1837 node, prev = ctx.node(), ctx.p1().node()
1838 1838 if stat:
1839 1839 self.ui.pushbuffer()
1840 1840 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1841 1841 match=matchfn, stat=True)
1842 1842 self.ui.write((',\n "diffstat": "%s"')
1843 1843 % j(self.ui.popbuffer()))
1844 1844 if diff:
1845 1845 self.ui.pushbuffer()
1846 1846 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1847 1847 match=matchfn, stat=False)
1848 1848 self.ui.write((',\n "diff": "%s"') % j(self.ui.popbuffer()))
1849 1849
1850 1850 self.ui.write("\n }")
1851 1851
1852 1852 class changeset_templater(changeset_printer):
1853 1853 '''format changeset information.
1854 1854
1855 1855 Note: there are a variety of convenience functions to build a
1856 1856 changeset_templater for common cases. See functions such as:
1857 1857 makelogtemplater, show_changeset, buildcommittemplate, or other
1858 1858 functions that use changesest_templater.
1859 1859 '''
1860 1860
1861 1861 # Arguments before "buffered" used to be positional. Consider not
1862 1862 # adding/removing arguments before "buffered" to not break callers.
1863 1863 def __init__(self, ui, repo, tmplspec, matchfn=None, diffopts=None,
1864 1864 buffered=False):
1865 1865 diffopts = diffopts or {}
1866 1866
1867 1867 changeset_printer.__init__(self, ui, repo, matchfn, diffopts, buffered)
1868 1868 self.t = formatter.loadtemplater(ui, tmplspec,
1869 1869 cache=templatekw.defaulttempl)
1870 1870 self._counter = itertools.count()
1871 1871 self.cache = {}
1872 1872
1873 1873 self._tref = tmplspec.ref
1874 1874 self._parts = {'header': '', 'footer': '',
1875 1875 tmplspec.ref: tmplspec.ref,
1876 1876 'docheader': '', 'docfooter': '',
1877 1877 'separator': ''}
1878 1878 if tmplspec.mapfile:
1879 1879 # find correct templates for current mode, for backward
1880 1880 # compatibility with 'log -v/-q/--debug' using a mapfile
1881 1881 tmplmodes = [
1882 1882 (True, ''),
1883 1883 (self.ui.verbose, '_verbose'),
1884 1884 (self.ui.quiet, '_quiet'),
1885 1885 (self.ui.debugflag, '_debug'),
1886 1886 ]
1887 1887 for mode, postfix in tmplmodes:
1888 1888 for t in self._parts:
1889 1889 cur = t + postfix
1890 1890 if mode and cur in self.t:
1891 1891 self._parts[t] = cur
1892 1892 else:
1893 1893 partnames = [p for p in self._parts.keys() if p != tmplspec.ref]
1894 1894 m = formatter.templatepartsmap(tmplspec, self.t, partnames)
1895 1895 self._parts.update(m)
1896 1896
1897 1897 if self._parts['docheader']:
1898 1898 self.ui.write(templater.stringify(self.t(self._parts['docheader'])))
1899 1899
1900 1900 def close(self):
1901 1901 if self._parts['docfooter']:
1902 1902 if not self.footer:
1903 1903 self.footer = ""
1904 1904 self.footer += templater.stringify(self.t(self._parts['docfooter']))
1905 1905 return super(changeset_templater, self).close()
1906 1906
1907 1907 def _show(self, ctx, copies, matchfn, hunksfilterfn, props):
1908 1908 '''show a single changeset or file revision'''
1909 1909 props = props.copy()
1910 1910 props.update(templatekw.keywords)
1911 1911 props['templ'] = self.t
1912 1912 props['ctx'] = ctx
1913 1913 props['repo'] = self.repo
1914 1914 props['ui'] = self.repo.ui
1915 1915 props['index'] = index = next(self._counter)
1916 1916 props['revcache'] = {'copies': copies}
1917 1917 props['cache'] = self.cache
1918 1918 props = pycompat.strkwargs(props)
1919 1919
1920 1920 # write separator, which wouldn't work well with the header part below
1921 1921 # since there's inherently a conflict between header (across items) and
1922 1922 # separator (per item)
1923 1923 if self._parts['separator'] and index > 0:
1924 1924 self.ui.write(templater.stringify(self.t(self._parts['separator'])))
1925 1925
1926 1926 # write header
1927 1927 if self._parts['header']:
1928 1928 h = templater.stringify(self.t(self._parts['header'], **props))
1929 1929 if self.buffered:
1930 1930 self.header[ctx.rev()] = h
1931 1931 else:
1932 1932 if self.lastheader != h:
1933 1933 self.lastheader = h
1934 1934 self.ui.write(h)
1935 1935
1936 1936 # write changeset metadata, then patch if requested
1937 1937 key = self._parts[self._tref]
1938 1938 self.ui.write(templater.stringify(self.t(key, **props)))
1939 1939 self.showpatch(ctx, matchfn, hunksfilterfn=hunksfilterfn)
1940 1940
1941 1941 if self._parts['footer']:
1942 1942 if not self.footer:
1943 1943 self.footer = templater.stringify(
1944 1944 self.t(self._parts['footer'], **props))
1945 1945
1946 1946 def logtemplatespec(tmpl, mapfile):
1947 1947 if mapfile:
1948 1948 return formatter.templatespec('changeset', tmpl, mapfile)
1949 1949 else:
1950 1950 return formatter.templatespec('', tmpl, None)
1951 1951
1952 1952 def _lookuplogtemplate(ui, tmpl, style):
1953 1953 """Find the template matching the given template spec or style
1954 1954
1955 1955 See formatter.lookuptemplate() for details.
1956 1956 """
1957 1957
1958 1958 # ui settings
1959 1959 if not tmpl and not style: # template are stronger than style
1960 1960 tmpl = ui.config('ui', 'logtemplate')
1961 1961 if tmpl:
1962 1962 return logtemplatespec(templater.unquotestring(tmpl), None)
1963 1963 else:
1964 1964 style = util.expandpath(ui.config('ui', 'style'))
1965 1965
1966 1966 if not tmpl and style:
1967 1967 mapfile = style
1968 1968 if not os.path.split(mapfile)[0]:
1969 1969 mapname = (templater.templatepath('map-cmdline.' + mapfile)
1970 1970 or templater.templatepath(mapfile))
1971 1971 if mapname:
1972 1972 mapfile = mapname
1973 1973 return logtemplatespec(None, mapfile)
1974 1974
1975 1975 if not tmpl:
1976 1976 return logtemplatespec(None, None)
1977 1977
1978 1978 return formatter.lookuptemplate(ui, 'changeset', tmpl)
1979 1979
1980 1980 def makelogtemplater(ui, repo, tmpl, buffered=False):
1981 1981 """Create a changeset_templater from a literal template 'tmpl'
1982 1982 byte-string."""
1983 1983 spec = logtemplatespec(tmpl, None)
1984 1984 return changeset_templater(ui, repo, spec, buffered=buffered)
1985 1985
1986 1986 def show_changeset(ui, repo, opts, buffered=False):
1987 1987 """show one changeset using template or regular display.
1988 1988
1989 1989 Display format will be the first non-empty hit of:
1990 1990 1. option 'template'
1991 1991 2. option 'style'
1992 1992 3. [ui] setting 'logtemplate'
1993 1993 4. [ui] setting 'style'
1994 1994 If all of these values are either the unset or the empty string,
1995 1995 regular display via changeset_printer() is done.
1996 1996 """
1997 1997 # options
1998 1998 match = None
1999 1999 if opts.get('patch') or opts.get('stat'):
2000 2000 match = scmutil.matchall(repo)
2001 2001
2002 2002 if opts.get('template') == 'json':
2003 2003 return jsonchangeset(ui, repo, match, opts, buffered)
2004 2004
2005 2005 spec = _lookuplogtemplate(ui, opts.get('template'), opts.get('style'))
2006 2006
2007 2007 if not spec.ref and not spec.tmpl and not spec.mapfile:
2008 2008 return changeset_printer(ui, repo, match, opts, buffered)
2009 2009
2010 2010 return changeset_templater(ui, repo, spec, match, opts, buffered)
2011 2011
2012 2012 def showmarker(fm, marker, index=None):
2013 2013 """utility function to display obsolescence marker in a readable way
2014 2014
2015 2015 To be used by debug function."""
2016 2016 if index is not None:
2017 2017 fm.write('index', '%i ', index)
2018 2018 fm.write('prednode', '%s ', hex(marker.prednode()))
2019 2019 succs = marker.succnodes()
2020 2020 fm.condwrite(succs, 'succnodes', '%s ',
2021 2021 fm.formatlist(map(hex, succs), name='node'))
2022 2022 fm.write('flag', '%X ', marker.flags())
2023 2023 parents = marker.parentnodes()
2024 2024 if parents is not None:
2025 2025 fm.write('parentnodes', '{%s} ',
2026 2026 fm.formatlist(map(hex, parents), name='node', sep=', '))
2027 2027 fm.write('date', '(%s) ', fm.formatdate(marker.date()))
2028 2028 meta = marker.metadata().copy()
2029 2029 meta.pop('date', None)
2030 2030 fm.write('metadata', '{%s}', fm.formatdict(meta, fmt='%r: %r', sep=', '))
2031 2031 fm.plain('\n')
2032 2032
2033 2033 def finddate(ui, repo, date):
2034 2034 """Find the tipmost changeset that matches the given date spec"""
2035 2035
2036 2036 df = util.matchdate(date)
2037 2037 m = scmutil.matchall(repo)
2038 2038 results = {}
2039 2039
2040 2040 def prep(ctx, fns):
2041 2041 d = ctx.date()
2042 2042 if df(d[0]):
2043 2043 results[ctx.rev()] = d
2044 2044
2045 2045 for ctx in walkchangerevs(repo, m, {'rev': None}, prep):
2046 2046 rev = ctx.rev()
2047 2047 if rev in results:
2048 2048 ui.status(_("found revision %s from %s\n") %
2049 2049 (rev, util.datestr(results[rev])))
2050 2050 return '%d' % rev
2051 2051
2052 2052 raise error.Abort(_("revision matching date not found"))
2053 2053
2054 2054 def increasingwindows(windowsize=8, sizelimit=512):
2055 2055 while True:
2056 2056 yield windowsize
2057 2057 if windowsize < sizelimit:
2058 2058 windowsize *= 2
2059 2059
2060 2060 class FileWalkError(Exception):
2061 2061 pass
2062 2062
2063 2063 def walkfilerevs(repo, match, follow, revs, fncache):
2064 2064 '''Walks the file history for the matched files.
2065 2065
2066 2066 Returns the changeset revs that are involved in the file history.
2067 2067
2068 2068 Throws FileWalkError if the file history can't be walked using
2069 2069 filelogs alone.
2070 2070 '''
2071 2071 wanted = set()
2072 2072 copies = []
2073 2073 minrev, maxrev = min(revs), max(revs)
2074 2074 def filerevgen(filelog, last):
2075 2075 """
2076 2076 Only files, no patterns. Check the history of each file.
2077 2077
2078 2078 Examines filelog entries within minrev, maxrev linkrev range
2079 2079 Returns an iterator yielding (linkrev, parentlinkrevs, copied)
2080 2080 tuples in backwards order
2081 2081 """
2082 2082 cl_count = len(repo)
2083 2083 revs = []
2084 2084 for j in xrange(0, last + 1):
2085 2085 linkrev = filelog.linkrev(j)
2086 2086 if linkrev < minrev:
2087 2087 continue
2088 2088 # only yield rev for which we have the changelog, it can
2089 2089 # happen while doing "hg log" during a pull or commit
2090 2090 if linkrev >= cl_count:
2091 2091 break
2092 2092
2093 2093 parentlinkrevs = []
2094 2094 for p in filelog.parentrevs(j):
2095 2095 if p != nullrev:
2096 2096 parentlinkrevs.append(filelog.linkrev(p))
2097 2097 n = filelog.node(j)
2098 2098 revs.append((linkrev, parentlinkrevs,
2099 2099 follow and filelog.renamed(n)))
2100 2100
2101 2101 return reversed(revs)
2102 2102 def iterfiles():
2103 2103 pctx = repo['.']
2104 2104 for filename in match.files():
2105 2105 if follow:
2106 2106 if filename not in pctx:
2107 2107 raise error.Abort(_('cannot follow file not in parent '
2108 2108 'revision: "%s"') % filename)
2109 2109 yield filename, pctx[filename].filenode()
2110 2110 else:
2111 2111 yield filename, None
2112 2112 for filename_node in copies:
2113 2113 yield filename_node
2114 2114
2115 2115 for file_, node in iterfiles():
2116 2116 filelog = repo.file(file_)
2117 2117 if not len(filelog):
2118 2118 if node is None:
2119 2119 # A zero count may be a directory or deleted file, so
2120 2120 # try to find matching entries on the slow path.
2121 2121 if follow:
2122 2122 raise error.Abort(
2123 2123 _('cannot follow nonexistent file: "%s"') % file_)
2124 2124 raise FileWalkError("Cannot walk via filelog")
2125 2125 else:
2126 2126 continue
2127 2127
2128 2128 if node is None:
2129 2129 last = len(filelog) - 1
2130 2130 else:
2131 2131 last = filelog.rev(node)
2132 2132
2133 2133 # keep track of all ancestors of the file
2134 2134 ancestors = {filelog.linkrev(last)}
2135 2135
2136 2136 # iterate from latest to oldest revision
2137 2137 for rev, flparentlinkrevs, copied in filerevgen(filelog, last):
2138 2138 if not follow:
2139 2139 if rev > maxrev:
2140 2140 continue
2141 2141 else:
2142 2142 # Note that last might not be the first interesting
2143 2143 # rev to us:
2144 2144 # if the file has been changed after maxrev, we'll
2145 2145 # have linkrev(last) > maxrev, and we still need
2146 2146 # to explore the file graph
2147 2147 if rev not in ancestors:
2148 2148 continue
2149 2149 # XXX insert 1327 fix here
2150 2150 if flparentlinkrevs:
2151 2151 ancestors.update(flparentlinkrevs)
2152 2152
2153 2153 fncache.setdefault(rev, []).append(file_)
2154 2154 wanted.add(rev)
2155 2155 if copied:
2156 2156 copies.append(copied)
2157 2157
2158 2158 return wanted
2159 2159
2160 2160 class _followfilter(object):
2161 2161 def __init__(self, repo, onlyfirst=False):
2162 2162 self.repo = repo
2163 2163 self.startrev = nullrev
2164 2164 self.roots = set()
2165 2165 self.onlyfirst = onlyfirst
2166 2166
2167 2167 def match(self, rev):
2168 2168 def realparents(rev):
2169 2169 if self.onlyfirst:
2170 2170 return self.repo.changelog.parentrevs(rev)[0:1]
2171 2171 else:
2172 2172 return filter(lambda x: x != nullrev,
2173 2173 self.repo.changelog.parentrevs(rev))
2174 2174
2175 2175 if self.startrev == nullrev:
2176 2176 self.startrev = rev
2177 2177 return True
2178 2178
2179 2179 if rev > self.startrev:
2180 2180 # forward: all descendants
2181 2181 if not self.roots:
2182 2182 self.roots.add(self.startrev)
2183 2183 for parent in realparents(rev):
2184 2184 if parent in self.roots:
2185 2185 self.roots.add(rev)
2186 2186 return True
2187 2187 else:
2188 2188 # backwards: all parents
2189 2189 if not self.roots:
2190 2190 self.roots.update(realparents(self.startrev))
2191 2191 if rev in self.roots:
2192 2192 self.roots.remove(rev)
2193 2193 self.roots.update(realparents(rev))
2194 2194 return True
2195 2195
2196 2196 return False
2197 2197
2198 2198 def walkchangerevs(repo, match, opts, prepare):
2199 2199 '''Iterate over files and the revs in which they changed.
2200 2200
2201 2201 Callers most commonly need to iterate backwards over the history
2202 2202 in which they are interested. Doing so has awful (quadratic-looking)
2203 2203 performance, so we use iterators in a "windowed" way.
2204 2204
2205 2205 We walk a window of revisions in the desired order. Within the
2206 2206 window, we first walk forwards to gather data, then in the desired
2207 2207 order (usually backwards) to display it.
2208 2208
2209 2209 This function returns an iterator yielding contexts. Before
2210 2210 yielding each context, the iterator will first call the prepare
2211 2211 function on each context in the window in forward order.'''
2212 2212
2213 2213 follow = opts.get('follow') or opts.get('follow_first')
2214 2214 revs = _logrevs(repo, opts)
2215 2215 if not revs:
2216 2216 return []
2217 2217 wanted = set()
2218 2218 slowpath = match.anypats() or ((match.isexact() or match.prefix()) and
2219 2219 opts.get('removed'))
2220 2220 fncache = {}
2221 2221 change = repo.changectx
2222 2222
2223 2223 # First step is to fill wanted, the set of revisions that we want to yield.
2224 2224 # When it does not induce extra cost, we also fill fncache for revisions in
2225 2225 # wanted: a cache of filenames that were changed (ctx.files()) and that
2226 2226 # match the file filtering conditions.
2227 2227
2228 2228 if match.always():
2229 2229 # No files, no patterns. Display all revs.
2230 2230 wanted = revs
2231 2231 elif not slowpath:
2232 2232 # We only have to read through the filelog to find wanted revisions
2233 2233
2234 2234 try:
2235 2235 wanted = walkfilerevs(repo, match, follow, revs, fncache)
2236 2236 except FileWalkError:
2237 2237 slowpath = True
2238 2238
2239 2239 # We decided to fall back to the slowpath because at least one
2240 2240 # of the paths was not a file. Check to see if at least one of them
2241 2241 # existed in history, otherwise simply return
2242 2242 for path in match.files():
2243 2243 if path == '.' or path in repo.store:
2244 2244 break
2245 2245 else:
2246 2246 return []
2247 2247
2248 2248 if slowpath:
2249 2249 # We have to read the changelog to match filenames against
2250 2250 # changed files
2251 2251
2252 2252 if follow:
2253 2253 raise error.Abort(_('can only follow copies/renames for explicit '
2254 2254 'filenames'))
2255 2255
2256 2256 # The slow path checks files modified in every changeset.
2257 2257 # This is really slow on large repos, so compute the set lazily.
2258 2258 class lazywantedset(object):
2259 2259 def __init__(self):
2260 2260 self.set = set()
2261 2261 self.revs = set(revs)
2262 2262
2263 2263 # No need to worry about locality here because it will be accessed
2264 2264 # in the same order as the increasing window below.
2265 2265 def __contains__(self, value):
2266 2266 if value in self.set:
2267 2267 return True
2268 2268 elif not value in self.revs:
2269 2269 return False
2270 2270 else:
2271 2271 self.revs.discard(value)
2272 2272 ctx = change(value)
2273 2273 matches = filter(match, ctx.files())
2274 2274 if matches:
2275 2275 fncache[value] = matches
2276 2276 self.set.add(value)
2277 2277 return True
2278 2278 return False
2279 2279
2280 2280 def discard(self, value):
2281 2281 self.revs.discard(value)
2282 2282 self.set.discard(value)
2283 2283
2284 2284 wanted = lazywantedset()
2285 2285
2286 2286 # it might be worthwhile to do this in the iterator if the rev range
2287 2287 # is descending and the prune args are all within that range
2288 2288 for rev in opts.get('prune', ()):
2289 2289 rev = repo[rev].rev()
2290 2290 ff = _followfilter(repo)
2291 2291 stop = min(revs[0], revs[-1])
2292 2292 for x in xrange(rev, stop - 1, -1):
2293 2293 if ff.match(x):
2294 2294 wanted = wanted - [x]
2295 2295
2296 2296 # Now that wanted is correctly initialized, we can iterate over the
2297 2297 # revision range, yielding only revisions in wanted.
2298 2298 def iterate():
2299 2299 if follow and match.always():
2300 2300 ff = _followfilter(repo, onlyfirst=opts.get('follow_first'))
2301 2301 def want(rev):
2302 2302 return ff.match(rev) and rev in wanted
2303 2303 else:
2304 2304 def want(rev):
2305 2305 return rev in wanted
2306 2306
2307 2307 it = iter(revs)
2308 2308 stopiteration = False
2309 2309 for windowsize in increasingwindows():
2310 2310 nrevs = []
2311 2311 for i in xrange(windowsize):
2312 2312 rev = next(it, None)
2313 2313 if rev is None:
2314 2314 stopiteration = True
2315 2315 break
2316 2316 elif want(rev):
2317 2317 nrevs.append(rev)
2318 2318 for rev in sorted(nrevs):
2319 2319 fns = fncache.get(rev)
2320 2320 ctx = change(rev)
2321 2321 if not fns:
2322 2322 def fns_generator():
2323 2323 for f in ctx.files():
2324 2324 if match(f):
2325 2325 yield f
2326 2326 fns = fns_generator()
2327 2327 prepare(ctx, fns)
2328 2328 for rev in nrevs:
2329 2329 yield change(rev)
2330 2330
2331 2331 if stopiteration:
2332 2332 break
2333 2333
2334 2334 return iterate()
2335 2335
2336 2336 def _makefollowlogfilematcher(repo, files, followfirst):
2337 2337 # When displaying a revision with --patch --follow FILE, we have
2338 2338 # to know which file of the revision must be diffed. With
2339 2339 # --follow, we want the names of the ancestors of FILE in the
2340 2340 # revision, stored in "fcache". "fcache" is populated by
2341 2341 # reproducing the graph traversal already done by --follow revset
2342 2342 # and relating revs to file names (which is not "correct" but
2343 2343 # good enough).
2344 2344 fcache = {}
2345 2345 fcacheready = [False]
2346 2346 pctx = repo['.']
2347 2347
2348 2348 def populate():
2349 2349 for fn in files:
2350 2350 fctx = pctx[fn]
2351 2351 fcache.setdefault(fctx.introrev(), set()).add(fctx.path())
2352 2352 for c in fctx.ancestors(followfirst=followfirst):
2353 2353 fcache.setdefault(c.rev(), set()).add(c.path())
2354 2354
2355 2355 def filematcher(rev):
2356 2356 if not fcacheready[0]:
2357 2357 # Lazy initialization
2358 2358 fcacheready[0] = True
2359 2359 populate()
2360 2360 return scmutil.matchfiles(repo, fcache.get(rev, []))
2361 2361
2362 2362 return filematcher
2363 2363
2364 2364 def _makenofollowlogfilematcher(repo, pats, opts):
2365 2365 '''hook for extensions to override the filematcher for non-follow cases'''
2366 2366 return None
2367 2367
2368 2368 def _makelogrevset(repo, pats, opts, revs):
2369 2369 """Return (expr, filematcher) where expr is a revset string built
2370 2370 from log options and file patterns or None. If --stat or --patch
2371 2371 are not passed filematcher is None. Otherwise it is a callable
2372 2372 taking a revision number and returning a match objects filtering
2373 2373 the files to be detailed when displaying the revision.
2374 2374 """
2375 2375 opt2revset = {
2376 2376 'no_merges': ('not merge()', None),
2377 2377 'only_merges': ('merge()', None),
2378 2378 '_ancestors': ('ancestors(%(val)s)', None),
2379 2379 '_fancestors': ('_firstancestors(%(val)s)', None),
2380 2380 '_descendants': ('descendants(%(val)s)', None),
2381 2381 '_fdescendants': ('_firstdescendants(%(val)s)', None),
2382 2382 '_matchfiles': ('_matchfiles(%(val)s)', None),
2383 2383 'date': ('date(%(val)r)', None),
2384 2384 'branch': ('branch(%(val)r)', ' or '),
2385 2385 '_patslog': ('filelog(%(val)r)', ' or '),
2386 2386 '_patsfollow': ('follow(%(val)r)', ' or '),
2387 2387 '_patsfollowfirst': ('_followfirst(%(val)r)', ' or '),
2388 2388 'keyword': ('keyword(%(val)r)', ' or '),
2389 2389 'prune': ('not (%(val)r or ancestors(%(val)r))', ' and '),
2390 2390 'user': ('user(%(val)r)', ' or '),
2391 2391 }
2392 2392
2393 2393 opts = dict(opts)
2394 2394 # follow or not follow?
2395 2395 follow = opts.get('follow') or opts.get('follow_first')
2396 2396 if opts.get('follow_first'):
2397 2397 followfirst = 1
2398 2398 else:
2399 2399 followfirst = 0
2400 2400 # --follow with FILE behavior depends on revs...
2401 2401 it = iter(revs)
2402 2402 startrev = next(it)
2403 2403 followdescendants = startrev < next(it, startrev)
2404 2404
2405 2405 # branch and only_branch are really aliases and must be handled at
2406 2406 # the same time
2407 2407 opts['branch'] = opts.get('branch', []) + opts.get('only_branch', [])
2408 2408 opts['branch'] = [repo.lookupbranch(b) for b in opts['branch']]
2409 2409 # pats/include/exclude are passed to match.match() directly in
2410 2410 # _matchfiles() revset but walkchangerevs() builds its matcher with
2411 2411 # scmutil.match(). The difference is input pats are globbed on
2412 2412 # platforms without shell expansion (windows).
2413 2413 wctx = repo[None]
2414 2414 match, pats = scmutil.matchandpats(wctx, pats, opts)
2415 2415 slowpath = match.anypats() or ((match.isexact() or match.prefix()) and
2416 2416 opts.get('removed'))
2417 2417 if not slowpath:
2418 2418 for f in match.files():
2419 2419 if follow and f not in wctx:
2420 2420 # If the file exists, it may be a directory, so let it
2421 2421 # take the slow path.
2422 2422 if os.path.exists(repo.wjoin(f)):
2423 2423 slowpath = True
2424 2424 continue
2425 2425 else:
2426 2426 raise error.Abort(_('cannot follow file not in parent '
2427 2427 'revision: "%s"') % f)
2428 2428 filelog = repo.file(f)
2429 2429 if not filelog:
2430 2430 # A zero count may be a directory or deleted file, so
2431 2431 # try to find matching entries on the slow path.
2432 2432 if follow:
2433 2433 raise error.Abort(
2434 2434 _('cannot follow nonexistent file: "%s"') % f)
2435 2435 slowpath = True
2436 2436
2437 2437 # We decided to fall back to the slowpath because at least one
2438 2438 # of the paths was not a file. Check to see if at least one of them
2439 2439 # existed in history - in that case, we'll continue down the
2440 2440 # slowpath; otherwise, we can turn off the slowpath
2441 2441 if slowpath:
2442 2442 for path in match.files():
2443 2443 if path == '.' or path in repo.store:
2444 2444 break
2445 2445 else:
2446 2446 slowpath = False
2447 2447
2448 2448 fpats = ('_patsfollow', '_patsfollowfirst')
2449 2449 fnopats = (('_ancestors', '_fancestors'),
2450 2450 ('_descendants', '_fdescendants'))
2451 2451 if slowpath:
2452 2452 # See walkchangerevs() slow path.
2453 2453 #
2454 2454 # pats/include/exclude cannot be represented as separate
2455 2455 # revset expressions as their filtering logic applies at file
2456 2456 # level. For instance "-I a -X a" matches a revision touching
2457 2457 # "a" and "b" while "file(a) and not file(b)" does
2458 2458 # not. Besides, filesets are evaluated against the working
2459 2459 # directory.
2460 2460 matchargs = ['r:', 'd:relpath']
2461 2461 for p in pats:
2462 2462 matchargs.append('p:' + p)
2463 2463 for p in opts.get('include', []):
2464 2464 matchargs.append('i:' + p)
2465 2465 for p in opts.get('exclude', []):
2466 2466 matchargs.append('x:' + p)
2467 2467 matchargs = ','.join(('%r' % p) for p in matchargs)
2468 2468 opts['_matchfiles'] = matchargs
2469 2469 if follow:
2470 2470 opts[fnopats[0][followfirst]] = '.'
2471 2471 else:
2472 2472 if follow:
2473 2473 if pats:
2474 2474 # follow() revset interprets its file argument as a
2475 2475 # manifest entry, so use match.files(), not pats.
2476 2476 opts[fpats[followfirst]] = list(match.files())
2477 2477 else:
2478 2478 op = fnopats[followdescendants][followfirst]
2479 2479 opts[op] = 'rev(%d)' % startrev
2480 2480 else:
2481 2481 opts['_patslog'] = list(pats)
2482 2482
2483 2483 filematcher = None
2484 2484 if opts.get('patch') or opts.get('stat'):
2485 2485 # When following files, track renames via a special matcher.
2486 2486 # If we're forced to take the slowpath it means we're following
2487 2487 # at least one pattern/directory, so don't bother with rename tracking.
2488 2488 if follow and not match.always() and not slowpath:
2489 2489 # _makefollowlogfilematcher expects its files argument to be
2490 2490 # relative to the repo root, so use match.files(), not pats.
2491 2491 filematcher = _makefollowlogfilematcher(repo, match.files(),
2492 2492 followfirst)
2493 2493 else:
2494 2494 filematcher = _makenofollowlogfilematcher(repo, pats, opts)
2495 2495 if filematcher is None:
2496 2496 filematcher = lambda rev: match
2497 2497
2498 2498 expr = []
2499 2499 for op, val in sorted(opts.iteritems()):
2500 2500 if not val:
2501 2501 continue
2502 2502 if op not in opt2revset:
2503 2503 continue
2504 2504 revop, andor = opt2revset[op]
2505 2505 if '%(val)' not in revop:
2506 2506 expr.append(revop)
2507 2507 else:
2508 2508 if not isinstance(val, list):
2509 2509 e = revop % {'val': val}
2510 2510 else:
2511 2511 e = '(' + andor.join((revop % {'val': v}) for v in val) + ')'
2512 2512 expr.append(e)
2513 2513
2514 2514 if expr:
2515 2515 expr = '(' + ' and '.join(expr) + ')'
2516 2516 else:
2517 2517 expr = None
2518 2518 return expr, filematcher
2519 2519
2520 2520 def _logrevs(repo, opts):
2521 2521 # Default --rev value depends on --follow but --follow behavior
2522 2522 # depends on revisions resolved from --rev...
2523 2523 follow = opts.get('follow') or opts.get('follow_first')
2524 2524 if opts.get('rev'):
2525 2525 revs = scmutil.revrange(repo, opts['rev'])
2526 2526 elif follow and repo.dirstate.p1() == nullid:
2527 2527 revs = smartset.baseset()
2528 2528 elif follow:
2529 2529 revs = repo.revs('reverse(:.)')
2530 2530 else:
2531 2531 revs = smartset.spanset(repo)
2532 2532 revs.reverse()
2533 2533 return revs
2534 2534
2535 2535 def getgraphlogrevs(repo, pats, opts):
2536 2536 """Return (revs, expr, filematcher) where revs is an iterable of
2537 2537 revision numbers, expr is a revset string built from log options
2538 2538 and file patterns or None, and used to filter 'revs'. If --stat or
2539 2539 --patch are not passed filematcher is None. Otherwise it is a
2540 2540 callable taking a revision number and returning a match objects
2541 2541 filtering the files to be detailed when displaying the revision.
2542 2542 """
2543 2543 limit = loglimit(opts)
2544 2544 revs = _logrevs(repo, opts)
2545 2545 if not revs:
2546 2546 return smartset.baseset(), None, None
2547 2547 expr, filematcher = _makelogrevset(repo, pats, opts, revs)
2548 2548 if opts.get('rev'):
2549 2549 # User-specified revs might be unsorted, but don't sort before
2550 2550 # _makelogrevset because it might depend on the order of revs
2551 2551 if not (revs.isdescending() or revs.istopo()):
2552 2552 revs.sort(reverse=True)
2553 2553 if expr:
2554 2554 matcher = revset.match(repo.ui, expr)
2555 2555 revs = matcher(repo, revs)
2556 2556 if limit is not None:
2557 2557 limitedrevs = []
2558 2558 for idx, rev in enumerate(revs):
2559 2559 if idx >= limit:
2560 2560 break
2561 2561 limitedrevs.append(rev)
2562 2562 revs = smartset.baseset(limitedrevs)
2563 2563
2564 2564 return revs, expr, filematcher
2565 2565
2566 2566 def getlogrevs(repo, pats, opts):
2567 2567 """Return (revs, expr, filematcher) where revs is an iterable of
2568 2568 revision numbers, expr is a revset string built from log options
2569 2569 and file patterns or None, and used to filter 'revs'. If --stat or
2570 2570 --patch are not passed filematcher is None. Otherwise it is a
2571 2571 callable taking a revision number and returning a match objects
2572 2572 filtering the files to be detailed when displaying the revision.
2573 2573 """
2574 2574 limit = loglimit(opts)
2575 2575 revs = _logrevs(repo, opts)
2576 2576 if not revs:
2577 2577 return smartset.baseset([]), None, None
2578 2578 expr, filematcher = _makelogrevset(repo, pats, opts, revs)
2579 2579 if expr:
2580 2580 matcher = revset.match(repo.ui, expr)
2581 2581 revs = matcher(repo, revs)
2582 2582 if limit is not None:
2583 2583 limitedrevs = []
2584 2584 for idx, r in enumerate(revs):
2585 2585 if limit <= idx:
2586 2586 break
2587 2587 limitedrevs.append(r)
2588 2588 revs = smartset.baseset(limitedrevs)
2589 2589
2590 2590 return revs, expr, filematcher
2591 2591
2592 2592 def _parselinerangelogopt(repo, opts):
2593 2593 """Parse --line-range log option and return a list of tuples (filename,
2594 2594 (fromline, toline)).
2595 2595 """
2596 2596 linerangebyfname = []
2597 2597 for pat in opts.get('line_range', []):
2598 2598 try:
2599 2599 pat, linerange = pat.rsplit(',', 1)
2600 2600 except ValueError:
2601 2601 raise error.Abort(_('malformatted line-range pattern %s') % pat)
2602 2602 try:
2603 2603 fromline, toline = map(int, linerange.split(':'))
2604 2604 except ValueError:
2605 2605 raise error.Abort(_("invalid line range for %s") % pat)
2606 2606 msg = _("line range pattern '%s' must match exactly one file") % pat
2607 2607 fname = scmutil.parsefollowlinespattern(repo, None, pat, msg)
2608 2608 linerangebyfname.append(
2609 2609 (fname, util.processlinerange(fromline, toline)))
2610 2610 return linerangebyfname
2611 2611
2612 2612 def getloglinerangerevs(repo, userrevs, opts):
2613 2613 """Return (revs, filematcher, hunksfilter).
2614 2614
2615 2615 "revs" are revisions obtained by processing "line-range" log options and
2616 2616 walking block ancestors of each specified file/line-range.
2617 2617
2618 2618 "filematcher(rev) -> match" is a factory function returning a match object
2619 2619 for a given revision for file patterns specified in --line-range option.
2620 2620 If neither --stat nor --patch options are passed, "filematcher" is None.
2621 2621
2622 2622 "hunksfilter(rev) -> filterfn(fctx, hunks)" is a factory function
2623 2623 returning a hunks filtering function.
2624 2624 If neither --stat nor --patch options are passed, "filterhunks" is None.
2625 2625 """
2626 2626 wctx = repo[None]
2627 2627
2628 2628 # Two-levels map of "rev -> file ctx -> [line range]".
2629 2629 linerangesbyrev = {}
2630 2630 for fname, (fromline, toline) in _parselinerangelogopt(repo, opts):
2631 2631 if fname not in wctx:
2632 2632 raise error.Abort(_('cannot follow file not in parent '
2633 2633 'revision: "%s"') % fname)
2634 2634 fctx = wctx.filectx(fname)
2635 2635 for fctx, linerange in dagop.blockancestors(fctx, fromline, toline):
2636 2636 rev = fctx.introrev()
2637 2637 if rev not in userrevs:
2638 2638 continue
2639 2639 linerangesbyrev.setdefault(
2640 2640 rev, {}).setdefault(
2641 2641 fctx.path(), []).append(linerange)
2642 2642
2643 2643 filematcher = None
2644 2644 hunksfilter = None
2645 2645 if opts.get('patch') or opts.get('stat'):
2646 2646
2647 2647 def nofilterhunksfn(fctx, hunks):
2648 2648 return hunks
2649 2649
2650 2650 def hunksfilter(rev):
2651 2651 fctxlineranges = linerangesbyrev.get(rev)
2652 2652 if fctxlineranges is None:
2653 2653 return nofilterhunksfn
2654 2654
2655 2655 def filterfn(fctx, hunks):
2656 2656 lineranges = fctxlineranges.get(fctx.path())
2657 2657 if lineranges is not None:
2658 2658 for hr, lines in hunks:
2659 2659 if hr is None: # binary
2660 2660 yield hr, lines
2661 2661 continue
2662 2662 if any(mdiff.hunkinrange(hr[2:], lr)
2663 2663 for lr in lineranges):
2664 2664 yield hr, lines
2665 2665 else:
2666 2666 for hunk in hunks:
2667 2667 yield hunk
2668 2668
2669 2669 return filterfn
2670 2670
2671 2671 def filematcher(rev):
2672 2672 files = list(linerangesbyrev.get(rev, []))
2673 2673 return scmutil.matchfiles(repo, files)
2674 2674
2675 2675 revs = sorted(linerangesbyrev, reverse=True)
2676 2676
2677 2677 return revs, filematcher, hunksfilter
2678 2678
2679 2679 def _graphnodeformatter(ui, displayer):
2680 2680 spec = ui.config('ui', 'graphnodetemplate')
2681 2681 if not spec:
2682 2682 return templatekw.showgraphnode # fast path for "{graphnode}"
2683 2683
2684 2684 spec = templater.unquotestring(spec)
2685 2685 templ = formatter.maketemplater(ui, spec)
2686 2686 cache = {}
2687 2687 if isinstance(displayer, changeset_templater):
2688 2688 cache = displayer.cache # reuse cache of slow templates
2689 2689 props = templatekw.keywords.copy()
2690 2690 props['templ'] = templ
2691 2691 props['cache'] = cache
2692 2692 def formatnode(repo, ctx):
2693 2693 props['ctx'] = ctx
2694 2694 props['repo'] = repo
2695 2695 props['ui'] = repo.ui
2696 2696 props['revcache'] = {}
2697 2697 return templ.render(props)
2698 2698 return formatnode
2699 2699
2700 2700 def displaygraph(ui, repo, dag, displayer, edgefn, getrenamed=None,
2701 2701 filematcher=None, props=None):
2702 2702 props = props or {}
2703 2703 formatnode = _graphnodeformatter(ui, displayer)
2704 2704 state = graphmod.asciistate()
2705 2705 styles = state['styles']
2706 2706
2707 2707 # only set graph styling if HGPLAIN is not set.
2708 2708 if ui.plain('graph'):
2709 2709 # set all edge styles to |, the default pre-3.8 behaviour
2710 2710 styles.update(dict.fromkeys(styles, '|'))
2711 2711 else:
2712 2712 edgetypes = {
2713 2713 'parent': graphmod.PARENT,
2714 2714 'grandparent': graphmod.GRANDPARENT,
2715 2715 'missing': graphmod.MISSINGPARENT
2716 2716 }
2717 2717 for name, key in edgetypes.items():
2718 2718 # experimental config: experimental.graphstyle.*
2719 2719 styles[key] = ui.config('experimental', 'graphstyle.%s' % name,
2720 2720 styles[key])
2721 2721 if not styles[key]:
2722 2722 styles[key] = None
2723 2723
2724 2724 # experimental config: experimental.graphshorten
2725 2725 state['graphshorten'] = ui.configbool('experimental', 'graphshorten')
2726 2726
2727 2727 for rev, type, ctx, parents in dag:
2728 2728 char = formatnode(repo, ctx)
2729 2729 copies = None
2730 2730 if getrenamed and ctx.rev():
2731 2731 copies = []
2732 2732 for fn in ctx.files():
2733 2733 rename = getrenamed(fn, ctx.rev())
2734 2734 if rename:
2735 2735 copies.append((fn, rename[0]))
2736 2736 revmatchfn = None
2737 2737 if filematcher is not None:
2738 2738 revmatchfn = filematcher(ctx.rev())
2739 2739 edges = edgefn(type, char, state, rev, parents)
2740 2740 firstedge = next(edges)
2741 2741 width = firstedge[2]
2742 2742 displayer.show(ctx, copies=copies, matchfn=revmatchfn,
2743 2743 _graphwidth=width, **props)
2744 2744 lines = displayer.hunk.pop(rev).split('\n')
2745 2745 if not lines[-1]:
2746 2746 del lines[-1]
2747 2747 displayer.flush(ctx)
2748 2748 for type, char, width, coldata in itertools.chain([firstedge], edges):
2749 2749 graphmod.ascii(ui, state, type, char, lines, coldata)
2750 2750 lines = []
2751 2751 displayer.close()
2752 2752
2753 2753 def graphlog(ui, repo, pats, opts):
2754 2754 # Parameters are identical to log command ones
2755 2755 revs, expr, filematcher = getgraphlogrevs(repo, pats, opts)
2756 2756 revdag = graphmod.dagwalker(repo, revs)
2757 2757
2758 2758 getrenamed = None
2759 2759 if opts.get('copies'):
2760 2760 endrev = None
2761 2761 if opts.get('rev'):
2762 2762 endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1
2763 2763 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
2764 2764
2765 2765 ui.pager('log')
2766 2766 displayer = show_changeset(ui, repo, opts, buffered=True)
2767 2767 displaygraph(ui, repo, revdag, displayer, graphmod.asciiedges, getrenamed,
2768 2768 filematcher)
2769 2769
2770 2770 def checkunsupportedgraphflags(pats, opts):
2771 2771 for op in ["newest_first"]:
2772 2772 if op in opts and opts[op]:
2773 2773 raise error.Abort(_("-G/--graph option is incompatible with --%s")
2774 2774 % op.replace("_", "-"))
2775 2775
2776 2776 def graphrevs(repo, nodes, opts):
2777 2777 limit = loglimit(opts)
2778 2778 nodes.reverse()
2779 2779 if limit is not None:
2780 2780 nodes = nodes[:limit]
2781 2781 return graphmod.nodes(repo, nodes)
2782 2782
2783 2783 def add(ui, repo, match, prefix, explicitonly, **opts):
2784 2784 join = lambda f: os.path.join(prefix, f)
2785 2785 bad = []
2786 2786
2787 2787 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2788 2788 names = []
2789 2789 wctx = repo[None]
2790 2790 cca = None
2791 2791 abort, warn = scmutil.checkportabilityalert(ui)
2792 2792 if abort or warn:
2793 2793 cca = scmutil.casecollisionauditor(ui, abort, repo.dirstate)
2794 2794
2795 2795 badmatch = matchmod.badmatch(match, badfn)
2796 2796 dirstate = repo.dirstate
2797 2797 # We don't want to just call wctx.walk here, since it would return a lot of
2798 2798 # clean files, which we aren't interested in and takes time.
2799 2799 for f in sorted(dirstate.walk(badmatch, subrepos=sorted(wctx.substate),
2800 2800 unknown=True, ignored=False, full=False)):
2801 2801 exact = match.exact(f)
2802 2802 if exact or not explicitonly and f not in wctx and repo.wvfs.lexists(f):
2803 2803 if cca:
2804 2804 cca(f)
2805 2805 names.append(f)
2806 2806 if ui.verbose or not exact:
2807 2807 ui.status(_('adding %s\n') % match.rel(f))
2808 2808
2809 2809 for subpath in sorted(wctx.substate):
2810 2810 sub = wctx.sub(subpath)
2811 2811 try:
2812 2812 submatch = matchmod.subdirmatcher(subpath, match)
2813 2813 if opts.get(r'subrepos'):
2814 2814 bad.extend(sub.add(ui, submatch, prefix, False, **opts))
2815 2815 else:
2816 2816 bad.extend(sub.add(ui, submatch, prefix, True, **opts))
2817 2817 except error.LookupError:
2818 2818 ui.status(_("skipping missing subrepository: %s\n")
2819 2819 % join(subpath))
2820 2820
2821 2821 if not opts.get(r'dry_run'):
2822 2822 rejected = wctx.add(names, prefix)
2823 2823 bad.extend(f for f in rejected if f in match.files())
2824 2824 return bad
2825 2825
2826 2826 def addwebdirpath(repo, serverpath, webconf):
2827 2827 webconf[serverpath] = repo.root
2828 2828 repo.ui.debug('adding %s = %s\n' % (serverpath, repo.root))
2829 2829
2830 2830 for r in repo.revs('filelog("path:.hgsub")'):
2831 2831 ctx = repo[r]
2832 2832 for subpath in ctx.substate:
2833 2833 ctx.sub(subpath).addwebdirpath(serverpath, webconf)
2834 2834
2835 2835 def forget(ui, repo, match, prefix, explicitonly):
2836 2836 join = lambda f: os.path.join(prefix, f)
2837 2837 bad = []
2838 2838 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2839 2839 wctx = repo[None]
2840 2840 forgot = []
2841 2841
2842 2842 s = repo.status(match=matchmod.badmatch(match, badfn), clean=True)
2843 2843 forget = sorted(s.modified + s.added + s.deleted + s.clean)
2844 2844 if explicitonly:
2845 2845 forget = [f for f in forget if match.exact(f)]
2846 2846
2847 2847 for subpath in sorted(wctx.substate):
2848 2848 sub = wctx.sub(subpath)
2849 2849 try:
2850 2850 submatch = matchmod.subdirmatcher(subpath, match)
2851 2851 subbad, subforgot = sub.forget(submatch, prefix)
2852 2852 bad.extend([subpath + '/' + f for f in subbad])
2853 2853 forgot.extend([subpath + '/' + f for f in subforgot])
2854 2854 except error.LookupError:
2855 2855 ui.status(_("skipping missing subrepository: %s\n")
2856 2856 % join(subpath))
2857 2857
2858 2858 if not explicitonly:
2859 2859 for f in match.files():
2860 2860 if f not in repo.dirstate and not repo.wvfs.isdir(f):
2861 2861 if f not in forgot:
2862 2862 if repo.wvfs.exists(f):
2863 2863 # Don't complain if the exact case match wasn't given.
2864 2864 # But don't do this until after checking 'forgot', so
2865 2865 # that subrepo files aren't normalized, and this op is
2866 2866 # purely from data cached by the status walk above.
2867 2867 if repo.dirstate.normalize(f) in repo.dirstate:
2868 2868 continue
2869 2869 ui.warn(_('not removing %s: '
2870 2870 'file is already untracked\n')
2871 2871 % match.rel(f))
2872 2872 bad.append(f)
2873 2873
2874 2874 for f in forget:
2875 2875 if ui.verbose or not match.exact(f):
2876 2876 ui.status(_('removing %s\n') % match.rel(f))
2877 2877
2878 2878 rejected = wctx.forget(forget, prefix)
2879 2879 bad.extend(f for f in rejected if f in match.files())
2880 2880 forgot.extend(f for f in forget if f not in rejected)
2881 2881 return bad, forgot
2882 2882
2883 2883 def files(ui, ctx, m, fm, fmt, subrepos):
2884 2884 rev = ctx.rev()
2885 2885 ret = 1
2886 2886 ds = ctx.repo().dirstate
2887 2887
2888 2888 for f in ctx.matches(m):
2889 2889 if rev is None and ds[f] == 'r':
2890 2890 continue
2891 2891 fm.startitem()
2892 2892 if ui.verbose:
2893 2893 fc = ctx[f]
2894 2894 fm.write('size flags', '% 10d % 1s ', fc.size(), fc.flags())
2895 2895 fm.data(abspath=f)
2896 2896 fm.write('path', fmt, m.rel(f))
2897 2897 ret = 0
2898 2898
2899 2899 for subpath in sorted(ctx.substate):
2900 2900 submatch = matchmod.subdirmatcher(subpath, m)
2901 2901 if (subrepos or m.exact(subpath) or any(submatch.files())):
2902 2902 sub = ctx.sub(subpath)
2903 2903 try:
2904 2904 recurse = m.exact(subpath) or subrepos
2905 2905 if sub.printfiles(ui, submatch, fm, fmt, recurse) == 0:
2906 2906 ret = 0
2907 2907 except error.LookupError:
2908 2908 ui.status(_("skipping missing subrepository: %s\n")
2909 2909 % m.abs(subpath))
2910 2910
2911 2911 return ret
2912 2912
2913 2913 def remove(ui, repo, m, prefix, after, force, subrepos, warnings=None):
2914 2914 join = lambda f: os.path.join(prefix, f)
2915 2915 ret = 0
2916 2916 s = repo.status(match=m, clean=True)
2917 2917 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
2918 2918
2919 2919 wctx = repo[None]
2920 2920
2921 2921 if warnings is None:
2922 2922 warnings = []
2923 2923 warn = True
2924 2924 else:
2925 2925 warn = False
2926 2926
2927 2927 subs = sorted(wctx.substate)
2928 2928 total = len(subs)
2929 2929 count = 0
2930 2930 for subpath in subs:
2931 2931 count += 1
2932 2932 submatch = matchmod.subdirmatcher(subpath, m)
2933 2933 if subrepos or m.exact(subpath) or any(submatch.files()):
2934 2934 ui.progress(_('searching'), count, total=total, unit=_('subrepos'))
2935 2935 sub = wctx.sub(subpath)
2936 2936 try:
2937 2937 if sub.removefiles(submatch, prefix, after, force, subrepos,
2938 2938 warnings):
2939 2939 ret = 1
2940 2940 except error.LookupError:
2941 2941 warnings.append(_("skipping missing subrepository: %s\n")
2942 2942 % join(subpath))
2943 2943 ui.progress(_('searching'), None)
2944 2944
2945 2945 # warn about failure to delete explicit files/dirs
2946 2946 deleteddirs = util.dirs(deleted)
2947 2947 files = m.files()
2948 2948 total = len(files)
2949 2949 count = 0
2950 2950 for f in files:
2951 2951 def insubrepo():
2952 2952 for subpath in wctx.substate:
2953 2953 if f.startswith(subpath + '/'):
2954 2954 return True
2955 2955 return False
2956 2956
2957 2957 count += 1
2958 2958 ui.progress(_('deleting'), count, total=total, unit=_('files'))
2959 2959 isdir = f in deleteddirs or wctx.hasdir(f)
2960 2960 if (f in repo.dirstate or isdir or f == '.'
2961 2961 or insubrepo() or f in subs):
2962 2962 continue
2963 2963
2964 2964 if repo.wvfs.exists(f):
2965 2965 if repo.wvfs.isdir(f):
2966 2966 warnings.append(_('not removing %s: no tracked files\n')
2967 2967 % m.rel(f))
2968 2968 else:
2969 2969 warnings.append(_('not removing %s: file is untracked\n')
2970 2970 % m.rel(f))
2971 2971 # missing files will generate a warning elsewhere
2972 2972 ret = 1
2973 2973 ui.progress(_('deleting'), None)
2974 2974
2975 2975 if force:
2976 2976 list = modified + deleted + clean + added
2977 2977 elif after:
2978 2978 list = deleted
2979 2979 remaining = modified + added + clean
2980 2980 total = len(remaining)
2981 2981 count = 0
2982 2982 for f in remaining:
2983 2983 count += 1
2984 2984 ui.progress(_('skipping'), count, total=total, unit=_('files'))
2985 2985 if ui.verbose or (f in files):
2986 2986 warnings.append(_('not removing %s: file still exists\n')
2987 2987 % m.rel(f))
2988 2988 ret = 1
2989 2989 ui.progress(_('skipping'), None)
2990 2990 else:
2991 2991 list = deleted + clean
2992 2992 total = len(modified) + len(added)
2993 2993 count = 0
2994 2994 for f in modified:
2995 2995 count += 1
2996 2996 ui.progress(_('skipping'), count, total=total, unit=_('files'))
2997 2997 warnings.append(_('not removing %s: file is modified (use -f'
2998 2998 ' to force removal)\n') % m.rel(f))
2999 2999 ret = 1
3000 3000 for f in added:
3001 3001 count += 1
3002 3002 ui.progress(_('skipping'), count, total=total, unit=_('files'))
3003 3003 warnings.append(_("not removing %s: file has been marked for add"
3004 3004 " (use 'hg forget' to undo add)\n") % m.rel(f))
3005 3005 ret = 1
3006 3006 ui.progress(_('skipping'), None)
3007 3007
3008 3008 list = sorted(list)
3009 3009 total = len(list)
3010 3010 count = 0
3011 3011 for f in list:
3012 3012 count += 1
3013 3013 if ui.verbose or not m.exact(f):
3014 3014 ui.progress(_('deleting'), count, total=total, unit=_('files'))
3015 3015 ui.status(_('removing %s\n') % m.rel(f))
3016 3016 ui.progress(_('deleting'), None)
3017 3017
3018 3018 with repo.wlock():
3019 3019 if not after:
3020 3020 for f in list:
3021 3021 if f in added:
3022 3022 continue # we never unlink added files on remove
3023 3023 repo.wvfs.unlinkpath(f, ignoremissing=True)
3024 3024 repo[None].forget(list)
3025 3025
3026 3026 if warn:
3027 3027 for warning in warnings:
3028 3028 ui.warn(warning)
3029 3029
3030 3030 return ret
3031 3031
3032 3032 def cat(ui, repo, ctx, matcher, basefm, fntemplate, prefix, **opts):
3033 3033 err = 1
3034 3034
3035 3035 def write(path):
3036 3036 filename = None
3037 3037 if fntemplate:
3038 3038 filename = makefilename(repo, fntemplate, ctx.node(),
3039 3039 pathname=os.path.join(prefix, path))
3040 3040 # attempt to create the directory if it does not already exist
3041 3041 try:
3042 3042 os.makedirs(os.path.dirname(filename))
3043 3043 except OSError:
3044 3044 pass
3045 3045 with formatter.maybereopen(basefm, filename, opts) as fm:
3046 3046 data = ctx[path].data()
3047 3047 if opts.get('decode'):
3048 3048 data = repo.wwritedata(path, data)
3049 3049 fm.startitem()
3050 3050 fm.write('data', '%s', data)
3051 3051 fm.data(abspath=path, path=matcher.rel(path))
3052 3052
3053 3053 # Automation often uses hg cat on single files, so special case it
3054 3054 # for performance to avoid the cost of parsing the manifest.
3055 3055 if len(matcher.files()) == 1 and not matcher.anypats():
3056 3056 file = matcher.files()[0]
3057 3057 mfl = repo.manifestlog
3058 3058 mfnode = ctx.manifestnode()
3059 3059 try:
3060 3060 if mfnode and mfl[mfnode].find(file)[0]:
3061 3061 write(file)
3062 3062 return 0
3063 3063 except KeyError:
3064 3064 pass
3065 3065
3066 3066 for abs in ctx.walk(matcher):
3067 3067 write(abs)
3068 3068 err = 0
3069 3069
3070 3070 for subpath in sorted(ctx.substate):
3071 3071 sub = ctx.sub(subpath)
3072 3072 try:
3073 3073 submatch = matchmod.subdirmatcher(subpath, matcher)
3074 3074
3075 3075 if not sub.cat(submatch, basefm, fntemplate,
3076 3076 os.path.join(prefix, sub._path), **opts):
3077 3077 err = 0
3078 3078 except error.RepoLookupError:
3079 3079 ui.status(_("skipping missing subrepository: %s\n")
3080 3080 % os.path.join(prefix, subpath))
3081 3081
3082 3082 return err
3083 3083
3084 3084 def commit(ui, repo, commitfunc, pats, opts):
3085 3085 '''commit the specified files or all outstanding changes'''
3086 3086 date = opts.get('date')
3087 3087 if date:
3088 3088 opts['date'] = util.parsedate(date)
3089 3089 message = logmessage(ui, opts)
3090 3090 matcher = scmutil.match(repo[None], pats, opts)
3091 3091
3092 3092 dsguard = None
3093 3093 # extract addremove carefully -- this function can be called from a command
3094 3094 # that doesn't support addremove
3095 3095 if opts.get('addremove'):
3096 3096 dsguard = dirstateguard.dirstateguard(repo, 'commit')
3097 3097 with dsguard or util.nullcontextmanager():
3098 3098 if dsguard:
3099 3099 if scmutil.addremove(repo, matcher, "", opts) != 0:
3100 3100 raise error.Abort(
3101 3101 _("failed to mark all new/missing files as added/removed"))
3102 3102
3103 3103 return commitfunc(ui, repo, message, matcher, opts)
3104 3104
3105 3105 def samefile(f, ctx1, ctx2):
3106 3106 if f in ctx1.manifest():
3107 3107 a = ctx1.filectx(f)
3108 3108 if f in ctx2.manifest():
3109 3109 b = ctx2.filectx(f)
3110 3110 return (not a.cmp(b)
3111 3111 and a.flags() == b.flags())
3112 3112 else:
3113 3113 return False
3114 3114 else:
3115 3115 return f not in ctx2.manifest()
3116 3116
3117 3117 def amend(ui, repo, old, extra, pats, opts):
3118 3118 # avoid cycle context -> subrepo -> cmdutil
3119 3119 from . import context
3120 3120
3121 3121 # amend will reuse the existing user if not specified, but the obsolete
3122 3122 # marker creation requires that the current user's name is specified.
3123 3123 if obsolete.isenabled(repo, obsolete.createmarkersopt):
3124 3124 ui.username() # raise exception if username not set
3125 3125
3126 3126 ui.note(_('amending changeset %s\n') % old)
3127 3127 base = old.p1()
3128 3128
3129 3129 with repo.wlock(), repo.lock(), repo.transaction('amend'):
3130 3130 # Participating changesets:
3131 3131 #
3132 3132 # wctx o - workingctx that contains changes from working copy
3133 3133 # | to go into amending commit
3134 3134 # |
3135 3135 # old o - changeset to amend
3136 3136 # |
3137 3137 # base o - first parent of the changeset to amend
3138 3138 wctx = repo[None]
3139 3139
3140 3140 # Update extra dict from amended commit (e.g. to preserve graft
3141 3141 # source)
3142 3142 extra.update(old.extra())
3143 3143
3144 3144 # Also update it from the from the wctx
3145 3145 extra.update(wctx.extra())
3146 3146
3147 3147 user = opts.get('user') or old.user()
3148 3148 date = opts.get('date') or old.date()
3149 3149
3150 3150 # Parse the date to allow comparison between date and old.date()
3151 3151 date = util.parsedate(date)
3152 3152
3153 3153 if len(old.parents()) > 1:
3154 3154 # ctx.files() isn't reliable for merges, so fall back to the
3155 3155 # slower repo.status() method
3156 3156 files = set([fn for st in repo.status(base, old)[:3]
3157 3157 for fn in st])
3158 3158 else:
3159 3159 files = set(old.files())
3160 3160
3161 3161 # add/remove the files to the working copy if the "addremove" option
3162 3162 # was specified.
3163 3163 matcher = scmutil.match(wctx, pats, opts)
3164 3164 if (opts.get('addremove')
3165 3165 and scmutil.addremove(repo, matcher, "", opts)):
3166 3166 raise error.Abort(
3167 3167 _("failed to mark all new/missing files as added/removed"))
3168 3168
3169 3169 filestoamend = set(f for f in wctx.files() if matcher(f))
3170 3170
3171 3171 changes = (len(filestoamend) > 0)
3172 3172 if changes:
3173 3173 # Recompute copies (avoid recording a -> b -> a)
3174 3174 copied = copies.pathcopies(base, wctx, matcher)
3175 3175 if old.p2:
3176 3176 copied.update(copies.pathcopies(old.p2(), wctx, matcher))
3177 3177
3178 3178 # Prune files which were reverted by the updates: if old
3179 3179 # introduced file X and the file was renamed in the working
3180 3180 # copy, then those two files are the same and
3181 3181 # we can discard X from our list of files. Likewise if X
3182 3182 # was deleted, it's no longer relevant
3183 3183 files.update(filestoamend)
3184 3184 files = [f for f in files if not samefile(f, wctx, base)]
3185 3185
3186 3186 def filectxfn(repo, ctx_, path):
3187 3187 try:
3188 3188 # If the file being considered is not amongst the files
3189 3189 # to be amended, we should return the file context from the
3190 3190 # old changeset. This avoids issues when only some files in
3191 3191 # the working copy are being amended but there are also
3192 3192 # changes to other files from the old changeset.
3193 3193 if path not in filestoamend:
3194 3194 return old.filectx(path)
3195 3195
3196 3196 fctx = wctx[path]
3197 3197
3198 3198 # Return None for removed files.
3199 3199 if not fctx.exists():
3200 3200 return None
3201 3201
3202 3202 flags = fctx.flags()
3203 3203 mctx = context.memfilectx(repo,
3204 3204 fctx.path(), fctx.data(),
3205 3205 islink='l' in flags,
3206 3206 isexec='x' in flags,
3207 3207 copied=copied.get(path))
3208 3208 return mctx
3209 3209 except KeyError:
3210 3210 return None
3211 3211 else:
3212 3212 ui.note(_('copying changeset %s to %s\n') % (old, base))
3213 3213
3214 3214 # Use version of files as in the old cset
3215 3215 def filectxfn(repo, ctx_, path):
3216 3216 try:
3217 3217 return old.filectx(path)
3218 3218 except KeyError:
3219 3219 return None
3220 3220
3221 3221 # See if we got a message from -m or -l, if not, open the editor with
3222 3222 # the message of the changeset to amend.
3223 3223 message = logmessage(ui, opts)
3224 3224
3225 3225 editform = mergeeditform(old, 'commit.amend')
3226 3226 editor = getcommiteditor(editform=editform,
3227 3227 **pycompat.strkwargs(opts))
3228 3228
3229 3229 if not message:
3230 3230 editor = getcommiteditor(edit=True, editform=editform)
3231 3231 message = old.description()
3232 3232
3233 3233 pureextra = extra.copy()
3234 3234 extra['amend_source'] = old.hex()
3235 3235
3236 3236 new = context.memctx(repo,
3237 3237 parents=[base.node(), old.p2().node()],
3238 3238 text=message,
3239 3239 files=files,
3240 3240 filectxfn=filectxfn,
3241 3241 user=user,
3242 3242 date=date,
3243 3243 extra=extra,
3244 3244 editor=editor)
3245 3245
3246 3246 newdesc = changelog.stripdesc(new.description())
3247 3247 if ((not changes)
3248 3248 and newdesc == old.description()
3249 3249 and user == old.user()
3250 3250 and date == old.date()
3251 3251 and pureextra == old.extra()):
3252 3252 # nothing changed. continuing here would create a new node
3253 3253 # anyway because of the amend_source noise.
3254 3254 #
3255 3255 # This not what we expect from amend.
3256 3256 return old.node()
3257 3257
3258 3258 if opts.get('secret'):
3259 3259 commitphase = 'secret'
3260 3260 else:
3261 3261 commitphase = old.phase()
3262 3262 overrides = {('phases', 'new-commit'): commitphase}
3263 3263 with ui.configoverride(overrides, 'amend'):
3264 3264 newid = repo.commitctx(new)
3265 3265
3266 3266 # Reroute the working copy parent to the new changeset
3267 3267 repo.setparents(newid, nullid)
3268 3268 mapping = {old.node(): (newid,)}
3269 3269 obsmetadata = None
3270 3270 if opts.get('note'):
3271 3271 obsmetadata = {'note': opts['note']}
3272 3272 scmutil.cleanupnodes(repo, mapping, 'amend', metadata=obsmetadata)
3273 3273
3274 3274 # Fixing the dirstate because localrepo.commitctx does not update
3275 3275 # it. This is rather convenient because we did not need to update
3276 3276 # the dirstate for all the files in the new commit which commitctx
3277 3277 # could have done if it updated the dirstate. Now, we can
3278 3278 # selectively update the dirstate only for the amended files.
3279 3279 dirstate = repo.dirstate
3280 3280
3281 3281 # Update the state of the files which were added and
3282 3282 # and modified in the amend to "normal" in the dirstate.
3283 3283 normalfiles = set(wctx.modified() + wctx.added()) & filestoamend
3284 3284 for f in normalfiles:
3285 3285 dirstate.normal(f)
3286 3286
3287 3287 # Update the state of files which were removed in the amend
3288 3288 # to "removed" in the dirstate.
3289 3289 removedfiles = set(wctx.removed()) & filestoamend
3290 3290 for f in removedfiles:
3291 3291 dirstate.drop(f)
3292 3292
3293 3293 return newid
3294 3294
3295 3295 def commiteditor(repo, ctx, subs, editform=''):
3296 3296 if ctx.description():
3297 3297 return ctx.description()
3298 3298 return commitforceeditor(repo, ctx, subs, editform=editform,
3299 3299 unchangedmessagedetection=True)
3300 3300
3301 3301 def commitforceeditor(repo, ctx, subs, finishdesc=None, extramsg=None,
3302 3302 editform='', unchangedmessagedetection=False):
3303 3303 if not extramsg:
3304 3304 extramsg = _("Leave message empty to abort commit.")
3305 3305
3306 3306 forms = [e for e in editform.split('.') if e]
3307 3307 forms.insert(0, 'changeset')
3308 3308 templatetext = None
3309 3309 while forms:
3310 3310 ref = '.'.join(forms)
3311 3311 if repo.ui.config('committemplate', ref):
3312 3312 templatetext = committext = buildcommittemplate(
3313 3313 repo, ctx, subs, extramsg, ref)
3314 3314 break
3315 3315 forms.pop()
3316 3316 else:
3317 3317 committext = buildcommittext(repo, ctx, subs, extramsg)
3318 3318
3319 3319 # run editor in the repository root
3320 3320 olddir = pycompat.getcwd()
3321 3321 os.chdir(repo.root)
3322 3322
3323 3323 # make in-memory changes visible to external process
3324 3324 tr = repo.currenttransaction()
3325 3325 repo.dirstate.write(tr)
3326 3326 pending = tr and tr.writepending() and repo.root
3327 3327
3328 3328 editortext = repo.ui.edit(committext, ctx.user(), ctx.extra(),
3329 3329 editform=editform, pending=pending,
3330 3330 repopath=repo.path, action='commit')
3331 3331 text = editortext
3332 3332
3333 3333 # strip away anything below this special string (used for editors that want
3334 3334 # to display the diff)
3335 3335 stripbelow = re.search(_linebelow, text, flags=re.MULTILINE)
3336 3336 if stripbelow:
3337 3337 text = text[:stripbelow.start()]
3338 3338
3339 3339 text = re.sub("(?m)^HG:.*(\n|$)", "", text)
3340 3340 os.chdir(olddir)
3341 3341
3342 3342 if finishdesc:
3343 3343 text = finishdesc(text)
3344 3344 if not text.strip():
3345 3345 raise error.Abort(_("empty commit message"))
3346 3346 if unchangedmessagedetection and editortext == templatetext:
3347 3347 raise error.Abort(_("commit message unchanged"))
3348 3348
3349 3349 return text
3350 3350
3351 3351 def buildcommittemplate(repo, ctx, subs, extramsg, ref):
3352 3352 ui = repo.ui
3353 3353 spec = formatter.templatespec(ref, None, None)
3354 3354 t = changeset_templater(ui, repo, spec, None, {}, False)
3355 3355 t.t.cache.update((k, templater.unquotestring(v))
3356 3356 for k, v in repo.ui.configitems('committemplate'))
3357 3357
3358 3358 if not extramsg:
3359 3359 extramsg = '' # ensure that extramsg is string
3360 3360
3361 3361 ui.pushbuffer()
3362 3362 t.show(ctx, extramsg=extramsg)
3363 3363 return ui.popbuffer()
3364 3364
3365 3365 def hgprefix(msg):
3366 3366 return "\n".join(["HG: %s" % a for a in msg.split("\n") if a])
3367 3367
3368 3368 def buildcommittext(repo, ctx, subs, extramsg):
3369 3369 edittext = []
3370 3370 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
3371 3371 if ctx.description():
3372 3372 edittext.append(ctx.description())
3373 3373 edittext.append("")
3374 3374 edittext.append("") # Empty line between message and comments.
3375 3375 edittext.append(hgprefix(_("Enter commit message."
3376 3376 " Lines beginning with 'HG:' are removed.")))
3377 3377 edittext.append(hgprefix(extramsg))
3378 3378 edittext.append("HG: --")
3379 3379 edittext.append(hgprefix(_("user: %s") % ctx.user()))
3380 3380 if ctx.p2():
3381 3381 edittext.append(hgprefix(_("branch merge")))
3382 3382 if ctx.branch():
3383 3383 edittext.append(hgprefix(_("branch '%s'") % ctx.branch()))
3384 3384 if bookmarks.isactivewdirparent(repo):
3385 3385 edittext.append(hgprefix(_("bookmark '%s'") % repo._activebookmark))
3386 3386 edittext.extend([hgprefix(_("subrepo %s") % s) for s in subs])
3387 3387 edittext.extend([hgprefix(_("added %s") % f) for f in added])
3388 3388 edittext.extend([hgprefix(_("changed %s") % f) for f in modified])
3389 3389 edittext.extend([hgprefix(_("removed %s") % f) for f in removed])
3390 3390 if not added and not modified and not removed:
3391 3391 edittext.append(hgprefix(_("no files changed")))
3392 3392 edittext.append("")
3393 3393
3394 3394 return "\n".join(edittext)
3395 3395
3396 3396 def commitstatus(repo, node, branch, bheads=None, opts=None):
3397 3397 if opts is None:
3398 3398 opts = {}
3399 3399 ctx = repo[node]
3400 3400 parents = ctx.parents()
3401 3401
3402 3402 if (not opts.get('amend') and bheads and node not in bheads and not
3403 3403 [x for x in parents if x.node() in bheads and x.branch() == branch]):
3404 3404 repo.ui.status(_('created new head\n'))
3405 3405 # The message is not printed for initial roots. For the other
3406 3406 # changesets, it is printed in the following situations:
3407 3407 #
3408 3408 # Par column: for the 2 parents with ...
3409 3409 # N: null or no parent
3410 3410 # B: parent is on another named branch
3411 3411 # C: parent is a regular non head changeset
3412 3412 # H: parent was a branch head of the current branch
3413 3413 # Msg column: whether we print "created new head" message
3414 3414 # In the following, it is assumed that there already exists some
3415 3415 # initial branch heads of the current branch, otherwise nothing is
3416 3416 # printed anyway.
3417 3417 #
3418 3418 # Par Msg Comment
3419 3419 # N N y additional topo root
3420 3420 #
3421 3421 # B N y additional branch root
3422 3422 # C N y additional topo head
3423 3423 # H N n usual case
3424 3424 #
3425 3425 # B B y weird additional branch root
3426 3426 # C B y branch merge
3427 3427 # H B n merge with named branch
3428 3428 #
3429 3429 # C C y additional head from merge
3430 3430 # C H n merge with a head
3431 3431 #
3432 3432 # H H n head merge: head count decreases
3433 3433
3434 3434 if not opts.get('close_branch'):
3435 3435 for r in parents:
3436 3436 if r.closesbranch() and r.branch() == branch:
3437 3437 repo.ui.status(_('reopening closed branch head %d\n') % r)
3438 3438
3439 3439 if repo.ui.debugflag:
3440 3440 repo.ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
3441 3441 elif repo.ui.verbose:
3442 3442 repo.ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
3443 3443
3444 3444 def postcommitstatus(repo, pats, opts):
3445 3445 return repo.status(match=scmutil.match(repo[None], pats, opts))
3446 3446
3447 3447 def revert(ui, repo, ctx, parents, *pats, **opts):
3448 opts = pycompat.byteskwargs(opts)
3448 3449 parent, p2 = parents
3449 3450 node = ctx.node()
3450 3451
3451 3452 mf = ctx.manifest()
3452 3453 if node == p2:
3453 3454 parent = p2
3454 3455
3455 3456 # need all matching names in dirstate and manifest of target rev,
3456 3457 # so have to walk both. do not print errors if files exist in one
3457 3458 # but not other. in both cases, filesets should be evaluated against
3458 3459 # workingctx to get consistent result (issue4497). this means 'set:**'
3459 3460 # cannot be used to select missing files from target rev.
3460 3461
3461 3462 # `names` is a mapping for all elements in working copy and target revision
3462 3463 # The mapping is in the form:
3463 3464 # <asb path in repo> -> (<path from CWD>, <exactly specified by matcher?>)
3464 3465 names = {}
3465 3466
3466 3467 with repo.wlock():
3467 3468 ## filling of the `names` mapping
3468 3469 # walk dirstate to fill `names`
3469 3470
3470 3471 interactive = opts.get('interactive', False)
3471 3472 wctx = repo[None]
3472 3473 m = scmutil.match(wctx, pats, opts)
3473 3474
3474 3475 # we'll need this later
3475 3476 targetsubs = sorted(s for s in wctx.substate if m(s))
3476 3477
3477 3478 if not m.always():
3478 3479 matcher = matchmod.badmatch(m, lambda x, y: False)
3479 3480 for abs in wctx.walk(matcher):
3480 3481 names[abs] = m.rel(abs), m.exact(abs)
3481 3482
3482 3483 # walk target manifest to fill `names`
3483 3484
3484 3485 def badfn(path, msg):
3485 3486 if path in names:
3486 3487 return
3487 3488 if path in ctx.substate:
3488 3489 return
3489 3490 path_ = path + '/'
3490 3491 for f in names:
3491 3492 if f.startswith(path_):
3492 3493 return
3493 3494 ui.warn("%s: %s\n" % (m.rel(path), msg))
3494 3495
3495 3496 for abs in ctx.walk(matchmod.badmatch(m, badfn)):
3496 3497 if abs not in names:
3497 3498 names[abs] = m.rel(abs), m.exact(abs)
3498 3499
3499 3500 # Find status of all file in `names`.
3500 3501 m = scmutil.matchfiles(repo, names)
3501 3502
3502 3503 changes = repo.status(node1=node, match=m,
3503 3504 unknown=True, ignored=True, clean=True)
3504 3505 else:
3505 3506 changes = repo.status(node1=node, match=m)
3506 3507 for kind in changes:
3507 3508 for abs in kind:
3508 3509 names[abs] = m.rel(abs), m.exact(abs)
3509 3510
3510 3511 m = scmutil.matchfiles(repo, names)
3511 3512
3512 3513 modified = set(changes.modified)
3513 3514 added = set(changes.added)
3514 3515 removed = set(changes.removed)
3515 3516 _deleted = set(changes.deleted)
3516 3517 unknown = set(changes.unknown)
3517 3518 unknown.update(changes.ignored)
3518 3519 clean = set(changes.clean)
3519 3520 modadded = set()
3520 3521
3521 3522 # We need to account for the state of the file in the dirstate,
3522 3523 # even when we revert against something else than parent. This will
3523 3524 # slightly alter the behavior of revert (doing back up or not, delete
3524 3525 # or just forget etc).
3525 3526 if parent == node:
3526 3527 dsmodified = modified
3527 3528 dsadded = added
3528 3529 dsremoved = removed
3529 3530 # store all local modifications, useful later for rename detection
3530 3531 localchanges = dsmodified | dsadded
3531 3532 modified, added, removed = set(), set(), set()
3532 3533 else:
3533 3534 changes = repo.status(node1=parent, match=m)
3534 3535 dsmodified = set(changes.modified)
3535 3536 dsadded = set(changes.added)
3536 3537 dsremoved = set(changes.removed)
3537 3538 # store all local modifications, useful later for rename detection
3538 3539 localchanges = dsmodified | dsadded
3539 3540
3540 3541 # only take into account for removes between wc and target
3541 3542 clean |= dsremoved - removed
3542 3543 dsremoved &= removed
3543 3544 # distinct between dirstate remove and other
3544 3545 removed -= dsremoved
3545 3546
3546 3547 modadded = added & dsmodified
3547 3548 added -= modadded
3548 3549
3549 3550 # tell newly modified apart.
3550 3551 dsmodified &= modified
3551 3552 dsmodified |= modified & dsadded # dirstate added may need backup
3552 3553 modified -= dsmodified
3553 3554
3554 3555 # We need to wait for some post-processing to update this set
3555 3556 # before making the distinction. The dirstate will be used for
3556 3557 # that purpose.
3557 3558 dsadded = added
3558 3559
3559 3560 # in case of merge, files that are actually added can be reported as
3560 3561 # modified, we need to post process the result
3561 3562 if p2 != nullid:
3562 3563 mergeadd = set(dsmodified)
3563 3564 for path in dsmodified:
3564 3565 if path in mf:
3565 3566 mergeadd.remove(path)
3566 3567 dsadded |= mergeadd
3567 3568 dsmodified -= mergeadd
3568 3569
3569 3570 # if f is a rename, update `names` to also revert the source
3570 3571 cwd = repo.getcwd()
3571 3572 for f in localchanges:
3572 3573 src = repo.dirstate.copied(f)
3573 3574 # XXX should we check for rename down to target node?
3574 3575 if src and src not in names and repo.dirstate[src] == 'r':
3575 3576 dsremoved.add(src)
3576 3577 names[src] = (repo.pathto(src, cwd), True)
3577 3578
3578 3579 # determine the exact nature of the deleted changesets
3579 3580 deladded = set(_deleted)
3580 3581 for path in _deleted:
3581 3582 if path in mf:
3582 3583 deladded.remove(path)
3583 3584 deleted = _deleted - deladded
3584 3585
3585 3586 # distinguish between file to forget and the other
3586 3587 added = set()
3587 3588 for abs in dsadded:
3588 3589 if repo.dirstate[abs] != 'a':
3589 3590 added.add(abs)
3590 3591 dsadded -= added
3591 3592
3592 3593 for abs in deladded:
3593 3594 if repo.dirstate[abs] == 'a':
3594 3595 dsadded.add(abs)
3595 3596 deladded -= dsadded
3596 3597
3597 3598 # For files marked as removed, we check if an unknown file is present at
3598 3599 # the same path. If a such file exists it may need to be backed up.
3599 3600 # Making the distinction at this stage helps have simpler backup
3600 3601 # logic.
3601 3602 removunk = set()
3602 3603 for abs in removed:
3603 3604 target = repo.wjoin(abs)
3604 3605 if os.path.lexists(target):
3605 3606 removunk.add(abs)
3606 3607 removed -= removunk
3607 3608
3608 3609 dsremovunk = set()
3609 3610 for abs in dsremoved:
3610 3611 target = repo.wjoin(abs)
3611 3612 if os.path.lexists(target):
3612 3613 dsremovunk.add(abs)
3613 3614 dsremoved -= dsremovunk
3614 3615
3615 3616 # action to be actually performed by revert
3616 3617 # (<list of file>, message>) tuple
3617 3618 actions = {'revert': ([], _('reverting %s\n')),
3618 3619 'add': ([], _('adding %s\n')),
3619 3620 'remove': ([], _('removing %s\n')),
3620 3621 'drop': ([], _('removing %s\n')),
3621 3622 'forget': ([], _('forgetting %s\n')),
3622 3623 'undelete': ([], _('undeleting %s\n')),
3623 3624 'noop': (None, _('no changes needed to %s\n')),
3624 3625 'unknown': (None, _('file not managed: %s\n')),
3625 3626 }
3626 3627
3627 3628 # "constant" that convey the backup strategy.
3628 3629 # All set to `discard` if `no-backup` is set do avoid checking
3629 3630 # no_backup lower in the code.
3630 3631 # These values are ordered for comparison purposes
3631 3632 backupinteractive = 3 # do backup if interactively modified
3632 3633 backup = 2 # unconditionally do backup
3633 3634 check = 1 # check if the existing file differs from target
3634 3635 discard = 0 # never do backup
3635 3636 if opts.get('no_backup'):
3636 3637 backupinteractive = backup = check = discard
3637 3638 if interactive:
3638 3639 dsmodifiedbackup = backupinteractive
3639 3640 else:
3640 3641 dsmodifiedbackup = backup
3641 3642 tobackup = set()
3642 3643
3643 3644 backupanddel = actions['remove']
3644 3645 if not opts.get('no_backup'):
3645 3646 backupanddel = actions['drop']
3646 3647
3647 3648 disptable = (
3648 3649 # dispatch table:
3649 3650 # file state
3650 3651 # action
3651 3652 # make backup
3652 3653
3653 3654 ## Sets that results that will change file on disk
3654 3655 # Modified compared to target, no local change
3655 3656 (modified, actions['revert'], discard),
3656 3657 # Modified compared to target, but local file is deleted
3657 3658 (deleted, actions['revert'], discard),
3658 3659 # Modified compared to target, local change
3659 3660 (dsmodified, actions['revert'], dsmodifiedbackup),
3660 3661 # Added since target
3661 3662 (added, actions['remove'], discard),
3662 3663 # Added in working directory
3663 3664 (dsadded, actions['forget'], discard),
3664 3665 # Added since target, have local modification
3665 3666 (modadded, backupanddel, backup),
3666 3667 # Added since target but file is missing in working directory
3667 3668 (deladded, actions['drop'], discard),
3668 3669 # Removed since target, before working copy parent
3669 3670 (removed, actions['add'], discard),
3670 3671 # Same as `removed` but an unknown file exists at the same path
3671 3672 (removunk, actions['add'], check),
3672 3673 # Removed since targe, marked as such in working copy parent
3673 3674 (dsremoved, actions['undelete'], discard),
3674 3675 # Same as `dsremoved` but an unknown file exists at the same path
3675 3676 (dsremovunk, actions['undelete'], check),
3676 3677 ## the following sets does not result in any file changes
3677 3678 # File with no modification
3678 3679 (clean, actions['noop'], discard),
3679 3680 # Existing file, not tracked anywhere
3680 3681 (unknown, actions['unknown'], discard),
3681 3682 )
3682 3683
3683 3684 for abs, (rel, exact) in sorted(names.items()):
3684 3685 # target file to be touch on disk (relative to cwd)
3685 3686 target = repo.wjoin(abs)
3686 3687 # search the entry in the dispatch table.
3687 3688 # if the file is in any of these sets, it was touched in the working
3688 3689 # directory parent and we are sure it needs to be reverted.
3689 3690 for table, (xlist, msg), dobackup in disptable:
3690 3691 if abs not in table:
3691 3692 continue
3692 3693 if xlist is not None:
3693 3694 xlist.append(abs)
3694 3695 if dobackup:
3695 3696 # If in interactive mode, don't automatically create
3696 3697 # .orig files (issue4793)
3697 3698 if dobackup == backupinteractive:
3698 3699 tobackup.add(abs)
3699 3700 elif (backup <= dobackup or wctx[abs].cmp(ctx[abs])):
3700 3701 bakname = scmutil.origpath(ui, repo, rel)
3701 3702 ui.note(_('saving current version of %s as %s\n') %
3702 3703 (rel, bakname))
3703 3704 if not opts.get('dry_run'):
3704 3705 if interactive:
3705 3706 util.copyfile(target, bakname)
3706 3707 else:
3707 3708 util.rename(target, bakname)
3708 3709 if ui.verbose or not exact:
3709 3710 if not isinstance(msg, basestring):
3710 3711 msg = msg(abs)
3711 3712 ui.status(msg % rel)
3712 3713 elif exact:
3713 3714 ui.warn(msg % rel)
3714 3715 break
3715 3716
3716 3717 if not opts.get('dry_run'):
3717 3718 needdata = ('revert', 'add', 'undelete')
3718 3719 _revertprefetch(repo, ctx, *[actions[name][0] for name in needdata])
3719 3720 _performrevert(repo, parents, ctx, actions, interactive, tobackup)
3720 3721
3721 3722 if targetsubs:
3722 3723 # Revert the subrepos on the revert list
3723 3724 for sub in targetsubs:
3724 3725 try:
3725 wctx.sub(sub).revert(ctx.substate[sub], *pats, **opts)
3726 wctx.sub(sub).revert(ctx.substate[sub], *pats,
3727 **pycompat.strkwargs(opts))
3726 3728 except KeyError:
3727 3729 raise error.Abort("subrepository '%s' does not exist in %s!"
3728 3730 % (sub, short(ctx.node())))
3729 3731
3730 3732 def _revertprefetch(repo, ctx, *files):
3731 3733 """Let extension changing the storage layer prefetch content"""
3732 3734
3733 3735 def _performrevert(repo, parents, ctx, actions, interactive=False,
3734 3736 tobackup=None):
3735 3737 """function that actually perform all the actions computed for revert
3736 3738
3737 3739 This is an independent function to let extension to plug in and react to
3738 3740 the imminent revert.
3739 3741
3740 3742 Make sure you have the working directory locked when calling this function.
3741 3743 """
3742 3744 parent, p2 = parents
3743 3745 node = ctx.node()
3744 3746 excluded_files = []
3745 3747 matcher_opts = {"exclude": excluded_files}
3746 3748
3747 3749 def checkout(f):
3748 3750 fc = ctx[f]
3749 3751 repo.wwrite(f, fc.data(), fc.flags())
3750 3752
3751 3753 def doremove(f):
3752 3754 try:
3753 3755 repo.wvfs.unlinkpath(f)
3754 3756 except OSError:
3755 3757 pass
3756 3758 repo.dirstate.remove(f)
3757 3759
3758 3760 audit_path = pathutil.pathauditor(repo.root, cached=True)
3759 3761 for f in actions['forget'][0]:
3760 3762 if interactive:
3761 3763 choice = repo.ui.promptchoice(
3762 3764 _("forget added file %s (Yn)?$$ &Yes $$ &No") % f)
3763 3765 if choice == 0:
3764 3766 repo.dirstate.drop(f)
3765 3767 else:
3766 3768 excluded_files.append(repo.wjoin(f))
3767 3769 else:
3768 3770 repo.dirstate.drop(f)
3769 3771 for f in actions['remove'][0]:
3770 3772 audit_path(f)
3771 3773 if interactive:
3772 3774 choice = repo.ui.promptchoice(
3773 3775 _("remove added file %s (Yn)?$$ &Yes $$ &No") % f)
3774 3776 if choice == 0:
3775 3777 doremove(f)
3776 3778 else:
3777 3779 excluded_files.append(repo.wjoin(f))
3778 3780 else:
3779 3781 doremove(f)
3780 3782 for f in actions['drop'][0]:
3781 3783 audit_path(f)
3782 3784 repo.dirstate.remove(f)
3783 3785
3784 3786 normal = None
3785 3787 if node == parent:
3786 3788 # We're reverting to our parent. If possible, we'd like status
3787 3789 # to report the file as clean. We have to use normallookup for
3788 3790 # merges to avoid losing information about merged/dirty files.
3789 3791 if p2 != nullid:
3790 3792 normal = repo.dirstate.normallookup
3791 3793 else:
3792 3794 normal = repo.dirstate.normal
3793 3795
3794 3796 newlyaddedandmodifiedfiles = set()
3795 3797 if interactive:
3796 3798 # Prompt the user for changes to revert
3797 3799 torevert = [repo.wjoin(f) for f in actions['revert'][0]]
3798 3800 m = scmutil.match(ctx, torevert, matcher_opts)
3799 3801 diffopts = patch.difffeatureopts(repo.ui, whitespace=True)
3800 3802 diffopts.nodates = True
3801 3803 diffopts.git = True
3802 3804 operation = 'discard'
3803 3805 reversehunks = True
3804 3806 if node != parent:
3805 3807 operation = 'apply'
3806 3808 reversehunks = False
3807 3809 if reversehunks:
3808 3810 diff = patch.diff(repo, ctx.node(), None, m, opts=diffopts)
3809 3811 else:
3810 3812 diff = patch.diff(repo, None, ctx.node(), m, opts=diffopts)
3811 3813 originalchunks = patch.parsepatch(diff)
3812 3814
3813 3815 try:
3814 3816
3815 3817 chunks, opts = recordfilter(repo.ui, originalchunks,
3816 3818 operation=operation)
3817 3819 if reversehunks:
3818 3820 chunks = patch.reversehunks(chunks)
3819 3821
3820 3822 except error.PatchError as err:
3821 3823 raise error.Abort(_('error parsing patch: %s') % err)
3822 3824
3823 3825 newlyaddedandmodifiedfiles = newandmodified(chunks, originalchunks)
3824 3826 if tobackup is None:
3825 3827 tobackup = set()
3826 3828 # Apply changes
3827 3829 fp = stringio()
3828 3830 for c in chunks:
3829 3831 # Create a backup file only if this hunk should be backed up
3830 3832 if ishunk(c) and c.header.filename() in tobackup:
3831 3833 abs = c.header.filename()
3832 3834 target = repo.wjoin(abs)
3833 3835 bakname = scmutil.origpath(repo.ui, repo, m.rel(abs))
3834 3836 util.copyfile(target, bakname)
3835 3837 tobackup.remove(abs)
3836 3838 c.write(fp)
3837 3839 dopatch = fp.tell()
3838 3840 fp.seek(0)
3839 3841 if dopatch:
3840 3842 try:
3841 3843 patch.internalpatch(repo.ui, repo, fp, 1, eolmode=None)
3842 3844 except error.PatchError as err:
3843 3845 raise error.Abort(str(err))
3844 3846 del fp
3845 3847 else:
3846 3848 for f in actions['revert'][0]:
3847 3849 checkout(f)
3848 3850 if normal:
3849 3851 normal(f)
3850 3852
3851 3853 for f in actions['add'][0]:
3852 3854 # Don't checkout modified files, they are already created by the diff
3853 3855 if f not in newlyaddedandmodifiedfiles:
3854 3856 checkout(f)
3855 3857 repo.dirstate.add(f)
3856 3858
3857 3859 normal = repo.dirstate.normallookup
3858 3860 if node == parent and p2 == nullid:
3859 3861 normal = repo.dirstate.normal
3860 3862 for f in actions['undelete'][0]:
3861 3863 checkout(f)
3862 3864 normal(f)
3863 3865
3864 3866 copied = copies.pathcopies(repo[parent], ctx)
3865 3867
3866 3868 for f in actions['add'][0] + actions['undelete'][0] + actions['revert'][0]:
3867 3869 if f in copied:
3868 3870 repo.dirstate.copy(copied[f], f)
3869 3871
3870 3872 class command(registrar.command):
3871 3873 """deprecated: used registrar.command instead"""
3872 3874 def _doregister(self, func, name, *args, **kwargs):
3873 3875 func._deprecatedregistrar = True # flag for deprecwarn in extensions.py
3874 3876 return super(command, self)._doregister(func, name, *args, **kwargs)
3875 3877
3876 3878 # a list of (ui, repo, otherpeer, opts, missing) functions called by
3877 3879 # commands.outgoing. "missing" is "missing" of the result of
3878 3880 # "findcommonoutgoing()"
3879 3881 outgoinghooks = util.hooks()
3880 3882
3881 3883 # a list of (ui, repo) functions called by commands.summary
3882 3884 summaryhooks = util.hooks()
3883 3885
3884 3886 # a list of (ui, repo, opts, changes) functions called by commands.summary.
3885 3887 #
3886 3888 # functions should return tuple of booleans below, if 'changes' is None:
3887 3889 # (whether-incomings-are-needed, whether-outgoings-are-needed)
3888 3890 #
3889 3891 # otherwise, 'changes' is a tuple of tuples below:
3890 3892 # - (sourceurl, sourcebranch, sourcepeer, incoming)
3891 3893 # - (desturl, destbranch, destpeer, outgoing)
3892 3894 summaryremotehooks = util.hooks()
3893 3895
3894 3896 # A list of state files kept by multistep operations like graft.
3895 3897 # Since graft cannot be aborted, it is considered 'clearable' by update.
3896 3898 # note: bisect is intentionally excluded
3897 3899 # (state file, clearable, allowcommit, error, hint)
3898 3900 unfinishedstates = [
3899 3901 ('graftstate', True, False, _('graft in progress'),
3900 3902 _("use 'hg graft --continue' or 'hg update' to abort")),
3901 3903 ('updatestate', True, False, _('last update was interrupted'),
3902 3904 _("use 'hg update' to get a consistent checkout"))
3903 3905 ]
3904 3906
3905 3907 def checkunfinished(repo, commit=False):
3906 3908 '''Look for an unfinished multistep operation, like graft, and abort
3907 3909 if found. It's probably good to check this right before
3908 3910 bailifchanged().
3909 3911 '''
3910 3912 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3911 3913 if commit and allowcommit:
3912 3914 continue
3913 3915 if repo.vfs.exists(f):
3914 3916 raise error.Abort(msg, hint=hint)
3915 3917
3916 3918 def clearunfinished(repo):
3917 3919 '''Check for unfinished operations (as above), and clear the ones
3918 3920 that are clearable.
3919 3921 '''
3920 3922 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3921 3923 if not clearable and repo.vfs.exists(f):
3922 3924 raise error.Abort(msg, hint=hint)
3923 3925 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3924 3926 if clearable and repo.vfs.exists(f):
3925 3927 util.unlink(repo.vfs.join(f))
3926 3928
3927 3929 afterresolvedstates = [
3928 3930 ('graftstate',
3929 3931 _('hg graft --continue')),
3930 3932 ]
3931 3933
3932 3934 def howtocontinue(repo):
3933 3935 '''Check for an unfinished operation and return the command to finish
3934 3936 it.
3935 3937
3936 3938 afterresolvedstates tuples define a .hg/{file} and the corresponding
3937 3939 command needed to finish it.
3938 3940
3939 3941 Returns a (msg, warning) tuple. 'msg' is a string and 'warning' is
3940 3942 a boolean.
3941 3943 '''
3942 3944 contmsg = _("continue: %s")
3943 3945 for f, msg in afterresolvedstates:
3944 3946 if repo.vfs.exists(f):
3945 3947 return contmsg % msg, True
3946 3948 if repo[None].dirty(missing=True, merge=False, branch=False):
3947 3949 return contmsg % _("hg commit"), False
3948 3950 return None, None
3949 3951
3950 3952 def checkafterresolved(repo):
3951 3953 '''Inform the user about the next action after completing hg resolve
3952 3954
3953 3955 If there's a matching afterresolvedstates, howtocontinue will yield
3954 3956 repo.ui.warn as the reporter.
3955 3957
3956 3958 Otherwise, it will yield repo.ui.note.
3957 3959 '''
3958 3960 msg, warning = howtocontinue(repo)
3959 3961 if msg is not None:
3960 3962 if warning:
3961 3963 repo.ui.warn("%s\n" % msg)
3962 3964 else:
3963 3965 repo.ui.note("%s\n" % msg)
3964 3966
3965 3967 def wrongtooltocontinue(repo, task):
3966 3968 '''Raise an abort suggesting how to properly continue if there is an
3967 3969 active task.
3968 3970
3969 3971 Uses howtocontinue() to find the active task.
3970 3972
3971 3973 If there's no task (repo.ui.note for 'hg commit'), it does not offer
3972 3974 a hint.
3973 3975 '''
3974 3976 after = howtocontinue(repo)
3975 3977 hint = None
3976 3978 if after[1]:
3977 3979 hint = after[0]
3978 3980 raise error.Abort(_('no %s in progress') % task, hint=hint)
@@ -1,5590 +1,5592 b''
1 1 # commands.py - command processing for 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 difflib
11 11 import errno
12 12 import os
13 13 import re
14 14 import sys
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 from . import (
24 24 archival,
25 25 bookmarks,
26 26 bundle2,
27 27 changegroup,
28 28 cmdutil,
29 29 copies,
30 30 debugcommands as debugcommandsmod,
31 31 destutil,
32 32 dirstateguard,
33 33 discovery,
34 34 encoding,
35 35 error,
36 36 exchange,
37 37 extensions,
38 38 formatter,
39 39 graphmod,
40 40 hbisect,
41 41 help,
42 42 hg,
43 43 lock as lockmod,
44 44 merge as mergemod,
45 45 obsolete,
46 46 patch,
47 47 phases,
48 48 pycompat,
49 49 rcutil,
50 50 registrar,
51 51 revsetlang,
52 52 scmutil,
53 53 server,
54 54 sshserver,
55 55 streamclone,
56 56 tags as tagsmod,
57 57 templatekw,
58 58 ui as uimod,
59 59 util,
60 60 )
61 61
62 62 release = lockmod.release
63 63
64 64 table = {}
65 65 table.update(debugcommandsmod.command._table)
66 66
67 67 command = registrar.command(table)
68 68 readonly = registrar.command.readonly
69 69
70 70 # common command options
71 71
72 72 globalopts = [
73 73 ('R', 'repository', '',
74 74 _('repository root directory or name of overlay bundle file'),
75 75 _('REPO')),
76 76 ('', 'cwd', '',
77 77 _('change working directory'), _('DIR')),
78 78 ('y', 'noninteractive', None,
79 79 _('do not prompt, automatically pick the first choice for all prompts')),
80 80 ('q', 'quiet', None, _('suppress output')),
81 81 ('v', 'verbose', None, _('enable additional output')),
82 82 ('', 'color', '',
83 83 # i18n: 'always', 'auto', 'never', and 'debug' are keywords
84 84 # and should not be translated
85 85 _("when to colorize (boolean, always, auto, never, or debug)"),
86 86 _('TYPE')),
87 87 ('', 'config', [],
88 88 _('set/override config option (use \'section.name=value\')'),
89 89 _('CONFIG')),
90 90 ('', 'debug', None, _('enable debugging output')),
91 91 ('', 'debugger', None, _('start debugger')),
92 92 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
93 93 _('ENCODE')),
94 94 ('', 'encodingmode', encoding.encodingmode,
95 95 _('set the charset encoding mode'), _('MODE')),
96 96 ('', 'traceback', None, _('always print a traceback on exception')),
97 97 ('', 'time', None, _('time how long the command takes')),
98 98 ('', 'profile', None, _('print command execution profile')),
99 99 ('', 'version', None, _('output version information and exit')),
100 100 ('h', 'help', None, _('display help and exit')),
101 101 ('', 'hidden', False, _('consider hidden changesets')),
102 102 ('', 'pager', 'auto',
103 103 _("when to paginate (boolean, always, auto, or never)"), _('TYPE')),
104 104 ]
105 105
106 106 dryrunopts = cmdutil.dryrunopts
107 107 remoteopts = cmdutil.remoteopts
108 108 walkopts = cmdutil.walkopts
109 109 commitopts = cmdutil.commitopts
110 110 commitopts2 = cmdutil.commitopts2
111 111 formatteropts = cmdutil.formatteropts
112 112 templateopts = cmdutil.templateopts
113 113 logopts = cmdutil.logopts
114 114 diffopts = cmdutil.diffopts
115 115 diffwsopts = cmdutil.diffwsopts
116 116 diffopts2 = cmdutil.diffopts2
117 117 mergetoolopts = cmdutil.mergetoolopts
118 118 similarityopts = cmdutil.similarityopts
119 119 subrepoopts = cmdutil.subrepoopts
120 120 debugrevlogopts = cmdutil.debugrevlogopts
121 121
122 122 # Commands start here, listed alphabetically
123 123
124 124 @command('^add',
125 125 walkopts + subrepoopts + dryrunopts,
126 126 _('[OPTION]... [FILE]...'),
127 127 inferrepo=True)
128 128 def add(ui, repo, *pats, **opts):
129 129 """add the specified files on the next commit
130 130
131 131 Schedule files to be version controlled and added to the
132 132 repository.
133 133
134 134 The files will be added to the repository at the next commit. To
135 135 undo an add before that, see :hg:`forget`.
136 136
137 137 If no names are given, add all files to the repository (except
138 138 files matching ``.hgignore``).
139 139
140 140 .. container:: verbose
141 141
142 142 Examples:
143 143
144 144 - New (unknown) files are added
145 145 automatically by :hg:`add`::
146 146
147 147 $ ls
148 148 foo.c
149 149 $ hg status
150 150 ? foo.c
151 151 $ hg add
152 152 adding foo.c
153 153 $ hg status
154 154 A foo.c
155 155
156 156 - Specific files to be added can be specified::
157 157
158 158 $ ls
159 159 bar.c foo.c
160 160 $ hg status
161 161 ? bar.c
162 162 ? foo.c
163 163 $ hg add bar.c
164 164 $ hg status
165 165 A bar.c
166 166 ? foo.c
167 167
168 168 Returns 0 if all files are successfully added.
169 169 """
170 170
171 171 m = scmutil.match(repo[None], pats, pycompat.byteskwargs(opts))
172 172 rejected = cmdutil.add(ui, repo, m, "", False, **opts)
173 173 return rejected and 1 or 0
174 174
175 175 @command('addremove',
176 176 similarityopts + subrepoopts + walkopts + dryrunopts,
177 177 _('[OPTION]... [FILE]...'),
178 178 inferrepo=True)
179 179 def addremove(ui, repo, *pats, **opts):
180 180 """add all new files, delete all missing files
181 181
182 182 Add all new files and remove all missing files from the
183 183 repository.
184 184
185 185 Unless names are given, new files are ignored if they match any of
186 186 the patterns in ``.hgignore``. As with add, these changes take
187 187 effect at the next commit.
188 188
189 189 Use the -s/--similarity option to detect renamed files. This
190 190 option takes a percentage between 0 (disabled) and 100 (files must
191 191 be identical) as its parameter. With a parameter greater than 0,
192 192 this compares every removed file with every added file and records
193 193 those similar enough as renames. Detecting renamed files this way
194 194 can be expensive. After using this option, :hg:`status -C` can be
195 195 used to check which files were identified as moved or renamed. If
196 196 not specified, -s/--similarity defaults to 100 and only renames of
197 197 identical files are detected.
198 198
199 199 .. container:: verbose
200 200
201 201 Examples:
202 202
203 203 - A number of files (bar.c and foo.c) are new,
204 204 while foobar.c has been removed (without using :hg:`remove`)
205 205 from the repository::
206 206
207 207 $ ls
208 208 bar.c foo.c
209 209 $ hg status
210 210 ! foobar.c
211 211 ? bar.c
212 212 ? foo.c
213 213 $ hg addremove
214 214 adding bar.c
215 215 adding foo.c
216 216 removing foobar.c
217 217 $ hg status
218 218 A bar.c
219 219 A foo.c
220 220 R foobar.c
221 221
222 222 - A file foobar.c was moved to foo.c without using :hg:`rename`.
223 223 Afterwards, it was edited slightly::
224 224
225 225 $ ls
226 226 foo.c
227 227 $ hg status
228 228 ! foobar.c
229 229 ? foo.c
230 230 $ hg addremove --similarity 90
231 231 removing foobar.c
232 232 adding foo.c
233 233 recording removal of foobar.c as rename to foo.c (94% similar)
234 234 $ hg status -C
235 235 A foo.c
236 236 foobar.c
237 237 R foobar.c
238 238
239 239 Returns 0 if all files are successfully added.
240 240 """
241 241 opts = pycompat.byteskwargs(opts)
242 242 try:
243 243 sim = float(opts.get('similarity') or 100)
244 244 except ValueError:
245 245 raise error.Abort(_('similarity must be a number'))
246 246 if sim < 0 or sim > 100:
247 247 raise error.Abort(_('similarity must be between 0 and 100'))
248 248 matcher = scmutil.match(repo[None], pats, opts)
249 249 return scmutil.addremove(repo, matcher, "", opts, similarity=sim / 100.0)
250 250
251 251 @command('^annotate|blame',
252 252 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
253 253 ('', 'follow', None,
254 254 _('follow copies/renames and list the filename (DEPRECATED)')),
255 255 ('', 'no-follow', None, _("don't follow copies and renames")),
256 256 ('a', 'text', None, _('treat all files as text')),
257 257 ('u', 'user', None, _('list the author (long with -v)')),
258 258 ('f', 'file', None, _('list the filename')),
259 259 ('d', 'date', None, _('list the date (short with -q)')),
260 260 ('n', 'number', None, _('list the revision number (default)')),
261 261 ('c', 'changeset', None, _('list the changeset')),
262 262 ('l', 'line-number', None, _('show line number at the first appearance')),
263 263 ('', 'skip', [], _('revision to not display (EXPERIMENTAL)'), _('REV')),
264 264 ] + diffwsopts + walkopts + formatteropts,
265 265 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'),
266 266 inferrepo=True)
267 267 def annotate(ui, repo, *pats, **opts):
268 268 """show changeset information by line for each file
269 269
270 270 List changes in files, showing the revision id responsible for
271 271 each line.
272 272
273 273 This command is useful for discovering when a change was made and
274 274 by whom.
275 275
276 276 If you include --file, --user, or --date, the revision number is
277 277 suppressed unless you also include --number.
278 278
279 279 Without the -a/--text option, annotate will avoid processing files
280 280 it detects as binary. With -a, annotate will annotate the file
281 281 anyway, although the results will probably be neither useful
282 282 nor desirable.
283 283
284 284 Returns 0 on success.
285 285 """
286 286 opts = pycompat.byteskwargs(opts)
287 287 if not pats:
288 288 raise error.Abort(_('at least one filename or pattern is required'))
289 289
290 290 if opts.get('follow'):
291 291 # --follow is deprecated and now just an alias for -f/--file
292 292 # to mimic the behavior of Mercurial before version 1.5
293 293 opts['file'] = True
294 294
295 295 ctx = scmutil.revsingle(repo, opts.get('rev'))
296 296
297 297 rootfm = ui.formatter('annotate', opts)
298 298 if ui.quiet:
299 299 datefunc = util.shortdate
300 300 else:
301 301 datefunc = util.datestr
302 302 if ctx.rev() is None:
303 303 def hexfn(node):
304 304 if node is None:
305 305 return None
306 306 else:
307 307 return rootfm.hexfunc(node)
308 308 if opts.get('changeset'):
309 309 # omit "+" suffix which is appended to node hex
310 310 def formatrev(rev):
311 311 if rev is None:
312 312 return '%d' % ctx.p1().rev()
313 313 else:
314 314 return '%d' % rev
315 315 else:
316 316 def formatrev(rev):
317 317 if rev is None:
318 318 return '%d+' % ctx.p1().rev()
319 319 else:
320 320 return '%d ' % rev
321 321 def formathex(hex):
322 322 if hex is None:
323 323 return '%s+' % rootfm.hexfunc(ctx.p1().node())
324 324 else:
325 325 return '%s ' % hex
326 326 else:
327 327 hexfn = rootfm.hexfunc
328 328 formatrev = formathex = pycompat.bytestr
329 329
330 330 opmap = [('user', ' ', lambda x: x.fctx.user(), ui.shortuser),
331 331 ('number', ' ', lambda x: x.fctx.rev(), formatrev),
332 332 ('changeset', ' ', lambda x: hexfn(x.fctx.node()), formathex),
333 333 ('date', ' ', lambda x: x.fctx.date(), util.cachefunc(datefunc)),
334 334 ('file', ' ', lambda x: x.fctx.path(), str),
335 335 ('line_number', ':', lambda x: x.lineno, str),
336 336 ]
337 337 fieldnamemap = {'number': 'rev', 'changeset': 'node'}
338 338
339 339 if (not opts.get('user') and not opts.get('changeset')
340 340 and not opts.get('date') and not opts.get('file')):
341 341 opts['number'] = True
342 342
343 343 linenumber = opts.get('line_number') is not None
344 344 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
345 345 raise error.Abort(_('at least one of -n/-c is required for -l'))
346 346
347 347 ui.pager('annotate')
348 348
349 349 if rootfm.isplain():
350 350 def makefunc(get, fmt):
351 351 return lambda x: fmt(get(x))
352 352 else:
353 353 def makefunc(get, fmt):
354 354 return get
355 355 funcmap = [(makefunc(get, fmt), sep) for op, sep, get, fmt in opmap
356 356 if opts.get(op)]
357 357 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
358 358 fields = ' '.join(fieldnamemap.get(op, op) for op, sep, get, fmt in opmap
359 359 if opts.get(op))
360 360
361 361 def bad(x, y):
362 362 raise error.Abort("%s: %s" % (x, y))
363 363
364 364 m = scmutil.match(ctx, pats, opts, badfn=bad)
365 365
366 366 follow = not opts.get('no_follow')
367 367 diffopts = patch.difffeatureopts(ui, opts, section='annotate',
368 368 whitespace=True)
369 369 skiprevs = opts.get('skip')
370 370 if skiprevs:
371 371 skiprevs = scmutil.revrange(repo, skiprevs)
372 372
373 373 for abs in ctx.walk(m):
374 374 fctx = ctx[abs]
375 375 rootfm.startitem()
376 376 rootfm.data(abspath=abs, path=m.rel(abs))
377 377 if not opts.get('text') and fctx.isbinary():
378 378 rootfm.plain(_("%s: binary file\n")
379 379 % ((pats and m.rel(abs)) or abs))
380 380 continue
381 381
382 382 fm = rootfm.nested('lines')
383 383 lines = fctx.annotate(follow=follow, linenumber=linenumber,
384 384 skiprevs=skiprevs, diffopts=diffopts)
385 385 if not lines:
386 386 fm.end()
387 387 continue
388 388 formats = []
389 389 pieces = []
390 390
391 391 for f, sep in funcmap:
392 392 l = [f(n) for n, dummy in lines]
393 393 if fm.isplain():
394 394 sizes = [encoding.colwidth(x) for x in l]
395 395 ml = max(sizes)
396 396 formats.append([sep + ' ' * (ml - w) + '%s' for w in sizes])
397 397 else:
398 398 formats.append(['%s' for x in l])
399 399 pieces.append(l)
400 400
401 401 for f, p, l in zip(zip(*formats), zip(*pieces), lines):
402 402 fm.startitem()
403 403 fm.write(fields, "".join(f), *p)
404 404 if l[0].skip:
405 405 fmt = "* %s"
406 406 else:
407 407 fmt = ": %s"
408 408 fm.write('line', fmt, l[1])
409 409
410 410 if not lines[-1][1].endswith('\n'):
411 411 fm.plain('\n')
412 412 fm.end()
413 413
414 414 rootfm.end()
415 415
416 416 @command('archive',
417 417 [('', 'no-decode', None, _('do not pass files through decoders')),
418 418 ('p', 'prefix', '', _('directory prefix for files in archive'),
419 419 _('PREFIX')),
420 420 ('r', 'rev', '', _('revision to distribute'), _('REV')),
421 421 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
422 422 ] + subrepoopts + walkopts,
423 423 _('[OPTION]... DEST'))
424 424 def archive(ui, repo, dest, **opts):
425 425 '''create an unversioned archive of a repository revision
426 426
427 427 By default, the revision used is the parent of the working
428 428 directory; use -r/--rev to specify a different revision.
429 429
430 430 The archive type is automatically detected based on file
431 431 extension (to override, use -t/--type).
432 432
433 433 .. container:: verbose
434 434
435 435 Examples:
436 436
437 437 - create a zip file containing the 1.0 release::
438 438
439 439 hg archive -r 1.0 project-1.0.zip
440 440
441 441 - create a tarball excluding .hg files::
442 442
443 443 hg archive project.tar.gz -X ".hg*"
444 444
445 445 Valid types are:
446 446
447 447 :``files``: a directory full of files (default)
448 448 :``tar``: tar archive, uncompressed
449 449 :``tbz2``: tar archive, compressed using bzip2
450 450 :``tgz``: tar archive, compressed using gzip
451 451 :``uzip``: zip archive, uncompressed
452 452 :``zip``: zip archive, compressed using deflate
453 453
454 454 The exact name of the destination archive or directory is given
455 455 using a format string; see :hg:`help export` for details.
456 456
457 457 Each member added to an archive file has a directory prefix
458 458 prepended. Use -p/--prefix to specify a format string for the
459 459 prefix. The default is the basename of the archive, with suffixes
460 460 removed.
461 461
462 462 Returns 0 on success.
463 463 '''
464 464
465 465 opts = pycompat.byteskwargs(opts)
466 466 ctx = scmutil.revsingle(repo, opts.get('rev'))
467 467 if not ctx:
468 468 raise error.Abort(_('no working directory: please specify a revision'))
469 469 node = ctx.node()
470 470 dest = cmdutil.makefilename(repo, dest, node)
471 471 if os.path.realpath(dest) == repo.root:
472 472 raise error.Abort(_('repository root cannot be destination'))
473 473
474 474 kind = opts.get('type') or archival.guesskind(dest) or 'files'
475 475 prefix = opts.get('prefix')
476 476
477 477 if dest == '-':
478 478 if kind == 'files':
479 479 raise error.Abort(_('cannot archive plain files to stdout'))
480 480 dest = cmdutil.makefileobj(repo, dest)
481 481 if not prefix:
482 482 prefix = os.path.basename(repo.root) + '-%h'
483 483
484 484 prefix = cmdutil.makefilename(repo, prefix, node)
485 485 match = scmutil.match(ctx, [], opts)
486 486 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
487 487 match, prefix, subrepos=opts.get('subrepos'))
488 488
489 489 @command('backout',
490 490 [('', 'merge', None, _('merge with old dirstate parent after backout')),
491 491 ('', 'commit', None,
492 492 _('commit if no conflicts were encountered (DEPRECATED)')),
493 493 ('', 'no-commit', None, _('do not commit')),
494 494 ('', 'parent', '',
495 495 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
496 496 ('r', 'rev', '', _('revision to backout'), _('REV')),
497 497 ('e', 'edit', False, _('invoke editor on commit messages')),
498 498 ] + mergetoolopts + walkopts + commitopts + commitopts2,
499 499 _('[OPTION]... [-r] REV'))
500 500 def backout(ui, repo, node=None, rev=None, **opts):
501 501 '''reverse effect of earlier changeset
502 502
503 503 Prepare a new changeset with the effect of REV undone in the
504 504 current working directory. If no conflicts were encountered,
505 505 it will be committed immediately.
506 506
507 507 If REV is the parent of the working directory, then this new changeset
508 508 is committed automatically (unless --no-commit is specified).
509 509
510 510 .. note::
511 511
512 512 :hg:`backout` cannot be used to fix either an unwanted or
513 513 incorrect merge.
514 514
515 515 .. container:: verbose
516 516
517 517 Examples:
518 518
519 519 - Reverse the effect of the parent of the working directory.
520 520 This backout will be committed immediately::
521 521
522 522 hg backout -r .
523 523
524 524 - Reverse the effect of previous bad revision 23::
525 525
526 526 hg backout -r 23
527 527
528 528 - Reverse the effect of previous bad revision 23 and
529 529 leave changes uncommitted::
530 530
531 531 hg backout -r 23 --no-commit
532 532 hg commit -m "Backout revision 23"
533 533
534 534 By default, the pending changeset will have one parent,
535 535 maintaining a linear history. With --merge, the pending
536 536 changeset will instead have two parents: the old parent of the
537 537 working directory and a new child of REV that simply undoes REV.
538 538
539 539 Before version 1.7, the behavior without --merge was equivalent
540 540 to specifying --merge followed by :hg:`update --clean .` to
541 541 cancel the merge and leave the child of REV as a head to be
542 542 merged separately.
543 543
544 544 See :hg:`help dates` for a list of formats valid for -d/--date.
545 545
546 546 See :hg:`help revert` for a way to restore files to the state
547 547 of another revision.
548 548
549 549 Returns 0 on success, 1 if nothing to backout or there are unresolved
550 550 files.
551 551 '''
552 552 wlock = lock = None
553 553 try:
554 554 wlock = repo.wlock()
555 555 lock = repo.lock()
556 556 return _dobackout(ui, repo, node, rev, **opts)
557 557 finally:
558 558 release(lock, wlock)
559 559
560 560 def _dobackout(ui, repo, node=None, rev=None, **opts):
561 561 opts = pycompat.byteskwargs(opts)
562 562 if opts.get('commit') and opts.get('no_commit'):
563 563 raise error.Abort(_("cannot use --commit with --no-commit"))
564 564 if opts.get('merge') and opts.get('no_commit'):
565 565 raise error.Abort(_("cannot use --merge with --no-commit"))
566 566
567 567 if rev and node:
568 568 raise error.Abort(_("please specify just one revision"))
569 569
570 570 if not rev:
571 571 rev = node
572 572
573 573 if not rev:
574 574 raise error.Abort(_("please specify a revision to backout"))
575 575
576 576 date = opts.get('date')
577 577 if date:
578 578 opts['date'] = util.parsedate(date)
579 579
580 580 cmdutil.checkunfinished(repo)
581 581 cmdutil.bailifchanged(repo)
582 582 node = scmutil.revsingle(repo, rev).node()
583 583
584 584 op1, op2 = repo.dirstate.parents()
585 585 if not repo.changelog.isancestor(node, op1):
586 586 raise error.Abort(_('cannot backout change that is not an ancestor'))
587 587
588 588 p1, p2 = repo.changelog.parents(node)
589 589 if p1 == nullid:
590 590 raise error.Abort(_('cannot backout a change with no parents'))
591 591 if p2 != nullid:
592 592 if not opts.get('parent'):
593 593 raise error.Abort(_('cannot backout a merge changeset'))
594 594 p = repo.lookup(opts['parent'])
595 595 if p not in (p1, p2):
596 596 raise error.Abort(_('%s is not a parent of %s') %
597 597 (short(p), short(node)))
598 598 parent = p
599 599 else:
600 600 if opts.get('parent'):
601 601 raise error.Abort(_('cannot use --parent on non-merge changeset'))
602 602 parent = p1
603 603
604 604 # the backout should appear on the same branch
605 605 branch = repo.dirstate.branch()
606 606 bheads = repo.branchheads(branch)
607 607 rctx = scmutil.revsingle(repo, hex(parent))
608 608 if not opts.get('merge') and op1 != node:
609 609 dsguard = dirstateguard.dirstateguard(repo, 'backout')
610 610 try:
611 611 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
612 612 'backout')
613 613 stats = mergemod.update(repo, parent, True, True, node, False)
614 614 repo.setparents(op1, op2)
615 615 dsguard.close()
616 616 hg._showstats(repo, stats)
617 617 if stats[3]:
618 618 repo.ui.status(_("use 'hg resolve' to retry unresolved "
619 619 "file merges\n"))
620 620 return 1
621 621 finally:
622 622 ui.setconfig('ui', 'forcemerge', '', '')
623 623 lockmod.release(dsguard)
624 624 else:
625 625 hg.clean(repo, node, show_stats=False)
626 626 repo.dirstate.setbranch(branch)
627 627 cmdutil.revert(ui, repo, rctx, repo.dirstate.parents())
628 628
629 629 if opts.get('no_commit'):
630 630 msg = _("changeset %s backed out, "
631 631 "don't forget to commit.\n")
632 632 ui.status(msg % short(node))
633 633 return 0
634 634
635 635 def commitfunc(ui, repo, message, match, opts):
636 636 editform = 'backout'
637 637 e = cmdutil.getcommiteditor(editform=editform,
638 638 **pycompat.strkwargs(opts))
639 639 if not message:
640 640 # we don't translate commit messages
641 641 message = "Backed out changeset %s" % short(node)
642 642 e = cmdutil.getcommiteditor(edit=True, editform=editform)
643 643 return repo.commit(message, opts.get('user'), opts.get('date'),
644 644 match, editor=e)
645 645 newnode = cmdutil.commit(ui, repo, commitfunc, [], opts)
646 646 if not newnode:
647 647 ui.status(_("nothing changed\n"))
648 648 return 1
649 649 cmdutil.commitstatus(repo, newnode, branch, bheads)
650 650
651 651 def nice(node):
652 652 return '%d:%s' % (repo.changelog.rev(node), short(node))
653 653 ui.status(_('changeset %s backs out changeset %s\n') %
654 654 (nice(repo.changelog.tip()), nice(node)))
655 655 if opts.get('merge') and op1 != node:
656 656 hg.clean(repo, op1, show_stats=False)
657 657 ui.status(_('merging with changeset %s\n')
658 658 % nice(repo.changelog.tip()))
659 659 try:
660 660 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
661 661 'backout')
662 662 return hg.merge(repo, hex(repo.changelog.tip()))
663 663 finally:
664 664 ui.setconfig('ui', 'forcemerge', '', '')
665 665 return 0
666 666
667 667 @command('bisect',
668 668 [('r', 'reset', False, _('reset bisect state')),
669 669 ('g', 'good', False, _('mark changeset good')),
670 670 ('b', 'bad', False, _('mark changeset bad')),
671 671 ('s', 'skip', False, _('skip testing changeset')),
672 672 ('e', 'extend', False, _('extend the bisect range')),
673 673 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
674 674 ('U', 'noupdate', False, _('do not update to target'))],
675 675 _("[-gbsr] [-U] [-c CMD] [REV]"))
676 676 def bisect(ui, repo, rev=None, extra=None, command=None,
677 677 reset=None, good=None, bad=None, skip=None, extend=None,
678 678 noupdate=None):
679 679 """subdivision search of changesets
680 680
681 681 This command helps to find changesets which introduce problems. To
682 682 use, mark the earliest changeset you know exhibits the problem as
683 683 bad, then mark the latest changeset which is free from the problem
684 684 as good. Bisect will update your working directory to a revision
685 685 for testing (unless the -U/--noupdate option is specified). Once
686 686 you have performed tests, mark the working directory as good or
687 687 bad, and bisect will either update to another candidate changeset
688 688 or announce that it has found the bad revision.
689 689
690 690 As a shortcut, you can also use the revision argument to mark a
691 691 revision as good or bad without checking it out first.
692 692
693 693 If you supply a command, it will be used for automatic bisection.
694 694 The environment variable HG_NODE will contain the ID of the
695 695 changeset being tested. The exit status of the command will be
696 696 used to mark revisions as good or bad: status 0 means good, 125
697 697 means to skip the revision, 127 (command not found) will abort the
698 698 bisection, and any other non-zero exit status means the revision
699 699 is bad.
700 700
701 701 .. container:: verbose
702 702
703 703 Some examples:
704 704
705 705 - start a bisection with known bad revision 34, and good revision 12::
706 706
707 707 hg bisect --bad 34
708 708 hg bisect --good 12
709 709
710 710 - advance the current bisection by marking current revision as good or
711 711 bad::
712 712
713 713 hg bisect --good
714 714 hg bisect --bad
715 715
716 716 - mark the current revision, or a known revision, to be skipped (e.g. if
717 717 that revision is not usable because of another issue)::
718 718
719 719 hg bisect --skip
720 720 hg bisect --skip 23
721 721
722 722 - skip all revisions that do not touch directories ``foo`` or ``bar``::
723 723
724 724 hg bisect --skip "!( file('path:foo') & file('path:bar') )"
725 725
726 726 - forget the current bisection::
727 727
728 728 hg bisect --reset
729 729
730 730 - use 'make && make tests' to automatically find the first broken
731 731 revision::
732 732
733 733 hg bisect --reset
734 734 hg bisect --bad 34
735 735 hg bisect --good 12
736 736 hg bisect --command "make && make tests"
737 737
738 738 - see all changesets whose states are already known in the current
739 739 bisection::
740 740
741 741 hg log -r "bisect(pruned)"
742 742
743 743 - see the changeset currently being bisected (especially useful
744 744 if running with -U/--noupdate)::
745 745
746 746 hg log -r "bisect(current)"
747 747
748 748 - see all changesets that took part in the current bisection::
749 749
750 750 hg log -r "bisect(range)"
751 751
752 752 - you can even get a nice graph::
753 753
754 754 hg log --graph -r "bisect(range)"
755 755
756 756 See :hg:`help revisions.bisect` for more about the `bisect()` predicate.
757 757
758 758 Returns 0 on success.
759 759 """
760 760 # backward compatibility
761 761 if rev in "good bad reset init".split():
762 762 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
763 763 cmd, rev, extra = rev, extra, None
764 764 if cmd == "good":
765 765 good = True
766 766 elif cmd == "bad":
767 767 bad = True
768 768 else:
769 769 reset = True
770 770 elif extra:
771 771 raise error.Abort(_('incompatible arguments'))
772 772
773 773 incompatibles = {
774 774 '--bad': bad,
775 775 '--command': bool(command),
776 776 '--extend': extend,
777 777 '--good': good,
778 778 '--reset': reset,
779 779 '--skip': skip,
780 780 }
781 781
782 782 enabled = [x for x in incompatibles if incompatibles[x]]
783 783
784 784 if len(enabled) > 1:
785 785 raise error.Abort(_('%s and %s are incompatible') %
786 786 tuple(sorted(enabled)[0:2]))
787 787
788 788 if reset:
789 789 hbisect.resetstate(repo)
790 790 return
791 791
792 792 state = hbisect.load_state(repo)
793 793
794 794 # update state
795 795 if good or bad or skip:
796 796 if rev:
797 797 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
798 798 else:
799 799 nodes = [repo.lookup('.')]
800 800 if good:
801 801 state['good'] += nodes
802 802 elif bad:
803 803 state['bad'] += nodes
804 804 elif skip:
805 805 state['skip'] += nodes
806 806 hbisect.save_state(repo, state)
807 807 if not (state['good'] and state['bad']):
808 808 return
809 809
810 810 def mayupdate(repo, node, show_stats=True):
811 811 """common used update sequence"""
812 812 if noupdate:
813 813 return
814 814 cmdutil.checkunfinished(repo)
815 815 cmdutil.bailifchanged(repo)
816 816 return hg.clean(repo, node, show_stats=show_stats)
817 817
818 818 displayer = cmdutil.show_changeset(ui, repo, {})
819 819
820 820 if command:
821 821 changesets = 1
822 822 if noupdate:
823 823 try:
824 824 node = state['current'][0]
825 825 except LookupError:
826 826 raise error.Abort(_('current bisect revision is unknown - '
827 827 'start a new bisect to fix'))
828 828 else:
829 829 node, p2 = repo.dirstate.parents()
830 830 if p2 != nullid:
831 831 raise error.Abort(_('current bisect revision is a merge'))
832 832 if rev:
833 833 node = repo[scmutil.revsingle(repo, rev, node)].node()
834 834 try:
835 835 while changesets:
836 836 # update state
837 837 state['current'] = [node]
838 838 hbisect.save_state(repo, state)
839 839 status = ui.system(command, environ={'HG_NODE': hex(node)},
840 840 blockedtag='bisect_check')
841 841 if status == 125:
842 842 transition = "skip"
843 843 elif status == 0:
844 844 transition = "good"
845 845 # status < 0 means process was killed
846 846 elif status == 127:
847 847 raise error.Abort(_("failed to execute %s") % command)
848 848 elif status < 0:
849 849 raise error.Abort(_("%s killed") % command)
850 850 else:
851 851 transition = "bad"
852 852 state[transition].append(node)
853 853 ctx = repo[node]
854 854 ui.status(_('changeset %d:%s: %s\n') % (ctx, ctx, transition))
855 855 hbisect.checkstate(state)
856 856 # bisect
857 857 nodes, changesets, bgood = hbisect.bisect(repo, state)
858 858 # update to next check
859 859 node = nodes[0]
860 860 mayupdate(repo, node, show_stats=False)
861 861 finally:
862 862 state['current'] = [node]
863 863 hbisect.save_state(repo, state)
864 864 hbisect.printresult(ui, repo, state, displayer, nodes, bgood)
865 865 return
866 866
867 867 hbisect.checkstate(state)
868 868
869 869 # actually bisect
870 870 nodes, changesets, good = hbisect.bisect(repo, state)
871 871 if extend:
872 872 if not changesets:
873 873 extendnode = hbisect.extendrange(repo, state, nodes, good)
874 874 if extendnode is not None:
875 875 ui.write(_("Extending search to changeset %d:%s\n")
876 876 % (extendnode.rev(), extendnode))
877 877 state['current'] = [extendnode.node()]
878 878 hbisect.save_state(repo, state)
879 879 return mayupdate(repo, extendnode.node())
880 880 raise error.Abort(_("nothing to extend"))
881 881
882 882 if changesets == 0:
883 883 hbisect.printresult(ui, repo, state, displayer, nodes, good)
884 884 else:
885 885 assert len(nodes) == 1 # only a single node can be tested next
886 886 node = nodes[0]
887 887 # compute the approximate number of remaining tests
888 888 tests, size = 0, 2
889 889 while size <= changesets:
890 890 tests, size = tests + 1, size * 2
891 891 rev = repo.changelog.rev(node)
892 892 ui.write(_("Testing changeset %d:%s "
893 893 "(%d changesets remaining, ~%d tests)\n")
894 894 % (rev, short(node), changesets, tests))
895 895 state['current'] = [node]
896 896 hbisect.save_state(repo, state)
897 897 return mayupdate(repo, node)
898 898
899 899 @command('bookmarks|bookmark',
900 900 [('f', 'force', False, _('force')),
901 901 ('r', 'rev', '', _('revision for bookmark action'), _('REV')),
902 902 ('d', 'delete', False, _('delete a given bookmark')),
903 903 ('m', 'rename', '', _('rename a given bookmark'), _('OLD')),
904 904 ('i', 'inactive', False, _('mark a bookmark inactive')),
905 905 ] + formatteropts,
906 906 _('hg bookmarks [OPTIONS]... [NAME]...'))
907 907 def bookmark(ui, repo, *names, **opts):
908 908 '''create a new bookmark or list existing bookmarks
909 909
910 910 Bookmarks are labels on changesets to help track lines of development.
911 911 Bookmarks are unversioned and can be moved, renamed and deleted.
912 912 Deleting or moving a bookmark has no effect on the associated changesets.
913 913
914 914 Creating or updating to a bookmark causes it to be marked as 'active'.
915 915 The active bookmark is indicated with a '*'.
916 916 When a commit is made, the active bookmark will advance to the new commit.
917 917 A plain :hg:`update` will also advance an active bookmark, if possible.
918 918 Updating away from a bookmark will cause it to be deactivated.
919 919
920 920 Bookmarks can be pushed and pulled between repositories (see
921 921 :hg:`help push` and :hg:`help pull`). If a shared bookmark has
922 922 diverged, a new 'divergent bookmark' of the form 'name@path' will
923 923 be created. Using :hg:`merge` will resolve the divergence.
924 924
925 925 Specifying bookmark as '.' to -m or -d options is equivalent to specifying
926 926 the active bookmark's name.
927 927
928 928 A bookmark named '@' has the special property that :hg:`clone` will
929 929 check it out by default if it exists.
930 930
931 931 .. container:: verbose
932 932
933 933 Examples:
934 934
935 935 - create an active bookmark for a new line of development::
936 936
937 937 hg book new-feature
938 938
939 939 - create an inactive bookmark as a place marker::
940 940
941 941 hg book -i reviewed
942 942
943 943 - create an inactive bookmark on another changeset::
944 944
945 945 hg book -r .^ tested
946 946
947 947 - rename bookmark turkey to dinner::
948 948
949 949 hg book -m turkey dinner
950 950
951 951 - move the '@' bookmark from another branch::
952 952
953 953 hg book -f @
954 954 '''
955 955 force = opts.get(r'force')
956 956 rev = opts.get(r'rev')
957 957 delete = opts.get(r'delete')
958 958 rename = opts.get(r'rename')
959 959 inactive = opts.get(r'inactive')
960 960
961 961 if delete and rename:
962 962 raise error.Abort(_("--delete and --rename are incompatible"))
963 963 if delete and rev:
964 964 raise error.Abort(_("--rev is incompatible with --delete"))
965 965 if rename and rev:
966 966 raise error.Abort(_("--rev is incompatible with --rename"))
967 967 if not names and (delete or rev):
968 968 raise error.Abort(_("bookmark name required"))
969 969
970 970 if delete or rename or names or inactive:
971 971 with repo.wlock(), repo.lock(), repo.transaction('bookmark') as tr:
972 972 if delete:
973 973 names = pycompat.maplist(repo._bookmarks.expandname, names)
974 974 bookmarks.delete(repo, tr, names)
975 975 elif rename:
976 976 if not names:
977 977 raise error.Abort(_("new bookmark name required"))
978 978 elif len(names) > 1:
979 979 raise error.Abort(_("only one new bookmark name allowed"))
980 980 rename = repo._bookmarks.expandname(rename)
981 981 bookmarks.rename(repo, tr, rename, names[0], force, inactive)
982 982 elif names:
983 983 bookmarks.addbookmarks(repo, tr, names, rev, force, inactive)
984 984 elif inactive:
985 985 if len(repo._bookmarks) == 0:
986 986 ui.status(_("no bookmarks set\n"))
987 987 elif not repo._activebookmark:
988 988 ui.status(_("no active bookmark\n"))
989 989 else:
990 990 bookmarks.deactivate(repo)
991 991 else: # show bookmarks
992 992 bookmarks.printbookmarks(ui, repo, **opts)
993 993
994 994 @command('branch',
995 995 [('f', 'force', None,
996 996 _('set branch name even if it shadows an existing branch')),
997 997 ('C', 'clean', None, _('reset branch name to parent branch name'))],
998 998 _('[-fC] [NAME]'))
999 999 def branch(ui, repo, label=None, **opts):
1000 1000 """set or show the current branch name
1001 1001
1002 1002 .. note::
1003 1003
1004 1004 Branch names are permanent and global. Use :hg:`bookmark` to create a
1005 1005 light-weight bookmark instead. See :hg:`help glossary` for more
1006 1006 information about named branches and bookmarks.
1007 1007
1008 1008 With no argument, show the current branch name. With one argument,
1009 1009 set the working directory branch name (the branch will not exist
1010 1010 in the repository until the next commit). Standard practice
1011 1011 recommends that primary development take place on the 'default'
1012 1012 branch.
1013 1013
1014 1014 Unless -f/--force is specified, branch will not let you set a
1015 1015 branch name that already exists.
1016 1016
1017 1017 Use -C/--clean to reset the working directory branch to that of
1018 1018 the parent of the working directory, negating a previous branch
1019 1019 change.
1020 1020
1021 1021 Use the command :hg:`update` to switch to an existing branch. Use
1022 1022 :hg:`commit --close-branch` to mark this branch head as closed.
1023 1023 When all heads of a branch are closed, the branch will be
1024 1024 considered closed.
1025 1025
1026 1026 Returns 0 on success.
1027 1027 """
1028 1028 opts = pycompat.byteskwargs(opts)
1029 1029 if label:
1030 1030 label = label.strip()
1031 1031
1032 1032 if not opts.get('clean') and not label:
1033 1033 ui.write("%s\n" % repo.dirstate.branch())
1034 1034 return
1035 1035
1036 1036 with repo.wlock():
1037 1037 if opts.get('clean'):
1038 1038 label = repo[None].p1().branch()
1039 1039 repo.dirstate.setbranch(label)
1040 1040 ui.status(_('reset working directory to branch %s\n') % label)
1041 1041 elif label:
1042 1042 if not opts.get('force') and label in repo.branchmap():
1043 1043 if label not in [p.branch() for p in repo[None].parents()]:
1044 1044 raise error.Abort(_('a branch of the same name already'
1045 1045 ' exists'),
1046 1046 # i18n: "it" refers to an existing branch
1047 1047 hint=_("use 'hg update' to switch to it"))
1048 1048 scmutil.checknewlabel(repo, label, 'branch')
1049 1049 repo.dirstate.setbranch(label)
1050 1050 ui.status(_('marked working directory as branch %s\n') % label)
1051 1051
1052 1052 # find any open named branches aside from default
1053 1053 others = [n for n, h, t, c in repo.branchmap().iterbranches()
1054 1054 if n != "default" and not c]
1055 1055 if not others:
1056 1056 ui.status(_('(branches are permanent and global, '
1057 1057 'did you want a bookmark?)\n'))
1058 1058
1059 1059 @command('branches',
1060 1060 [('a', 'active', False,
1061 1061 _('show only branches that have unmerged heads (DEPRECATED)')),
1062 1062 ('c', 'closed', False, _('show normal and closed branches')),
1063 1063 ] + formatteropts,
1064 1064 _('[-c]'), cmdtype=readonly)
1065 1065 def branches(ui, repo, active=False, closed=False, **opts):
1066 1066 """list repository named branches
1067 1067
1068 1068 List the repository's named branches, indicating which ones are
1069 1069 inactive. If -c/--closed is specified, also list branches which have
1070 1070 been marked closed (see :hg:`commit --close-branch`).
1071 1071
1072 1072 Use the command :hg:`update` to switch to an existing branch.
1073 1073
1074 1074 Returns 0.
1075 1075 """
1076 1076
1077 1077 opts = pycompat.byteskwargs(opts)
1078 1078 ui.pager('branches')
1079 1079 fm = ui.formatter('branches', opts)
1080 1080 hexfunc = fm.hexfunc
1081 1081
1082 1082 allheads = set(repo.heads())
1083 1083 branches = []
1084 1084 for tag, heads, tip, isclosed in repo.branchmap().iterbranches():
1085 1085 isactive = False
1086 1086 if not isclosed:
1087 1087 openheads = set(repo.branchmap().iteropen(heads))
1088 1088 isactive = bool(openheads & allheads)
1089 1089 branches.append((tag, repo[tip], isactive, not isclosed))
1090 1090 branches.sort(key=lambda i: (i[2], i[1].rev(), i[0], i[3]),
1091 1091 reverse=True)
1092 1092
1093 1093 for tag, ctx, isactive, isopen in branches:
1094 1094 if active and not isactive:
1095 1095 continue
1096 1096 if isactive:
1097 1097 label = 'branches.active'
1098 1098 notice = ''
1099 1099 elif not isopen:
1100 1100 if not closed:
1101 1101 continue
1102 1102 label = 'branches.closed'
1103 1103 notice = _(' (closed)')
1104 1104 else:
1105 1105 label = 'branches.inactive'
1106 1106 notice = _(' (inactive)')
1107 1107 current = (tag == repo.dirstate.branch())
1108 1108 if current:
1109 1109 label = 'branches.current'
1110 1110
1111 1111 fm.startitem()
1112 1112 fm.write('branch', '%s', tag, label=label)
1113 1113 rev = ctx.rev()
1114 1114 padsize = max(31 - len(str(rev)) - encoding.colwidth(tag), 0)
1115 1115 fmt = ' ' * padsize + ' %d:%s'
1116 1116 fm.condwrite(not ui.quiet, 'rev node', fmt, rev, hexfunc(ctx.node()),
1117 1117 label='log.changeset changeset.%s' % ctx.phasestr())
1118 1118 fm.context(ctx=ctx)
1119 1119 fm.data(active=isactive, closed=not isopen, current=current)
1120 1120 if not ui.quiet:
1121 1121 fm.plain(notice)
1122 1122 fm.plain('\n')
1123 1123 fm.end()
1124 1124
1125 1125 @command('bundle',
1126 1126 [('f', 'force', None, _('run even when the destination is unrelated')),
1127 1127 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
1128 1128 _('REV')),
1129 1129 ('b', 'branch', [], _('a specific branch you would like to bundle'),
1130 1130 _('BRANCH')),
1131 1131 ('', 'base', [],
1132 1132 _('a base changeset assumed to be available at the destination'),
1133 1133 _('REV')),
1134 1134 ('a', 'all', None, _('bundle all changesets in the repository')),
1135 1135 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
1136 1136 ] + remoteopts,
1137 1137 _('[-f] [-t BUNDLESPEC] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
1138 1138 def bundle(ui, repo, fname, dest=None, **opts):
1139 1139 """create a bundle file
1140 1140
1141 1141 Generate a bundle file containing data to be added to a repository.
1142 1142
1143 1143 To create a bundle containing all changesets, use -a/--all
1144 1144 (or --base null). Otherwise, hg assumes the destination will have
1145 1145 all the nodes you specify with --base parameters. Otherwise, hg
1146 1146 will assume the repository has all the nodes in destination, or
1147 1147 default-push/default if no destination is specified.
1148 1148
1149 1149 You can change bundle format with the -t/--type option. See
1150 1150 :hg:`help bundlespec` for documentation on this format. By default,
1151 1151 the most appropriate format is used and compression defaults to
1152 1152 bzip2.
1153 1153
1154 1154 The bundle file can then be transferred using conventional means
1155 1155 and applied to another repository with the unbundle or pull
1156 1156 command. This is useful when direct push and pull are not
1157 1157 available or when exporting an entire repository is undesirable.
1158 1158
1159 1159 Applying bundles preserves all changeset contents including
1160 1160 permissions, copy/rename information, and revision history.
1161 1161
1162 1162 Returns 0 on success, 1 if no changes found.
1163 1163 """
1164 1164 opts = pycompat.byteskwargs(opts)
1165 1165 revs = None
1166 1166 if 'rev' in opts:
1167 1167 revstrings = opts['rev']
1168 1168 revs = scmutil.revrange(repo, revstrings)
1169 1169 if revstrings and not revs:
1170 1170 raise error.Abort(_('no commits to bundle'))
1171 1171
1172 1172 bundletype = opts.get('type', 'bzip2').lower()
1173 1173 try:
1174 1174 bcompression, cgversion, params = exchange.parsebundlespec(
1175 1175 repo, bundletype, strict=False)
1176 1176 except error.UnsupportedBundleSpecification as e:
1177 1177 raise error.Abort(str(e),
1178 1178 hint=_("see 'hg help bundlespec' for supported "
1179 1179 "values for --type"))
1180 1180
1181 1181 # Packed bundles are a pseudo bundle format for now.
1182 1182 if cgversion == 's1':
1183 1183 raise error.Abort(_('packed bundles cannot be produced by "hg bundle"'),
1184 1184 hint=_("use 'hg debugcreatestreamclonebundle'"))
1185 1185
1186 1186 if opts.get('all'):
1187 1187 if dest:
1188 1188 raise error.Abort(_("--all is incompatible with specifying "
1189 1189 "a destination"))
1190 1190 if opts.get('base'):
1191 1191 ui.warn(_("ignoring --base because --all was specified\n"))
1192 1192 base = ['null']
1193 1193 else:
1194 1194 base = scmutil.revrange(repo, opts.get('base'))
1195 1195 if cgversion not in changegroup.supportedoutgoingversions(repo):
1196 1196 raise error.Abort(_("repository does not support bundle version %s") %
1197 1197 cgversion)
1198 1198
1199 1199 if base:
1200 1200 if dest:
1201 1201 raise error.Abort(_("--base is incompatible with specifying "
1202 1202 "a destination"))
1203 1203 common = [repo.lookup(rev) for rev in base]
1204 1204 heads = revs and map(repo.lookup, revs) or None
1205 1205 outgoing = discovery.outgoing(repo, common, heads)
1206 1206 else:
1207 1207 dest = ui.expandpath(dest or 'default-push', dest or 'default')
1208 1208 dest, branches = hg.parseurl(dest, opts.get('branch'))
1209 1209 other = hg.peer(repo, opts, dest)
1210 1210 revs, checkout = hg.addbranchrevs(repo, repo, branches, revs)
1211 1211 heads = revs and map(repo.lookup, revs) or revs
1212 1212 outgoing = discovery.findcommonoutgoing(repo, other,
1213 1213 onlyheads=heads,
1214 1214 force=opts.get('force'),
1215 1215 portable=True)
1216 1216
1217 1217 if not outgoing.missing:
1218 1218 scmutil.nochangesfound(ui, repo, not base and outgoing.excluded)
1219 1219 return 1
1220 1220
1221 1221 if cgversion == '01': #bundle1
1222 1222 if bcompression is None:
1223 1223 bcompression = 'UN'
1224 1224 bversion = 'HG10' + bcompression
1225 1225 bcompression = None
1226 1226 elif cgversion in ('02', '03'):
1227 1227 bversion = 'HG20'
1228 1228 else:
1229 1229 raise error.ProgrammingError(
1230 1230 'bundle: unexpected changegroup version %s' % cgversion)
1231 1231
1232 1232 # TODO compression options should be derived from bundlespec parsing.
1233 1233 # This is a temporary hack to allow adjusting bundle compression
1234 1234 # level without a) formalizing the bundlespec changes to declare it
1235 1235 # b) introducing a command flag.
1236 1236 compopts = {}
1237 1237 complevel = ui.configint('experimental', 'bundlecomplevel')
1238 1238 if complevel is not None:
1239 1239 compopts['level'] = complevel
1240 1240
1241 1241
1242 1242 contentopts = {'cg.version': cgversion}
1243 1243 if repo.ui.configbool('experimental', 'evolution.bundle-obsmarker'):
1244 1244 contentopts['obsolescence'] = True
1245 1245 if repo.ui.configbool('experimental', 'bundle-phases'):
1246 1246 contentopts['phases'] = True
1247 1247 bundle2.writenewbundle(ui, repo, 'bundle', fname, bversion, outgoing,
1248 1248 contentopts, compression=bcompression,
1249 1249 compopts=compopts)
1250 1250
1251 1251 @command('cat',
1252 1252 [('o', 'output', '',
1253 1253 _('print output to file with formatted name'), _('FORMAT')),
1254 1254 ('r', 'rev', '', _('print the given revision'), _('REV')),
1255 1255 ('', 'decode', None, _('apply any matching decode filter')),
1256 1256 ] + walkopts + formatteropts,
1257 1257 _('[OPTION]... FILE...'),
1258 1258 inferrepo=True, cmdtype=readonly)
1259 1259 def cat(ui, repo, file1, *pats, **opts):
1260 1260 """output the current or given revision of files
1261 1261
1262 1262 Print the specified files as they were at the given revision. If
1263 1263 no revision is given, the parent of the working directory is used.
1264 1264
1265 1265 Output may be to a file, in which case the name of the file is
1266 1266 given using a format string. The formatting rules as follows:
1267 1267
1268 1268 :``%%``: literal "%" character
1269 1269 :``%s``: basename of file being printed
1270 1270 :``%d``: dirname of file being printed, or '.' if in repository root
1271 1271 :``%p``: root-relative path name of file being printed
1272 1272 :``%H``: changeset hash (40 hexadecimal digits)
1273 1273 :``%R``: changeset revision number
1274 1274 :``%h``: short-form changeset hash (12 hexadecimal digits)
1275 1275 :``%r``: zero-padded changeset revision number
1276 1276 :``%b``: basename of the exporting repository
1277 1277
1278 1278 Returns 0 on success.
1279 1279 """
1280 1280 ctx = scmutil.revsingle(repo, opts.get('rev'))
1281 1281 m = scmutil.match(ctx, (file1,) + pats, opts)
1282 1282 fntemplate = opts.pop('output', '')
1283 1283 if cmdutil.isstdiofilename(fntemplate):
1284 1284 fntemplate = ''
1285 1285
1286 1286 if fntemplate:
1287 1287 fm = formatter.nullformatter(ui, 'cat')
1288 1288 else:
1289 1289 ui.pager('cat')
1290 1290 fm = ui.formatter('cat', opts)
1291 1291 with fm:
1292 1292 return cmdutil.cat(ui, repo, ctx, m, fm, fntemplate, '', **opts)
1293 1293
1294 1294 @command('^clone',
1295 1295 [('U', 'noupdate', None, _('the clone will include an empty working '
1296 1296 'directory (only a repository)')),
1297 1297 ('u', 'updaterev', '', _('revision, tag, or branch to check out'),
1298 1298 _('REV')),
1299 1299 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
1300 1300 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
1301 1301 ('', 'pull', None, _('use pull protocol to copy metadata')),
1302 1302 ('', 'uncompressed', None,
1303 1303 _('an alias to --stream (DEPRECATED)')),
1304 1304 ('', 'stream', None,
1305 1305 _('clone with minimal data processing')),
1306 1306 ] + remoteopts,
1307 1307 _('[OPTION]... SOURCE [DEST]'),
1308 1308 norepo=True)
1309 1309 def clone(ui, source, dest=None, **opts):
1310 1310 """make a copy of an existing repository
1311 1311
1312 1312 Create a copy of an existing repository in a new directory.
1313 1313
1314 1314 If no destination directory name is specified, it defaults to the
1315 1315 basename of the source.
1316 1316
1317 1317 The location of the source is added to the new repository's
1318 1318 ``.hg/hgrc`` file, as the default to be used for future pulls.
1319 1319
1320 1320 Only local paths and ``ssh://`` URLs are supported as
1321 1321 destinations. For ``ssh://`` destinations, no working directory or
1322 1322 ``.hg/hgrc`` will be created on the remote side.
1323 1323
1324 1324 If the source repository has a bookmark called '@' set, that
1325 1325 revision will be checked out in the new repository by default.
1326 1326
1327 1327 To check out a particular version, use -u/--update, or
1328 1328 -U/--noupdate to create a clone with no working directory.
1329 1329
1330 1330 To pull only a subset of changesets, specify one or more revisions
1331 1331 identifiers with -r/--rev or branches with -b/--branch. The
1332 1332 resulting clone will contain only the specified changesets and
1333 1333 their ancestors. These options (or 'clone src#rev dest') imply
1334 1334 --pull, even for local source repositories.
1335 1335
1336 1336 In normal clone mode, the remote normalizes repository data into a common
1337 1337 exchange format and the receiving end translates this data into its local
1338 1338 storage format. --stream activates a different clone mode that essentially
1339 1339 copies repository files from the remote with minimal data processing. This
1340 1340 significantly reduces the CPU cost of a clone both remotely and locally.
1341 1341 However, it often increases the transferred data size by 30-40%. This can
1342 1342 result in substantially faster clones where I/O throughput is plentiful,
1343 1343 especially for larger repositories. A side-effect of --stream clones is
1344 1344 that storage settings and requirements on the remote are applied locally:
1345 1345 a modern client may inherit legacy or inefficient storage used by the
1346 1346 remote or a legacy Mercurial client may not be able to clone from a
1347 1347 modern Mercurial remote.
1348 1348
1349 1349 .. note::
1350 1350
1351 1351 Specifying a tag will include the tagged changeset but not the
1352 1352 changeset containing the tag.
1353 1353
1354 1354 .. container:: verbose
1355 1355
1356 1356 For efficiency, hardlinks are used for cloning whenever the
1357 1357 source and destination are on the same filesystem (note this
1358 1358 applies only to the repository data, not to the working
1359 1359 directory). Some filesystems, such as AFS, implement hardlinking
1360 1360 incorrectly, but do not report errors. In these cases, use the
1361 1361 --pull option to avoid hardlinking.
1362 1362
1363 1363 Mercurial will update the working directory to the first applicable
1364 1364 revision from this list:
1365 1365
1366 1366 a) null if -U or the source repository has no changesets
1367 1367 b) if -u . and the source repository is local, the first parent of
1368 1368 the source repository's working directory
1369 1369 c) the changeset specified with -u (if a branch name, this means the
1370 1370 latest head of that branch)
1371 1371 d) the changeset specified with -r
1372 1372 e) the tipmost head specified with -b
1373 1373 f) the tipmost head specified with the url#branch source syntax
1374 1374 g) the revision marked with the '@' bookmark, if present
1375 1375 h) the tipmost head of the default branch
1376 1376 i) tip
1377 1377
1378 1378 When cloning from servers that support it, Mercurial may fetch
1379 1379 pre-generated data from a server-advertised URL. When this is done,
1380 1380 hooks operating on incoming changesets and changegroups may fire twice,
1381 1381 once for the bundle fetched from the URL and another for any additional
1382 1382 data not fetched from this URL. In addition, if an error occurs, the
1383 1383 repository may be rolled back to a partial clone. This behavior may
1384 1384 change in future releases. See :hg:`help -e clonebundles` for more.
1385 1385
1386 1386 Examples:
1387 1387
1388 1388 - clone a remote repository to a new directory named hg/::
1389 1389
1390 1390 hg clone https://www.mercurial-scm.org/repo/hg/
1391 1391
1392 1392 - create a lightweight local clone::
1393 1393
1394 1394 hg clone project/ project-feature/
1395 1395
1396 1396 - clone from an absolute path on an ssh server (note double-slash)::
1397 1397
1398 1398 hg clone ssh://user@server//home/projects/alpha/
1399 1399
1400 1400 - do a streaming clone while checking out a specified version::
1401 1401
1402 1402 hg clone --stream http://server/repo -u 1.5
1403 1403
1404 1404 - create a repository without changesets after a particular revision::
1405 1405
1406 1406 hg clone -r 04e544 experimental/ good/
1407 1407
1408 1408 - clone (and track) a particular named branch::
1409 1409
1410 1410 hg clone https://www.mercurial-scm.org/repo/hg/#stable
1411 1411
1412 1412 See :hg:`help urls` for details on specifying URLs.
1413 1413
1414 1414 Returns 0 on success.
1415 1415 """
1416 1416 opts = pycompat.byteskwargs(opts)
1417 1417 if opts.get('noupdate') and opts.get('updaterev'):
1418 1418 raise error.Abort(_("cannot specify both --noupdate and --updaterev"))
1419 1419
1420 1420 r = hg.clone(ui, opts, source, dest,
1421 1421 pull=opts.get('pull'),
1422 1422 stream=opts.get('stream') or opts.get('uncompressed'),
1423 1423 rev=opts.get('rev'),
1424 1424 update=opts.get('updaterev') or not opts.get('noupdate'),
1425 1425 branch=opts.get('branch'),
1426 1426 shareopts=opts.get('shareopts'))
1427 1427
1428 1428 return r is None
1429 1429
1430 1430 @command('^commit|ci',
1431 1431 [('A', 'addremove', None,
1432 1432 _('mark new/missing files as added/removed before committing')),
1433 1433 ('', 'close-branch', None,
1434 1434 _('mark a branch head as closed')),
1435 1435 ('', 'amend', None, _('amend the parent of the working directory')),
1436 1436 ('s', 'secret', None, _('use the secret phase for committing')),
1437 1437 ('e', 'edit', None, _('invoke editor on commit messages')),
1438 1438 ('i', 'interactive', None, _('use interactive mode')),
1439 1439 ] + walkopts + commitopts + commitopts2 + subrepoopts,
1440 1440 _('[OPTION]... [FILE]...'),
1441 1441 inferrepo=True)
1442 1442 def commit(ui, repo, *pats, **opts):
1443 1443 """commit the specified files or all outstanding changes
1444 1444
1445 1445 Commit changes to the given files into the repository. Unlike a
1446 1446 centralized SCM, this operation is a local operation. See
1447 1447 :hg:`push` for a way to actively distribute your changes.
1448 1448
1449 1449 If a list of files is omitted, all changes reported by :hg:`status`
1450 1450 will be committed.
1451 1451
1452 1452 If you are committing the result of a merge, do not provide any
1453 1453 filenames or -I/-X filters.
1454 1454
1455 1455 If no commit message is specified, Mercurial starts your
1456 1456 configured editor where you can enter a message. In case your
1457 1457 commit fails, you will find a backup of your message in
1458 1458 ``.hg/last-message.txt``.
1459 1459
1460 1460 The --close-branch flag can be used to mark the current branch
1461 1461 head closed. When all heads of a branch are closed, the branch
1462 1462 will be considered closed and no longer listed.
1463 1463
1464 1464 The --amend flag can be used to amend the parent of the
1465 1465 working directory with a new commit that contains the changes
1466 1466 in the parent in addition to those currently reported by :hg:`status`,
1467 1467 if there are any. The old commit is stored in a backup bundle in
1468 1468 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
1469 1469 on how to restore it).
1470 1470
1471 1471 Message, user and date are taken from the amended commit unless
1472 1472 specified. When a message isn't specified on the command line,
1473 1473 the editor will open with the message of the amended commit.
1474 1474
1475 1475 It is not possible to amend public changesets (see :hg:`help phases`)
1476 1476 or changesets that have children.
1477 1477
1478 1478 See :hg:`help dates` for a list of formats valid for -d/--date.
1479 1479
1480 1480 Returns 0 on success, 1 if nothing changed.
1481 1481
1482 1482 .. container:: verbose
1483 1483
1484 1484 Examples:
1485 1485
1486 1486 - commit all files ending in .py::
1487 1487
1488 1488 hg commit --include "set:**.py"
1489 1489
1490 1490 - commit all non-binary files::
1491 1491
1492 1492 hg commit --exclude "set:binary()"
1493 1493
1494 1494 - amend the current commit and set the date to now::
1495 1495
1496 1496 hg commit --amend --date now
1497 1497 """
1498 1498 wlock = lock = None
1499 1499 try:
1500 1500 wlock = repo.wlock()
1501 1501 lock = repo.lock()
1502 1502 return _docommit(ui, repo, *pats, **opts)
1503 1503 finally:
1504 1504 release(lock, wlock)
1505 1505
1506 1506 def _docommit(ui, repo, *pats, **opts):
1507 1507 if opts.get(r'interactive'):
1508 1508 opts.pop(r'interactive')
1509 1509 ret = cmdutil.dorecord(ui, repo, commit, None, False,
1510 1510 cmdutil.recordfilter, *pats,
1511 1511 **opts)
1512 1512 # ret can be 0 (no changes to record) or the value returned by
1513 1513 # commit(), 1 if nothing changed or None on success.
1514 1514 return 1 if ret == 0 else ret
1515 1515
1516 1516 opts = pycompat.byteskwargs(opts)
1517 1517 if opts.get('subrepos'):
1518 1518 if opts.get('amend'):
1519 1519 raise error.Abort(_('cannot amend with --subrepos'))
1520 1520 # Let --subrepos on the command line override config setting.
1521 1521 ui.setconfig('ui', 'commitsubrepos', True, 'commit')
1522 1522
1523 1523 cmdutil.checkunfinished(repo, commit=True)
1524 1524
1525 1525 branch = repo[None].branch()
1526 1526 bheads = repo.branchheads(branch)
1527 1527
1528 1528 extra = {}
1529 1529 if opts.get('close_branch'):
1530 1530 extra['close'] = 1
1531 1531
1532 1532 if not bheads:
1533 1533 raise error.Abort(_('can only close branch heads'))
1534 1534 elif opts.get('amend'):
1535 1535 if repo[None].parents()[0].p1().branch() != branch and \
1536 1536 repo[None].parents()[0].p2().branch() != branch:
1537 1537 raise error.Abort(_('can only close branch heads'))
1538 1538
1539 1539 if opts.get('amend'):
1540 1540 if ui.configbool('ui', 'commitsubrepos'):
1541 1541 raise error.Abort(_('cannot amend with ui.commitsubrepos enabled'))
1542 1542
1543 1543 old = repo['.']
1544 1544 if not old.mutable():
1545 1545 raise error.Abort(_('cannot amend public changesets'))
1546 1546 if len(repo[None].parents()) > 1:
1547 1547 raise error.Abort(_('cannot amend while merging'))
1548 1548 allowunstable = obsolete.isenabled(repo, obsolete.allowunstableopt)
1549 1549 if not allowunstable and old.children():
1550 1550 raise error.Abort(_('cannot amend changeset with children'))
1551 1551
1552 1552 # Currently histedit gets confused if an amend happens while histedit
1553 1553 # is in progress. Since we have a checkunfinished command, we are
1554 1554 # temporarily honoring it.
1555 1555 #
1556 1556 # Note: eventually this guard will be removed. Please do not expect
1557 1557 # this behavior to remain.
1558 1558 if not obsolete.isenabled(repo, obsolete.createmarkersopt):
1559 1559 cmdutil.checkunfinished(repo)
1560 1560
1561 1561 node = cmdutil.amend(ui, repo, old, extra, pats, opts)
1562 1562 if node == old.node():
1563 1563 ui.status(_("nothing changed\n"))
1564 1564 return 1
1565 1565 else:
1566 1566 def commitfunc(ui, repo, message, match, opts):
1567 1567 overrides = {}
1568 1568 if opts.get('secret'):
1569 1569 overrides[('phases', 'new-commit')] = 'secret'
1570 1570
1571 1571 baseui = repo.baseui
1572 1572 with baseui.configoverride(overrides, 'commit'):
1573 1573 with ui.configoverride(overrides, 'commit'):
1574 1574 editform = cmdutil.mergeeditform(repo[None],
1575 1575 'commit.normal')
1576 1576 editor = cmdutil.getcommiteditor(
1577 1577 editform=editform, **pycompat.strkwargs(opts))
1578 1578 return repo.commit(message,
1579 1579 opts.get('user'),
1580 1580 opts.get('date'),
1581 1581 match,
1582 1582 editor=editor,
1583 1583 extra=extra)
1584 1584
1585 1585 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1586 1586
1587 1587 if not node:
1588 1588 stat = cmdutil.postcommitstatus(repo, pats, opts)
1589 1589 if stat[3]:
1590 1590 ui.status(_("nothing changed (%d missing files, see "
1591 1591 "'hg status')\n") % len(stat[3]))
1592 1592 else:
1593 1593 ui.status(_("nothing changed\n"))
1594 1594 return 1
1595 1595
1596 1596 cmdutil.commitstatus(repo, node, branch, bheads, opts)
1597 1597
1598 1598 @command('config|showconfig|debugconfig',
1599 1599 [('u', 'untrusted', None, _('show untrusted configuration options')),
1600 1600 ('e', 'edit', None, _('edit user config')),
1601 1601 ('l', 'local', None, _('edit repository config')),
1602 1602 ('g', 'global', None, _('edit global config'))] + formatteropts,
1603 1603 _('[-u] [NAME]...'),
1604 1604 optionalrepo=True, cmdtype=readonly)
1605 1605 def config(ui, repo, *values, **opts):
1606 1606 """show combined config settings from all hgrc files
1607 1607
1608 1608 With no arguments, print names and values of all config items.
1609 1609
1610 1610 With one argument of the form section.name, print just the value
1611 1611 of that config item.
1612 1612
1613 1613 With multiple arguments, print names and values of all config
1614 1614 items with matching section names.
1615 1615
1616 1616 With --edit, start an editor on the user-level config file. With
1617 1617 --global, edit the system-wide config file. With --local, edit the
1618 1618 repository-level config file.
1619 1619
1620 1620 With --debug, the source (filename and line number) is printed
1621 1621 for each config item.
1622 1622
1623 1623 See :hg:`help config` for more information about config files.
1624 1624
1625 1625 Returns 0 on success, 1 if NAME does not exist.
1626 1626
1627 1627 """
1628 1628
1629 1629 opts = pycompat.byteskwargs(opts)
1630 1630 if opts.get('edit') or opts.get('local') or opts.get('global'):
1631 1631 if opts.get('local') and opts.get('global'):
1632 1632 raise error.Abort(_("can't use --local and --global together"))
1633 1633
1634 1634 if opts.get('local'):
1635 1635 if not repo:
1636 1636 raise error.Abort(_("can't use --local outside a repository"))
1637 1637 paths = [repo.vfs.join('hgrc')]
1638 1638 elif opts.get('global'):
1639 1639 paths = rcutil.systemrcpath()
1640 1640 else:
1641 1641 paths = rcutil.userrcpath()
1642 1642
1643 1643 for f in paths:
1644 1644 if os.path.exists(f):
1645 1645 break
1646 1646 else:
1647 1647 if opts.get('global'):
1648 1648 samplehgrc = uimod.samplehgrcs['global']
1649 1649 elif opts.get('local'):
1650 1650 samplehgrc = uimod.samplehgrcs['local']
1651 1651 else:
1652 1652 samplehgrc = uimod.samplehgrcs['user']
1653 1653
1654 1654 f = paths[0]
1655 1655 fp = open(f, "wb")
1656 1656 fp.write(util.tonativeeol(samplehgrc))
1657 1657 fp.close()
1658 1658
1659 1659 editor = ui.geteditor()
1660 1660 ui.system("%s \"%s\"" % (editor, f),
1661 1661 onerr=error.Abort, errprefix=_("edit failed"),
1662 1662 blockedtag='config_edit')
1663 1663 return
1664 1664 ui.pager('config')
1665 1665 fm = ui.formatter('config', opts)
1666 1666 for t, f in rcutil.rccomponents():
1667 1667 if t == 'path':
1668 1668 ui.debug('read config from: %s\n' % f)
1669 1669 elif t == 'items':
1670 1670 for section, name, value, source in f:
1671 1671 ui.debug('set config by: %s\n' % source)
1672 1672 else:
1673 1673 raise error.ProgrammingError('unknown rctype: %s' % t)
1674 1674 untrusted = bool(opts.get('untrusted'))
1675 1675 if values:
1676 1676 sections = [v for v in values if '.' not in v]
1677 1677 items = [v for v in values if '.' in v]
1678 1678 if len(items) > 1 or items and sections:
1679 1679 raise error.Abort(_('only one config item permitted'))
1680 1680 matched = False
1681 1681 for section, name, value in ui.walkconfig(untrusted=untrusted):
1682 1682 source = ui.configsource(section, name, untrusted)
1683 1683 value = pycompat.bytestr(value)
1684 1684 if fm.isplain():
1685 1685 source = source or 'none'
1686 1686 value = value.replace('\n', '\\n')
1687 1687 entryname = section + '.' + name
1688 1688 if values:
1689 1689 for v in values:
1690 1690 if v == section:
1691 1691 fm.startitem()
1692 1692 fm.condwrite(ui.debugflag, 'source', '%s: ', source)
1693 1693 fm.write('name value', '%s=%s\n', entryname, value)
1694 1694 matched = True
1695 1695 elif v == entryname:
1696 1696 fm.startitem()
1697 1697 fm.condwrite(ui.debugflag, 'source', '%s: ', source)
1698 1698 fm.write('value', '%s\n', value)
1699 1699 fm.data(name=entryname)
1700 1700 matched = True
1701 1701 else:
1702 1702 fm.startitem()
1703 1703 fm.condwrite(ui.debugflag, 'source', '%s: ', source)
1704 1704 fm.write('name value', '%s=%s\n', entryname, value)
1705 1705 matched = True
1706 1706 fm.end()
1707 1707 if matched:
1708 1708 return 0
1709 1709 return 1
1710 1710
1711 1711 @command('copy|cp',
1712 1712 [('A', 'after', None, _('record a copy that has already occurred')),
1713 1713 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1714 1714 ] + walkopts + dryrunopts,
1715 1715 _('[OPTION]... [SOURCE]... DEST'))
1716 1716 def copy(ui, repo, *pats, **opts):
1717 1717 """mark files as copied for the next commit
1718 1718
1719 1719 Mark dest as having copies of source files. If dest is a
1720 1720 directory, copies are put in that directory. If dest is a file,
1721 1721 the source must be a single file.
1722 1722
1723 1723 By default, this command copies the contents of files as they
1724 1724 exist in the working directory. If invoked with -A/--after, the
1725 1725 operation is recorded, but no copying is performed.
1726 1726
1727 1727 This command takes effect with the next commit. To undo a copy
1728 1728 before that, see :hg:`revert`.
1729 1729
1730 1730 Returns 0 on success, 1 if errors are encountered.
1731 1731 """
1732 1732 opts = pycompat.byteskwargs(opts)
1733 1733 with repo.wlock(False):
1734 1734 return cmdutil.copy(ui, repo, pats, opts)
1735 1735
1736 1736 @command('debugcommands', [], _('[COMMAND]'), norepo=True)
1737 1737 def debugcommands(ui, cmd='', *args):
1738 1738 """list all available commands and options"""
1739 1739 for cmd, vals in sorted(table.iteritems()):
1740 1740 cmd = cmd.split('|')[0].strip('^')
1741 1741 opts = ', '.join([i[1] for i in vals[1]])
1742 1742 ui.write('%s: %s\n' % (cmd, opts))
1743 1743
1744 1744 @command('debugcomplete',
1745 1745 [('o', 'options', None, _('show the command options'))],
1746 1746 _('[-o] CMD'),
1747 1747 norepo=True)
1748 1748 def debugcomplete(ui, cmd='', **opts):
1749 1749 """returns the completion list associated with the given command"""
1750 1750
1751 1751 if opts.get('options'):
1752 1752 options = []
1753 1753 otables = [globalopts]
1754 1754 if cmd:
1755 1755 aliases, entry = cmdutil.findcmd(cmd, table, False)
1756 1756 otables.append(entry[1])
1757 1757 for t in otables:
1758 1758 for o in t:
1759 1759 if "(DEPRECATED)" in o[3]:
1760 1760 continue
1761 1761 if o[0]:
1762 1762 options.append('-%s' % o[0])
1763 1763 options.append('--%s' % o[1])
1764 1764 ui.write("%s\n" % "\n".join(options))
1765 1765 return
1766 1766
1767 1767 cmdlist, unused_allcmds = cmdutil.findpossible(cmd, table)
1768 1768 if ui.verbose:
1769 1769 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1770 1770 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1771 1771
1772 1772 @command('^diff',
1773 1773 [('r', 'rev', [], _('revision'), _('REV')),
1774 1774 ('c', 'change', '', _('change made by revision'), _('REV'))
1775 1775 ] + diffopts + diffopts2 + walkopts + subrepoopts,
1776 1776 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'),
1777 1777 inferrepo=True, cmdtype=readonly)
1778 1778 def diff(ui, repo, *pats, **opts):
1779 1779 """diff repository (or selected files)
1780 1780
1781 1781 Show differences between revisions for the specified files.
1782 1782
1783 1783 Differences between files are shown using the unified diff format.
1784 1784
1785 1785 .. note::
1786 1786
1787 1787 :hg:`diff` may generate unexpected results for merges, as it will
1788 1788 default to comparing against the working directory's first
1789 1789 parent changeset if no revisions are specified.
1790 1790
1791 1791 When two revision arguments are given, then changes are shown
1792 1792 between those revisions. If only one revision is specified then
1793 1793 that revision is compared to the working directory, and, when no
1794 1794 revisions are specified, the working directory files are compared
1795 1795 to its first parent.
1796 1796
1797 1797 Alternatively you can specify -c/--change with a revision to see
1798 1798 the changes in that changeset relative to its first parent.
1799 1799
1800 1800 Without the -a/--text option, diff will avoid generating diffs of
1801 1801 files it detects as binary. With -a, diff will generate a diff
1802 1802 anyway, probably with undesirable results.
1803 1803
1804 1804 Use the -g/--git option to generate diffs in the git extended diff
1805 1805 format. For more information, read :hg:`help diffs`.
1806 1806
1807 1807 .. container:: verbose
1808 1808
1809 1809 Examples:
1810 1810
1811 1811 - compare a file in the current working directory to its parent::
1812 1812
1813 1813 hg diff foo.c
1814 1814
1815 1815 - compare two historical versions of a directory, with rename info::
1816 1816
1817 1817 hg diff --git -r 1.0:1.2 lib/
1818 1818
1819 1819 - get change stats relative to the last change on some date::
1820 1820
1821 1821 hg diff --stat -r "date('may 2')"
1822 1822
1823 1823 - diff all newly-added files that contain a keyword::
1824 1824
1825 1825 hg diff "set:added() and grep(GNU)"
1826 1826
1827 1827 - compare a revision and its parents::
1828 1828
1829 1829 hg diff -c 9353 # compare against first parent
1830 1830 hg diff -r 9353^:9353 # same using revset syntax
1831 1831 hg diff -r 9353^2:9353 # compare against the second parent
1832 1832
1833 1833 Returns 0 on success.
1834 1834 """
1835 1835
1836 1836 opts = pycompat.byteskwargs(opts)
1837 1837 revs = opts.get('rev')
1838 1838 change = opts.get('change')
1839 1839 stat = opts.get('stat')
1840 1840 reverse = opts.get('reverse')
1841 1841
1842 1842 if revs and change:
1843 1843 msg = _('cannot specify --rev and --change at the same time')
1844 1844 raise error.Abort(msg)
1845 1845 elif change:
1846 1846 node2 = scmutil.revsingle(repo, change, None).node()
1847 1847 node1 = repo[node2].p1().node()
1848 1848 else:
1849 1849 node1, node2 = scmutil.revpair(repo, revs)
1850 1850
1851 1851 if reverse:
1852 1852 node1, node2 = node2, node1
1853 1853
1854 1854 diffopts = patch.diffallopts(ui, opts)
1855 1855 m = scmutil.match(repo[node2], pats, opts)
1856 1856 ui.pager('diff')
1857 1857 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
1858 1858 listsubrepos=opts.get('subrepos'),
1859 1859 root=opts.get('root'))
1860 1860
1861 1861 @command('^export',
1862 1862 [('o', 'output', '',
1863 1863 _('print output to file with formatted name'), _('FORMAT')),
1864 1864 ('', 'switch-parent', None, _('diff against the second parent')),
1865 1865 ('r', 'rev', [], _('revisions to export'), _('REV')),
1866 1866 ] + diffopts,
1867 1867 _('[OPTION]... [-o OUTFILESPEC] [-r] [REV]...'), cmdtype=readonly)
1868 1868 def export(ui, repo, *changesets, **opts):
1869 1869 """dump the header and diffs for one or more changesets
1870 1870
1871 1871 Print the changeset header and diffs for one or more revisions.
1872 1872 If no revision is given, the parent of the working directory is used.
1873 1873
1874 1874 The information shown in the changeset header is: author, date,
1875 1875 branch name (if non-default), changeset hash, parent(s) and commit
1876 1876 comment.
1877 1877
1878 1878 .. note::
1879 1879
1880 1880 :hg:`export` may generate unexpected diff output for merge
1881 1881 changesets, as it will compare the merge changeset against its
1882 1882 first parent only.
1883 1883
1884 1884 Output may be to a file, in which case the name of the file is
1885 1885 given using a format string. The formatting rules are as follows:
1886 1886
1887 1887 :``%%``: literal "%" character
1888 1888 :``%H``: changeset hash (40 hexadecimal digits)
1889 1889 :``%N``: number of patches being generated
1890 1890 :``%R``: changeset revision number
1891 1891 :``%b``: basename of the exporting repository
1892 1892 :``%h``: short-form changeset hash (12 hexadecimal digits)
1893 1893 :``%m``: first line of the commit message (only alphanumeric characters)
1894 1894 :``%n``: zero-padded sequence number, starting at 1
1895 1895 :``%r``: zero-padded changeset revision number
1896 1896
1897 1897 Without the -a/--text option, export will avoid generating diffs
1898 1898 of files it detects as binary. With -a, export will generate a
1899 1899 diff anyway, probably with undesirable results.
1900 1900
1901 1901 Use the -g/--git option to generate diffs in the git extended diff
1902 1902 format. See :hg:`help diffs` for more information.
1903 1903
1904 1904 With the --switch-parent option, the diff will be against the
1905 1905 second parent. It can be useful to review a merge.
1906 1906
1907 1907 .. container:: verbose
1908 1908
1909 1909 Examples:
1910 1910
1911 1911 - use export and import to transplant a bugfix to the current
1912 1912 branch::
1913 1913
1914 1914 hg export -r 9353 | hg import -
1915 1915
1916 1916 - export all the changesets between two revisions to a file with
1917 1917 rename information::
1918 1918
1919 1919 hg export --git -r 123:150 > changes.txt
1920 1920
1921 1921 - split outgoing changes into a series of patches with
1922 1922 descriptive names::
1923 1923
1924 1924 hg export -r "outgoing()" -o "%n-%m.patch"
1925 1925
1926 1926 Returns 0 on success.
1927 1927 """
1928 1928 opts = pycompat.byteskwargs(opts)
1929 1929 changesets += tuple(opts.get('rev', []))
1930 1930 if not changesets:
1931 1931 changesets = ['.']
1932 1932 revs = scmutil.revrange(repo, changesets)
1933 1933 if not revs:
1934 1934 raise error.Abort(_("export requires at least one changeset"))
1935 1935 if len(revs) > 1:
1936 1936 ui.note(_('exporting patches:\n'))
1937 1937 else:
1938 1938 ui.note(_('exporting patch:\n'))
1939 1939 ui.pager('export')
1940 1940 cmdutil.export(repo, revs, fntemplate=opts.get('output'),
1941 1941 switch_parent=opts.get('switch_parent'),
1942 1942 opts=patch.diffallopts(ui, opts))
1943 1943
1944 1944 @command('files',
1945 1945 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
1946 1946 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
1947 1947 ] + walkopts + formatteropts + subrepoopts,
1948 1948 _('[OPTION]... [FILE]...'), cmdtype=readonly)
1949 1949 def files(ui, repo, *pats, **opts):
1950 1950 """list tracked files
1951 1951
1952 1952 Print files under Mercurial control in the working directory or
1953 1953 specified revision for given files (excluding removed files).
1954 1954 Files can be specified as filenames or filesets.
1955 1955
1956 1956 If no files are given to match, this command prints the names
1957 1957 of all files under Mercurial control.
1958 1958
1959 1959 .. container:: verbose
1960 1960
1961 1961 Examples:
1962 1962
1963 1963 - list all files under the current directory::
1964 1964
1965 1965 hg files .
1966 1966
1967 1967 - shows sizes and flags for current revision::
1968 1968
1969 1969 hg files -vr .
1970 1970
1971 1971 - list all files named README::
1972 1972
1973 1973 hg files -I "**/README"
1974 1974
1975 1975 - list all binary files::
1976 1976
1977 1977 hg files "set:binary()"
1978 1978
1979 1979 - find files containing a regular expression::
1980 1980
1981 1981 hg files "set:grep('bob')"
1982 1982
1983 1983 - search tracked file contents with xargs and grep::
1984 1984
1985 1985 hg files -0 | xargs -0 grep foo
1986 1986
1987 1987 See :hg:`help patterns` and :hg:`help filesets` for more information
1988 1988 on specifying file patterns.
1989 1989
1990 1990 Returns 0 if a match is found, 1 otherwise.
1991 1991
1992 1992 """
1993 1993
1994 1994 opts = pycompat.byteskwargs(opts)
1995 1995 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
1996 1996
1997 1997 end = '\n'
1998 1998 if opts.get('print0'):
1999 1999 end = '\0'
2000 2000 fmt = '%s' + end
2001 2001
2002 2002 m = scmutil.match(ctx, pats, opts)
2003 2003 ui.pager('files')
2004 2004 with ui.formatter('files', opts) as fm:
2005 2005 return cmdutil.files(ui, ctx, m, fm, fmt, opts.get('subrepos'))
2006 2006
2007 2007 @command('^forget', walkopts, _('[OPTION]... FILE...'), inferrepo=True)
2008 2008 def forget(ui, repo, *pats, **opts):
2009 2009 """forget the specified files on the next commit
2010 2010
2011 2011 Mark the specified files so they will no longer be tracked
2012 2012 after the next commit.
2013 2013
2014 2014 This only removes files from the current branch, not from the
2015 2015 entire project history, and it does not delete them from the
2016 2016 working directory.
2017 2017
2018 2018 To delete the file from the working directory, see :hg:`remove`.
2019 2019
2020 2020 To undo a forget before the next commit, see :hg:`add`.
2021 2021
2022 2022 .. container:: verbose
2023 2023
2024 2024 Examples:
2025 2025
2026 2026 - forget newly-added binary files::
2027 2027
2028 2028 hg forget "set:added() and binary()"
2029 2029
2030 2030 - forget files that would be excluded by .hgignore::
2031 2031
2032 2032 hg forget "set:hgignore()"
2033 2033
2034 2034 Returns 0 on success.
2035 2035 """
2036 2036
2037 2037 opts = pycompat.byteskwargs(opts)
2038 2038 if not pats:
2039 2039 raise error.Abort(_('no files specified'))
2040 2040
2041 2041 m = scmutil.match(repo[None], pats, opts)
2042 2042 rejected = cmdutil.forget(ui, repo, m, prefix="", explicitonly=False)[0]
2043 2043 return rejected and 1 or 0
2044 2044
2045 2045 @command(
2046 2046 'graft',
2047 2047 [('r', 'rev', [], _('revisions to graft'), _('REV')),
2048 2048 ('c', 'continue', False, _('resume interrupted graft')),
2049 2049 ('e', 'edit', False, _('invoke editor on commit messages')),
2050 2050 ('', 'log', None, _('append graft info to log message')),
2051 2051 ('f', 'force', False, _('force graft')),
2052 2052 ('D', 'currentdate', False,
2053 2053 _('record the current date as commit date')),
2054 2054 ('U', 'currentuser', False,
2055 2055 _('record the current user as committer'), _('DATE'))]
2056 2056 + commitopts2 + mergetoolopts + dryrunopts,
2057 2057 _('[OPTION]... [-r REV]... REV...'))
2058 2058 def graft(ui, repo, *revs, **opts):
2059 2059 '''copy changes from other branches onto the current branch
2060 2060
2061 2061 This command uses Mercurial's merge logic to copy individual
2062 2062 changes from other branches without merging branches in the
2063 2063 history graph. This is sometimes known as 'backporting' or
2064 2064 'cherry-picking'. By default, graft will copy user, date, and
2065 2065 description from the source changesets.
2066 2066
2067 2067 Changesets that are ancestors of the current revision, that have
2068 2068 already been grafted, or that are merges will be skipped.
2069 2069
2070 2070 If --log is specified, log messages will have a comment appended
2071 2071 of the form::
2072 2072
2073 2073 (grafted from CHANGESETHASH)
2074 2074
2075 2075 If --force is specified, revisions will be grafted even if they
2076 2076 are already ancestors of, or have been grafted to, the destination.
2077 2077 This is useful when the revisions have since been backed out.
2078 2078
2079 2079 If a graft merge results in conflicts, the graft process is
2080 2080 interrupted so that the current merge can be manually resolved.
2081 2081 Once all conflicts are addressed, the graft process can be
2082 2082 continued with the -c/--continue option.
2083 2083
2084 2084 .. note::
2085 2085
2086 2086 The -c/--continue option does not reapply earlier options, except
2087 2087 for --force.
2088 2088
2089 2089 .. container:: verbose
2090 2090
2091 2091 Examples:
2092 2092
2093 2093 - copy a single change to the stable branch and edit its description::
2094 2094
2095 2095 hg update stable
2096 2096 hg graft --edit 9393
2097 2097
2098 2098 - graft a range of changesets with one exception, updating dates::
2099 2099
2100 2100 hg graft -D "2085::2093 and not 2091"
2101 2101
2102 2102 - continue a graft after resolving conflicts::
2103 2103
2104 2104 hg graft -c
2105 2105
2106 2106 - show the source of a grafted changeset::
2107 2107
2108 2108 hg log --debug -r .
2109 2109
2110 2110 - show revisions sorted by date::
2111 2111
2112 2112 hg log -r "sort(all(), date)"
2113 2113
2114 2114 See :hg:`help revisions` for more about specifying revisions.
2115 2115
2116 2116 Returns 0 on successful completion.
2117 2117 '''
2118 2118 with repo.wlock():
2119 2119 return _dograft(ui, repo, *revs, **opts)
2120 2120
2121 2121 def _dograft(ui, repo, *revs, **opts):
2122 2122 opts = pycompat.byteskwargs(opts)
2123 2123 if revs and opts.get('rev'):
2124 2124 ui.warn(_('warning: inconsistent use of --rev might give unexpected '
2125 2125 'revision ordering!\n'))
2126 2126
2127 2127 revs = list(revs)
2128 2128 revs.extend(opts.get('rev'))
2129 2129
2130 2130 if not opts.get('user') and opts.get('currentuser'):
2131 2131 opts['user'] = ui.username()
2132 2132 if not opts.get('date') and opts.get('currentdate'):
2133 2133 opts['date'] = "%d %d" % util.makedate()
2134 2134
2135 2135 editor = cmdutil.getcommiteditor(editform='graft',
2136 2136 **pycompat.strkwargs(opts))
2137 2137
2138 2138 cont = False
2139 2139 if opts.get('continue'):
2140 2140 cont = True
2141 2141 if revs:
2142 2142 raise error.Abort(_("can't specify --continue and revisions"))
2143 2143 # read in unfinished revisions
2144 2144 try:
2145 2145 nodes = repo.vfs.read('graftstate').splitlines()
2146 2146 revs = [repo[node].rev() for node in nodes]
2147 2147 except IOError as inst:
2148 2148 if inst.errno != errno.ENOENT:
2149 2149 raise
2150 2150 cmdutil.wrongtooltocontinue(repo, _('graft'))
2151 2151 else:
2152 2152 cmdutil.checkunfinished(repo)
2153 2153 cmdutil.bailifchanged(repo)
2154 2154 if not revs:
2155 2155 raise error.Abort(_('no revisions specified'))
2156 2156 revs = scmutil.revrange(repo, revs)
2157 2157
2158 2158 skipped = set()
2159 2159 # check for merges
2160 2160 for rev in repo.revs('%ld and merge()', revs):
2161 2161 ui.warn(_('skipping ungraftable merge revision %d\n') % rev)
2162 2162 skipped.add(rev)
2163 2163 revs = [r for r in revs if r not in skipped]
2164 2164 if not revs:
2165 2165 return -1
2166 2166
2167 2167 # Don't check in the --continue case, in effect retaining --force across
2168 2168 # --continues. That's because without --force, any revisions we decided to
2169 2169 # skip would have been filtered out here, so they wouldn't have made their
2170 2170 # way to the graftstate. With --force, any revisions we would have otherwise
2171 2171 # skipped would not have been filtered out, and if they hadn't been applied
2172 2172 # already, they'd have been in the graftstate.
2173 2173 if not (cont or opts.get('force')):
2174 2174 # check for ancestors of dest branch
2175 2175 crev = repo['.'].rev()
2176 2176 ancestors = repo.changelog.ancestors([crev], inclusive=True)
2177 2177 # XXX make this lazy in the future
2178 2178 # don't mutate while iterating, create a copy
2179 2179 for rev in list(revs):
2180 2180 if rev in ancestors:
2181 2181 ui.warn(_('skipping ancestor revision %d:%s\n') %
2182 2182 (rev, repo[rev]))
2183 2183 # XXX remove on list is slow
2184 2184 revs.remove(rev)
2185 2185 if not revs:
2186 2186 return -1
2187 2187
2188 2188 # analyze revs for earlier grafts
2189 2189 ids = {}
2190 2190 for ctx in repo.set("%ld", revs):
2191 2191 ids[ctx.hex()] = ctx.rev()
2192 2192 n = ctx.extra().get('source')
2193 2193 if n:
2194 2194 ids[n] = ctx.rev()
2195 2195
2196 2196 # check ancestors for earlier grafts
2197 2197 ui.debug('scanning for duplicate grafts\n')
2198 2198
2199 2199 # The only changesets we can be sure doesn't contain grafts of any
2200 2200 # revs, are the ones that are common ancestors of *all* revs:
2201 2201 for rev in repo.revs('only(%d,ancestor(%ld))', crev, revs):
2202 2202 ctx = repo[rev]
2203 2203 n = ctx.extra().get('source')
2204 2204 if n in ids:
2205 2205 try:
2206 2206 r = repo[n].rev()
2207 2207 except error.RepoLookupError:
2208 2208 r = None
2209 2209 if r in revs:
2210 2210 ui.warn(_('skipping revision %d:%s '
2211 2211 '(already grafted to %d:%s)\n')
2212 2212 % (r, repo[r], rev, ctx))
2213 2213 revs.remove(r)
2214 2214 elif ids[n] in revs:
2215 2215 if r is None:
2216 2216 ui.warn(_('skipping already grafted revision %d:%s '
2217 2217 '(%d:%s also has unknown origin %s)\n')
2218 2218 % (ids[n], repo[ids[n]], rev, ctx, n[:12]))
2219 2219 else:
2220 2220 ui.warn(_('skipping already grafted revision %d:%s '
2221 2221 '(%d:%s also has origin %d:%s)\n')
2222 2222 % (ids[n], repo[ids[n]], rev, ctx, r, n[:12]))
2223 2223 revs.remove(ids[n])
2224 2224 elif ctx.hex() in ids:
2225 2225 r = ids[ctx.hex()]
2226 2226 ui.warn(_('skipping already grafted revision %d:%s '
2227 2227 '(was grafted from %d:%s)\n') %
2228 2228 (r, repo[r], rev, ctx))
2229 2229 revs.remove(r)
2230 2230 if not revs:
2231 2231 return -1
2232 2232
2233 2233 for pos, ctx in enumerate(repo.set("%ld", revs)):
2234 2234 desc = '%d:%s "%s"' % (ctx.rev(), ctx,
2235 2235 ctx.description().split('\n', 1)[0])
2236 2236 names = repo.nodetags(ctx.node()) + repo.nodebookmarks(ctx.node())
2237 2237 if names:
2238 2238 desc += ' (%s)' % ' '.join(names)
2239 2239 ui.status(_('grafting %s\n') % desc)
2240 2240 if opts.get('dry_run'):
2241 2241 continue
2242 2242
2243 2243 source = ctx.extra().get('source')
2244 2244 extra = {}
2245 2245 if source:
2246 2246 extra['source'] = source
2247 2247 extra['intermediate-source'] = ctx.hex()
2248 2248 else:
2249 2249 extra['source'] = ctx.hex()
2250 2250 user = ctx.user()
2251 2251 if opts.get('user'):
2252 2252 user = opts['user']
2253 2253 date = ctx.date()
2254 2254 if opts.get('date'):
2255 2255 date = opts['date']
2256 2256 message = ctx.description()
2257 2257 if opts.get('log'):
2258 2258 message += '\n(grafted from %s)' % ctx.hex()
2259 2259
2260 2260 # we don't merge the first commit when continuing
2261 2261 if not cont:
2262 2262 # perform the graft merge with p1(rev) as 'ancestor'
2263 2263 try:
2264 2264 # ui.forcemerge is an internal variable, do not document
2265 2265 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
2266 2266 'graft')
2267 2267 stats = mergemod.graft(repo, ctx, ctx.p1(),
2268 2268 ['local', 'graft'])
2269 2269 finally:
2270 2270 repo.ui.setconfig('ui', 'forcemerge', '', 'graft')
2271 2271 # report any conflicts
2272 2272 if stats and stats[3] > 0:
2273 2273 # write out state for --continue
2274 2274 nodelines = [repo[rev].hex() + "\n" for rev in revs[pos:]]
2275 2275 repo.vfs.write('graftstate', ''.join(nodelines))
2276 2276 extra = ''
2277 2277 if opts.get('user'):
2278 2278 extra += ' --user %s' % util.shellquote(opts['user'])
2279 2279 if opts.get('date'):
2280 2280 extra += ' --date %s' % util.shellquote(opts['date'])
2281 2281 if opts.get('log'):
2282 2282 extra += ' --log'
2283 2283 hint=_("use 'hg resolve' and 'hg graft --continue%s'") % extra
2284 2284 raise error.Abort(
2285 2285 _("unresolved conflicts, can't continue"),
2286 2286 hint=hint)
2287 2287 else:
2288 2288 cont = False
2289 2289
2290 2290 # commit
2291 2291 node = repo.commit(text=message, user=user,
2292 2292 date=date, extra=extra, editor=editor)
2293 2293 if node is None:
2294 2294 ui.warn(
2295 2295 _('note: graft of %d:%s created no changes to commit\n') %
2296 2296 (ctx.rev(), ctx))
2297 2297
2298 2298 # remove state when we complete successfully
2299 2299 if not opts.get('dry_run'):
2300 2300 repo.vfs.unlinkpath('graftstate', ignoremissing=True)
2301 2301
2302 2302 return 0
2303 2303
2304 2304 @command('grep',
2305 2305 [('0', 'print0', None, _('end fields with NUL')),
2306 2306 ('', 'all', None, _('print all revisions that match')),
2307 2307 ('a', 'text', None, _('treat all files as text')),
2308 2308 ('f', 'follow', None,
2309 2309 _('follow changeset history,'
2310 2310 ' or file history across copies and renames')),
2311 2311 ('i', 'ignore-case', None, _('ignore case when matching')),
2312 2312 ('l', 'files-with-matches', None,
2313 2313 _('print only filenames and revisions that match')),
2314 2314 ('n', 'line-number', None, _('print matching line numbers')),
2315 2315 ('r', 'rev', [],
2316 2316 _('only search files changed within revision range'), _('REV')),
2317 2317 ('u', 'user', None, _('list the author (long with -v)')),
2318 2318 ('d', 'date', None, _('list the date (short with -q)')),
2319 2319 ] + formatteropts + walkopts,
2320 2320 _('[OPTION]... PATTERN [FILE]...'),
2321 2321 inferrepo=True, cmdtype=readonly)
2322 2322 def grep(ui, repo, pattern, *pats, **opts):
2323 2323 """search revision history for a pattern in specified files
2324 2324
2325 2325 Search revision history for a regular expression in the specified
2326 2326 files or the entire project.
2327 2327
2328 2328 By default, grep prints the most recent revision number for each
2329 2329 file in which it finds a match. To get it to print every revision
2330 2330 that contains a change in match status ("-" for a match that becomes
2331 2331 a non-match, or "+" for a non-match that becomes a match), use the
2332 2332 --all flag.
2333 2333
2334 2334 PATTERN can be any Python (roughly Perl-compatible) regular
2335 2335 expression.
2336 2336
2337 2337 If no FILEs are specified (and -f/--follow isn't set), all files in
2338 2338 the repository are searched, including those that don't exist in the
2339 2339 current branch or have been deleted in a prior changeset.
2340 2340
2341 2341 Returns 0 if a match is found, 1 otherwise.
2342 2342 """
2343 2343 opts = pycompat.byteskwargs(opts)
2344 2344 reflags = re.M
2345 2345 if opts.get('ignore_case'):
2346 2346 reflags |= re.I
2347 2347 try:
2348 2348 regexp = util.re.compile(pattern, reflags)
2349 2349 except re.error as inst:
2350 2350 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
2351 2351 return 1
2352 2352 sep, eol = ':', '\n'
2353 2353 if opts.get('print0'):
2354 2354 sep = eol = '\0'
2355 2355
2356 2356 getfile = util.lrucachefunc(repo.file)
2357 2357
2358 2358 def matchlines(body):
2359 2359 begin = 0
2360 2360 linenum = 0
2361 2361 while begin < len(body):
2362 2362 match = regexp.search(body, begin)
2363 2363 if not match:
2364 2364 break
2365 2365 mstart, mend = match.span()
2366 2366 linenum += body.count('\n', begin, mstart) + 1
2367 2367 lstart = body.rfind('\n', begin, mstart) + 1 or begin
2368 2368 begin = body.find('\n', mend) + 1 or len(body) + 1
2369 2369 lend = begin - 1
2370 2370 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
2371 2371
2372 2372 class linestate(object):
2373 2373 def __init__(self, line, linenum, colstart, colend):
2374 2374 self.line = line
2375 2375 self.linenum = linenum
2376 2376 self.colstart = colstart
2377 2377 self.colend = colend
2378 2378
2379 2379 def __hash__(self):
2380 2380 return hash((self.linenum, self.line))
2381 2381
2382 2382 def __eq__(self, other):
2383 2383 return self.line == other.line
2384 2384
2385 2385 def findpos(self):
2386 2386 """Iterate all (start, end) indices of matches"""
2387 2387 yield self.colstart, self.colend
2388 2388 p = self.colend
2389 2389 while p < len(self.line):
2390 2390 m = regexp.search(self.line, p)
2391 2391 if not m:
2392 2392 break
2393 2393 yield m.span()
2394 2394 p = m.end()
2395 2395
2396 2396 matches = {}
2397 2397 copies = {}
2398 2398 def grepbody(fn, rev, body):
2399 2399 matches[rev].setdefault(fn, [])
2400 2400 m = matches[rev][fn]
2401 2401 for lnum, cstart, cend, line in matchlines(body):
2402 2402 s = linestate(line, lnum, cstart, cend)
2403 2403 m.append(s)
2404 2404
2405 2405 def difflinestates(a, b):
2406 2406 sm = difflib.SequenceMatcher(None, a, b)
2407 2407 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2408 2408 if tag == 'insert':
2409 2409 for i in xrange(blo, bhi):
2410 2410 yield ('+', b[i])
2411 2411 elif tag == 'delete':
2412 2412 for i in xrange(alo, ahi):
2413 2413 yield ('-', a[i])
2414 2414 elif tag == 'replace':
2415 2415 for i in xrange(alo, ahi):
2416 2416 yield ('-', a[i])
2417 2417 for i in xrange(blo, bhi):
2418 2418 yield ('+', b[i])
2419 2419
2420 2420 def display(fm, fn, ctx, pstates, states):
2421 2421 rev = ctx.rev()
2422 2422 if fm.isplain():
2423 2423 formatuser = ui.shortuser
2424 2424 else:
2425 2425 formatuser = str
2426 2426 if ui.quiet:
2427 2427 datefmt = '%Y-%m-%d'
2428 2428 else:
2429 2429 datefmt = '%a %b %d %H:%M:%S %Y %1%2'
2430 2430 found = False
2431 2431 @util.cachefunc
2432 2432 def binary():
2433 2433 flog = getfile(fn)
2434 2434 return util.binary(flog.read(ctx.filenode(fn)))
2435 2435
2436 2436 fieldnamemap = {'filename': 'file', 'linenumber': 'line_number'}
2437 2437 if opts.get('all'):
2438 2438 iter = difflinestates(pstates, states)
2439 2439 else:
2440 2440 iter = [('', l) for l in states]
2441 2441 for change, l in iter:
2442 2442 fm.startitem()
2443 2443 fm.data(node=fm.hexfunc(ctx.node()))
2444 2444 cols = [
2445 2445 ('filename', fn, True),
2446 2446 ('rev', rev, True),
2447 2447 ('linenumber', l.linenum, opts.get('line_number')),
2448 2448 ]
2449 2449 if opts.get('all'):
2450 2450 cols.append(('change', change, True))
2451 2451 cols.extend([
2452 2452 ('user', formatuser(ctx.user()), opts.get('user')),
2453 2453 ('date', fm.formatdate(ctx.date(), datefmt), opts.get('date')),
2454 2454 ])
2455 2455 lastcol = next(name for name, data, cond in reversed(cols) if cond)
2456 2456 for name, data, cond in cols:
2457 2457 field = fieldnamemap.get(name, name)
2458 2458 fm.condwrite(cond, field, '%s', data, label='grep.%s' % name)
2459 2459 if cond and name != lastcol:
2460 2460 fm.plain(sep, label='grep.sep')
2461 2461 if not opts.get('files_with_matches'):
2462 2462 fm.plain(sep, label='grep.sep')
2463 2463 if not opts.get('text') and binary():
2464 2464 fm.plain(_(" Binary file matches"))
2465 2465 else:
2466 2466 displaymatches(fm.nested('texts'), l)
2467 2467 fm.plain(eol)
2468 2468 found = True
2469 2469 if opts.get('files_with_matches'):
2470 2470 break
2471 2471 return found
2472 2472
2473 2473 def displaymatches(fm, l):
2474 2474 p = 0
2475 2475 for s, e in l.findpos():
2476 2476 if p < s:
2477 2477 fm.startitem()
2478 2478 fm.write('text', '%s', l.line[p:s])
2479 2479 fm.data(matched=False)
2480 2480 fm.startitem()
2481 2481 fm.write('text', '%s', l.line[s:e], label='grep.match')
2482 2482 fm.data(matched=True)
2483 2483 p = e
2484 2484 if p < len(l.line):
2485 2485 fm.startitem()
2486 2486 fm.write('text', '%s', l.line[p:])
2487 2487 fm.data(matched=False)
2488 2488 fm.end()
2489 2489
2490 2490 skip = {}
2491 2491 revfiles = {}
2492 2492 match = scmutil.match(repo[None], pats, opts)
2493 2493 found = False
2494 2494 follow = opts.get('follow')
2495 2495
2496 2496 def prep(ctx, fns):
2497 2497 rev = ctx.rev()
2498 2498 pctx = ctx.p1()
2499 2499 parent = pctx.rev()
2500 2500 matches.setdefault(rev, {})
2501 2501 matches.setdefault(parent, {})
2502 2502 files = revfiles.setdefault(rev, [])
2503 2503 for fn in fns:
2504 2504 flog = getfile(fn)
2505 2505 try:
2506 2506 fnode = ctx.filenode(fn)
2507 2507 except error.LookupError:
2508 2508 continue
2509 2509
2510 2510 copied = flog.renamed(fnode)
2511 2511 copy = follow and copied and copied[0]
2512 2512 if copy:
2513 2513 copies.setdefault(rev, {})[fn] = copy
2514 2514 if fn in skip:
2515 2515 if copy:
2516 2516 skip[copy] = True
2517 2517 continue
2518 2518 files.append(fn)
2519 2519
2520 2520 if fn not in matches[rev]:
2521 2521 grepbody(fn, rev, flog.read(fnode))
2522 2522
2523 2523 pfn = copy or fn
2524 2524 if pfn not in matches[parent]:
2525 2525 try:
2526 2526 fnode = pctx.filenode(pfn)
2527 2527 grepbody(pfn, parent, flog.read(fnode))
2528 2528 except error.LookupError:
2529 2529 pass
2530 2530
2531 2531 ui.pager('grep')
2532 2532 fm = ui.formatter('grep', opts)
2533 2533 for ctx in cmdutil.walkchangerevs(repo, match, opts, prep):
2534 2534 rev = ctx.rev()
2535 2535 parent = ctx.p1().rev()
2536 2536 for fn in sorted(revfiles.get(rev, [])):
2537 2537 states = matches[rev][fn]
2538 2538 copy = copies.get(rev, {}).get(fn)
2539 2539 if fn in skip:
2540 2540 if copy:
2541 2541 skip[copy] = True
2542 2542 continue
2543 2543 pstates = matches.get(parent, {}).get(copy or fn, [])
2544 2544 if pstates or states:
2545 2545 r = display(fm, fn, ctx, pstates, states)
2546 2546 found = found or r
2547 2547 if r and not opts.get('all'):
2548 2548 skip[fn] = True
2549 2549 if copy:
2550 2550 skip[copy] = True
2551 2551 del matches[rev]
2552 2552 del revfiles[rev]
2553 2553 fm.end()
2554 2554
2555 2555 return not found
2556 2556
2557 2557 @command('heads',
2558 2558 [('r', 'rev', '',
2559 2559 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
2560 2560 ('t', 'topo', False, _('show topological heads only')),
2561 2561 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
2562 2562 ('c', 'closed', False, _('show normal and closed branch heads')),
2563 2563 ] + templateopts,
2564 2564 _('[-ct] [-r STARTREV] [REV]...'), cmdtype=readonly)
2565 2565 def heads(ui, repo, *branchrevs, **opts):
2566 2566 """show branch heads
2567 2567
2568 2568 With no arguments, show all open branch heads in the repository.
2569 2569 Branch heads are changesets that have no descendants on the
2570 2570 same branch. They are where development generally takes place and
2571 2571 are the usual targets for update and merge operations.
2572 2572
2573 2573 If one or more REVs are given, only open branch heads on the
2574 2574 branches associated with the specified changesets are shown. This
2575 2575 means that you can use :hg:`heads .` to see the heads on the
2576 2576 currently checked-out branch.
2577 2577
2578 2578 If -c/--closed is specified, also show branch heads marked closed
2579 2579 (see :hg:`commit --close-branch`).
2580 2580
2581 2581 If STARTREV is specified, only those heads that are descendants of
2582 2582 STARTREV will be displayed.
2583 2583
2584 2584 If -t/--topo is specified, named branch mechanics will be ignored and only
2585 2585 topological heads (changesets with no children) will be shown.
2586 2586
2587 2587 Returns 0 if matching heads are found, 1 if not.
2588 2588 """
2589 2589
2590 2590 opts = pycompat.byteskwargs(opts)
2591 2591 start = None
2592 2592 if 'rev' in opts:
2593 2593 start = scmutil.revsingle(repo, opts['rev'], None).node()
2594 2594
2595 2595 if opts.get('topo'):
2596 2596 heads = [repo[h] for h in repo.heads(start)]
2597 2597 else:
2598 2598 heads = []
2599 2599 for branch in repo.branchmap():
2600 2600 heads += repo.branchheads(branch, start, opts.get('closed'))
2601 2601 heads = [repo[h] for h in heads]
2602 2602
2603 2603 if branchrevs:
2604 2604 branches = set(repo[br].branch() for br in branchrevs)
2605 2605 heads = [h for h in heads if h.branch() in branches]
2606 2606
2607 2607 if opts.get('active') and branchrevs:
2608 2608 dagheads = repo.heads(start)
2609 2609 heads = [h for h in heads if h.node() in dagheads]
2610 2610
2611 2611 if branchrevs:
2612 2612 haveheads = set(h.branch() for h in heads)
2613 2613 if branches - haveheads:
2614 2614 headless = ', '.join(b for b in branches - haveheads)
2615 2615 msg = _('no open branch heads found on branches %s')
2616 2616 if opts.get('rev'):
2617 2617 msg += _(' (started at %s)') % opts['rev']
2618 2618 ui.warn((msg + '\n') % headless)
2619 2619
2620 2620 if not heads:
2621 2621 return 1
2622 2622
2623 2623 ui.pager('heads')
2624 2624 heads = sorted(heads, key=lambda x: -x.rev())
2625 2625 displayer = cmdutil.show_changeset(ui, repo, opts)
2626 2626 for ctx in heads:
2627 2627 displayer.show(ctx)
2628 2628 displayer.close()
2629 2629
2630 2630 @command('help',
2631 2631 [('e', 'extension', None, _('show only help for extensions')),
2632 2632 ('c', 'command', None, _('show only help for commands')),
2633 2633 ('k', 'keyword', None, _('show topics matching keyword')),
2634 2634 ('s', 'system', [], _('show help for specific platform(s)')),
2635 2635 ],
2636 2636 _('[-ecks] [TOPIC]'),
2637 2637 norepo=True, cmdtype=readonly)
2638 2638 def help_(ui, name=None, **opts):
2639 2639 """show help for a given topic or a help overview
2640 2640
2641 2641 With no arguments, print a list of commands with short help messages.
2642 2642
2643 2643 Given a topic, extension, or command name, print help for that
2644 2644 topic.
2645 2645
2646 2646 Returns 0 if successful.
2647 2647 """
2648 2648
2649 2649 keep = opts.get(r'system') or []
2650 2650 if len(keep) == 0:
2651 2651 if pycompat.sysplatform.startswith('win'):
2652 2652 keep.append('windows')
2653 2653 elif pycompat.sysplatform == 'OpenVMS':
2654 2654 keep.append('vms')
2655 2655 elif pycompat.sysplatform == 'plan9':
2656 2656 keep.append('plan9')
2657 2657 else:
2658 2658 keep.append('unix')
2659 2659 keep.append(pycompat.sysplatform.lower())
2660 2660 if ui.verbose:
2661 2661 keep.append('verbose')
2662 2662
2663 2663 commands = sys.modules[__name__]
2664 2664 formatted = help.formattedhelp(ui, commands, name, keep=keep, **opts)
2665 2665 ui.pager('help')
2666 2666 ui.write(formatted)
2667 2667
2668 2668
2669 2669 @command('identify|id',
2670 2670 [('r', 'rev', '',
2671 2671 _('identify the specified revision'), _('REV')),
2672 2672 ('n', 'num', None, _('show local revision number')),
2673 2673 ('i', 'id', None, _('show global revision id')),
2674 2674 ('b', 'branch', None, _('show branch')),
2675 2675 ('t', 'tags', None, _('show tags')),
2676 2676 ('B', 'bookmarks', None, _('show bookmarks')),
2677 2677 ] + remoteopts + formatteropts,
2678 2678 _('[-nibtB] [-r REV] [SOURCE]'),
2679 2679 optionalrepo=True, cmdtype=readonly)
2680 2680 def identify(ui, repo, source=None, rev=None,
2681 2681 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
2682 2682 """identify the working directory or specified revision
2683 2683
2684 2684 Print a summary identifying the repository state at REV using one or
2685 2685 two parent hash identifiers, followed by a "+" if the working
2686 2686 directory has uncommitted changes, the branch name (if not default),
2687 2687 a list of tags, and a list of bookmarks.
2688 2688
2689 2689 When REV is not given, print a summary of the current state of the
2690 2690 repository.
2691 2691
2692 2692 Specifying a path to a repository root or Mercurial bundle will
2693 2693 cause lookup to operate on that repository/bundle.
2694 2694
2695 2695 .. container:: verbose
2696 2696
2697 2697 Examples:
2698 2698
2699 2699 - generate a build identifier for the working directory::
2700 2700
2701 2701 hg id --id > build-id.dat
2702 2702
2703 2703 - find the revision corresponding to a tag::
2704 2704
2705 2705 hg id -n -r 1.3
2706 2706
2707 2707 - check the most recent revision of a remote repository::
2708 2708
2709 2709 hg id -r tip https://www.mercurial-scm.org/repo/hg/
2710 2710
2711 2711 See :hg:`log` for generating more information about specific revisions,
2712 2712 including full hash identifiers.
2713 2713
2714 2714 Returns 0 if successful.
2715 2715 """
2716 2716
2717 2717 opts = pycompat.byteskwargs(opts)
2718 2718 if not repo and not source:
2719 2719 raise error.Abort(_("there is no Mercurial repository here "
2720 2720 "(.hg not found)"))
2721 2721
2722 2722 if ui.debugflag:
2723 2723 hexfunc = hex
2724 2724 else:
2725 2725 hexfunc = short
2726 2726 default = not (num or id or branch or tags or bookmarks)
2727 2727 output = []
2728 2728 revs = []
2729 2729
2730 2730 if source:
2731 2731 source, branches = hg.parseurl(ui.expandpath(source))
2732 2732 peer = hg.peer(repo or ui, opts, source) # only pass ui when no repo
2733 2733 repo = peer.local()
2734 2734 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
2735 2735
2736 2736 fm = ui.formatter('identify', opts)
2737 2737 fm.startitem()
2738 2738
2739 2739 if not repo:
2740 2740 if num or branch or tags:
2741 2741 raise error.Abort(
2742 2742 _("can't query remote revision number, branch, or tags"))
2743 2743 if not rev and revs:
2744 2744 rev = revs[0]
2745 2745 if not rev:
2746 2746 rev = "tip"
2747 2747
2748 2748 remoterev = peer.lookup(rev)
2749 2749 hexrev = hexfunc(remoterev)
2750 2750 if default or id:
2751 2751 output = [hexrev]
2752 2752 fm.data(id=hexrev)
2753 2753
2754 2754 def getbms():
2755 2755 bms = []
2756 2756
2757 2757 if 'bookmarks' in peer.listkeys('namespaces'):
2758 2758 hexremoterev = hex(remoterev)
2759 2759 bms = [bm for bm, bmr in peer.listkeys('bookmarks').iteritems()
2760 2760 if bmr == hexremoterev]
2761 2761
2762 2762 return sorted(bms)
2763 2763
2764 2764 bms = getbms()
2765 2765 if bookmarks:
2766 2766 output.extend(bms)
2767 2767 elif default and not ui.quiet:
2768 2768 # multiple bookmarks for a single parent separated by '/'
2769 2769 bm = '/'.join(bms)
2770 2770 if bm:
2771 2771 output.append(bm)
2772 2772
2773 2773 fm.data(node=hex(remoterev))
2774 2774 fm.data(bookmarks=fm.formatlist(bms, name='bookmark'))
2775 2775 else:
2776 2776 ctx = scmutil.revsingle(repo, rev, None)
2777 2777
2778 2778 if ctx.rev() is None:
2779 2779 ctx = repo[None]
2780 2780 parents = ctx.parents()
2781 2781 taglist = []
2782 2782 for p in parents:
2783 2783 taglist.extend(p.tags())
2784 2784
2785 2785 dirty = ""
2786 2786 if ctx.dirty(missing=True, merge=False, branch=False):
2787 2787 dirty = '+'
2788 2788 fm.data(dirty=dirty)
2789 2789
2790 2790 hexoutput = [hexfunc(p.node()) for p in parents]
2791 2791 if default or id:
2792 2792 output = ["%s%s" % ('+'.join(hexoutput), dirty)]
2793 2793 fm.data(id="%s%s" % ('+'.join(hexoutput), dirty))
2794 2794
2795 2795 if num:
2796 2796 numoutput = ["%d" % p.rev() for p in parents]
2797 2797 output.append("%s%s" % ('+'.join(numoutput), dirty))
2798 2798
2799 2799 fn = fm.nested('parents')
2800 2800 for p in parents:
2801 2801 fn.startitem()
2802 2802 fn.data(rev=p.rev())
2803 2803 fn.data(node=p.hex())
2804 2804 fn.context(ctx=p)
2805 2805 fn.end()
2806 2806 else:
2807 2807 hexoutput = hexfunc(ctx.node())
2808 2808 if default or id:
2809 2809 output = [hexoutput]
2810 2810 fm.data(id=hexoutput)
2811 2811
2812 2812 if num:
2813 2813 output.append(pycompat.bytestr(ctx.rev()))
2814 2814 taglist = ctx.tags()
2815 2815
2816 2816 if default and not ui.quiet:
2817 2817 b = ctx.branch()
2818 2818 if b != 'default':
2819 2819 output.append("(%s)" % b)
2820 2820
2821 2821 # multiple tags for a single parent separated by '/'
2822 2822 t = '/'.join(taglist)
2823 2823 if t:
2824 2824 output.append(t)
2825 2825
2826 2826 # multiple bookmarks for a single parent separated by '/'
2827 2827 bm = '/'.join(ctx.bookmarks())
2828 2828 if bm:
2829 2829 output.append(bm)
2830 2830 else:
2831 2831 if branch:
2832 2832 output.append(ctx.branch())
2833 2833
2834 2834 if tags:
2835 2835 output.extend(taglist)
2836 2836
2837 2837 if bookmarks:
2838 2838 output.extend(ctx.bookmarks())
2839 2839
2840 2840 fm.data(node=ctx.hex())
2841 2841 fm.data(branch=ctx.branch())
2842 2842 fm.data(tags=fm.formatlist(taglist, name='tag', sep=':'))
2843 2843 fm.data(bookmarks=fm.formatlist(ctx.bookmarks(), name='bookmark'))
2844 2844 fm.context(ctx=ctx)
2845 2845
2846 2846 fm.plain("%s\n" % ' '.join(output))
2847 2847 fm.end()
2848 2848
2849 2849 @command('import|patch',
2850 2850 [('p', 'strip', 1,
2851 2851 _('directory strip option for patch. This has the same '
2852 2852 'meaning as the corresponding patch option'), _('NUM')),
2853 2853 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
2854 2854 ('e', 'edit', False, _('invoke editor on commit messages')),
2855 2855 ('f', 'force', None,
2856 2856 _('skip check for outstanding uncommitted changes (DEPRECATED)')),
2857 2857 ('', 'no-commit', None,
2858 2858 _("don't commit, just update the working directory")),
2859 2859 ('', 'bypass', None,
2860 2860 _("apply patch without touching the working directory")),
2861 2861 ('', 'partial', None,
2862 2862 _('commit even if some hunks fail')),
2863 2863 ('', 'exact', None,
2864 2864 _('abort if patch would apply lossily')),
2865 2865 ('', 'prefix', '',
2866 2866 _('apply patch to subdirectory'), _('DIR')),
2867 2867 ('', 'import-branch', None,
2868 2868 _('use any branch information in patch (implied by --exact)'))] +
2869 2869 commitopts + commitopts2 + similarityopts,
2870 2870 _('[OPTION]... PATCH...'))
2871 2871 def import_(ui, repo, patch1=None, *patches, **opts):
2872 2872 """import an ordered set of patches
2873 2873
2874 2874 Import a list of patches and commit them individually (unless
2875 2875 --no-commit is specified).
2876 2876
2877 2877 To read a patch from standard input (stdin), use "-" as the patch
2878 2878 name. If a URL is specified, the patch will be downloaded from
2879 2879 there.
2880 2880
2881 2881 Import first applies changes to the working directory (unless
2882 2882 --bypass is specified), import will abort if there are outstanding
2883 2883 changes.
2884 2884
2885 2885 Use --bypass to apply and commit patches directly to the
2886 2886 repository, without affecting the working directory. Without
2887 2887 --exact, patches will be applied on top of the working directory
2888 2888 parent revision.
2889 2889
2890 2890 You can import a patch straight from a mail message. Even patches
2891 2891 as attachments work (to use the body part, it must have type
2892 2892 text/plain or text/x-patch). From and Subject headers of email
2893 2893 message are used as default committer and commit message. All
2894 2894 text/plain body parts before first diff are added to the commit
2895 2895 message.
2896 2896
2897 2897 If the imported patch was generated by :hg:`export`, user and
2898 2898 description from patch override values from message headers and
2899 2899 body. Values given on command line with -m/--message and -u/--user
2900 2900 override these.
2901 2901
2902 2902 If --exact is specified, import will set the working directory to
2903 2903 the parent of each patch before applying it, and will abort if the
2904 2904 resulting changeset has a different ID than the one recorded in
2905 2905 the patch. This will guard against various ways that portable
2906 2906 patch formats and mail systems might fail to transfer Mercurial
2907 2907 data or metadata. See :hg:`bundle` for lossless transmission.
2908 2908
2909 2909 Use --partial to ensure a changeset will be created from the patch
2910 2910 even if some hunks fail to apply. Hunks that fail to apply will be
2911 2911 written to a <target-file>.rej file. Conflicts can then be resolved
2912 2912 by hand before :hg:`commit --amend` is run to update the created
2913 2913 changeset. This flag exists to let people import patches that
2914 2914 partially apply without losing the associated metadata (author,
2915 2915 date, description, ...).
2916 2916
2917 2917 .. note::
2918 2918
2919 2919 When no hunks apply cleanly, :hg:`import --partial` will create
2920 2920 an empty changeset, importing only the patch metadata.
2921 2921
2922 2922 With -s/--similarity, hg will attempt to discover renames and
2923 2923 copies in the patch in the same way as :hg:`addremove`.
2924 2924
2925 2925 It is possible to use external patch programs to perform the patch
2926 2926 by setting the ``ui.patch`` configuration option. For the default
2927 2927 internal tool, the fuzz can also be configured via ``patch.fuzz``.
2928 2928 See :hg:`help config` for more information about configuration
2929 2929 files and how to use these options.
2930 2930
2931 2931 See :hg:`help dates` for a list of formats valid for -d/--date.
2932 2932
2933 2933 .. container:: verbose
2934 2934
2935 2935 Examples:
2936 2936
2937 2937 - import a traditional patch from a website and detect renames::
2938 2938
2939 2939 hg import -s 80 http://example.com/bugfix.patch
2940 2940
2941 2941 - import a changeset from an hgweb server::
2942 2942
2943 2943 hg import https://www.mercurial-scm.org/repo/hg/rev/5ca8c111e9aa
2944 2944
2945 2945 - import all the patches in an Unix-style mbox::
2946 2946
2947 2947 hg import incoming-patches.mbox
2948 2948
2949 2949 - import patches from stdin::
2950 2950
2951 2951 hg import -
2952 2952
2953 2953 - attempt to exactly restore an exported changeset (not always
2954 2954 possible)::
2955 2955
2956 2956 hg import --exact proposed-fix.patch
2957 2957
2958 2958 - use an external tool to apply a patch which is too fuzzy for
2959 2959 the default internal tool.
2960 2960
2961 2961 hg import --config ui.patch="patch --merge" fuzzy.patch
2962 2962
2963 2963 - change the default fuzzing from 2 to a less strict 7
2964 2964
2965 2965 hg import --config ui.fuzz=7 fuzz.patch
2966 2966
2967 2967 Returns 0 on success, 1 on partial success (see --partial).
2968 2968 """
2969 2969
2970 2970 opts = pycompat.byteskwargs(opts)
2971 2971 if not patch1:
2972 2972 raise error.Abort(_('need at least one patch to import'))
2973 2973
2974 2974 patches = (patch1,) + patches
2975 2975
2976 2976 date = opts.get('date')
2977 2977 if date:
2978 2978 opts['date'] = util.parsedate(date)
2979 2979
2980 2980 exact = opts.get('exact')
2981 2981 update = not opts.get('bypass')
2982 2982 if not update and opts.get('no_commit'):
2983 2983 raise error.Abort(_('cannot use --no-commit with --bypass'))
2984 2984 try:
2985 2985 sim = float(opts.get('similarity') or 0)
2986 2986 except ValueError:
2987 2987 raise error.Abort(_('similarity must be a number'))
2988 2988 if sim < 0 or sim > 100:
2989 2989 raise error.Abort(_('similarity must be between 0 and 100'))
2990 2990 if sim and not update:
2991 2991 raise error.Abort(_('cannot use --similarity with --bypass'))
2992 2992 if exact:
2993 2993 if opts.get('edit'):
2994 2994 raise error.Abort(_('cannot use --exact with --edit'))
2995 2995 if opts.get('prefix'):
2996 2996 raise error.Abort(_('cannot use --exact with --prefix'))
2997 2997
2998 2998 base = opts["base"]
2999 2999 wlock = dsguard = lock = tr = None
3000 3000 msgs = []
3001 3001 ret = 0
3002 3002
3003 3003
3004 3004 try:
3005 3005 wlock = repo.wlock()
3006 3006
3007 3007 if update:
3008 3008 cmdutil.checkunfinished(repo)
3009 3009 if (exact or not opts.get('force')):
3010 3010 cmdutil.bailifchanged(repo)
3011 3011
3012 3012 if not opts.get('no_commit'):
3013 3013 lock = repo.lock()
3014 3014 tr = repo.transaction('import')
3015 3015 else:
3016 3016 dsguard = dirstateguard.dirstateguard(repo, 'import')
3017 3017 parents = repo[None].parents()
3018 3018 for patchurl in patches:
3019 3019 if patchurl == '-':
3020 3020 ui.status(_('applying patch from stdin\n'))
3021 3021 patchfile = ui.fin
3022 3022 patchurl = 'stdin' # for error message
3023 3023 else:
3024 3024 patchurl = os.path.join(base, patchurl)
3025 3025 ui.status(_('applying %s\n') % patchurl)
3026 3026 patchfile = hg.openpath(ui, patchurl)
3027 3027
3028 3028 haspatch = False
3029 3029 for hunk in patch.split(patchfile):
3030 3030 (msg, node, rej) = cmdutil.tryimportone(ui, repo, hunk,
3031 3031 parents, opts,
3032 3032 msgs, hg.clean)
3033 3033 if msg:
3034 3034 haspatch = True
3035 3035 ui.note(msg + '\n')
3036 3036 if update or exact:
3037 3037 parents = repo[None].parents()
3038 3038 else:
3039 3039 parents = [repo[node]]
3040 3040 if rej:
3041 3041 ui.write_err(_("patch applied partially\n"))
3042 3042 ui.write_err(_("(fix the .rej files and run "
3043 3043 "`hg commit --amend`)\n"))
3044 3044 ret = 1
3045 3045 break
3046 3046
3047 3047 if not haspatch:
3048 3048 raise error.Abort(_('%s: no diffs found') % patchurl)
3049 3049
3050 3050 if tr:
3051 3051 tr.close()
3052 3052 if msgs:
3053 3053 repo.savecommitmessage('\n* * *\n'.join(msgs))
3054 3054 if dsguard:
3055 3055 dsguard.close()
3056 3056 return ret
3057 3057 finally:
3058 3058 if tr:
3059 3059 tr.release()
3060 3060 release(lock, dsguard, wlock)
3061 3061
3062 3062 @command('incoming|in',
3063 3063 [('f', 'force', None,
3064 3064 _('run even if remote repository is unrelated')),
3065 3065 ('n', 'newest-first', None, _('show newest record first')),
3066 3066 ('', 'bundle', '',
3067 3067 _('file to store the bundles into'), _('FILE')),
3068 3068 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3069 3069 ('B', 'bookmarks', False, _("compare bookmarks")),
3070 3070 ('b', 'branch', [],
3071 3071 _('a specific branch you would like to pull'), _('BRANCH')),
3072 3072 ] + logopts + remoteopts + subrepoopts,
3073 3073 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3074 3074 def incoming(ui, repo, source="default", **opts):
3075 3075 """show new changesets found in source
3076 3076
3077 3077 Show new changesets found in the specified path/URL or the default
3078 3078 pull location. These are the changesets that would have been pulled
3079 3079 by :hg:`pull` at the time you issued this command.
3080 3080
3081 3081 See pull for valid source format details.
3082 3082
3083 3083 .. container:: verbose
3084 3084
3085 3085 With -B/--bookmarks, the result of bookmark comparison between
3086 3086 local and remote repositories is displayed. With -v/--verbose,
3087 3087 status is also displayed for each bookmark like below::
3088 3088
3089 3089 BM1 01234567890a added
3090 3090 BM2 1234567890ab advanced
3091 3091 BM3 234567890abc diverged
3092 3092 BM4 34567890abcd changed
3093 3093
3094 3094 The action taken locally when pulling depends on the
3095 3095 status of each bookmark:
3096 3096
3097 3097 :``added``: pull will create it
3098 3098 :``advanced``: pull will update it
3099 3099 :``diverged``: pull will create a divergent bookmark
3100 3100 :``changed``: result depends on remote changesets
3101 3101
3102 3102 From the point of view of pulling behavior, bookmark
3103 3103 existing only in the remote repository are treated as ``added``,
3104 3104 even if it is in fact locally deleted.
3105 3105
3106 3106 .. container:: verbose
3107 3107
3108 3108 For remote repository, using --bundle avoids downloading the
3109 3109 changesets twice if the incoming is followed by a pull.
3110 3110
3111 3111 Examples:
3112 3112
3113 3113 - show incoming changes with patches and full description::
3114 3114
3115 3115 hg incoming -vp
3116 3116
3117 3117 - show incoming changes excluding merges, store a bundle::
3118 3118
3119 3119 hg in -vpM --bundle incoming.hg
3120 3120 hg pull incoming.hg
3121 3121
3122 3122 - briefly list changes inside a bundle::
3123 3123
3124 3124 hg in changes.hg -T "{desc|firstline}\\n"
3125 3125
3126 3126 Returns 0 if there are incoming changes, 1 otherwise.
3127 3127 """
3128 3128 opts = pycompat.byteskwargs(opts)
3129 3129 if opts.get('graph'):
3130 3130 cmdutil.checkunsupportedgraphflags([], opts)
3131 3131 def display(other, chlist, displayer):
3132 3132 revdag = cmdutil.graphrevs(other, chlist, opts)
3133 3133 cmdutil.displaygraph(ui, repo, revdag, displayer,
3134 3134 graphmod.asciiedges)
3135 3135
3136 3136 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
3137 3137 return 0
3138 3138
3139 3139 if opts.get('bundle') and opts.get('subrepos'):
3140 3140 raise error.Abort(_('cannot combine --bundle and --subrepos'))
3141 3141
3142 3142 if opts.get('bookmarks'):
3143 3143 source, branches = hg.parseurl(ui.expandpath(source),
3144 3144 opts.get('branch'))
3145 3145 other = hg.peer(repo, opts, source)
3146 3146 if 'bookmarks' not in other.listkeys('namespaces'):
3147 3147 ui.warn(_("remote doesn't support bookmarks\n"))
3148 3148 return 0
3149 3149 ui.pager('incoming')
3150 3150 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3151 3151 return bookmarks.incoming(ui, repo, other)
3152 3152
3153 3153 repo._subtoppath = ui.expandpath(source)
3154 3154 try:
3155 3155 return hg.incoming(ui, repo, source, opts)
3156 3156 finally:
3157 3157 del repo._subtoppath
3158 3158
3159 3159
3160 3160 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'),
3161 3161 norepo=True)
3162 3162 def init(ui, dest=".", **opts):
3163 3163 """create a new repository in the given directory
3164 3164
3165 3165 Initialize a new repository in the given directory. If the given
3166 3166 directory does not exist, it will be created.
3167 3167
3168 3168 If no directory is given, the current directory is used.
3169 3169
3170 3170 It is possible to specify an ``ssh://`` URL as the destination.
3171 3171 See :hg:`help urls` for more information.
3172 3172
3173 3173 Returns 0 on success.
3174 3174 """
3175 3175 opts = pycompat.byteskwargs(opts)
3176 3176 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3177 3177
3178 3178 @command('locate',
3179 3179 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3180 3180 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3181 3181 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3182 3182 ] + walkopts,
3183 3183 _('[OPTION]... [PATTERN]...'))
3184 3184 def locate(ui, repo, *pats, **opts):
3185 3185 """locate files matching specific patterns (DEPRECATED)
3186 3186
3187 3187 Print files under Mercurial control in the working directory whose
3188 3188 names match the given patterns.
3189 3189
3190 3190 By default, this command searches all directories in the working
3191 3191 directory. To search just the current directory and its
3192 3192 subdirectories, use "--include .".
3193 3193
3194 3194 If no patterns are given to match, this command prints the names
3195 3195 of all files under Mercurial control in the working directory.
3196 3196
3197 3197 If you want to feed the output of this command into the "xargs"
3198 3198 command, use the -0 option to both this command and "xargs". This
3199 3199 will avoid the problem of "xargs" treating single filenames that
3200 3200 contain whitespace as multiple filenames.
3201 3201
3202 3202 See :hg:`help files` for a more versatile command.
3203 3203
3204 3204 Returns 0 if a match is found, 1 otherwise.
3205 3205 """
3206 3206 opts = pycompat.byteskwargs(opts)
3207 3207 if opts.get('print0'):
3208 3208 end = '\0'
3209 3209 else:
3210 3210 end = '\n'
3211 3211 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
3212 3212
3213 3213 ret = 1
3214 3214 ctx = repo[rev]
3215 3215 m = scmutil.match(ctx, pats, opts, default='relglob',
3216 3216 badfn=lambda x, y: False)
3217 3217
3218 3218 ui.pager('locate')
3219 3219 for abs in ctx.matches(m):
3220 3220 if opts.get('fullpath'):
3221 3221 ui.write(repo.wjoin(abs), end)
3222 3222 else:
3223 3223 ui.write(((pats and m.rel(abs)) or abs), end)
3224 3224 ret = 0
3225 3225
3226 3226 return ret
3227 3227
3228 3228 @command('^log|history',
3229 3229 [('f', 'follow', None,
3230 3230 _('follow changeset history, or file history across copies and renames')),
3231 3231 ('', 'follow-first', None,
3232 3232 _('only follow the first parent of merge changesets (DEPRECATED)')),
3233 3233 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3234 3234 ('C', 'copies', None, _('show copied files')),
3235 3235 ('k', 'keyword', [],
3236 3236 _('do case-insensitive search for a given text'), _('TEXT')),
3237 3237 ('r', 'rev', [], _('show the specified revision or revset'), _('REV')),
3238 3238 ('L', 'line-range', [],
3239 3239 _('follow line range of specified file (EXPERIMENTAL)'),
3240 3240 _('FILE,RANGE')),
3241 3241 ('', 'removed', None, _('include revisions where files were removed')),
3242 3242 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
3243 3243 ('u', 'user', [], _('revisions committed by user'), _('USER')),
3244 3244 ('', 'only-branch', [],
3245 3245 _('show only changesets within the given named branch (DEPRECATED)'),
3246 3246 _('BRANCH')),
3247 3247 ('b', 'branch', [],
3248 3248 _('show changesets within the given named branch'), _('BRANCH')),
3249 3249 ('P', 'prune', [],
3250 3250 _('do not display revision or any of its ancestors'), _('REV')),
3251 3251 ] + logopts + walkopts,
3252 3252 _('[OPTION]... [FILE]'),
3253 3253 inferrepo=True, cmdtype=readonly)
3254 3254 def log(ui, repo, *pats, **opts):
3255 3255 """show revision history of entire repository or files
3256 3256
3257 3257 Print the revision history of the specified files or the entire
3258 3258 project.
3259 3259
3260 3260 If no revision range is specified, the default is ``tip:0`` unless
3261 3261 --follow is set, in which case the working directory parent is
3262 3262 used as the starting revision.
3263 3263
3264 3264 File history is shown without following rename or copy history of
3265 3265 files. Use -f/--follow with a filename to follow history across
3266 3266 renames and copies. --follow without a filename will only show
3267 3267 ancestors or descendants of the starting revision.
3268 3268
3269 3269 By default this command prints revision number and changeset id,
3270 3270 tags, non-trivial parents, user, date and time, and a summary for
3271 3271 each commit. When the -v/--verbose switch is used, the list of
3272 3272 changed files and full commit message are shown.
3273 3273
3274 3274 With --graph the revisions are shown as an ASCII art DAG with the most
3275 3275 recent changeset at the top.
3276 3276 'o' is a changeset, '@' is a working directory parent, 'x' is obsolete,
3277 3277 and '+' represents a fork where the changeset from the lines below is a
3278 3278 parent of the 'o' merge on the same line.
3279 3279 Paths in the DAG are represented with '|', '/' and so forth. ':' in place
3280 3280 of a '|' indicates one or more revisions in a path are omitted.
3281 3281
3282 3282 .. container:: verbose
3283 3283
3284 3284 Use -L/--line-range FILE,M:N options to follow the history of lines
3285 3285 from M to N in FILE. With -p/--patch only diff hunks affecting
3286 3286 specified line range will be shown. This option requires --follow;
3287 3287 it can be specified multiple times. Currently, this option is not
3288 3288 compatible with --graph. This option is experimental.
3289 3289
3290 3290 .. note::
3291 3291
3292 3292 :hg:`log --patch` may generate unexpected diff output for merge
3293 3293 changesets, as it will only compare the merge changeset against
3294 3294 its first parent. Also, only files different from BOTH parents
3295 3295 will appear in files:.
3296 3296
3297 3297 .. note::
3298 3298
3299 3299 For performance reasons, :hg:`log FILE` may omit duplicate changes
3300 3300 made on branches and will not show removals or mode changes. To
3301 3301 see all such changes, use the --removed switch.
3302 3302
3303 3303 .. container:: verbose
3304 3304
3305 3305 .. note::
3306 3306
3307 3307 The history resulting from -L/--line-range options depends on diff
3308 3308 options; for instance if white-spaces are ignored, respective changes
3309 3309 with only white-spaces in specified line range will not be listed.
3310 3310
3311 3311 .. container:: verbose
3312 3312
3313 3313 Some examples:
3314 3314
3315 3315 - changesets with full descriptions and file lists::
3316 3316
3317 3317 hg log -v
3318 3318
3319 3319 - changesets ancestral to the working directory::
3320 3320
3321 3321 hg log -f
3322 3322
3323 3323 - last 10 commits on the current branch::
3324 3324
3325 3325 hg log -l 10 -b .
3326 3326
3327 3327 - changesets showing all modifications of a file, including removals::
3328 3328
3329 3329 hg log --removed file.c
3330 3330
3331 3331 - all changesets that touch a directory, with diffs, excluding merges::
3332 3332
3333 3333 hg log -Mp lib/
3334 3334
3335 3335 - all revision numbers that match a keyword::
3336 3336
3337 3337 hg log -k bug --template "{rev}\\n"
3338 3338
3339 3339 - the full hash identifier of the working directory parent::
3340 3340
3341 3341 hg log -r . --template "{node}\\n"
3342 3342
3343 3343 - list available log templates::
3344 3344
3345 3345 hg log -T list
3346 3346
3347 3347 - check if a given changeset is included in a tagged release::
3348 3348
3349 3349 hg log -r "a21ccf and ancestor(1.9)"
3350 3350
3351 3351 - find all changesets by some user in a date range::
3352 3352
3353 3353 hg log -k alice -d "may 2008 to jul 2008"
3354 3354
3355 3355 - summary of all changesets after the last tag::
3356 3356
3357 3357 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
3358 3358
3359 3359 - changesets touching lines 13 to 23 for file.c::
3360 3360
3361 3361 hg log -L file.c,13:23
3362 3362
3363 3363 - changesets touching lines 13 to 23 for file.c and lines 2 to 6 of
3364 3364 main.c with patch::
3365 3365
3366 3366 hg log -L file.c,13:23 -L main.c,2:6 -p
3367 3367
3368 3368 See :hg:`help dates` for a list of formats valid for -d/--date.
3369 3369
3370 3370 See :hg:`help revisions` for more about specifying and ordering
3371 3371 revisions.
3372 3372
3373 3373 See :hg:`help templates` for more about pre-packaged styles and
3374 3374 specifying custom templates. The default template used by the log
3375 3375 command can be customized via the ``ui.logtemplate`` configuration
3376 3376 setting.
3377 3377
3378 3378 Returns 0 on success.
3379 3379
3380 3380 """
3381 3381 opts = pycompat.byteskwargs(opts)
3382 3382 linerange = opts.get('line_range')
3383 3383
3384 3384 if linerange and not opts.get('follow'):
3385 3385 raise error.Abort(_('--line-range requires --follow'))
3386 3386
3387 3387 if linerange and pats:
3388 3388 raise error.Abort(
3389 3389 _('FILE arguments are not compatible with --line-range option')
3390 3390 )
3391 3391
3392 3392 if opts.get('follow') and opts.get('rev'):
3393 3393 opts['rev'] = [revsetlang.formatspec('reverse(::%lr)', opts.get('rev'))]
3394 3394 del opts['follow']
3395 3395
3396 3396 if opts.get('graph'):
3397 3397 if linerange:
3398 3398 raise error.Abort(_('graph not supported with line range patterns'))
3399 3399 return cmdutil.graphlog(ui, repo, pats, opts)
3400 3400
3401 3401 revs, expr, filematcher = cmdutil.getlogrevs(repo, pats, opts)
3402 3402 hunksfilter = None
3403 3403
3404 3404 if linerange:
3405 3405 revs, lrfilematcher, hunksfilter = cmdutil.getloglinerangerevs(
3406 3406 repo, revs, opts)
3407 3407
3408 3408 if filematcher is not None and lrfilematcher is not None:
3409 3409 basefilematcher = filematcher
3410 3410
3411 3411 def filematcher(rev):
3412 3412 files = (basefilematcher(rev).files()
3413 3413 + lrfilematcher(rev).files())
3414 3414 return scmutil.matchfiles(repo, files)
3415 3415
3416 3416 elif filematcher is None:
3417 3417 filematcher = lrfilematcher
3418 3418
3419 3419 limit = cmdutil.loglimit(opts)
3420 3420 count = 0
3421 3421
3422 3422 getrenamed = None
3423 3423 if opts.get('copies'):
3424 3424 endrev = None
3425 3425 if opts.get('rev'):
3426 3426 endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1
3427 3427 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
3428 3428
3429 3429 ui.pager('log')
3430 3430 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
3431 3431 for rev in revs:
3432 3432 if count == limit:
3433 3433 break
3434 3434 ctx = repo[rev]
3435 3435 copies = None
3436 3436 if getrenamed is not None and rev:
3437 3437 copies = []
3438 3438 for fn in ctx.files():
3439 3439 rename = getrenamed(fn, rev)
3440 3440 if rename:
3441 3441 copies.append((fn, rename[0]))
3442 3442 if filematcher:
3443 3443 revmatchfn = filematcher(ctx.rev())
3444 3444 else:
3445 3445 revmatchfn = None
3446 3446 if hunksfilter:
3447 3447 revhunksfilter = hunksfilter(rev)
3448 3448 else:
3449 3449 revhunksfilter = None
3450 3450 displayer.show(ctx, copies=copies, matchfn=revmatchfn,
3451 3451 hunksfilterfn=revhunksfilter)
3452 3452 if displayer.flush(ctx):
3453 3453 count += 1
3454 3454
3455 3455 displayer.close()
3456 3456
3457 3457 @command('manifest',
3458 3458 [('r', 'rev', '', _('revision to display'), _('REV')),
3459 3459 ('', 'all', False, _("list files from all revisions"))]
3460 3460 + formatteropts,
3461 3461 _('[-r REV]'), cmdtype=readonly)
3462 3462 def manifest(ui, repo, node=None, rev=None, **opts):
3463 3463 """output the current or given revision of the project manifest
3464 3464
3465 3465 Print a list of version controlled files for the given revision.
3466 3466 If no revision is given, the first parent of the working directory
3467 3467 is used, or the null revision if no revision is checked out.
3468 3468
3469 3469 With -v, print file permissions, symlink and executable bits.
3470 3470 With --debug, print file revision hashes.
3471 3471
3472 3472 If option --all is specified, the list of all files from all revisions
3473 3473 is printed. This includes deleted and renamed files.
3474 3474
3475 3475 Returns 0 on success.
3476 3476 """
3477 3477 opts = pycompat.byteskwargs(opts)
3478 3478 fm = ui.formatter('manifest', opts)
3479 3479
3480 3480 if opts.get('all'):
3481 3481 if rev or node:
3482 3482 raise error.Abort(_("can't specify a revision with --all"))
3483 3483
3484 3484 res = []
3485 3485 prefix = "data/"
3486 3486 suffix = ".i"
3487 3487 plen = len(prefix)
3488 3488 slen = len(suffix)
3489 3489 with repo.lock():
3490 3490 for fn, b, size in repo.store.datafiles():
3491 3491 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
3492 3492 res.append(fn[plen:-slen])
3493 3493 ui.pager('manifest')
3494 3494 for f in res:
3495 3495 fm.startitem()
3496 3496 fm.write("path", '%s\n', f)
3497 3497 fm.end()
3498 3498 return
3499 3499
3500 3500 if rev and node:
3501 3501 raise error.Abort(_("please specify just one revision"))
3502 3502
3503 3503 if not node:
3504 3504 node = rev
3505 3505
3506 3506 char = {'l': '@', 'x': '*', '': ''}
3507 3507 mode = {'l': '644', 'x': '755', '': '644'}
3508 3508 ctx = scmutil.revsingle(repo, node)
3509 3509 mf = ctx.manifest()
3510 3510 ui.pager('manifest')
3511 3511 for f in ctx:
3512 3512 fm.startitem()
3513 3513 fl = ctx[f].flags()
3514 3514 fm.condwrite(ui.debugflag, 'hash', '%s ', hex(mf[f]))
3515 3515 fm.condwrite(ui.verbose, 'mode type', '%s %1s ', mode[fl], char[fl])
3516 3516 fm.write('path', '%s\n', f)
3517 3517 fm.end()
3518 3518
3519 3519 @command('^merge',
3520 3520 [('f', 'force', None,
3521 3521 _('force a merge including outstanding changes (DEPRECATED)')),
3522 3522 ('r', 'rev', '', _('revision to merge'), _('REV')),
3523 3523 ('P', 'preview', None,
3524 3524 _('review revisions to merge (no merge is performed)'))
3525 3525 ] + mergetoolopts,
3526 3526 _('[-P] [[-r] REV]'))
3527 3527 def merge(ui, repo, node=None, **opts):
3528 3528 """merge another revision into working directory
3529 3529
3530 3530 The current working directory is updated with all changes made in
3531 3531 the requested revision since the last common predecessor revision.
3532 3532
3533 3533 Files that changed between either parent are marked as changed for
3534 3534 the next commit and a commit must be performed before any further
3535 3535 updates to the repository are allowed. The next commit will have
3536 3536 two parents.
3537 3537
3538 3538 ``--tool`` can be used to specify the merge tool used for file
3539 3539 merges. It overrides the HGMERGE environment variable and your
3540 3540 configuration files. See :hg:`help merge-tools` for options.
3541 3541
3542 3542 If no revision is specified, the working directory's parent is a
3543 3543 head revision, and the current branch contains exactly one other
3544 3544 head, the other head is merged with by default. Otherwise, an
3545 3545 explicit revision with which to merge with must be provided.
3546 3546
3547 3547 See :hg:`help resolve` for information on handling file conflicts.
3548 3548
3549 3549 To undo an uncommitted merge, use :hg:`update --clean .` which
3550 3550 will check out a clean copy of the original merge parent, losing
3551 3551 all changes.
3552 3552
3553 3553 Returns 0 on success, 1 if there are unresolved files.
3554 3554 """
3555 3555
3556 3556 opts = pycompat.byteskwargs(opts)
3557 3557 if opts.get('rev') and node:
3558 3558 raise error.Abort(_("please specify just one revision"))
3559 3559 if not node:
3560 3560 node = opts.get('rev')
3561 3561
3562 3562 if node:
3563 3563 node = scmutil.revsingle(repo, node).node()
3564 3564
3565 3565 if not node:
3566 3566 node = repo[destutil.destmerge(repo)].node()
3567 3567
3568 3568 if opts.get('preview'):
3569 3569 # find nodes that are ancestors of p2 but not of p1
3570 3570 p1 = repo.lookup('.')
3571 3571 p2 = repo.lookup(node)
3572 3572 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
3573 3573
3574 3574 displayer = cmdutil.show_changeset(ui, repo, opts)
3575 3575 for node in nodes:
3576 3576 displayer.show(repo[node])
3577 3577 displayer.close()
3578 3578 return 0
3579 3579
3580 3580 try:
3581 3581 # ui.forcemerge is an internal variable, do not document
3582 3582 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''), 'merge')
3583 3583 force = opts.get('force')
3584 3584 labels = ['working copy', 'merge rev']
3585 3585 return hg.merge(repo, node, force=force, mergeforce=force,
3586 3586 labels=labels)
3587 3587 finally:
3588 3588 ui.setconfig('ui', 'forcemerge', '', 'merge')
3589 3589
3590 3590 @command('outgoing|out',
3591 3591 [('f', 'force', None, _('run even when the destination is unrelated')),
3592 3592 ('r', 'rev', [],
3593 3593 _('a changeset intended to be included in the destination'), _('REV')),
3594 3594 ('n', 'newest-first', None, _('show newest record first')),
3595 3595 ('B', 'bookmarks', False, _('compare bookmarks')),
3596 3596 ('b', 'branch', [], _('a specific branch you would like to push'),
3597 3597 _('BRANCH')),
3598 3598 ] + logopts + remoteopts + subrepoopts,
3599 3599 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
3600 3600 def outgoing(ui, repo, dest=None, **opts):
3601 3601 """show changesets not found in the destination
3602 3602
3603 3603 Show changesets not found in the specified destination repository
3604 3604 or the default push location. These are the changesets that would
3605 3605 be pushed if a push was requested.
3606 3606
3607 3607 See pull for details of valid destination formats.
3608 3608
3609 3609 .. container:: verbose
3610 3610
3611 3611 With -B/--bookmarks, the result of bookmark comparison between
3612 3612 local and remote repositories is displayed. With -v/--verbose,
3613 3613 status is also displayed for each bookmark like below::
3614 3614
3615 3615 BM1 01234567890a added
3616 3616 BM2 deleted
3617 3617 BM3 234567890abc advanced
3618 3618 BM4 34567890abcd diverged
3619 3619 BM5 4567890abcde changed
3620 3620
3621 3621 The action taken when pushing depends on the
3622 3622 status of each bookmark:
3623 3623
3624 3624 :``added``: push with ``-B`` will create it
3625 3625 :``deleted``: push with ``-B`` will delete it
3626 3626 :``advanced``: push will update it
3627 3627 :``diverged``: push with ``-B`` will update it
3628 3628 :``changed``: push with ``-B`` will update it
3629 3629
3630 3630 From the point of view of pushing behavior, bookmarks
3631 3631 existing only in the remote repository are treated as
3632 3632 ``deleted``, even if it is in fact added remotely.
3633 3633
3634 3634 Returns 0 if there are outgoing changes, 1 otherwise.
3635 3635 """
3636 3636 opts = pycompat.byteskwargs(opts)
3637 3637 if opts.get('graph'):
3638 3638 cmdutil.checkunsupportedgraphflags([], opts)
3639 3639 o, other = hg._outgoing(ui, repo, dest, opts)
3640 3640 if not o:
3641 3641 cmdutil.outgoinghooks(ui, repo, other, opts, o)
3642 3642 return
3643 3643
3644 3644 revdag = cmdutil.graphrevs(repo, o, opts)
3645 3645 ui.pager('outgoing')
3646 3646 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
3647 3647 cmdutil.displaygraph(ui, repo, revdag, displayer, graphmod.asciiedges)
3648 3648 cmdutil.outgoinghooks(ui, repo, other, opts, o)
3649 3649 return 0
3650 3650
3651 3651 if opts.get('bookmarks'):
3652 3652 dest = ui.expandpath(dest or 'default-push', dest or 'default')
3653 3653 dest, branches = hg.parseurl(dest, opts.get('branch'))
3654 3654 other = hg.peer(repo, opts, dest)
3655 3655 if 'bookmarks' not in other.listkeys('namespaces'):
3656 3656 ui.warn(_("remote doesn't support bookmarks\n"))
3657 3657 return 0
3658 3658 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
3659 3659 ui.pager('outgoing')
3660 3660 return bookmarks.outgoing(ui, repo, other)
3661 3661
3662 3662 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
3663 3663 try:
3664 3664 return hg.outgoing(ui, repo, dest, opts)
3665 3665 finally:
3666 3666 del repo._subtoppath
3667 3667
3668 3668 @command('parents',
3669 3669 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
3670 3670 ] + templateopts,
3671 3671 _('[-r REV] [FILE]'),
3672 3672 inferrepo=True)
3673 3673 def parents(ui, repo, file_=None, **opts):
3674 3674 """show the parents of the working directory or revision (DEPRECATED)
3675 3675
3676 3676 Print the working directory's parent revisions. If a revision is
3677 3677 given via -r/--rev, the parent of that revision will be printed.
3678 3678 If a file argument is given, the revision in which the file was
3679 3679 last changed (before the working directory revision or the
3680 3680 argument to --rev if given) is printed.
3681 3681
3682 3682 This command is equivalent to::
3683 3683
3684 3684 hg log -r "p1()+p2()" or
3685 3685 hg log -r "p1(REV)+p2(REV)" or
3686 3686 hg log -r "max(::p1() and file(FILE))+max(::p2() and file(FILE))" or
3687 3687 hg log -r "max(::p1(REV) and file(FILE))+max(::p2(REV) and file(FILE))"
3688 3688
3689 3689 See :hg:`summary` and :hg:`help revsets` for related information.
3690 3690
3691 3691 Returns 0 on success.
3692 3692 """
3693 3693
3694 3694 opts = pycompat.byteskwargs(opts)
3695 3695 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
3696 3696
3697 3697 if file_:
3698 3698 m = scmutil.match(ctx, (file_,), opts)
3699 3699 if m.anypats() or len(m.files()) != 1:
3700 3700 raise error.Abort(_('can only specify an explicit filename'))
3701 3701 file_ = m.files()[0]
3702 3702 filenodes = []
3703 3703 for cp in ctx.parents():
3704 3704 if not cp:
3705 3705 continue
3706 3706 try:
3707 3707 filenodes.append(cp.filenode(file_))
3708 3708 except error.LookupError:
3709 3709 pass
3710 3710 if not filenodes:
3711 3711 raise error.Abort(_("'%s' not found in manifest!") % file_)
3712 3712 p = []
3713 3713 for fn in filenodes:
3714 3714 fctx = repo.filectx(file_, fileid=fn)
3715 3715 p.append(fctx.node())
3716 3716 else:
3717 3717 p = [cp.node() for cp in ctx.parents()]
3718 3718
3719 3719 displayer = cmdutil.show_changeset(ui, repo, opts)
3720 3720 for n in p:
3721 3721 if n != nullid:
3722 3722 displayer.show(repo[n])
3723 3723 displayer.close()
3724 3724
3725 3725 @command('paths', formatteropts, _('[NAME]'), optionalrepo=True,
3726 3726 cmdtype=readonly)
3727 3727 def paths(ui, repo, search=None, **opts):
3728 3728 """show aliases for remote repositories
3729 3729
3730 3730 Show definition of symbolic path name NAME. If no name is given,
3731 3731 show definition of all available names.
3732 3732
3733 3733 Option -q/--quiet suppresses all output when searching for NAME
3734 3734 and shows only the path names when listing all definitions.
3735 3735
3736 3736 Path names are defined in the [paths] section of your
3737 3737 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
3738 3738 repository, ``.hg/hgrc`` is used, too.
3739 3739
3740 3740 The path names ``default`` and ``default-push`` have a special
3741 3741 meaning. When performing a push or pull operation, they are used
3742 3742 as fallbacks if no location is specified on the command-line.
3743 3743 When ``default-push`` is set, it will be used for push and
3744 3744 ``default`` will be used for pull; otherwise ``default`` is used
3745 3745 as the fallback for both. When cloning a repository, the clone
3746 3746 source is written as ``default`` in ``.hg/hgrc``.
3747 3747
3748 3748 .. note::
3749 3749
3750 3750 ``default`` and ``default-push`` apply to all inbound (e.g.
3751 3751 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email`
3752 3752 and :hg:`bundle`) operations.
3753 3753
3754 3754 See :hg:`help urls` for more information.
3755 3755
3756 3756 Returns 0 on success.
3757 3757 """
3758 3758
3759 3759 opts = pycompat.byteskwargs(opts)
3760 3760 ui.pager('paths')
3761 3761 if search:
3762 3762 pathitems = [(name, path) for name, path in ui.paths.iteritems()
3763 3763 if name == search]
3764 3764 else:
3765 3765 pathitems = sorted(ui.paths.iteritems())
3766 3766
3767 3767 fm = ui.formatter('paths', opts)
3768 3768 if fm.isplain():
3769 3769 hidepassword = util.hidepassword
3770 3770 else:
3771 3771 hidepassword = str
3772 3772 if ui.quiet:
3773 3773 namefmt = '%s\n'
3774 3774 else:
3775 3775 namefmt = '%s = '
3776 3776 showsubopts = not search and not ui.quiet
3777 3777
3778 3778 for name, path in pathitems:
3779 3779 fm.startitem()
3780 3780 fm.condwrite(not search, 'name', namefmt, name)
3781 3781 fm.condwrite(not ui.quiet, 'url', '%s\n', hidepassword(path.rawloc))
3782 3782 for subopt, value in sorted(path.suboptions.items()):
3783 3783 assert subopt not in ('name', 'url')
3784 3784 if showsubopts:
3785 3785 fm.plain('%s:%s = ' % (name, subopt))
3786 3786 fm.condwrite(showsubopts, subopt, '%s\n', value)
3787 3787
3788 3788 fm.end()
3789 3789
3790 3790 if search and not pathitems:
3791 3791 if not ui.quiet:
3792 3792 ui.warn(_("not found!\n"))
3793 3793 return 1
3794 3794 else:
3795 3795 return 0
3796 3796
3797 3797 @command('phase',
3798 3798 [('p', 'public', False, _('set changeset phase to public')),
3799 3799 ('d', 'draft', False, _('set changeset phase to draft')),
3800 3800 ('s', 'secret', False, _('set changeset phase to secret')),
3801 3801 ('f', 'force', False, _('allow to move boundary backward')),
3802 3802 ('r', 'rev', [], _('target revision'), _('REV')),
3803 3803 ],
3804 3804 _('[-p|-d|-s] [-f] [-r] [REV...]'))
3805 3805 def phase(ui, repo, *revs, **opts):
3806 3806 """set or show the current phase name
3807 3807
3808 3808 With no argument, show the phase name of the current revision(s).
3809 3809
3810 3810 With one of -p/--public, -d/--draft or -s/--secret, change the
3811 3811 phase value of the specified revisions.
3812 3812
3813 3813 Unless -f/--force is specified, :hg:`phase` won't move changesets from a
3814 3814 lower phase to a higher phase. Phases are ordered as follows::
3815 3815
3816 3816 public < draft < secret
3817 3817
3818 3818 Returns 0 on success, 1 if some phases could not be changed.
3819 3819
3820 3820 (For more information about the phases concept, see :hg:`help phases`.)
3821 3821 """
3822 3822 opts = pycompat.byteskwargs(opts)
3823 3823 # search for a unique phase argument
3824 3824 targetphase = None
3825 3825 for idx, name in enumerate(phases.phasenames):
3826 3826 if opts[name]:
3827 3827 if targetphase is not None:
3828 3828 raise error.Abort(_('only one phase can be specified'))
3829 3829 targetphase = idx
3830 3830
3831 3831 # look for specified revision
3832 3832 revs = list(revs)
3833 3833 revs.extend(opts['rev'])
3834 3834 if not revs:
3835 3835 # display both parents as the second parent phase can influence
3836 3836 # the phase of a merge commit
3837 3837 revs = [c.rev() for c in repo[None].parents()]
3838 3838
3839 3839 revs = scmutil.revrange(repo, revs)
3840 3840
3841 3841 lock = None
3842 3842 ret = 0
3843 3843 if targetphase is None:
3844 3844 # display
3845 3845 for r in revs:
3846 3846 ctx = repo[r]
3847 3847 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
3848 3848 else:
3849 3849 tr = None
3850 3850 lock = repo.lock()
3851 3851 try:
3852 3852 tr = repo.transaction("phase")
3853 3853 # set phase
3854 3854 if not revs:
3855 3855 raise error.Abort(_('empty revision set'))
3856 3856 nodes = [repo[r].node() for r in revs]
3857 3857 # moving revision from public to draft may hide them
3858 3858 # We have to check result on an unfiltered repository
3859 3859 unfi = repo.unfiltered()
3860 3860 getphase = unfi._phasecache.phase
3861 3861 olddata = [getphase(unfi, r) for r in unfi]
3862 3862 phases.advanceboundary(repo, tr, targetphase, nodes)
3863 3863 if opts['force']:
3864 3864 phases.retractboundary(repo, tr, targetphase, nodes)
3865 3865 tr.close()
3866 3866 finally:
3867 3867 if tr is not None:
3868 3868 tr.release()
3869 3869 lock.release()
3870 3870 getphase = unfi._phasecache.phase
3871 3871 newdata = [getphase(unfi, r) for r in unfi]
3872 3872 changes = sum(newdata[r] != olddata[r] for r in unfi)
3873 3873 cl = unfi.changelog
3874 3874 rejected = [n for n in nodes
3875 3875 if newdata[cl.rev(n)] < targetphase]
3876 3876 if rejected:
3877 3877 ui.warn(_('cannot move %i changesets to a higher '
3878 3878 'phase, use --force\n') % len(rejected))
3879 3879 ret = 1
3880 3880 if changes:
3881 3881 msg = _('phase changed for %i changesets\n') % changes
3882 3882 if ret:
3883 3883 ui.status(msg)
3884 3884 else:
3885 3885 ui.note(msg)
3886 3886 else:
3887 3887 ui.warn(_('no phases changed\n'))
3888 3888 return ret
3889 3889
3890 3890 def postincoming(ui, repo, modheads, optupdate, checkout, brev):
3891 3891 """Run after a changegroup has been added via pull/unbundle
3892 3892
3893 3893 This takes arguments below:
3894 3894
3895 3895 :modheads: change of heads by pull/unbundle
3896 3896 :optupdate: updating working directory is needed or not
3897 3897 :checkout: update destination revision (or None to default destination)
3898 3898 :brev: a name, which might be a bookmark to be activated after updating
3899 3899 """
3900 3900 if modheads == 0:
3901 3901 return
3902 3902 if optupdate:
3903 3903 try:
3904 3904 return hg.updatetotally(ui, repo, checkout, brev)
3905 3905 except error.UpdateAbort as inst:
3906 3906 msg = _("not updating: %s") % str(inst)
3907 3907 hint = inst.hint
3908 3908 raise error.UpdateAbort(msg, hint=hint)
3909 3909 if modheads > 1:
3910 3910 currentbranchheads = len(repo.branchheads())
3911 3911 if currentbranchheads == modheads:
3912 3912 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
3913 3913 elif currentbranchheads > 1:
3914 3914 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to "
3915 3915 "merge)\n"))
3916 3916 else:
3917 3917 ui.status(_("(run 'hg heads' to see heads)\n"))
3918 3918 elif not ui.configbool('commands', 'update.requiredest'):
3919 3919 ui.status(_("(run 'hg update' to get a working copy)\n"))
3920 3920
3921 3921 @command('^pull',
3922 3922 [('u', 'update', None,
3923 3923 _('update to new branch head if new descendants were pulled')),
3924 3924 ('f', 'force', None, _('run even when remote repository is unrelated')),
3925 3925 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3926 3926 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
3927 3927 ('b', 'branch', [], _('a specific branch you would like to pull'),
3928 3928 _('BRANCH')),
3929 3929 ] + remoteopts,
3930 3930 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
3931 3931 def pull(ui, repo, source="default", **opts):
3932 3932 """pull changes from the specified source
3933 3933
3934 3934 Pull changes from a remote repository to a local one.
3935 3935
3936 3936 This finds all changes from the repository at the specified path
3937 3937 or URL and adds them to a local repository (the current one unless
3938 3938 -R is specified). By default, this does not update the copy of the
3939 3939 project in the working directory.
3940 3940
3941 3941 Use :hg:`incoming` if you want to see what would have been added
3942 3942 by a pull at the time you issued this command. If you then decide
3943 3943 to add those changes to the repository, you should use :hg:`pull
3944 3944 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
3945 3945
3946 3946 If SOURCE is omitted, the 'default' path will be used.
3947 3947 See :hg:`help urls` for more information.
3948 3948
3949 3949 Specifying bookmark as ``.`` is equivalent to specifying the active
3950 3950 bookmark's name.
3951 3951
3952 3952 Returns 0 on success, 1 if an update had unresolved files.
3953 3953 """
3954 3954
3955 3955 opts = pycompat.byteskwargs(opts)
3956 3956 if ui.configbool('commands', 'update.requiredest') and opts.get('update'):
3957 3957 msg = _('update destination required by configuration')
3958 3958 hint = _('use hg pull followed by hg update DEST')
3959 3959 raise error.Abort(msg, hint=hint)
3960 3960
3961 3961 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
3962 3962 ui.status(_('pulling from %s\n') % util.hidepassword(source))
3963 3963 other = hg.peer(repo, opts, source)
3964 3964 try:
3965 3965 revs, checkout = hg.addbranchrevs(repo, other, branches,
3966 3966 opts.get('rev'))
3967 3967
3968 3968
3969 3969 pullopargs = {}
3970 3970 if opts.get('bookmark'):
3971 3971 if not revs:
3972 3972 revs = []
3973 3973 # The list of bookmark used here is not the one used to actually
3974 3974 # update the bookmark name. This can result in the revision pulled
3975 3975 # not ending up with the name of the bookmark because of a race
3976 3976 # condition on the server. (See issue 4689 for details)
3977 3977 remotebookmarks = other.listkeys('bookmarks')
3978 3978 remotebookmarks = bookmarks.unhexlifybookmarks(remotebookmarks)
3979 3979 pullopargs['remotebookmarks'] = remotebookmarks
3980 3980 for b in opts['bookmark']:
3981 3981 b = repo._bookmarks.expandname(b)
3982 3982 if b not in remotebookmarks:
3983 3983 raise error.Abort(_('remote bookmark %s not found!') % b)
3984 3984 revs.append(hex(remotebookmarks[b]))
3985 3985
3986 3986 if revs:
3987 3987 try:
3988 3988 # When 'rev' is a bookmark name, we cannot guarantee that it
3989 3989 # will be updated with that name because of a race condition
3990 3990 # server side. (See issue 4689 for details)
3991 3991 oldrevs = revs
3992 3992 revs = [] # actually, nodes
3993 3993 for r in oldrevs:
3994 3994 node = other.lookup(r)
3995 3995 revs.append(node)
3996 3996 if r == checkout:
3997 3997 checkout = node
3998 3998 except error.CapabilityError:
3999 3999 err = _("other repository doesn't support revision lookup, "
4000 4000 "so a rev cannot be specified.")
4001 4001 raise error.Abort(err)
4002 4002
4003 4003 pullopargs.update(opts.get('opargs', {}))
4004 4004 modheads = exchange.pull(repo, other, heads=revs,
4005 4005 force=opts.get('force'),
4006 4006 bookmarks=opts.get('bookmark', ()),
4007 4007 opargs=pullopargs).cgresult
4008 4008
4009 4009 # brev is a name, which might be a bookmark to be activated at
4010 4010 # the end of the update. In other words, it is an explicit
4011 4011 # destination of the update
4012 4012 brev = None
4013 4013
4014 4014 if checkout:
4015 4015 checkout = str(repo.changelog.rev(checkout))
4016 4016
4017 4017 # order below depends on implementation of
4018 4018 # hg.addbranchrevs(). opts['bookmark'] is ignored,
4019 4019 # because 'checkout' is determined without it.
4020 4020 if opts.get('rev'):
4021 4021 brev = opts['rev'][0]
4022 4022 elif opts.get('branch'):
4023 4023 brev = opts['branch'][0]
4024 4024 else:
4025 4025 brev = branches[0]
4026 4026 repo._subtoppath = source
4027 4027 try:
4028 4028 ret = postincoming(ui, repo, modheads, opts.get('update'),
4029 4029 checkout, brev)
4030 4030
4031 4031 finally:
4032 4032 del repo._subtoppath
4033 4033
4034 4034 finally:
4035 4035 other.close()
4036 4036 return ret
4037 4037
4038 4038 @command('^push',
4039 4039 [('f', 'force', None, _('force push')),
4040 4040 ('r', 'rev', [],
4041 4041 _('a changeset intended to be included in the destination'),
4042 4042 _('REV')),
4043 4043 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4044 4044 ('b', 'branch', [],
4045 4045 _('a specific branch you would like to push'), _('BRANCH')),
4046 4046 ('', 'new-branch', False, _('allow pushing a new branch')),
4047 4047 ('', 'pushvars', [], _('variables that can be sent to server (ADVANCED)')),
4048 4048 ] + remoteopts,
4049 4049 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
4050 4050 def push(ui, repo, dest=None, **opts):
4051 4051 """push changes to the specified destination
4052 4052
4053 4053 Push changesets from the local repository to the specified
4054 4054 destination.
4055 4055
4056 4056 This operation is symmetrical to pull: it is identical to a pull
4057 4057 in the destination repository from the current one.
4058 4058
4059 4059 By default, push will not allow creation of new heads at the
4060 4060 destination, since multiple heads would make it unclear which head
4061 4061 to use. In this situation, it is recommended to pull and merge
4062 4062 before pushing.
4063 4063
4064 4064 Use --new-branch if you want to allow push to create a new named
4065 4065 branch that is not present at the destination. This allows you to
4066 4066 only create a new branch without forcing other changes.
4067 4067
4068 4068 .. note::
4069 4069
4070 4070 Extra care should be taken with the -f/--force option,
4071 4071 which will push all new heads on all branches, an action which will
4072 4072 almost always cause confusion for collaborators.
4073 4073
4074 4074 If -r/--rev is used, the specified revision and all its ancestors
4075 4075 will be pushed to the remote repository.
4076 4076
4077 4077 If -B/--bookmark is used, the specified bookmarked revision, its
4078 4078 ancestors, and the bookmark will be pushed to the remote
4079 4079 repository. Specifying ``.`` is equivalent to specifying the active
4080 4080 bookmark's name.
4081 4081
4082 4082 Please see :hg:`help urls` for important details about ``ssh://``
4083 4083 URLs. If DESTINATION is omitted, a default path will be used.
4084 4084
4085 4085 .. container:: verbose
4086 4086
4087 4087 The --pushvars option sends strings to the server that become
4088 4088 environment variables prepended with ``HG_USERVAR_``. For example,
4089 4089 ``--pushvars ENABLE_FEATURE=true``, provides the server side hooks with
4090 4090 ``HG_USERVAR_ENABLE_FEATURE=true`` as part of their environment.
4091 4091
4092 4092 pushvars can provide for user-overridable hooks as well as set debug
4093 4093 levels. One example is having a hook that blocks commits containing
4094 4094 conflict markers, but enables the user to override the hook if the file
4095 4095 is using conflict markers for testing purposes or the file format has
4096 4096 strings that look like conflict markers.
4097 4097
4098 4098 By default, servers will ignore `--pushvars`. To enable it add the
4099 4099 following to your configuration file::
4100 4100
4101 4101 [push]
4102 4102 pushvars.server = true
4103 4103
4104 4104 Returns 0 if push was successful, 1 if nothing to push.
4105 4105 """
4106 4106
4107 4107 opts = pycompat.byteskwargs(opts)
4108 4108 if opts.get('bookmark'):
4109 4109 ui.setconfig('bookmarks', 'pushing', opts['bookmark'], 'push')
4110 4110 for b in opts['bookmark']:
4111 4111 # translate -B options to -r so changesets get pushed
4112 4112 b = repo._bookmarks.expandname(b)
4113 4113 if b in repo._bookmarks:
4114 4114 opts.setdefault('rev', []).append(b)
4115 4115 else:
4116 4116 # if we try to push a deleted bookmark, translate it to null
4117 4117 # this lets simultaneous -r, -b options continue working
4118 4118 opts.setdefault('rev', []).append("null")
4119 4119
4120 4120 path = ui.paths.getpath(dest, default=('default-push', 'default'))
4121 4121 if not path:
4122 4122 raise error.Abort(_('default repository not configured!'),
4123 4123 hint=_("see 'hg help config.paths'"))
4124 4124 dest = path.pushloc or path.loc
4125 4125 branches = (path.branch, opts.get('branch') or [])
4126 4126 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
4127 4127 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
4128 4128 other = hg.peer(repo, opts, dest)
4129 4129
4130 4130 if revs:
4131 4131 revs = [repo.lookup(r) for r in scmutil.revrange(repo, revs)]
4132 4132 if not revs:
4133 4133 raise error.Abort(_("specified revisions evaluate to an empty set"),
4134 4134 hint=_("use different revision arguments"))
4135 4135 elif path.pushrev:
4136 4136 # It doesn't make any sense to specify ancestor revisions. So limit
4137 4137 # to DAG heads to make discovery simpler.
4138 4138 expr = revsetlang.formatspec('heads(%r)', path.pushrev)
4139 4139 revs = scmutil.revrange(repo, [expr])
4140 4140 revs = [repo[rev].node() for rev in revs]
4141 4141 if not revs:
4142 4142 raise error.Abort(_('default push revset for path evaluates to an '
4143 4143 'empty set'))
4144 4144
4145 4145 repo._subtoppath = dest
4146 4146 try:
4147 4147 # push subrepos depth-first for coherent ordering
4148 4148 c = repo['']
4149 4149 subs = c.substate # only repos that are committed
4150 4150 for s in sorted(subs):
4151 4151 result = c.sub(s).push(opts)
4152 4152 if result == 0:
4153 4153 return not result
4154 4154 finally:
4155 4155 del repo._subtoppath
4156 4156
4157 4157 opargs = dict(opts.get('opargs', {})) # copy opargs since we may mutate it
4158 4158 opargs.setdefault('pushvars', []).extend(opts.get('pushvars', []))
4159 4159
4160 4160 pushop = exchange.push(repo, other, opts.get('force'), revs=revs,
4161 4161 newbranch=opts.get('new_branch'),
4162 4162 bookmarks=opts.get('bookmark', ()),
4163 4163 opargs=opargs)
4164 4164
4165 4165 result = not pushop.cgresult
4166 4166
4167 4167 if pushop.bkresult is not None:
4168 4168 if pushop.bkresult == 2:
4169 4169 result = 2
4170 4170 elif not result and pushop.bkresult:
4171 4171 result = 2
4172 4172
4173 4173 return result
4174 4174
4175 4175 @command('recover', [])
4176 4176 def recover(ui, repo):
4177 4177 """roll back an interrupted transaction
4178 4178
4179 4179 Recover from an interrupted commit or pull.
4180 4180
4181 4181 This command tries to fix the repository status after an
4182 4182 interrupted operation. It should only be necessary when Mercurial
4183 4183 suggests it.
4184 4184
4185 4185 Returns 0 if successful, 1 if nothing to recover or verify fails.
4186 4186 """
4187 4187 if repo.recover():
4188 4188 return hg.verify(repo)
4189 4189 return 1
4190 4190
4191 4191 @command('^remove|rm',
4192 4192 [('A', 'after', None, _('record delete for missing files')),
4193 4193 ('f', 'force', None,
4194 4194 _('forget added files, delete modified files')),
4195 4195 ] + subrepoopts + walkopts,
4196 4196 _('[OPTION]... FILE...'),
4197 4197 inferrepo=True)
4198 4198 def remove(ui, repo, *pats, **opts):
4199 4199 """remove the specified files on the next commit
4200 4200
4201 4201 Schedule the indicated files for removal from the current branch.
4202 4202
4203 4203 This command schedules the files to be removed at the next commit.
4204 4204 To undo a remove before that, see :hg:`revert`. To undo added
4205 4205 files, see :hg:`forget`.
4206 4206
4207 4207 .. container:: verbose
4208 4208
4209 4209 -A/--after can be used to remove only files that have already
4210 4210 been deleted, -f/--force can be used to force deletion, and -Af
4211 4211 can be used to remove files from the next revision without
4212 4212 deleting them from the working directory.
4213 4213
4214 4214 The following table details the behavior of remove for different
4215 4215 file states (columns) and option combinations (rows). The file
4216 4216 states are Added [A], Clean [C], Modified [M] and Missing [!]
4217 4217 (as reported by :hg:`status`). The actions are Warn, Remove
4218 4218 (from branch) and Delete (from disk):
4219 4219
4220 4220 ========= == == == ==
4221 4221 opt/state A C M !
4222 4222 ========= == == == ==
4223 4223 none W RD W R
4224 4224 -f R RD RD R
4225 4225 -A W W W R
4226 4226 -Af R R R R
4227 4227 ========= == == == ==
4228 4228
4229 4229 .. note::
4230 4230
4231 4231 :hg:`remove` never deletes files in Added [A] state from the
4232 4232 working directory, not even if ``--force`` is specified.
4233 4233
4234 4234 Returns 0 on success, 1 if any warnings encountered.
4235 4235 """
4236 4236
4237 4237 opts = pycompat.byteskwargs(opts)
4238 4238 after, force = opts.get('after'), opts.get('force')
4239 4239 if not pats and not after:
4240 4240 raise error.Abort(_('no files specified'))
4241 4241
4242 4242 m = scmutil.match(repo[None], pats, opts)
4243 4243 subrepos = opts.get('subrepos')
4244 4244 return cmdutil.remove(ui, repo, m, "", after, force, subrepos)
4245 4245
4246 4246 @command('rename|move|mv',
4247 4247 [('A', 'after', None, _('record a rename that has already occurred')),
4248 4248 ('f', 'force', None, _('forcibly copy over an existing managed file')),
4249 4249 ] + walkopts + dryrunopts,
4250 4250 _('[OPTION]... SOURCE... DEST'))
4251 4251 def rename(ui, repo, *pats, **opts):
4252 4252 """rename files; equivalent of copy + remove
4253 4253
4254 4254 Mark dest as copies of sources; mark sources for deletion. If dest
4255 4255 is a directory, copies are put in that directory. If dest is a
4256 4256 file, there can only be one source.
4257 4257
4258 4258 By default, this command copies the contents of files as they
4259 4259 exist in the working directory. If invoked with -A/--after, the
4260 4260 operation is recorded, but no copying is performed.
4261 4261
4262 4262 This command takes effect at the next commit. To undo a rename
4263 4263 before that, see :hg:`revert`.
4264 4264
4265 4265 Returns 0 on success, 1 if errors are encountered.
4266 4266 """
4267 4267 opts = pycompat.byteskwargs(opts)
4268 4268 with repo.wlock(False):
4269 4269 return cmdutil.copy(ui, repo, pats, opts, rename=True)
4270 4270
4271 4271 @command('resolve',
4272 4272 [('a', 'all', None, _('select all unresolved files')),
4273 4273 ('l', 'list', None, _('list state of files needing merge')),
4274 4274 ('m', 'mark', None, _('mark files as resolved')),
4275 4275 ('u', 'unmark', None, _('mark files as unresolved')),
4276 4276 ('n', 'no-status', None, _('hide status prefix'))]
4277 4277 + mergetoolopts + walkopts + formatteropts,
4278 4278 _('[OPTION]... [FILE]...'),
4279 4279 inferrepo=True)
4280 4280 def resolve(ui, repo, *pats, **opts):
4281 4281 """redo merges or set/view the merge status of files
4282 4282
4283 4283 Merges with unresolved conflicts are often the result of
4284 4284 non-interactive merging using the ``internal:merge`` configuration
4285 4285 setting, or a command-line merge tool like ``diff3``. The resolve
4286 4286 command is used to manage the files involved in a merge, after
4287 4287 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4288 4288 working directory must have two parents). See :hg:`help
4289 4289 merge-tools` for information on configuring merge tools.
4290 4290
4291 4291 The resolve command can be used in the following ways:
4292 4292
4293 4293 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4294 4294 files, discarding any previous merge attempts. Re-merging is not
4295 4295 performed for files already marked as resolved. Use ``--all/-a``
4296 4296 to select all unresolved files. ``--tool`` can be used to specify
4297 4297 the merge tool used for the given files. It overrides the HGMERGE
4298 4298 environment variable and your configuration files. Previous file
4299 4299 contents are saved with a ``.orig`` suffix.
4300 4300
4301 4301 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4302 4302 (e.g. after having manually fixed-up the files). The default is
4303 4303 to mark all unresolved files.
4304 4304
4305 4305 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4306 4306 default is to mark all resolved files.
4307 4307
4308 4308 - :hg:`resolve -l`: list files which had or still have conflicts.
4309 4309 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4310 4310 You can use ``set:unresolved()`` or ``set:resolved()`` to filter
4311 4311 the list. See :hg:`help filesets` for details.
4312 4312
4313 4313 .. note::
4314 4314
4315 4315 Mercurial will not let you commit files with unresolved merge
4316 4316 conflicts. You must use :hg:`resolve -m ...` before you can
4317 4317 commit after a conflicting merge.
4318 4318
4319 4319 Returns 0 on success, 1 if any files fail a resolve attempt.
4320 4320 """
4321 4321
4322 4322 opts = pycompat.byteskwargs(opts)
4323 4323 flaglist = 'all mark unmark list no_status'.split()
4324 4324 all, mark, unmark, show, nostatus = \
4325 4325 [opts.get(o) for o in flaglist]
4326 4326
4327 4327 if (show and (mark or unmark)) or (mark and unmark):
4328 4328 raise error.Abort(_("too many options specified"))
4329 4329 if pats and all:
4330 4330 raise error.Abort(_("can't specify --all and patterns"))
4331 4331 if not (all or pats or show or mark or unmark):
4332 4332 raise error.Abort(_('no files or directories specified'),
4333 4333 hint=('use --all to re-merge all unresolved files'))
4334 4334
4335 4335 if show:
4336 4336 ui.pager('resolve')
4337 4337 fm = ui.formatter('resolve', opts)
4338 4338 ms = mergemod.mergestate.read(repo)
4339 4339 m = scmutil.match(repo[None], pats, opts)
4340 4340
4341 4341 # Labels and keys based on merge state. Unresolved path conflicts show
4342 4342 # as 'P'. Resolved path conflicts show as 'R', the same as normal
4343 4343 # resolved conflicts.
4344 4344 mergestateinfo = {
4345 4345 'u': ('resolve.unresolved', 'U'),
4346 4346 'r': ('resolve.resolved', 'R'),
4347 4347 'pu': ('resolve.unresolved', 'P'),
4348 4348 'pr': ('resolve.resolved', 'R'),
4349 4349 'd': ('resolve.driverresolved', 'D'),
4350 4350 }
4351 4351
4352 4352 for f in ms:
4353 4353 if not m(f):
4354 4354 continue
4355 4355
4356 4356 label, key = mergestateinfo[ms[f]]
4357 4357 fm.startitem()
4358 4358 fm.condwrite(not nostatus, 'status', '%s ', key, label=label)
4359 4359 fm.write('path', '%s\n', f, label=label)
4360 4360 fm.end()
4361 4361 return 0
4362 4362
4363 4363 with repo.wlock():
4364 4364 ms = mergemod.mergestate.read(repo)
4365 4365
4366 4366 if not (ms.active() or repo.dirstate.p2() != nullid):
4367 4367 raise error.Abort(
4368 4368 _('resolve command not applicable when not merging'))
4369 4369
4370 4370 wctx = repo[None]
4371 4371
4372 4372 if ms.mergedriver and ms.mdstate() == 'u':
4373 4373 proceed = mergemod.driverpreprocess(repo, ms, wctx)
4374 4374 ms.commit()
4375 4375 # allow mark and unmark to go through
4376 4376 if not mark and not unmark and not proceed:
4377 4377 return 1
4378 4378
4379 4379 m = scmutil.match(wctx, pats, opts)
4380 4380 ret = 0
4381 4381 didwork = False
4382 4382 runconclude = False
4383 4383
4384 4384 tocomplete = []
4385 4385 for f in ms:
4386 4386 if not m(f):
4387 4387 continue
4388 4388
4389 4389 didwork = True
4390 4390
4391 4391 # don't let driver-resolved files be marked, and run the conclude
4392 4392 # step if asked to resolve
4393 4393 if ms[f] == "d":
4394 4394 exact = m.exact(f)
4395 4395 if mark:
4396 4396 if exact:
4397 4397 ui.warn(_('not marking %s as it is driver-resolved\n')
4398 4398 % f)
4399 4399 elif unmark:
4400 4400 if exact:
4401 4401 ui.warn(_('not unmarking %s as it is driver-resolved\n')
4402 4402 % f)
4403 4403 else:
4404 4404 runconclude = True
4405 4405 continue
4406 4406
4407 4407 # path conflicts must be resolved manually
4408 4408 if ms[f] in ("pu", "pr"):
4409 4409 if mark:
4410 4410 ms.mark(f, "pr")
4411 4411 elif unmark:
4412 4412 ms.mark(f, "pu")
4413 4413 elif ms[f] == "pu":
4414 4414 ui.warn(_('%s: path conflict must be resolved manually\n')
4415 4415 % f)
4416 4416 continue
4417 4417
4418 4418 if mark:
4419 4419 ms.mark(f, "r")
4420 4420 elif unmark:
4421 4421 ms.mark(f, "u")
4422 4422 else:
4423 4423 # backup pre-resolve (merge uses .orig for its own purposes)
4424 4424 a = repo.wjoin(f)
4425 4425 try:
4426 4426 util.copyfile(a, a + ".resolve")
4427 4427 except (IOError, OSError) as inst:
4428 4428 if inst.errno != errno.ENOENT:
4429 4429 raise
4430 4430
4431 4431 try:
4432 4432 # preresolve file
4433 4433 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
4434 4434 'resolve')
4435 4435 complete, r = ms.preresolve(f, wctx)
4436 4436 if not complete:
4437 4437 tocomplete.append(f)
4438 4438 elif r:
4439 4439 ret = 1
4440 4440 finally:
4441 4441 ui.setconfig('ui', 'forcemerge', '', 'resolve')
4442 4442 ms.commit()
4443 4443
4444 4444 # replace filemerge's .orig file with our resolve file, but only
4445 4445 # for merges that are complete
4446 4446 if complete:
4447 4447 try:
4448 4448 util.rename(a + ".resolve",
4449 4449 scmutil.origpath(ui, repo, a))
4450 4450 except OSError as inst:
4451 4451 if inst.errno != errno.ENOENT:
4452 4452 raise
4453 4453
4454 4454 for f in tocomplete:
4455 4455 try:
4456 4456 # resolve file
4457 4457 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
4458 4458 'resolve')
4459 4459 r = ms.resolve(f, wctx)
4460 4460 if r:
4461 4461 ret = 1
4462 4462 finally:
4463 4463 ui.setconfig('ui', 'forcemerge', '', 'resolve')
4464 4464 ms.commit()
4465 4465
4466 4466 # replace filemerge's .orig file with our resolve file
4467 4467 a = repo.wjoin(f)
4468 4468 try:
4469 4469 util.rename(a + ".resolve", scmutil.origpath(ui, repo, a))
4470 4470 except OSError as inst:
4471 4471 if inst.errno != errno.ENOENT:
4472 4472 raise
4473 4473
4474 4474 ms.commit()
4475 4475 ms.recordactions()
4476 4476
4477 4477 if not didwork and pats:
4478 4478 hint = None
4479 4479 if not any([p for p in pats if p.find(':') >= 0]):
4480 4480 pats = ['path:%s' % p for p in pats]
4481 4481 m = scmutil.match(wctx, pats, opts)
4482 4482 for f in ms:
4483 4483 if not m(f):
4484 4484 continue
4485 4485 flags = ''.join(['-%s ' % o[0] for o in flaglist
4486 4486 if opts.get(o)])
4487 4487 hint = _("(try: hg resolve %s%s)\n") % (
4488 4488 flags,
4489 4489 ' '.join(pats))
4490 4490 break
4491 4491 ui.warn(_("arguments do not match paths that need resolving\n"))
4492 4492 if hint:
4493 4493 ui.warn(hint)
4494 4494 elif ms.mergedriver and ms.mdstate() != 's':
4495 4495 # run conclude step when either a driver-resolved file is requested
4496 4496 # or there are no driver-resolved files
4497 4497 # we can't use 'ret' to determine whether any files are unresolved
4498 4498 # because we might not have tried to resolve some
4499 4499 if ((runconclude or not list(ms.driverresolved()))
4500 4500 and not list(ms.unresolved())):
4501 4501 proceed = mergemod.driverconclude(repo, ms, wctx)
4502 4502 ms.commit()
4503 4503 if not proceed:
4504 4504 return 1
4505 4505
4506 4506 # Nudge users into finishing an unfinished operation
4507 4507 unresolvedf = list(ms.unresolved())
4508 4508 driverresolvedf = list(ms.driverresolved())
4509 4509 if not unresolvedf and not driverresolvedf:
4510 4510 ui.status(_('(no more unresolved files)\n'))
4511 4511 cmdutil.checkafterresolved(repo)
4512 4512 elif not unresolvedf:
4513 4513 ui.status(_('(no more unresolved files -- '
4514 4514 'run "hg resolve --all" to conclude)\n'))
4515 4515
4516 4516 return ret
4517 4517
4518 4518 @command('revert',
4519 4519 [('a', 'all', None, _('revert all changes when no arguments given')),
4520 4520 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4521 4521 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
4522 4522 ('C', 'no-backup', None, _('do not save backup copies of files')),
4523 4523 ('i', 'interactive', None, _('interactively select the changes')),
4524 4524 ] + walkopts + dryrunopts,
4525 4525 _('[OPTION]... [-r REV] [NAME]...'))
4526 4526 def revert(ui, repo, *pats, **opts):
4527 4527 """restore files to their checkout state
4528 4528
4529 4529 .. note::
4530 4530
4531 4531 To check out earlier revisions, you should use :hg:`update REV`.
4532 4532 To cancel an uncommitted merge (and lose your changes),
4533 4533 use :hg:`update --clean .`.
4534 4534
4535 4535 With no revision specified, revert the specified files or directories
4536 4536 to the contents they had in the parent of the working directory.
4537 4537 This restores the contents of files to an unmodified
4538 4538 state and unschedules adds, removes, copies, and renames. If the
4539 4539 working directory has two parents, you must explicitly specify a
4540 4540 revision.
4541 4541
4542 4542 Using the -r/--rev or -d/--date options, revert the given files or
4543 4543 directories to their states as of a specific revision. Because
4544 4544 revert does not change the working directory parents, this will
4545 4545 cause these files to appear modified. This can be helpful to "back
4546 4546 out" some or all of an earlier change. See :hg:`backout` for a
4547 4547 related method.
4548 4548
4549 4549 Modified files are saved with a .orig suffix before reverting.
4550 4550 To disable these backups, use --no-backup. It is possible to store
4551 4551 the backup files in a custom directory relative to the root of the
4552 4552 repository by setting the ``ui.origbackuppath`` configuration
4553 4553 option.
4554 4554
4555 4555 See :hg:`help dates` for a list of formats valid for -d/--date.
4556 4556
4557 4557 See :hg:`help backout` for a way to reverse the effect of an
4558 4558 earlier changeset.
4559 4559
4560 4560 Returns 0 on success.
4561 4561 """
4562 4562
4563 opts = pycompat.byteskwargs(opts)
4563 4564 if opts.get("date"):
4564 4565 if opts.get("rev"):
4565 4566 raise error.Abort(_("you can't specify a revision and a date"))
4566 4567 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
4567 4568
4568 4569 parent, p2 = repo.dirstate.parents()
4569 4570 if not opts.get('rev') and p2 != nullid:
4570 4571 # revert after merge is a trap for new users (issue2915)
4571 4572 raise error.Abort(_('uncommitted merge with no revision specified'),
4572 4573 hint=_("use 'hg update' or see 'hg help revert'"))
4573 4574
4574 4575 ctx = scmutil.revsingle(repo, opts.get('rev'))
4575 4576
4576 4577 if (not (pats or opts.get('include') or opts.get('exclude') or
4577 4578 opts.get('all') or opts.get('interactive'))):
4578 4579 msg = _("no files or directories specified")
4579 4580 if p2 != nullid:
4580 4581 hint = _("uncommitted merge, use --all to discard all changes,"
4581 4582 " or 'hg update -C .' to abort the merge")
4582 4583 raise error.Abort(msg, hint=hint)
4583 4584 dirty = any(repo.status())
4584 4585 node = ctx.node()
4585 4586 if node != parent:
4586 4587 if dirty:
4587 4588 hint = _("uncommitted changes, use --all to discard all"
4588 4589 " changes, or 'hg update %s' to update") % ctx.rev()
4589 4590 else:
4590 4591 hint = _("use --all to revert all files,"
4591 4592 " or 'hg update %s' to update") % ctx.rev()
4592 4593 elif dirty:
4593 4594 hint = _("uncommitted changes, use --all to discard all changes")
4594 4595 else:
4595 4596 hint = _("use --all to revert all files")
4596 4597 raise error.Abort(msg, hint=hint)
4597 4598
4598 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats, **opts)
4599 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats,
4600 **pycompat.strkwargs(opts))
4599 4601
4600 4602 @command('rollback', dryrunopts +
4601 4603 [('f', 'force', False, _('ignore safety measures'))])
4602 4604 def rollback(ui, repo, **opts):
4603 4605 """roll back the last transaction (DANGEROUS) (DEPRECATED)
4604 4606
4605 4607 Please use :hg:`commit --amend` instead of rollback to correct
4606 4608 mistakes in the last commit.
4607 4609
4608 4610 This command should be used with care. There is only one level of
4609 4611 rollback, and there is no way to undo a rollback. It will also
4610 4612 restore the dirstate at the time of the last transaction, losing
4611 4613 any dirstate changes since that time. This command does not alter
4612 4614 the working directory.
4613 4615
4614 4616 Transactions are used to encapsulate the effects of all commands
4615 4617 that create new changesets or propagate existing changesets into a
4616 4618 repository.
4617 4619
4618 4620 .. container:: verbose
4619 4621
4620 4622 For example, the following commands are transactional, and their
4621 4623 effects can be rolled back:
4622 4624
4623 4625 - commit
4624 4626 - import
4625 4627 - pull
4626 4628 - push (with this repository as the destination)
4627 4629 - unbundle
4628 4630
4629 4631 To avoid permanent data loss, rollback will refuse to rollback a
4630 4632 commit transaction if it isn't checked out. Use --force to
4631 4633 override this protection.
4632 4634
4633 4635 The rollback command can be entirely disabled by setting the
4634 4636 ``ui.rollback`` configuration setting to false. If you're here
4635 4637 because you want to use rollback and it's disabled, you can
4636 4638 re-enable the command by setting ``ui.rollback`` to true.
4637 4639
4638 4640 This command is not intended for use on public repositories. Once
4639 4641 changes are visible for pull by other users, rolling a transaction
4640 4642 back locally is ineffective (someone else may already have pulled
4641 4643 the changes). Furthermore, a race is possible with readers of the
4642 4644 repository; for example an in-progress pull from the repository
4643 4645 may fail if a rollback is performed.
4644 4646
4645 4647 Returns 0 on success, 1 if no rollback data is available.
4646 4648 """
4647 4649 if not ui.configbool('ui', 'rollback'):
4648 4650 raise error.Abort(_('rollback is disabled because it is unsafe'),
4649 4651 hint=('see `hg help -v rollback` for information'))
4650 4652 return repo.rollback(dryrun=opts.get(r'dry_run'),
4651 4653 force=opts.get(r'force'))
4652 4654
4653 4655 @command('root', [], cmdtype=readonly)
4654 4656 def root(ui, repo):
4655 4657 """print the root (top) of the current working directory
4656 4658
4657 4659 Print the root directory of the current repository.
4658 4660
4659 4661 Returns 0 on success.
4660 4662 """
4661 4663 ui.write(repo.root + "\n")
4662 4664
4663 4665 @command('^serve',
4664 4666 [('A', 'accesslog', '', _('name of access log file to write to'),
4665 4667 _('FILE')),
4666 4668 ('d', 'daemon', None, _('run server in background')),
4667 4669 ('', 'daemon-postexec', [], _('used internally by daemon mode')),
4668 4670 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
4669 4671 # use string type, then we can check if something was passed
4670 4672 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
4671 4673 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
4672 4674 _('ADDR')),
4673 4675 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
4674 4676 _('PREFIX')),
4675 4677 ('n', 'name', '',
4676 4678 _('name to show in web pages (default: working directory)'), _('NAME')),
4677 4679 ('', 'web-conf', '',
4678 4680 _("name of the hgweb config file (see 'hg help hgweb')"), _('FILE')),
4679 4681 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
4680 4682 _('FILE')),
4681 4683 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
4682 4684 ('', 'stdio', None, _('for remote clients (ADVANCED)')),
4683 4685 ('', 'cmdserver', '', _('for remote clients (ADVANCED)'), _('MODE')),
4684 4686 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
4685 4687 ('', 'style', '', _('template style to use'), _('STYLE')),
4686 4688 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
4687 4689 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))]
4688 4690 + subrepoopts,
4689 4691 _('[OPTION]...'),
4690 4692 optionalrepo=True)
4691 4693 def serve(ui, repo, **opts):
4692 4694 """start stand-alone webserver
4693 4695
4694 4696 Start a local HTTP repository browser and pull server. You can use
4695 4697 this for ad-hoc sharing and browsing of repositories. It is
4696 4698 recommended to use a real web server to serve a repository for
4697 4699 longer periods of time.
4698 4700
4699 4701 Please note that the server does not implement access control.
4700 4702 This means that, by default, anybody can read from the server and
4701 4703 nobody can write to it by default. Set the ``web.allow-push``
4702 4704 option to ``*`` to allow everybody to push to the server. You
4703 4705 should use a real web server if you need to authenticate users.
4704 4706
4705 4707 By default, the server logs accesses to stdout and errors to
4706 4708 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
4707 4709 files.
4708 4710
4709 4711 To have the server choose a free port number to listen on, specify
4710 4712 a port number of 0; in this case, the server will print the port
4711 4713 number it uses.
4712 4714
4713 4715 Returns 0 on success.
4714 4716 """
4715 4717
4716 4718 opts = pycompat.byteskwargs(opts)
4717 4719 if opts["stdio"] and opts["cmdserver"]:
4718 4720 raise error.Abort(_("cannot use --stdio with --cmdserver"))
4719 4721
4720 4722 if opts["stdio"]:
4721 4723 if repo is None:
4722 4724 raise error.RepoError(_("there is no Mercurial repository here"
4723 4725 " (.hg not found)"))
4724 4726 s = sshserver.sshserver(ui, repo)
4725 4727 s.serve_forever()
4726 4728
4727 4729 service = server.createservice(ui, repo, opts)
4728 4730 return server.runservice(opts, initfn=service.init, runfn=service.run)
4729 4731
4730 4732 @command('^status|st',
4731 4733 [('A', 'all', None, _('show status of all files')),
4732 4734 ('m', 'modified', None, _('show only modified files')),
4733 4735 ('a', 'added', None, _('show only added files')),
4734 4736 ('r', 'removed', None, _('show only removed files')),
4735 4737 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
4736 4738 ('c', 'clean', None, _('show only files without changes')),
4737 4739 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
4738 4740 ('i', 'ignored', None, _('show only ignored files')),
4739 4741 ('n', 'no-status', None, _('hide status prefix')),
4740 4742 ('t', 'terse', '', _('show the terse output (EXPERIMENTAL)')),
4741 4743 ('C', 'copies', None, _('show source of copied files')),
4742 4744 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
4743 4745 ('', 'rev', [], _('show difference from revision'), _('REV')),
4744 4746 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
4745 4747 ] + walkopts + subrepoopts + formatteropts,
4746 4748 _('[OPTION]... [FILE]...'),
4747 4749 inferrepo=True, cmdtype=readonly)
4748 4750 def status(ui, repo, *pats, **opts):
4749 4751 """show changed files in the working directory
4750 4752
4751 4753 Show status of files in the repository. If names are given, only
4752 4754 files that match are shown. Files that are clean or ignored or
4753 4755 the source of a copy/move operation, are not listed unless
4754 4756 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
4755 4757 Unless options described with "show only ..." are given, the
4756 4758 options -mardu are used.
4757 4759
4758 4760 Option -q/--quiet hides untracked (unknown and ignored) files
4759 4761 unless explicitly requested with -u/--unknown or -i/--ignored.
4760 4762
4761 4763 .. note::
4762 4764
4763 4765 :hg:`status` may appear to disagree with diff if permissions have
4764 4766 changed or a merge has occurred. The standard diff format does
4765 4767 not report permission changes and diff only reports changes
4766 4768 relative to one merge parent.
4767 4769
4768 4770 If one revision is given, it is used as the base revision.
4769 4771 If two revisions are given, the differences between them are
4770 4772 shown. The --change option can also be used as a shortcut to list
4771 4773 the changed files of a revision from its first parent.
4772 4774
4773 4775 The codes used to show the status of files are::
4774 4776
4775 4777 M = modified
4776 4778 A = added
4777 4779 R = removed
4778 4780 C = clean
4779 4781 ! = missing (deleted by non-hg command, but still tracked)
4780 4782 ? = not tracked
4781 4783 I = ignored
4782 4784 = origin of the previous file (with --copies)
4783 4785
4784 4786 .. container:: verbose
4785 4787
4786 4788 The -t/--terse option abbreviates the output by showing only the directory
4787 4789 name if all the files in it share the same status. The option takes an
4788 4790 argument indicating the statuses to abbreviate: 'm' for 'modified', 'a'
4789 4791 for 'added', 'r' for 'removed', 'd' for 'deleted', 'u' for 'unknown', 'i'
4790 4792 for 'ignored' and 'c' for clean.
4791 4793
4792 4794 It abbreviates only those statuses which are passed. Note that clean and
4793 4795 ignored files are not displayed with '--terse ic' unless the -c/--clean
4794 4796 and -i/--ignored options are also used.
4795 4797
4796 4798 The -v/--verbose option shows information when the repository is in an
4797 4799 unfinished merge, shelve, rebase state etc. You can have this behavior
4798 4800 turned on by default by enabling the ``commands.status.verbose`` option.
4799 4801
4800 4802 You can skip displaying some of these states by setting
4801 4803 ``commands.status.skipstates`` to one or more of: 'bisect', 'graft',
4802 4804 'histedit', 'merge', 'rebase', or 'unshelve'.
4803 4805
4804 4806 Examples:
4805 4807
4806 4808 - show changes in the working directory relative to a
4807 4809 changeset::
4808 4810
4809 4811 hg status --rev 9353
4810 4812
4811 4813 - show changes in the working directory relative to the
4812 4814 current directory (see :hg:`help patterns` for more information)::
4813 4815
4814 4816 hg status re:
4815 4817
4816 4818 - show all changes including copies in an existing changeset::
4817 4819
4818 4820 hg status --copies --change 9353
4819 4821
4820 4822 - get a NUL separated list of added files, suitable for xargs::
4821 4823
4822 4824 hg status -an0
4823 4825
4824 4826 - show more information about the repository status, abbreviating
4825 4827 added, removed, modified, deleted, and untracked paths::
4826 4828
4827 4829 hg status -v -t mardu
4828 4830
4829 4831 Returns 0 on success.
4830 4832
4831 4833 """
4832 4834
4833 4835 opts = pycompat.byteskwargs(opts)
4834 4836 revs = opts.get('rev')
4835 4837 change = opts.get('change')
4836 4838 terse = opts.get('terse')
4837 4839
4838 4840 if revs and change:
4839 4841 msg = _('cannot specify --rev and --change at the same time')
4840 4842 raise error.Abort(msg)
4841 4843 elif revs and terse:
4842 4844 msg = _('cannot use --terse with --rev')
4843 4845 raise error.Abort(msg)
4844 4846 elif change:
4845 4847 node2 = scmutil.revsingle(repo, change, None).node()
4846 4848 node1 = repo[node2].p1().node()
4847 4849 else:
4848 4850 node1, node2 = scmutil.revpair(repo, revs)
4849 4851
4850 4852 if pats or ui.configbool('commands', 'status.relative'):
4851 4853 cwd = repo.getcwd()
4852 4854 else:
4853 4855 cwd = ''
4854 4856
4855 4857 if opts.get('print0'):
4856 4858 end = '\0'
4857 4859 else:
4858 4860 end = '\n'
4859 4861 copy = {}
4860 4862 states = 'modified added removed deleted unknown ignored clean'.split()
4861 4863 show = [k for k in states if opts.get(k)]
4862 4864 if opts.get('all'):
4863 4865 show += ui.quiet and (states[:4] + ['clean']) or states
4864 4866
4865 4867 if not show:
4866 4868 if ui.quiet:
4867 4869 show = states[:4]
4868 4870 else:
4869 4871 show = states[:5]
4870 4872
4871 4873 m = scmutil.match(repo[node2], pats, opts)
4872 4874 if terse:
4873 4875 # we need to compute clean and unknown to terse
4874 4876 stat = repo.status(node1, node2, m,
4875 4877 'ignored' in show or 'i' in terse,
4876 4878 True, True, opts.get('subrepos'))
4877 4879
4878 4880 stat = cmdutil.tersedir(stat, terse)
4879 4881 else:
4880 4882 stat = repo.status(node1, node2, m,
4881 4883 'ignored' in show, 'clean' in show,
4882 4884 'unknown' in show, opts.get('subrepos'))
4883 4885
4884 4886 changestates = zip(states, pycompat.iterbytestr('MAR!?IC'), stat)
4885 4887
4886 4888 if (opts.get('all') or opts.get('copies')
4887 4889 or ui.configbool('ui', 'statuscopies')) and not opts.get('no_status'):
4888 4890 copy = copies.pathcopies(repo[node1], repo[node2], m)
4889 4891
4890 4892 ui.pager('status')
4891 4893 fm = ui.formatter('status', opts)
4892 4894 fmt = '%s' + end
4893 4895 showchar = not opts.get('no_status')
4894 4896
4895 4897 for state, char, files in changestates:
4896 4898 if state in show:
4897 4899 label = 'status.' + state
4898 4900 for f in files:
4899 4901 fm.startitem()
4900 4902 fm.condwrite(showchar, 'status', '%s ', char, label=label)
4901 4903 fm.write('path', fmt, repo.pathto(f, cwd), label=label)
4902 4904 if f in copy:
4903 4905 fm.write("copy", ' %s' + end, repo.pathto(copy[f], cwd),
4904 4906 label='status.copied')
4905 4907
4906 4908 if ((ui.verbose or ui.configbool('commands', 'status.verbose'))
4907 4909 and not ui.plain()):
4908 4910 cmdutil.morestatus(repo, fm)
4909 4911 fm.end()
4910 4912
4911 4913 @command('^summary|sum',
4912 4914 [('', 'remote', None, _('check for push and pull'))],
4913 4915 '[--remote]', cmdtype=readonly)
4914 4916 def summary(ui, repo, **opts):
4915 4917 """summarize working directory state
4916 4918
4917 4919 This generates a brief summary of the working directory state,
4918 4920 including parents, branch, commit status, phase and available updates.
4919 4921
4920 4922 With the --remote option, this will check the default paths for
4921 4923 incoming and outgoing changes. This can be time-consuming.
4922 4924
4923 4925 Returns 0 on success.
4924 4926 """
4925 4927
4926 4928 opts = pycompat.byteskwargs(opts)
4927 4929 ui.pager('summary')
4928 4930 ctx = repo[None]
4929 4931 parents = ctx.parents()
4930 4932 pnode = parents[0].node()
4931 4933 marks = []
4932 4934
4933 4935 ms = None
4934 4936 try:
4935 4937 ms = mergemod.mergestate.read(repo)
4936 4938 except error.UnsupportedMergeRecords as e:
4937 4939 s = ' '.join(e.recordtypes)
4938 4940 ui.warn(
4939 4941 _('warning: merge state has unsupported record types: %s\n') % s)
4940 4942 unresolved = []
4941 4943 else:
4942 4944 unresolved = list(ms.unresolved())
4943 4945
4944 4946 for p in parents:
4945 4947 # label with log.changeset (instead of log.parent) since this
4946 4948 # shows a working directory parent *changeset*:
4947 4949 # i18n: column positioning for "hg summary"
4948 4950 ui.write(_('parent: %d:%s ') % (p.rev(), p),
4949 4951 label=cmdutil._changesetlabels(p))
4950 4952 ui.write(' '.join(p.tags()), label='log.tag')
4951 4953 if p.bookmarks():
4952 4954 marks.extend(p.bookmarks())
4953 4955 if p.rev() == -1:
4954 4956 if not len(repo):
4955 4957 ui.write(_(' (empty repository)'))
4956 4958 else:
4957 4959 ui.write(_(' (no revision checked out)'))
4958 4960 if p.obsolete():
4959 4961 ui.write(_(' (obsolete)'))
4960 4962 if p.isunstable():
4961 4963 instabilities = (ui.label(instability, 'trouble.%s' % instability)
4962 4964 for instability in p.instabilities())
4963 4965 ui.write(' ('
4964 4966 + ', '.join(instabilities)
4965 4967 + ')')
4966 4968 ui.write('\n')
4967 4969 if p.description():
4968 4970 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
4969 4971 label='log.summary')
4970 4972
4971 4973 branch = ctx.branch()
4972 4974 bheads = repo.branchheads(branch)
4973 4975 # i18n: column positioning for "hg summary"
4974 4976 m = _('branch: %s\n') % branch
4975 4977 if branch != 'default':
4976 4978 ui.write(m, label='log.branch')
4977 4979 else:
4978 4980 ui.status(m, label='log.branch')
4979 4981
4980 4982 if marks:
4981 4983 active = repo._activebookmark
4982 4984 # i18n: column positioning for "hg summary"
4983 4985 ui.write(_('bookmarks:'), label='log.bookmark')
4984 4986 if active is not None:
4985 4987 if active in marks:
4986 4988 ui.write(' *' + active, label=bookmarks.activebookmarklabel)
4987 4989 marks.remove(active)
4988 4990 else:
4989 4991 ui.write(' [%s]' % active, label=bookmarks.activebookmarklabel)
4990 4992 for m in marks:
4991 4993 ui.write(' ' + m, label='log.bookmark')
4992 4994 ui.write('\n', label='log.bookmark')
4993 4995
4994 4996 status = repo.status(unknown=True)
4995 4997
4996 4998 c = repo.dirstate.copies()
4997 4999 copied, renamed = [], []
4998 5000 for d, s in c.iteritems():
4999 5001 if s in status.removed:
5000 5002 status.removed.remove(s)
5001 5003 renamed.append(d)
5002 5004 else:
5003 5005 copied.append(d)
5004 5006 if d in status.added:
5005 5007 status.added.remove(d)
5006 5008
5007 5009 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
5008 5010
5009 5011 labels = [(ui.label(_('%d modified'), 'status.modified'), status.modified),
5010 5012 (ui.label(_('%d added'), 'status.added'), status.added),
5011 5013 (ui.label(_('%d removed'), 'status.removed'), status.removed),
5012 5014 (ui.label(_('%d renamed'), 'status.copied'), renamed),
5013 5015 (ui.label(_('%d copied'), 'status.copied'), copied),
5014 5016 (ui.label(_('%d deleted'), 'status.deleted'), status.deleted),
5015 5017 (ui.label(_('%d unknown'), 'status.unknown'), status.unknown),
5016 5018 (ui.label(_('%d unresolved'), 'resolve.unresolved'), unresolved),
5017 5019 (ui.label(_('%d subrepos'), 'status.modified'), subs)]
5018 5020 t = []
5019 5021 for l, s in labels:
5020 5022 if s:
5021 5023 t.append(l % len(s))
5022 5024
5023 5025 t = ', '.join(t)
5024 5026 cleanworkdir = False
5025 5027
5026 5028 if repo.vfs.exists('graftstate'):
5027 5029 t += _(' (graft in progress)')
5028 5030 if repo.vfs.exists('updatestate'):
5029 5031 t += _(' (interrupted update)')
5030 5032 elif len(parents) > 1:
5031 5033 t += _(' (merge)')
5032 5034 elif branch != parents[0].branch():
5033 5035 t += _(' (new branch)')
5034 5036 elif (parents[0].closesbranch() and
5035 5037 pnode in repo.branchheads(branch, closed=True)):
5036 5038 t += _(' (head closed)')
5037 5039 elif not (status.modified or status.added or status.removed or renamed or
5038 5040 copied or subs):
5039 5041 t += _(' (clean)')
5040 5042 cleanworkdir = True
5041 5043 elif pnode not in bheads:
5042 5044 t += _(' (new branch head)')
5043 5045
5044 5046 if parents:
5045 5047 pendingphase = max(p.phase() for p in parents)
5046 5048 else:
5047 5049 pendingphase = phases.public
5048 5050
5049 5051 if pendingphase > phases.newcommitphase(ui):
5050 5052 t += ' (%s)' % phases.phasenames[pendingphase]
5051 5053
5052 5054 if cleanworkdir:
5053 5055 # i18n: column positioning for "hg summary"
5054 5056 ui.status(_('commit: %s\n') % t.strip())
5055 5057 else:
5056 5058 # i18n: column positioning for "hg summary"
5057 5059 ui.write(_('commit: %s\n') % t.strip())
5058 5060
5059 5061 # all ancestors of branch heads - all ancestors of parent = new csets
5060 5062 new = len(repo.changelog.findmissing([pctx.node() for pctx in parents],
5061 5063 bheads))
5062 5064
5063 5065 if new == 0:
5064 5066 # i18n: column positioning for "hg summary"
5065 5067 ui.status(_('update: (current)\n'))
5066 5068 elif pnode not in bheads:
5067 5069 # i18n: column positioning for "hg summary"
5068 5070 ui.write(_('update: %d new changesets (update)\n') % new)
5069 5071 else:
5070 5072 # i18n: column positioning for "hg summary"
5071 5073 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
5072 5074 (new, len(bheads)))
5073 5075
5074 5076 t = []
5075 5077 draft = len(repo.revs('draft()'))
5076 5078 if draft:
5077 5079 t.append(_('%d draft') % draft)
5078 5080 secret = len(repo.revs('secret()'))
5079 5081 if secret:
5080 5082 t.append(_('%d secret') % secret)
5081 5083
5082 5084 if draft or secret:
5083 5085 ui.status(_('phases: %s\n') % ', '.join(t))
5084 5086
5085 5087 if obsolete.isenabled(repo, obsolete.createmarkersopt):
5086 5088 for trouble in ("orphan", "contentdivergent", "phasedivergent"):
5087 5089 numtrouble = len(repo.revs(trouble + "()"))
5088 5090 # We write all the possibilities to ease translation
5089 5091 troublemsg = {
5090 5092 "orphan": _("orphan: %d changesets"),
5091 5093 "contentdivergent": _("content-divergent: %d changesets"),
5092 5094 "phasedivergent": _("phase-divergent: %d changesets"),
5093 5095 }
5094 5096 if numtrouble > 0:
5095 5097 ui.status(troublemsg[trouble] % numtrouble + "\n")
5096 5098
5097 5099 cmdutil.summaryhooks(ui, repo)
5098 5100
5099 5101 if opts.get('remote'):
5100 5102 needsincoming, needsoutgoing = True, True
5101 5103 else:
5102 5104 needsincoming, needsoutgoing = False, False
5103 5105 for i, o in cmdutil.summaryremotehooks(ui, repo, opts, None):
5104 5106 if i:
5105 5107 needsincoming = True
5106 5108 if o:
5107 5109 needsoutgoing = True
5108 5110 if not needsincoming and not needsoutgoing:
5109 5111 return
5110 5112
5111 5113 def getincoming():
5112 5114 source, branches = hg.parseurl(ui.expandpath('default'))
5113 5115 sbranch = branches[0]
5114 5116 try:
5115 5117 other = hg.peer(repo, {}, source)
5116 5118 except error.RepoError:
5117 5119 if opts.get('remote'):
5118 5120 raise
5119 5121 return source, sbranch, None, None, None
5120 5122 revs, checkout = hg.addbranchrevs(repo, other, branches, None)
5121 5123 if revs:
5122 5124 revs = [other.lookup(rev) for rev in revs]
5123 5125 ui.debug('comparing with %s\n' % util.hidepassword(source))
5124 5126 repo.ui.pushbuffer()
5125 5127 commoninc = discovery.findcommonincoming(repo, other, heads=revs)
5126 5128 repo.ui.popbuffer()
5127 5129 return source, sbranch, other, commoninc, commoninc[1]
5128 5130
5129 5131 if needsincoming:
5130 5132 source, sbranch, sother, commoninc, incoming = getincoming()
5131 5133 else:
5132 5134 source = sbranch = sother = commoninc = incoming = None
5133 5135
5134 5136 def getoutgoing():
5135 5137 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5136 5138 dbranch = branches[0]
5137 5139 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5138 5140 if source != dest:
5139 5141 try:
5140 5142 dother = hg.peer(repo, {}, dest)
5141 5143 except error.RepoError:
5142 5144 if opts.get('remote'):
5143 5145 raise
5144 5146 return dest, dbranch, None, None
5145 5147 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5146 5148 elif sother is None:
5147 5149 # there is no explicit destination peer, but source one is invalid
5148 5150 return dest, dbranch, None, None
5149 5151 else:
5150 5152 dother = sother
5151 5153 if (source != dest or (sbranch is not None and sbranch != dbranch)):
5152 5154 common = None
5153 5155 else:
5154 5156 common = commoninc
5155 5157 if revs:
5156 5158 revs = [repo.lookup(rev) for rev in revs]
5157 5159 repo.ui.pushbuffer()
5158 5160 outgoing = discovery.findcommonoutgoing(repo, dother, onlyheads=revs,
5159 5161 commoninc=common)
5160 5162 repo.ui.popbuffer()
5161 5163 return dest, dbranch, dother, outgoing
5162 5164
5163 5165 if needsoutgoing:
5164 5166 dest, dbranch, dother, outgoing = getoutgoing()
5165 5167 else:
5166 5168 dest = dbranch = dother = outgoing = None
5167 5169
5168 5170 if opts.get('remote'):
5169 5171 t = []
5170 5172 if incoming:
5171 5173 t.append(_('1 or more incoming'))
5172 5174 o = outgoing.missing
5173 5175 if o:
5174 5176 t.append(_('%d outgoing') % len(o))
5175 5177 other = dother or sother
5176 5178 if 'bookmarks' in other.listkeys('namespaces'):
5177 5179 counts = bookmarks.summary(repo, other)
5178 5180 if counts[0] > 0:
5179 5181 t.append(_('%d incoming bookmarks') % counts[0])
5180 5182 if counts[1] > 0:
5181 5183 t.append(_('%d outgoing bookmarks') % counts[1])
5182 5184
5183 5185 if t:
5184 5186 # i18n: column positioning for "hg summary"
5185 5187 ui.write(_('remote: %s\n') % (', '.join(t)))
5186 5188 else:
5187 5189 # i18n: column positioning for "hg summary"
5188 5190 ui.status(_('remote: (synced)\n'))
5189 5191
5190 5192 cmdutil.summaryremotehooks(ui, repo, opts,
5191 5193 ((source, sbranch, sother, commoninc),
5192 5194 (dest, dbranch, dother, outgoing)))
5193 5195
5194 5196 @command('tag',
5195 5197 [('f', 'force', None, _('force tag')),
5196 5198 ('l', 'local', None, _('make the tag local')),
5197 5199 ('r', 'rev', '', _('revision to tag'), _('REV')),
5198 5200 ('', 'remove', None, _('remove a tag')),
5199 5201 # -l/--local is already there, commitopts cannot be used
5200 5202 ('e', 'edit', None, _('invoke editor on commit messages')),
5201 5203 ('m', 'message', '', _('use text as commit message'), _('TEXT')),
5202 5204 ] + commitopts2,
5203 5205 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
5204 5206 def tag(ui, repo, name1, *names, **opts):
5205 5207 """add one or more tags for the current or given revision
5206 5208
5207 5209 Name a particular revision using <name>.
5208 5210
5209 5211 Tags are used to name particular revisions of the repository and are
5210 5212 very useful to compare different revisions, to go back to significant
5211 5213 earlier versions or to mark branch points as releases, etc. Changing
5212 5214 an existing tag is normally disallowed; use -f/--force to override.
5213 5215
5214 5216 If no revision is given, the parent of the working directory is
5215 5217 used.
5216 5218
5217 5219 To facilitate version control, distribution, and merging of tags,
5218 5220 they are stored as a file named ".hgtags" which is managed similarly
5219 5221 to other project files and can be hand-edited if necessary. This
5220 5222 also means that tagging creates a new commit. The file
5221 5223 ".hg/localtags" is used for local tags (not shared among
5222 5224 repositories).
5223 5225
5224 5226 Tag commits are usually made at the head of a branch. If the parent
5225 5227 of the working directory is not a branch head, :hg:`tag` aborts; use
5226 5228 -f/--force to force the tag commit to be based on a non-head
5227 5229 changeset.
5228 5230
5229 5231 See :hg:`help dates` for a list of formats valid for -d/--date.
5230 5232
5231 5233 Since tag names have priority over branch names during revision
5232 5234 lookup, using an existing branch name as a tag name is discouraged.
5233 5235
5234 5236 Returns 0 on success.
5235 5237 """
5236 5238 opts = pycompat.byteskwargs(opts)
5237 5239 wlock = lock = None
5238 5240 try:
5239 5241 wlock = repo.wlock()
5240 5242 lock = repo.lock()
5241 5243 rev_ = "."
5242 5244 names = [t.strip() for t in (name1,) + names]
5243 5245 if len(names) != len(set(names)):
5244 5246 raise error.Abort(_('tag names must be unique'))
5245 5247 for n in names:
5246 5248 scmutil.checknewlabel(repo, n, 'tag')
5247 5249 if not n:
5248 5250 raise error.Abort(_('tag names cannot consist entirely of '
5249 5251 'whitespace'))
5250 5252 if opts.get('rev') and opts.get('remove'):
5251 5253 raise error.Abort(_("--rev and --remove are incompatible"))
5252 5254 if opts.get('rev'):
5253 5255 rev_ = opts['rev']
5254 5256 message = opts.get('message')
5255 5257 if opts.get('remove'):
5256 5258 if opts.get('local'):
5257 5259 expectedtype = 'local'
5258 5260 else:
5259 5261 expectedtype = 'global'
5260 5262
5261 5263 for n in names:
5262 5264 if not repo.tagtype(n):
5263 5265 raise error.Abort(_("tag '%s' does not exist") % n)
5264 5266 if repo.tagtype(n) != expectedtype:
5265 5267 if expectedtype == 'global':
5266 5268 raise error.Abort(_("tag '%s' is not a global tag") % n)
5267 5269 else:
5268 5270 raise error.Abort(_("tag '%s' is not a local tag") % n)
5269 5271 rev_ = 'null'
5270 5272 if not message:
5271 5273 # we don't translate commit messages
5272 5274 message = 'Removed tag %s' % ', '.join(names)
5273 5275 elif not opts.get('force'):
5274 5276 for n in names:
5275 5277 if n in repo.tags():
5276 5278 raise error.Abort(_("tag '%s' already exists "
5277 5279 "(use -f to force)") % n)
5278 5280 if not opts.get('local'):
5279 5281 p1, p2 = repo.dirstate.parents()
5280 5282 if p2 != nullid:
5281 5283 raise error.Abort(_('uncommitted merge'))
5282 5284 bheads = repo.branchheads()
5283 5285 if not opts.get('force') and bheads and p1 not in bheads:
5284 5286 raise error.Abort(_('working directory is not at a branch head '
5285 5287 '(use -f to force)'))
5286 5288 r = scmutil.revsingle(repo, rev_).node()
5287 5289
5288 5290 if not message:
5289 5291 # we don't translate commit messages
5290 5292 message = ('Added tag %s for changeset %s' %
5291 5293 (', '.join(names), short(r)))
5292 5294
5293 5295 date = opts.get('date')
5294 5296 if date:
5295 5297 date = util.parsedate(date)
5296 5298
5297 5299 if opts.get('remove'):
5298 5300 editform = 'tag.remove'
5299 5301 else:
5300 5302 editform = 'tag.add'
5301 5303 editor = cmdutil.getcommiteditor(editform=editform,
5302 5304 **pycompat.strkwargs(opts))
5303 5305
5304 5306 # don't allow tagging the null rev
5305 5307 if (not opts.get('remove') and
5306 5308 scmutil.revsingle(repo, rev_).rev() == nullrev):
5307 5309 raise error.Abort(_("cannot tag null revision"))
5308 5310
5309 5311 tagsmod.tag(repo, names, r, message, opts.get('local'),
5310 5312 opts.get('user'), date, editor=editor)
5311 5313 finally:
5312 5314 release(lock, wlock)
5313 5315
5314 5316 @command('tags', formatteropts, '', cmdtype=readonly)
5315 5317 def tags(ui, repo, **opts):
5316 5318 """list repository tags
5317 5319
5318 5320 This lists both regular and local tags. When the -v/--verbose
5319 5321 switch is used, a third column "local" is printed for local tags.
5320 5322 When the -q/--quiet switch is used, only the tag name is printed.
5321 5323
5322 5324 Returns 0 on success.
5323 5325 """
5324 5326
5325 5327 opts = pycompat.byteskwargs(opts)
5326 5328 ui.pager('tags')
5327 5329 fm = ui.formatter('tags', opts)
5328 5330 hexfunc = fm.hexfunc
5329 5331 tagtype = ""
5330 5332
5331 5333 for t, n in reversed(repo.tagslist()):
5332 5334 hn = hexfunc(n)
5333 5335 label = 'tags.normal'
5334 5336 tagtype = ''
5335 5337 if repo.tagtype(t) == 'local':
5336 5338 label = 'tags.local'
5337 5339 tagtype = 'local'
5338 5340
5339 5341 fm.startitem()
5340 5342 fm.write('tag', '%s', t, label=label)
5341 5343 fmt = " " * (30 - encoding.colwidth(t)) + ' %5d:%s'
5342 5344 fm.condwrite(not ui.quiet, 'rev node', fmt,
5343 5345 repo.changelog.rev(n), hn, label=label)
5344 5346 fm.condwrite(ui.verbose and tagtype, 'type', ' %s',
5345 5347 tagtype, label=label)
5346 5348 fm.plain('\n')
5347 5349 fm.end()
5348 5350
5349 5351 @command('tip',
5350 5352 [('p', 'patch', None, _('show patch')),
5351 5353 ('g', 'git', None, _('use git extended diff format')),
5352 5354 ] + templateopts,
5353 5355 _('[-p] [-g]'))
5354 5356 def tip(ui, repo, **opts):
5355 5357 """show the tip revision (DEPRECATED)
5356 5358
5357 5359 The tip revision (usually just called the tip) is the changeset
5358 5360 most recently added to the repository (and therefore the most
5359 5361 recently changed head).
5360 5362
5361 5363 If you have just made a commit, that commit will be the tip. If
5362 5364 you have just pulled changes from another repository, the tip of
5363 5365 that repository becomes the current tip. The "tip" tag is special
5364 5366 and cannot be renamed or assigned to a different changeset.
5365 5367
5366 5368 This command is deprecated, please use :hg:`heads` instead.
5367 5369
5368 5370 Returns 0 on success.
5369 5371 """
5370 5372 opts = pycompat.byteskwargs(opts)
5371 5373 displayer = cmdutil.show_changeset(ui, repo, opts)
5372 5374 displayer.show(repo['tip'])
5373 5375 displayer.close()
5374 5376
5375 5377 @command('unbundle',
5376 5378 [('u', 'update', None,
5377 5379 _('update to new branch head if changesets were unbundled'))],
5378 5380 _('[-u] FILE...'))
5379 5381 def unbundle(ui, repo, fname1, *fnames, **opts):
5380 5382 """apply one or more bundle files
5381 5383
5382 5384 Apply one or more bundle files generated by :hg:`bundle`.
5383 5385
5384 5386 Returns 0 on success, 1 if an update has unresolved files.
5385 5387 """
5386 5388 fnames = (fname1,) + fnames
5387 5389
5388 5390 with repo.lock():
5389 5391 for fname in fnames:
5390 5392 f = hg.openpath(ui, fname)
5391 5393 gen = exchange.readbundle(ui, f, fname)
5392 5394 if isinstance(gen, streamclone.streamcloneapplier):
5393 5395 raise error.Abort(
5394 5396 _('packed bundles cannot be applied with '
5395 5397 '"hg unbundle"'),
5396 5398 hint=_('use "hg debugapplystreamclonebundle"'))
5397 5399 url = 'bundle:' + fname
5398 5400 try:
5399 5401 txnname = 'unbundle'
5400 5402 if not isinstance(gen, bundle2.unbundle20):
5401 5403 txnname = 'unbundle\n%s' % util.hidepassword(url)
5402 5404 with repo.transaction(txnname) as tr:
5403 5405 op = bundle2.applybundle(repo, gen, tr, source='unbundle',
5404 5406 url=url)
5405 5407 except error.BundleUnknownFeatureError as exc:
5406 5408 raise error.Abort(
5407 5409 _('%s: unknown bundle feature, %s') % (fname, exc),
5408 5410 hint=_("see https://mercurial-scm.org/"
5409 5411 "wiki/BundleFeature for more "
5410 5412 "information"))
5411 5413 modheads = bundle2.combinechangegroupresults(op)
5412 5414
5413 5415 return postincoming(ui, repo, modheads, opts.get(r'update'), None, None)
5414 5416
5415 5417 @command('^update|up|checkout|co',
5416 5418 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
5417 5419 ('c', 'check', None, _('require clean working directory')),
5418 5420 ('m', 'merge', None, _('merge uncommitted changes')),
5419 5421 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5420 5422 ('r', 'rev', '', _('revision'), _('REV'))
5421 5423 ] + mergetoolopts,
5422 5424 _('[-C|-c|-m] [-d DATE] [[-r] REV]'))
5423 5425 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False,
5424 5426 merge=None, tool=None):
5425 5427 """update working directory (or switch revisions)
5426 5428
5427 5429 Update the repository's working directory to the specified
5428 5430 changeset. If no changeset is specified, update to the tip of the
5429 5431 current named branch and move the active bookmark (see :hg:`help
5430 5432 bookmarks`).
5431 5433
5432 5434 Update sets the working directory's parent revision to the specified
5433 5435 changeset (see :hg:`help parents`).
5434 5436
5435 5437 If the changeset is not a descendant or ancestor of the working
5436 5438 directory's parent and there are uncommitted changes, the update is
5437 5439 aborted. With the -c/--check option, the working directory is checked
5438 5440 for uncommitted changes; if none are found, the working directory is
5439 5441 updated to the specified changeset.
5440 5442
5441 5443 .. container:: verbose
5442 5444
5443 5445 The -C/--clean, -c/--check, and -m/--merge options control what
5444 5446 happens if the working directory contains uncommitted changes.
5445 5447 At most of one of them can be specified.
5446 5448
5447 5449 1. If no option is specified, and if
5448 5450 the requested changeset is an ancestor or descendant of
5449 5451 the working directory's parent, the uncommitted changes
5450 5452 are merged into the requested changeset and the merged
5451 5453 result is left uncommitted. If the requested changeset is
5452 5454 not an ancestor or descendant (that is, it is on another
5453 5455 branch), the update is aborted and the uncommitted changes
5454 5456 are preserved.
5455 5457
5456 5458 2. With the -m/--merge option, the update is allowed even if the
5457 5459 requested changeset is not an ancestor or descendant of
5458 5460 the working directory's parent.
5459 5461
5460 5462 3. With the -c/--check option, the update is aborted and the
5461 5463 uncommitted changes are preserved.
5462 5464
5463 5465 4. With the -C/--clean option, uncommitted changes are discarded and
5464 5466 the working directory is updated to the requested changeset.
5465 5467
5466 5468 To cancel an uncommitted merge (and lose your changes), use
5467 5469 :hg:`update --clean .`.
5468 5470
5469 5471 Use null as the changeset to remove the working directory (like
5470 5472 :hg:`clone -U`).
5471 5473
5472 5474 If you want to revert just one file to an older revision, use
5473 5475 :hg:`revert [-r REV] NAME`.
5474 5476
5475 5477 See :hg:`help dates` for a list of formats valid for -d/--date.
5476 5478
5477 5479 Returns 0 on success, 1 if there are unresolved files.
5478 5480 """
5479 5481 if rev and node:
5480 5482 raise error.Abort(_("please specify just one revision"))
5481 5483
5482 5484 if ui.configbool('commands', 'update.requiredest'):
5483 5485 if not node and not rev and not date:
5484 5486 raise error.Abort(_('you must specify a destination'),
5485 5487 hint=_('for example: hg update ".::"'))
5486 5488
5487 5489 if rev is None or rev == '':
5488 5490 rev = node
5489 5491
5490 5492 if date and rev is not None:
5491 5493 raise error.Abort(_("you can't specify a revision and a date"))
5492 5494
5493 5495 if len([x for x in (clean, check, merge) if x]) > 1:
5494 5496 raise error.Abort(_("can only specify one of -C/--clean, -c/--check, "
5495 5497 "or -m/--merge"))
5496 5498
5497 5499 updatecheck = None
5498 5500 if check:
5499 5501 updatecheck = 'abort'
5500 5502 elif merge:
5501 5503 updatecheck = 'none'
5502 5504
5503 5505 with repo.wlock():
5504 5506 cmdutil.clearunfinished(repo)
5505 5507
5506 5508 if date:
5507 5509 rev = cmdutil.finddate(ui, repo, date)
5508 5510
5509 5511 # if we defined a bookmark, we have to remember the original name
5510 5512 brev = rev
5511 5513 rev = scmutil.revsingle(repo, rev, rev).rev()
5512 5514
5513 5515 repo.ui.setconfig('ui', 'forcemerge', tool, 'update')
5514 5516
5515 5517 return hg.updatetotally(ui, repo, rev, brev, clean=clean,
5516 5518 updatecheck=updatecheck)
5517 5519
5518 5520 @command('verify', [])
5519 5521 def verify(ui, repo):
5520 5522 """verify the integrity of the repository
5521 5523
5522 5524 Verify the integrity of the current repository.
5523 5525
5524 5526 This will perform an extensive check of the repository's
5525 5527 integrity, validating the hashes and checksums of each entry in
5526 5528 the changelog, manifest, and tracked files, as well as the
5527 5529 integrity of their crosslinks and indices.
5528 5530
5529 5531 Please see https://mercurial-scm.org/wiki/RepositoryCorruption
5530 5532 for more information about recovery from corruption of the
5531 5533 repository.
5532 5534
5533 5535 Returns 0 on success, 1 if errors are encountered.
5534 5536 """
5535 5537 return hg.verify(repo)
5536 5538
5537 5539 @command('version', [] + formatteropts, norepo=True, cmdtype=readonly)
5538 5540 def version_(ui, **opts):
5539 5541 """output version and copyright information"""
5540 5542 opts = pycompat.byteskwargs(opts)
5541 5543 if ui.verbose:
5542 5544 ui.pager('version')
5543 5545 fm = ui.formatter("version", opts)
5544 5546 fm.startitem()
5545 5547 fm.write("ver", _("Mercurial Distributed SCM (version %s)\n"),
5546 5548 util.version())
5547 5549 license = _(
5548 5550 "(see https://mercurial-scm.org for more information)\n"
5549 5551 "\nCopyright (C) 2005-2017 Matt Mackall and others\n"
5550 5552 "This is free software; see the source for copying conditions. "
5551 5553 "There is NO\nwarranty; "
5552 5554 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5553 5555 )
5554 5556 if not ui.quiet:
5555 5557 fm.plain(license)
5556 5558
5557 5559 if ui.verbose:
5558 5560 fm.plain(_("\nEnabled extensions:\n\n"))
5559 5561 # format names and versions into columns
5560 5562 names = []
5561 5563 vers = []
5562 5564 isinternals = []
5563 5565 for name, module in extensions.extensions():
5564 5566 names.append(name)
5565 5567 vers.append(extensions.moduleversion(module) or None)
5566 5568 isinternals.append(extensions.ismoduleinternal(module))
5567 5569 fn = fm.nested("extensions")
5568 5570 if names:
5569 5571 namefmt = " %%-%ds " % max(len(n) for n in names)
5570 5572 places = [_("external"), _("internal")]
5571 5573 for n, v, p in zip(names, vers, isinternals):
5572 5574 fn.startitem()
5573 5575 fn.condwrite(ui.verbose, "name", namefmt, n)
5574 5576 if ui.verbose:
5575 5577 fn.plain("%s " % places[p])
5576 5578 fn.data(bundled=p)
5577 5579 fn.condwrite(ui.verbose and v, "ver", "%s", v)
5578 5580 if ui.verbose:
5579 5581 fn.plain("\n")
5580 5582 fn.end()
5581 5583 fm.end()
5582 5584
5583 5585 def loadcmdtable(ui, name, cmdtable):
5584 5586 """Load command functions from specified cmdtable
5585 5587 """
5586 5588 overrides = [cmd for cmd in cmdtable if cmd in table]
5587 5589 if overrides:
5588 5590 ui.warn(_("extension '%s' overrides commands: %s\n")
5589 5591 % (name, " ".join(overrides)))
5590 5592 table.update(cmdtable)
@@ -1,2063 +1,2063 b''
1 1 # subrepo.py - sub-repository handling for Mercurial
2 2 #
3 3 # Copyright 2009-2010 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 from __future__ import absolute_import
9 9
10 10 import copy
11 11 import errno
12 12 import hashlib
13 13 import os
14 14 import posixpath
15 15 import re
16 16 import stat
17 17 import subprocess
18 18 import sys
19 19 import tarfile
20 20 import xml.dom.minidom
21 21
22 22
23 23 from .i18n import _
24 24 from . import (
25 25 cmdutil,
26 26 config,
27 27 encoding,
28 28 error,
29 29 exchange,
30 30 filemerge,
31 31 match as matchmod,
32 32 node,
33 33 pathutil,
34 34 phases,
35 35 pycompat,
36 36 scmutil,
37 37 util,
38 38 vfs as vfsmod,
39 39 )
40 40
41 41 hg = None
42 42 propertycache = util.propertycache
43 43
44 44 nullstate = ('', '', 'empty')
45 45
46 46 def _expandedabspath(path):
47 47 '''
48 48 get a path or url and if it is a path expand it and return an absolute path
49 49 '''
50 50 expandedpath = util.urllocalpath(util.expandpath(path))
51 51 u = util.url(expandedpath)
52 52 if not u.scheme:
53 53 path = util.normpath(os.path.abspath(u.path))
54 54 return path
55 55
56 56 def _getstorehashcachename(remotepath):
57 57 '''get a unique filename for the store hash cache of a remote repository'''
58 58 return hashlib.sha1(_expandedabspath(remotepath)).hexdigest()[0:12]
59 59
60 60 class SubrepoAbort(error.Abort):
61 61 """Exception class used to avoid handling a subrepo error more than once"""
62 62 def __init__(self, *args, **kw):
63 63 self.subrepo = kw.pop('subrepo', None)
64 64 self.cause = kw.pop('cause', None)
65 65 error.Abort.__init__(self, *args, **kw)
66 66
67 67 def annotatesubrepoerror(func):
68 68 def decoratedmethod(self, *args, **kargs):
69 69 try:
70 70 res = func(self, *args, **kargs)
71 71 except SubrepoAbort as ex:
72 72 # This exception has already been handled
73 73 raise ex
74 74 except error.Abort as ex:
75 75 subrepo = subrelpath(self)
76 76 errormsg = str(ex) + ' ' + _('(in subrepository "%s")') % subrepo
77 77 # avoid handling this exception by raising a SubrepoAbort exception
78 78 raise SubrepoAbort(errormsg, hint=ex.hint, subrepo=subrepo,
79 79 cause=sys.exc_info())
80 80 return res
81 81 return decoratedmethod
82 82
83 83 def state(ctx, ui):
84 84 """return a state dict, mapping subrepo paths configured in .hgsub
85 85 to tuple: (source from .hgsub, revision from .hgsubstate, kind
86 86 (key in types dict))
87 87 """
88 88 p = config.config()
89 89 repo = ctx.repo()
90 90 def read(f, sections=None, remap=None):
91 91 if f in ctx:
92 92 try:
93 93 data = ctx[f].data()
94 94 except IOError as err:
95 95 if err.errno != errno.ENOENT:
96 96 raise
97 97 # handle missing subrepo spec files as removed
98 98 ui.warn(_("warning: subrepo spec file \'%s\' not found\n") %
99 99 repo.pathto(f))
100 100 return
101 101 p.parse(f, data, sections, remap, read)
102 102 else:
103 103 raise error.Abort(_("subrepo spec file \'%s\' not found") %
104 104 repo.pathto(f))
105 105 if '.hgsub' in ctx:
106 106 read('.hgsub')
107 107
108 108 for path, src in ui.configitems('subpaths'):
109 109 p.set('subpaths', path, src, ui.configsource('subpaths', path))
110 110
111 111 rev = {}
112 112 if '.hgsubstate' in ctx:
113 113 try:
114 114 for i, l in enumerate(ctx['.hgsubstate'].data().splitlines()):
115 115 l = l.lstrip()
116 116 if not l:
117 117 continue
118 118 try:
119 119 revision, path = l.split(" ", 1)
120 120 except ValueError:
121 121 raise error.Abort(_("invalid subrepository revision "
122 122 "specifier in \'%s\' line %d")
123 123 % (repo.pathto('.hgsubstate'), (i + 1)))
124 124 rev[path] = revision
125 125 except IOError as err:
126 126 if err.errno != errno.ENOENT:
127 127 raise
128 128
129 129 def remap(src):
130 130 for pattern, repl in p.items('subpaths'):
131 131 # Turn r'C:\foo\bar' into r'C:\\foo\\bar' since re.sub
132 132 # does a string decode.
133 133 repl = util.escapestr(repl)
134 134 # However, we still want to allow back references to go
135 135 # through unharmed, so we turn r'\\1' into r'\1'. Again,
136 136 # extra escapes are needed because re.sub string decodes.
137 137 repl = re.sub(br'\\\\([0-9]+)', br'\\\1', repl)
138 138 try:
139 139 src = re.sub(pattern, repl, src, 1)
140 140 except re.error as e:
141 141 raise error.Abort(_("bad subrepository pattern in %s: %s")
142 142 % (p.source('subpaths', pattern), e))
143 143 return src
144 144
145 145 state = {}
146 146 for path, src in p[''].items():
147 147 kind = 'hg'
148 148 if src.startswith('['):
149 149 if ']' not in src:
150 150 raise error.Abort(_('missing ] in subrepository source'))
151 151 kind, src = src.split(']', 1)
152 152 kind = kind[1:]
153 153 src = src.lstrip() # strip any extra whitespace after ']'
154 154
155 155 if not util.url(src).isabs():
156 156 parent = _abssource(repo, abort=False)
157 157 if parent:
158 158 parent = util.url(parent)
159 159 parent.path = posixpath.join(parent.path or '', src)
160 160 parent.path = posixpath.normpath(parent.path)
161 161 joined = str(parent)
162 162 # Remap the full joined path and use it if it changes,
163 163 # else remap the original source.
164 164 remapped = remap(joined)
165 165 if remapped == joined:
166 166 src = remap(src)
167 167 else:
168 168 src = remapped
169 169
170 170 src = remap(src)
171 171 state[util.pconvert(path)] = (src.strip(), rev.get(path, ''), kind)
172 172
173 173 return state
174 174
175 175 def writestate(repo, state):
176 176 """rewrite .hgsubstate in (outer) repo with these subrepo states"""
177 177 lines = ['%s %s\n' % (state[s][1], s) for s in sorted(state)
178 178 if state[s][1] != nullstate[1]]
179 179 repo.wwrite('.hgsubstate', ''.join(lines), '')
180 180
181 181 def submerge(repo, wctx, mctx, actx, overwrite, labels=None):
182 182 """delegated from merge.applyupdates: merging of .hgsubstate file
183 183 in working context, merging context and ancestor context"""
184 184 if mctx == actx: # backwards?
185 185 actx = wctx.p1()
186 186 s1 = wctx.substate
187 187 s2 = mctx.substate
188 188 sa = actx.substate
189 189 sm = {}
190 190
191 191 repo.ui.debug("subrepo merge %s %s %s\n" % (wctx, mctx, actx))
192 192
193 193 def debug(s, msg, r=""):
194 194 if r:
195 195 r = "%s:%s:%s" % r
196 196 repo.ui.debug(" subrepo %s: %s %s\n" % (s, msg, r))
197 197
198 198 promptssrc = filemerge.partextras(labels)
199 199 for s, l in sorted(s1.iteritems()):
200 200 prompts = None
201 201 a = sa.get(s, nullstate)
202 202 ld = l # local state with possible dirty flag for compares
203 203 if wctx.sub(s).dirty():
204 204 ld = (l[0], l[1] + "+")
205 205 if wctx == actx: # overwrite
206 206 a = ld
207 207
208 208 prompts = promptssrc.copy()
209 209 prompts['s'] = s
210 210 if s in s2:
211 211 r = s2[s]
212 212 if ld == r or r == a: # no change or local is newer
213 213 sm[s] = l
214 214 continue
215 215 elif ld == a: # other side changed
216 216 debug(s, "other changed, get", r)
217 217 wctx.sub(s).get(r, overwrite)
218 218 sm[s] = r
219 219 elif ld[0] != r[0]: # sources differ
220 220 prompts['lo'] = l[0]
221 221 prompts['ro'] = r[0]
222 222 if repo.ui.promptchoice(
223 223 _(' subrepository sources for %(s)s differ\n'
224 224 'use (l)ocal%(l)s source (%(lo)s)'
225 225 ' or (r)emote%(o)s source (%(ro)s)?'
226 226 '$$ &Local $$ &Remote') % prompts, 0):
227 227 debug(s, "prompt changed, get", r)
228 228 wctx.sub(s).get(r, overwrite)
229 229 sm[s] = r
230 230 elif ld[1] == a[1]: # local side is unchanged
231 231 debug(s, "other side changed, get", r)
232 232 wctx.sub(s).get(r, overwrite)
233 233 sm[s] = r
234 234 else:
235 235 debug(s, "both sides changed")
236 236 srepo = wctx.sub(s)
237 237 prompts['sl'] = srepo.shortid(l[1])
238 238 prompts['sr'] = srepo.shortid(r[1])
239 239 option = repo.ui.promptchoice(
240 240 _(' subrepository %(s)s diverged (local revision: %(sl)s, '
241 241 'remote revision: %(sr)s)\n'
242 242 '(M)erge, keep (l)ocal%(l)s or keep (r)emote%(o)s?'
243 243 '$$ &Merge $$ &Local $$ &Remote')
244 244 % prompts, 0)
245 245 if option == 0:
246 246 wctx.sub(s).merge(r)
247 247 sm[s] = l
248 248 debug(s, "merge with", r)
249 249 elif option == 1:
250 250 sm[s] = l
251 251 debug(s, "keep local subrepo revision", l)
252 252 else:
253 253 wctx.sub(s).get(r, overwrite)
254 254 sm[s] = r
255 255 debug(s, "get remote subrepo revision", r)
256 256 elif ld == a: # remote removed, local unchanged
257 257 debug(s, "remote removed, remove")
258 258 wctx.sub(s).remove()
259 259 elif a == nullstate: # not present in remote or ancestor
260 260 debug(s, "local added, keep")
261 261 sm[s] = l
262 262 continue
263 263 else:
264 264 if repo.ui.promptchoice(
265 265 _(' local%(l)s changed subrepository %(s)s'
266 266 ' which remote%(o)s removed\n'
267 267 'use (c)hanged version or (d)elete?'
268 268 '$$ &Changed $$ &Delete') % prompts, 0):
269 269 debug(s, "prompt remove")
270 270 wctx.sub(s).remove()
271 271
272 272 for s, r in sorted(s2.items()):
273 273 prompts = None
274 274 if s in s1:
275 275 continue
276 276 elif s not in sa:
277 277 debug(s, "remote added, get", r)
278 278 mctx.sub(s).get(r)
279 279 sm[s] = r
280 280 elif r != sa[s]:
281 281 prompts = promptssrc.copy()
282 282 prompts['s'] = s
283 283 if repo.ui.promptchoice(
284 284 _(' remote%(o)s changed subrepository %(s)s'
285 285 ' which local%(l)s removed\n'
286 286 'use (c)hanged version or (d)elete?'
287 287 '$$ &Changed $$ &Delete') % prompts, 0) == 0:
288 288 debug(s, "prompt recreate", r)
289 289 mctx.sub(s).get(r)
290 290 sm[s] = r
291 291
292 292 # record merged .hgsubstate
293 293 writestate(repo, sm)
294 294 return sm
295 295
296 296 def _updateprompt(ui, sub, dirty, local, remote):
297 297 if dirty:
298 298 msg = (_(' subrepository sources for %s differ\n'
299 299 'use (l)ocal source (%s) or (r)emote source (%s)?'
300 300 '$$ &Local $$ &Remote')
301 301 % (subrelpath(sub), local, remote))
302 302 else:
303 303 msg = (_(' subrepository sources for %s differ (in checked out '
304 304 'version)\n'
305 305 'use (l)ocal source (%s) or (r)emote source (%s)?'
306 306 '$$ &Local $$ &Remote')
307 307 % (subrelpath(sub), local, remote))
308 308 return ui.promptchoice(msg, 0)
309 309
310 310 def reporelpath(repo):
311 311 """return path to this (sub)repo as seen from outermost repo"""
312 312 parent = repo
313 313 while util.safehasattr(parent, '_subparent'):
314 314 parent = parent._subparent
315 315 return repo.root[len(pathutil.normasprefix(parent.root)):]
316 316
317 317 def subrelpath(sub):
318 318 """return path to this subrepo as seen from outermost repo"""
319 319 return sub._relpath
320 320
321 321 def _abssource(repo, push=False, abort=True):
322 322 """return pull/push path of repo - either based on parent repo .hgsub info
323 323 or on the top repo config. Abort or return None if no source found."""
324 324 if util.safehasattr(repo, '_subparent'):
325 325 source = util.url(repo._subsource)
326 326 if source.isabs():
327 327 return str(source)
328 328 source.path = posixpath.normpath(source.path)
329 329 parent = _abssource(repo._subparent, push, abort=False)
330 330 if parent:
331 331 parent = util.url(util.pconvert(parent))
332 332 parent.path = posixpath.join(parent.path or '', source.path)
333 333 parent.path = posixpath.normpath(parent.path)
334 334 return str(parent)
335 335 else: # recursion reached top repo
336 336 if util.safehasattr(repo, '_subtoppath'):
337 337 return repo._subtoppath
338 338 if push and repo.ui.config('paths', 'default-push'):
339 339 return repo.ui.config('paths', 'default-push')
340 340 if repo.ui.config('paths', 'default'):
341 341 return repo.ui.config('paths', 'default')
342 342 if repo.shared():
343 343 # chop off the .hg component to get the default path form
344 344 return os.path.dirname(repo.sharedpath)
345 345 if abort:
346 346 raise error.Abort(_("default path for subrepository not found"))
347 347
348 348 def _sanitize(ui, vfs, ignore):
349 349 for dirname, dirs, names in vfs.walk():
350 350 for i, d in enumerate(dirs):
351 351 if d.lower() == ignore:
352 352 del dirs[i]
353 353 break
354 354 if vfs.basename(dirname).lower() != '.hg':
355 355 continue
356 356 for f in names:
357 357 if f.lower() == 'hgrc':
358 358 ui.warn(_("warning: removing potentially hostile 'hgrc' "
359 359 "in '%s'\n") % vfs.join(dirname))
360 360 vfs.unlink(vfs.reljoin(dirname, f))
361 361
362 362 def _auditsubrepopath(repo, path):
363 363 # auditor doesn't check if the path itself is a symlink
364 364 pathutil.pathauditor(repo.root)(path)
365 365 if repo.wvfs.islink(path):
366 366 raise error.Abort(_("subrepo '%s' traverses symbolic link") % path)
367 367
368 368 SUBREPO_ALLOWED_DEFAULTS = {
369 369 'hg': True,
370 370 'git': False,
371 371 'svn': False,
372 372 }
373 373
374 374 def _checktype(ui, kind):
375 375 # subrepos.allowed is a master kill switch. If disabled, subrepos are
376 376 # disabled period.
377 377 if not ui.configbool('subrepos', 'allowed', True):
378 378 raise error.Abort(_('subrepos not enabled'),
379 379 hint=_("see 'hg help config.subrepos' for details"))
380 380
381 381 default = SUBREPO_ALLOWED_DEFAULTS.get(kind, False)
382 382 if not ui.configbool('subrepos', '%s:allowed' % kind, default):
383 383 raise error.Abort(_('%s subrepos not allowed') % kind,
384 384 hint=_("see 'hg help config.subrepos' for details"))
385 385
386 386 if kind not in types:
387 387 raise error.Abort(_('unknown subrepo type %s') % kind)
388 388
389 389 def subrepo(ctx, path, allowwdir=False, allowcreate=True):
390 390 """return instance of the right subrepo class for subrepo in path"""
391 391 # subrepo inherently violates our import layering rules
392 392 # because it wants to make repo objects from deep inside the stack
393 393 # so we manually delay the circular imports to not break
394 394 # scripts that don't use our demand-loading
395 395 global hg
396 396 from . import hg as h
397 397 hg = h
398 398
399 399 repo = ctx.repo()
400 400 _auditsubrepopath(repo, path)
401 401 state = ctx.substate[path]
402 402 _checktype(repo.ui, state[2])
403 403 if allowwdir:
404 404 state = (state[0], ctx.subrev(path), state[2])
405 405 return types[state[2]](ctx, path, state[:2], allowcreate)
406 406
407 407 def nullsubrepo(ctx, path, pctx):
408 408 """return an empty subrepo in pctx for the extant subrepo in ctx"""
409 409 # subrepo inherently violates our import layering rules
410 410 # because it wants to make repo objects from deep inside the stack
411 411 # so we manually delay the circular imports to not break
412 412 # scripts that don't use our demand-loading
413 413 global hg
414 414 from . import hg as h
415 415 hg = h
416 416
417 417 repo = ctx.repo()
418 418 _auditsubrepopath(repo, path)
419 419 state = ctx.substate[path]
420 420 _checktype(repo.ui, state[2])
421 421 subrev = ''
422 422 if state[2] == 'hg':
423 423 subrev = "0" * 40
424 424 return types[state[2]](pctx, path, (state[0], subrev), True)
425 425
426 426 def newcommitphase(ui, ctx):
427 427 commitphase = phases.newcommitphase(ui)
428 428 substate = getattr(ctx, "substate", None)
429 429 if not substate:
430 430 return commitphase
431 431 check = ui.config('phases', 'checksubrepos')
432 432 if check not in ('ignore', 'follow', 'abort'):
433 433 raise error.Abort(_('invalid phases.checksubrepos configuration: %s')
434 434 % (check))
435 435 if check == 'ignore':
436 436 return commitphase
437 437 maxphase = phases.public
438 438 maxsub = None
439 439 for s in sorted(substate):
440 440 sub = ctx.sub(s)
441 441 subphase = sub.phase(substate[s][1])
442 442 if maxphase < subphase:
443 443 maxphase = subphase
444 444 maxsub = s
445 445 if commitphase < maxphase:
446 446 if check == 'abort':
447 447 raise error.Abort(_("can't commit in %s phase"
448 448 " conflicting %s from subrepository %s") %
449 449 (phases.phasenames[commitphase],
450 450 phases.phasenames[maxphase], maxsub))
451 451 ui.warn(_("warning: changes are committed in"
452 452 " %s phase from subrepository %s\n") %
453 453 (phases.phasenames[maxphase], maxsub))
454 454 return maxphase
455 455 return commitphase
456 456
457 457 # subrepo classes need to implement the following abstract class:
458 458
459 459 class abstractsubrepo(object):
460 460
461 461 def __init__(self, ctx, path):
462 462 """Initialize abstractsubrepo part
463 463
464 464 ``ctx`` is the context referring this subrepository in the
465 465 parent repository.
466 466
467 467 ``path`` is the path to this subrepository as seen from
468 468 innermost repository.
469 469 """
470 470 self.ui = ctx.repo().ui
471 471 self._ctx = ctx
472 472 self._path = path
473 473
474 474 def addwebdirpath(self, serverpath, webconf):
475 475 """Add the hgwebdir entries for this subrepo, and any of its subrepos.
476 476
477 477 ``serverpath`` is the path component of the URL for this repo.
478 478
479 479 ``webconf`` is the dictionary of hgwebdir entries.
480 480 """
481 481 pass
482 482
483 483 def storeclean(self, path):
484 484 """
485 485 returns true if the repository has not changed since it was last
486 486 cloned from or pushed to a given repository.
487 487 """
488 488 return False
489 489
490 490 def dirty(self, ignoreupdate=False, missing=False):
491 491 """returns true if the dirstate of the subrepo is dirty or does not
492 492 match current stored state. If ignoreupdate is true, only check
493 493 whether the subrepo has uncommitted changes in its dirstate. If missing
494 494 is true, check for deleted files.
495 495 """
496 496 raise NotImplementedError
497 497
498 498 def dirtyreason(self, ignoreupdate=False, missing=False):
499 499 """return reason string if it is ``dirty()``
500 500
501 501 Returned string should have enough information for the message
502 502 of exception.
503 503
504 504 This returns None, otherwise.
505 505 """
506 506 if self.dirty(ignoreupdate=ignoreupdate, missing=missing):
507 507 return _('uncommitted changes in subrepository "%s"'
508 508 ) % subrelpath(self)
509 509
510 510 def bailifchanged(self, ignoreupdate=False, hint=None):
511 511 """raise Abort if subrepository is ``dirty()``
512 512 """
513 513 dirtyreason = self.dirtyreason(ignoreupdate=ignoreupdate,
514 514 missing=True)
515 515 if dirtyreason:
516 516 raise error.Abort(dirtyreason, hint=hint)
517 517
518 518 def basestate(self):
519 519 """current working directory base state, disregarding .hgsubstate
520 520 state and working directory modifications"""
521 521 raise NotImplementedError
522 522
523 523 def checknested(self, path):
524 524 """check if path is a subrepository within this repository"""
525 525 return False
526 526
527 527 def commit(self, text, user, date):
528 528 """commit the current changes to the subrepo with the given
529 529 log message. Use given user and date if possible. Return the
530 530 new state of the subrepo.
531 531 """
532 532 raise NotImplementedError
533 533
534 534 def phase(self, state):
535 535 """returns phase of specified state in the subrepository.
536 536 """
537 537 return phases.public
538 538
539 539 def remove(self):
540 540 """remove the subrepo
541 541
542 542 (should verify the dirstate is not dirty first)
543 543 """
544 544 raise NotImplementedError
545 545
546 546 def get(self, state, overwrite=False):
547 547 """run whatever commands are needed to put the subrepo into
548 548 this state
549 549 """
550 550 raise NotImplementedError
551 551
552 552 def merge(self, state):
553 553 """merge currently-saved state with the new state."""
554 554 raise NotImplementedError
555 555
556 556 def push(self, opts):
557 557 """perform whatever action is analogous to 'hg push'
558 558
559 559 This may be a no-op on some systems.
560 560 """
561 561 raise NotImplementedError
562 562
563 563 def add(self, ui, match, prefix, explicitonly, **opts):
564 564 return []
565 565
566 566 def addremove(self, matcher, prefix, opts, dry_run, similarity):
567 567 self.ui.warn("%s: %s" % (prefix, _("addremove is not supported")))
568 568 return 1
569 569
570 570 def cat(self, match, fm, fntemplate, prefix, **opts):
571 571 return 1
572 572
573 573 def status(self, rev2, **opts):
574 574 return scmutil.status([], [], [], [], [], [], [])
575 575
576 576 def diff(self, ui, diffopts, node2, match, prefix, **opts):
577 577 pass
578 578
579 579 def outgoing(self, ui, dest, opts):
580 580 return 1
581 581
582 582 def incoming(self, ui, source, opts):
583 583 return 1
584 584
585 585 def files(self):
586 586 """return filename iterator"""
587 587 raise NotImplementedError
588 588
589 589 def filedata(self, name, decode):
590 590 """return file data, optionally passed through repo decoders"""
591 591 raise NotImplementedError
592 592
593 593 def fileflags(self, name):
594 594 """return file flags"""
595 595 return ''
596 596
597 597 def getfileset(self, expr):
598 598 """Resolve the fileset expression for this repo"""
599 599 return set()
600 600
601 601 def printfiles(self, ui, m, fm, fmt, subrepos):
602 602 """handle the files command for this subrepo"""
603 603 return 1
604 604
605 605 def archive(self, archiver, prefix, match=None, decode=True):
606 606 if match is not None:
607 607 files = [f for f in self.files() if match(f)]
608 608 else:
609 609 files = self.files()
610 610 total = len(files)
611 611 relpath = subrelpath(self)
612 612 self.ui.progress(_('archiving (%s)') % relpath, 0,
613 613 unit=_('files'), total=total)
614 614 for i, name in enumerate(files):
615 615 flags = self.fileflags(name)
616 616 mode = 'x' in flags and 0o755 or 0o644
617 617 symlink = 'l' in flags
618 618 archiver.addfile(prefix + self._path + '/' + name,
619 619 mode, symlink, self.filedata(name, decode))
620 620 self.ui.progress(_('archiving (%s)') % relpath, i + 1,
621 621 unit=_('files'), total=total)
622 622 self.ui.progress(_('archiving (%s)') % relpath, None)
623 623 return total
624 624
625 625 def walk(self, match):
626 626 '''
627 627 walk recursively through the directory tree, finding all files
628 628 matched by the match function
629 629 '''
630 630
631 631 def forget(self, match, prefix):
632 632 return ([], [])
633 633
634 634 def removefiles(self, matcher, prefix, after, force, subrepos, warnings):
635 635 """remove the matched files from the subrepository and the filesystem,
636 636 possibly by force and/or after the file has been removed from the
637 637 filesystem. Return 0 on success, 1 on any warning.
638 638 """
639 639 warnings.append(_("warning: removefiles not implemented (%s)")
640 640 % self._path)
641 641 return 1
642 642
643 643 def revert(self, substate, *pats, **opts):
644 644 self.ui.warn(_('%s: reverting %s subrepos is unsupported\n') \
645 645 % (substate[0], substate[2]))
646 646 return []
647 647
648 648 def shortid(self, revid):
649 649 return revid
650 650
651 651 def unshare(self):
652 652 '''
653 653 convert this repository from shared to normal storage.
654 654 '''
655 655
656 656 def verify(self):
657 657 '''verify the integrity of the repository. Return 0 on success or
658 658 warning, 1 on any error.
659 659 '''
660 660 return 0
661 661
662 662 @propertycache
663 663 def wvfs(self):
664 664 """return vfs to access the working directory of this subrepository
665 665 """
666 666 return vfsmod.vfs(self._ctx.repo().wvfs.join(self._path))
667 667
668 668 @propertycache
669 669 def _relpath(self):
670 670 """return path to this subrepository as seen from outermost repository
671 671 """
672 672 return self.wvfs.reljoin(reporelpath(self._ctx.repo()), self._path)
673 673
674 674 class hgsubrepo(abstractsubrepo):
675 675 def __init__(self, ctx, path, state, allowcreate):
676 676 super(hgsubrepo, self).__init__(ctx, path)
677 677 self._state = state
678 678 r = ctx.repo()
679 679 root = r.wjoin(path)
680 680 create = allowcreate and not r.wvfs.exists('%s/.hg' % path)
681 681 self._repo = hg.repository(r.baseui, root, create=create)
682 682
683 683 # Propagate the parent's --hidden option
684 684 if r is r.unfiltered():
685 685 self._repo = self._repo.unfiltered()
686 686
687 687 self.ui = self._repo.ui
688 688 for s, k in [('ui', 'commitsubrepos')]:
689 689 v = r.ui.config(s, k)
690 690 if v:
691 691 self.ui.setconfig(s, k, v, 'subrepo')
692 692 # internal config: ui._usedassubrepo
693 693 self.ui.setconfig('ui', '_usedassubrepo', 'True', 'subrepo')
694 694 self._initrepo(r, state[0], create)
695 695
696 696 @annotatesubrepoerror
697 697 def addwebdirpath(self, serverpath, webconf):
698 698 cmdutil.addwebdirpath(self._repo, subrelpath(self), webconf)
699 699
700 700 def storeclean(self, path):
701 701 with self._repo.lock():
702 702 return self._storeclean(path)
703 703
704 704 def _storeclean(self, path):
705 705 clean = True
706 706 itercache = self._calcstorehash(path)
707 707 for filehash in self._readstorehashcache(path):
708 708 if filehash != next(itercache, None):
709 709 clean = False
710 710 break
711 711 if clean:
712 712 # if not empty:
713 713 # the cached and current pull states have a different size
714 714 clean = next(itercache, None) is None
715 715 return clean
716 716
717 717 def _calcstorehash(self, remotepath):
718 718 '''calculate a unique "store hash"
719 719
720 720 This method is used to to detect when there are changes that may
721 721 require a push to a given remote path.'''
722 722 # sort the files that will be hashed in increasing (likely) file size
723 723 filelist = ('bookmarks', 'store/phaseroots', 'store/00changelog.i')
724 724 yield '# %s\n' % _expandedabspath(remotepath)
725 725 vfs = self._repo.vfs
726 726 for relname in filelist:
727 727 filehash = hashlib.sha1(vfs.tryread(relname)).hexdigest()
728 728 yield '%s = %s\n' % (relname, filehash)
729 729
730 730 @propertycache
731 731 def _cachestorehashvfs(self):
732 732 return vfsmod.vfs(self._repo.vfs.join('cache/storehash'))
733 733
734 734 def _readstorehashcache(self, remotepath):
735 735 '''read the store hash cache for a given remote repository'''
736 736 cachefile = _getstorehashcachename(remotepath)
737 737 return self._cachestorehashvfs.tryreadlines(cachefile, 'r')
738 738
739 739 def _cachestorehash(self, remotepath):
740 740 '''cache the current store hash
741 741
742 742 Each remote repo requires its own store hash cache, because a subrepo
743 743 store may be "clean" versus a given remote repo, but not versus another
744 744 '''
745 745 cachefile = _getstorehashcachename(remotepath)
746 746 with self._repo.lock():
747 747 storehash = list(self._calcstorehash(remotepath))
748 748 vfs = self._cachestorehashvfs
749 749 vfs.writelines(cachefile, storehash, mode='w', notindexed=True)
750 750
751 751 def _getctx(self):
752 752 '''fetch the context for this subrepo revision, possibly a workingctx
753 753 '''
754 754 if self._ctx.rev() is None:
755 755 return self._repo[None] # workingctx if parent is workingctx
756 756 else:
757 757 rev = self._state[1]
758 758 return self._repo[rev]
759 759
760 760 @annotatesubrepoerror
761 761 def _initrepo(self, parentrepo, source, create):
762 762 self._repo._subparent = parentrepo
763 763 self._repo._subsource = source
764 764
765 765 if create:
766 766 lines = ['[paths]\n']
767 767
768 768 def addpathconfig(key, value):
769 769 if value:
770 770 lines.append('%s = %s\n' % (key, value))
771 771 self.ui.setconfig('paths', key, value, 'subrepo')
772 772
773 773 defpath = _abssource(self._repo, abort=False)
774 774 defpushpath = _abssource(self._repo, True, abort=False)
775 775 addpathconfig('default', defpath)
776 776 if defpath != defpushpath:
777 777 addpathconfig('default-push', defpushpath)
778 778
779 779 fp = self._repo.vfs("hgrc", "w", text=True)
780 780 try:
781 781 fp.write(''.join(lines))
782 782 finally:
783 783 fp.close()
784 784
785 785 @annotatesubrepoerror
786 786 def add(self, ui, match, prefix, explicitonly, **opts):
787 787 return cmdutil.add(ui, self._repo, match,
788 788 self.wvfs.reljoin(prefix, self._path),
789 789 explicitonly, **opts)
790 790
791 791 @annotatesubrepoerror
792 792 def addremove(self, m, prefix, opts, dry_run, similarity):
793 793 # In the same way as sub directories are processed, once in a subrepo,
794 794 # always entry any of its subrepos. Don't corrupt the options that will
795 795 # be used to process sibling subrepos however.
796 796 opts = copy.copy(opts)
797 797 opts['subrepos'] = True
798 798 return scmutil.addremove(self._repo, m,
799 799 self.wvfs.reljoin(prefix, self._path), opts,
800 800 dry_run, similarity)
801 801
802 802 @annotatesubrepoerror
803 803 def cat(self, match, fm, fntemplate, prefix, **opts):
804 804 rev = self._state[1]
805 805 ctx = self._repo[rev]
806 806 return cmdutil.cat(self.ui, self._repo, ctx, match, fm, fntemplate,
807 807 prefix, **opts)
808 808
809 809 @annotatesubrepoerror
810 810 def status(self, rev2, **opts):
811 811 try:
812 812 rev1 = self._state[1]
813 813 ctx1 = self._repo[rev1]
814 814 ctx2 = self._repo[rev2]
815 815 return self._repo.status(ctx1, ctx2, **opts)
816 816 except error.RepoLookupError as inst:
817 817 self.ui.warn(_('warning: error "%s" in subrepository "%s"\n')
818 818 % (inst, subrelpath(self)))
819 819 return scmutil.status([], [], [], [], [], [], [])
820 820
821 821 @annotatesubrepoerror
822 822 def diff(self, ui, diffopts, node2, match, prefix, **opts):
823 823 try:
824 824 node1 = node.bin(self._state[1])
825 825 # We currently expect node2 to come from substate and be
826 826 # in hex format
827 827 if node2 is not None:
828 828 node2 = node.bin(node2)
829 829 cmdutil.diffordiffstat(ui, self._repo, diffopts,
830 830 node1, node2, match,
831 831 prefix=posixpath.join(prefix, self._path),
832 832 listsubrepos=True, **opts)
833 833 except error.RepoLookupError as inst:
834 834 self.ui.warn(_('warning: error "%s" in subrepository "%s"\n')
835 835 % (inst, subrelpath(self)))
836 836
837 837 @annotatesubrepoerror
838 838 def archive(self, archiver, prefix, match=None, decode=True):
839 839 self._get(self._state + ('hg',))
840 840 total = abstractsubrepo.archive(self, archiver, prefix, match)
841 841 rev = self._state[1]
842 842 ctx = self._repo[rev]
843 843 for subpath in ctx.substate:
844 844 s = subrepo(ctx, subpath, True)
845 845 submatch = matchmod.subdirmatcher(subpath, match)
846 846 total += s.archive(archiver, prefix + self._path + '/', submatch,
847 847 decode)
848 848 return total
849 849
850 850 @annotatesubrepoerror
851 851 def dirty(self, ignoreupdate=False, missing=False):
852 852 r = self._state[1]
853 853 if r == '' and not ignoreupdate: # no state recorded
854 854 return True
855 855 w = self._repo[None]
856 856 if r != w.p1().hex() and not ignoreupdate:
857 857 # different version checked out
858 858 return True
859 859 return w.dirty(missing=missing) # working directory changed
860 860
861 861 def basestate(self):
862 862 return self._repo['.'].hex()
863 863
864 864 def checknested(self, path):
865 865 return self._repo._checknested(self._repo.wjoin(path))
866 866
867 867 @annotatesubrepoerror
868 868 def commit(self, text, user, date):
869 869 # don't bother committing in the subrepo if it's only been
870 870 # updated
871 871 if not self.dirty(True):
872 872 return self._repo['.'].hex()
873 873 self.ui.debug("committing subrepo %s\n" % subrelpath(self))
874 874 n = self._repo.commit(text, user, date)
875 875 if not n:
876 876 return self._repo['.'].hex() # different version checked out
877 877 return node.hex(n)
878 878
879 879 @annotatesubrepoerror
880 880 def phase(self, state):
881 881 return self._repo[state].phase()
882 882
883 883 @annotatesubrepoerror
884 884 def remove(self):
885 885 # we can't fully delete the repository as it may contain
886 886 # local-only history
887 887 self.ui.note(_('removing subrepo %s\n') % subrelpath(self))
888 888 hg.clean(self._repo, node.nullid, False)
889 889
890 890 def _get(self, state):
891 891 source, revision, kind = state
892 892 parentrepo = self._repo._subparent
893 893
894 894 if revision in self._repo.unfiltered():
895 895 # Allow shared subrepos tracked at null to setup the sharedpath
896 896 if len(self._repo) != 0 or not parentrepo.shared():
897 897 return True
898 898 self._repo._subsource = source
899 899 srcurl = _abssource(self._repo)
900 900 other = hg.peer(self._repo, {}, srcurl)
901 901 if len(self._repo) == 0:
902 902 # use self._repo.vfs instead of self.wvfs to remove .hg only
903 903 self._repo.vfs.rmtree()
904 904 if parentrepo.shared():
905 905 self.ui.status(_('sharing subrepo %s from %s\n')
906 906 % (subrelpath(self), srcurl))
907 907 shared = hg.share(self._repo._subparent.baseui,
908 908 other, self._repo.root,
909 909 update=False, bookmarks=False)
910 910 self._repo = shared.local()
911 911 else:
912 912 self.ui.status(_('cloning subrepo %s from %s\n')
913 913 % (subrelpath(self), srcurl))
914 914 other, cloned = hg.clone(self._repo._subparent.baseui, {},
915 915 other, self._repo.root,
916 916 update=False)
917 917 self._repo = cloned.local()
918 918 self._initrepo(parentrepo, source, create=True)
919 919 self._cachestorehash(srcurl)
920 920 else:
921 921 self.ui.status(_('pulling subrepo %s from %s\n')
922 922 % (subrelpath(self), srcurl))
923 923 cleansub = self.storeclean(srcurl)
924 924 exchange.pull(self._repo, other)
925 925 if cleansub:
926 926 # keep the repo clean after pull
927 927 self._cachestorehash(srcurl)
928 928 return False
929 929
930 930 @annotatesubrepoerror
931 931 def get(self, state, overwrite=False):
932 932 inrepo = self._get(state)
933 933 source, revision, kind = state
934 934 repo = self._repo
935 935 repo.ui.debug("getting subrepo %s\n" % self._path)
936 936 if inrepo:
937 937 urepo = repo.unfiltered()
938 938 ctx = urepo[revision]
939 939 if ctx.hidden():
940 940 urepo.ui.warn(
941 941 _('revision %s in subrepository "%s" is hidden\n') \
942 942 % (revision[0:12], self._path))
943 943 repo = urepo
944 944 hg.updaterepo(repo, revision, overwrite)
945 945
946 946 @annotatesubrepoerror
947 947 def merge(self, state):
948 948 self._get(state)
949 949 cur = self._repo['.']
950 950 dst = self._repo[state[1]]
951 951 anc = dst.ancestor(cur)
952 952
953 953 def mergefunc():
954 954 if anc == cur and dst.branch() == cur.branch():
955 955 self.ui.debug('updating subrepository "%s"\n'
956 956 % subrelpath(self))
957 957 hg.update(self._repo, state[1])
958 958 elif anc == dst:
959 959 self.ui.debug('skipping subrepository "%s"\n'
960 960 % subrelpath(self))
961 961 else:
962 962 self.ui.debug('merging subrepository "%s"\n' % subrelpath(self))
963 963 hg.merge(self._repo, state[1], remind=False)
964 964
965 965 wctx = self._repo[None]
966 966 if self.dirty():
967 967 if anc != dst:
968 968 if _updateprompt(self.ui, self, wctx.dirty(), cur, dst):
969 969 mergefunc()
970 970 else:
971 971 mergefunc()
972 972 else:
973 973 mergefunc()
974 974
975 975 @annotatesubrepoerror
976 976 def push(self, opts):
977 977 force = opts.get('force')
978 978 newbranch = opts.get('new_branch')
979 979 ssh = opts.get('ssh')
980 980
981 981 # push subrepos depth-first for coherent ordering
982 982 c = self._repo['']
983 983 subs = c.substate # only repos that are committed
984 984 for s in sorted(subs):
985 985 if c.sub(s).push(opts) == 0:
986 986 return False
987 987
988 988 dsturl = _abssource(self._repo, True)
989 989 if not force:
990 990 if self.storeclean(dsturl):
991 991 self.ui.status(
992 992 _('no changes made to subrepo %s since last push to %s\n')
993 993 % (subrelpath(self), dsturl))
994 994 return None
995 995 self.ui.status(_('pushing subrepo %s to %s\n') %
996 996 (subrelpath(self), dsturl))
997 997 other = hg.peer(self._repo, {'ssh': ssh}, dsturl)
998 998 res = exchange.push(self._repo, other, force, newbranch=newbranch)
999 999
1000 1000 # the repo is now clean
1001 1001 self._cachestorehash(dsturl)
1002 1002 return res.cgresult
1003 1003
1004 1004 @annotatesubrepoerror
1005 1005 def outgoing(self, ui, dest, opts):
1006 1006 if 'rev' in opts or 'branch' in opts:
1007 1007 opts = copy.copy(opts)
1008 1008 opts.pop('rev', None)
1009 1009 opts.pop('branch', None)
1010 1010 return hg.outgoing(ui, self._repo, _abssource(self._repo, True), opts)
1011 1011
1012 1012 @annotatesubrepoerror
1013 1013 def incoming(self, ui, source, opts):
1014 1014 if 'rev' in opts or 'branch' in opts:
1015 1015 opts = copy.copy(opts)
1016 1016 opts.pop('rev', None)
1017 1017 opts.pop('branch', None)
1018 1018 return hg.incoming(ui, self._repo, _abssource(self._repo, False), opts)
1019 1019
1020 1020 @annotatesubrepoerror
1021 1021 def files(self):
1022 1022 rev = self._state[1]
1023 1023 ctx = self._repo[rev]
1024 1024 return ctx.manifest().keys()
1025 1025
1026 1026 def filedata(self, name, decode):
1027 1027 rev = self._state[1]
1028 1028 data = self._repo[rev][name].data()
1029 1029 if decode:
1030 1030 data = self._repo.wwritedata(name, data)
1031 1031 return data
1032 1032
1033 1033 def fileflags(self, name):
1034 1034 rev = self._state[1]
1035 1035 ctx = self._repo[rev]
1036 1036 return ctx.flags(name)
1037 1037
1038 1038 @annotatesubrepoerror
1039 1039 def printfiles(self, ui, m, fm, fmt, subrepos):
1040 1040 # If the parent context is a workingctx, use the workingctx here for
1041 1041 # consistency.
1042 1042 if self._ctx.rev() is None:
1043 1043 ctx = self._repo[None]
1044 1044 else:
1045 1045 rev = self._state[1]
1046 1046 ctx = self._repo[rev]
1047 1047 return cmdutil.files(ui, ctx, m, fm, fmt, subrepos)
1048 1048
1049 1049 @annotatesubrepoerror
1050 1050 def getfileset(self, expr):
1051 1051 if self._ctx.rev() is None:
1052 1052 ctx = self._repo[None]
1053 1053 else:
1054 1054 rev = self._state[1]
1055 1055 ctx = self._repo[rev]
1056 1056
1057 1057 files = ctx.getfileset(expr)
1058 1058
1059 1059 for subpath in ctx.substate:
1060 1060 sub = ctx.sub(subpath)
1061 1061
1062 1062 try:
1063 1063 files.extend(subpath + '/' + f for f in sub.getfileset(expr))
1064 1064 except error.LookupError:
1065 1065 self.ui.status(_("skipping missing subrepository: %s\n")
1066 1066 % self.wvfs.reljoin(reporelpath(self), subpath))
1067 1067 return files
1068 1068
1069 1069 def walk(self, match):
1070 1070 ctx = self._repo[None]
1071 1071 return ctx.walk(match)
1072 1072
1073 1073 @annotatesubrepoerror
1074 1074 def forget(self, match, prefix):
1075 1075 return cmdutil.forget(self.ui, self._repo, match,
1076 1076 self.wvfs.reljoin(prefix, self._path), True)
1077 1077
1078 1078 @annotatesubrepoerror
1079 1079 def removefiles(self, matcher, prefix, after, force, subrepos, warnings):
1080 1080 return cmdutil.remove(self.ui, self._repo, matcher,
1081 1081 self.wvfs.reljoin(prefix, self._path),
1082 1082 after, force, subrepos)
1083 1083
1084 1084 @annotatesubrepoerror
1085 1085 def revert(self, substate, *pats, **opts):
1086 1086 # reverting a subrepo is a 2 step process:
1087 1087 # 1. if the no_backup is not set, revert all modified
1088 1088 # files inside the subrepo
1089 1089 # 2. update the subrepo to the revision specified in
1090 1090 # the corresponding substate dictionary
1091 1091 self.ui.status(_('reverting subrepo %s\n') % substate[0])
1092 if not opts.get('no_backup'):
1092 if not opts.get(r'no_backup'):
1093 1093 # Revert all files on the subrepo, creating backups
1094 1094 # Note that this will not recursively revert subrepos
1095 1095 # We could do it if there was a set:subrepos() predicate
1096 1096 opts = opts.copy()
1097 opts['date'] = None
1098 opts['rev'] = substate[1]
1097 opts[r'date'] = None
1098 opts[r'rev'] = substate[1]
1099 1099
1100 1100 self.filerevert(*pats, **opts)
1101 1101
1102 1102 # Update the repo to the revision specified in the given substate
1103 if not opts.get('dry_run'):
1103 if not opts.get(r'dry_run'):
1104 1104 self.get(substate, overwrite=True)
1105 1105
1106 1106 def filerevert(self, *pats, **opts):
1107 ctx = self._repo[opts['rev']]
1107 ctx = self._repo[opts[r'rev']]
1108 1108 parents = self._repo.dirstate.parents()
1109 if opts.get('all'):
1109 if opts.get(r'all'):
1110 1110 pats = ['set:modified()']
1111 1111 else:
1112 1112 pats = []
1113 1113 cmdutil.revert(self.ui, self._repo, ctx, parents, *pats, **opts)
1114 1114
1115 1115 def shortid(self, revid):
1116 1116 return revid[:12]
1117 1117
1118 1118 @annotatesubrepoerror
1119 1119 def unshare(self):
1120 1120 # subrepo inherently violates our import layering rules
1121 1121 # because it wants to make repo objects from deep inside the stack
1122 1122 # so we manually delay the circular imports to not break
1123 1123 # scripts that don't use our demand-loading
1124 1124 global hg
1125 1125 from . import hg as h
1126 1126 hg = h
1127 1127
1128 1128 # Nothing prevents a user from sharing in a repo, and then making that a
1129 1129 # subrepo. Alternately, the previous unshare attempt may have failed
1130 1130 # part way through. So recurse whether or not this layer is shared.
1131 1131 if self._repo.shared():
1132 1132 self.ui.status(_("unsharing subrepo '%s'\n") % self._relpath)
1133 1133
1134 1134 hg.unshare(self.ui, self._repo)
1135 1135
1136 1136 def verify(self):
1137 1137 try:
1138 1138 rev = self._state[1]
1139 1139 ctx = self._repo.unfiltered()[rev]
1140 1140 if ctx.hidden():
1141 1141 # Since hidden revisions aren't pushed/pulled, it seems worth an
1142 1142 # explicit warning.
1143 1143 ui = self._repo.ui
1144 1144 ui.warn(_("subrepo '%s' is hidden in revision %s\n") %
1145 1145 (self._relpath, node.short(self._ctx.node())))
1146 1146 return 0
1147 1147 except error.RepoLookupError:
1148 1148 # A missing subrepo revision may be a case of needing to pull it, so
1149 1149 # don't treat this as an error.
1150 1150 self._repo.ui.warn(_("subrepo '%s' not found in revision %s\n") %
1151 1151 (self._relpath, node.short(self._ctx.node())))
1152 1152 return 0
1153 1153
1154 1154 @propertycache
1155 1155 def wvfs(self):
1156 1156 """return own wvfs for efficiency and consistency
1157 1157 """
1158 1158 return self._repo.wvfs
1159 1159
1160 1160 @propertycache
1161 1161 def _relpath(self):
1162 1162 """return path to this subrepository as seen from outermost repository
1163 1163 """
1164 1164 # Keep consistent dir separators by avoiding vfs.join(self._path)
1165 1165 return reporelpath(self._repo)
1166 1166
1167 1167 class svnsubrepo(abstractsubrepo):
1168 1168 def __init__(self, ctx, path, state, allowcreate):
1169 1169 super(svnsubrepo, self).__init__(ctx, path)
1170 1170 self._state = state
1171 1171 self._exe = util.findexe('svn')
1172 1172 if not self._exe:
1173 1173 raise error.Abort(_("'svn' executable not found for subrepo '%s'")
1174 1174 % self._path)
1175 1175
1176 1176 def _svncommand(self, commands, filename='', failok=False):
1177 1177 cmd = [self._exe]
1178 1178 extrakw = {}
1179 1179 if not self.ui.interactive():
1180 1180 # Making stdin be a pipe should prevent svn from behaving
1181 1181 # interactively even if we can't pass --non-interactive.
1182 1182 extrakw['stdin'] = subprocess.PIPE
1183 1183 # Starting in svn 1.5 --non-interactive is a global flag
1184 1184 # instead of being per-command, but we need to support 1.4 so
1185 1185 # we have to be intelligent about what commands take
1186 1186 # --non-interactive.
1187 1187 if commands[0] in ('update', 'checkout', 'commit'):
1188 1188 cmd.append('--non-interactive')
1189 1189 cmd.extend(commands)
1190 1190 if filename is not None:
1191 1191 path = self.wvfs.reljoin(self._ctx.repo().origroot,
1192 1192 self._path, filename)
1193 1193 cmd.append(path)
1194 1194 env = dict(encoding.environ)
1195 1195 # Avoid localized output, preserve current locale for everything else.
1196 1196 lc_all = env.get('LC_ALL')
1197 1197 if lc_all:
1198 1198 env['LANG'] = lc_all
1199 1199 del env['LC_ALL']
1200 1200 env['LC_MESSAGES'] = 'C'
1201 1201 p = subprocess.Popen(cmd, bufsize=-1, close_fds=util.closefds,
1202 1202 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
1203 1203 universal_newlines=True, env=env, **extrakw)
1204 1204 stdout, stderr = p.communicate()
1205 1205 stderr = stderr.strip()
1206 1206 if not failok:
1207 1207 if p.returncode:
1208 1208 raise error.Abort(stderr or 'exited with code %d'
1209 1209 % p.returncode)
1210 1210 if stderr:
1211 1211 self.ui.warn(stderr + '\n')
1212 1212 return stdout, stderr
1213 1213
1214 1214 @propertycache
1215 1215 def _svnversion(self):
1216 1216 output, err = self._svncommand(['--version', '--quiet'], filename=None)
1217 1217 m = re.search(br'^(\d+)\.(\d+)', output)
1218 1218 if not m:
1219 1219 raise error.Abort(_('cannot retrieve svn tool version'))
1220 1220 return (int(m.group(1)), int(m.group(2)))
1221 1221
1222 1222 def _wcrevs(self):
1223 1223 # Get the working directory revision as well as the last
1224 1224 # commit revision so we can compare the subrepo state with
1225 1225 # both. We used to store the working directory one.
1226 1226 output, err = self._svncommand(['info', '--xml'])
1227 1227 doc = xml.dom.minidom.parseString(output)
1228 1228 entries = doc.getElementsByTagName('entry')
1229 1229 lastrev, rev = '0', '0'
1230 1230 if entries:
1231 1231 rev = str(entries[0].getAttribute('revision')) or '0'
1232 1232 commits = entries[0].getElementsByTagName('commit')
1233 1233 if commits:
1234 1234 lastrev = str(commits[0].getAttribute('revision')) or '0'
1235 1235 return (lastrev, rev)
1236 1236
1237 1237 def _wcrev(self):
1238 1238 return self._wcrevs()[0]
1239 1239
1240 1240 def _wcchanged(self):
1241 1241 """Return (changes, extchanges, missing) where changes is True
1242 1242 if the working directory was changed, extchanges is
1243 1243 True if any of these changes concern an external entry and missing
1244 1244 is True if any change is a missing entry.
1245 1245 """
1246 1246 output, err = self._svncommand(['status', '--xml'])
1247 1247 externals, changes, missing = [], [], []
1248 1248 doc = xml.dom.minidom.parseString(output)
1249 1249 for e in doc.getElementsByTagName('entry'):
1250 1250 s = e.getElementsByTagName('wc-status')
1251 1251 if not s:
1252 1252 continue
1253 1253 item = s[0].getAttribute('item')
1254 1254 props = s[0].getAttribute('props')
1255 1255 path = e.getAttribute('path')
1256 1256 if item == 'external':
1257 1257 externals.append(path)
1258 1258 elif item == 'missing':
1259 1259 missing.append(path)
1260 1260 if (item not in ('', 'normal', 'unversioned', 'external')
1261 1261 or props not in ('', 'none', 'normal')):
1262 1262 changes.append(path)
1263 1263 for path in changes:
1264 1264 for ext in externals:
1265 1265 if path == ext or path.startswith(ext + pycompat.ossep):
1266 1266 return True, True, bool(missing)
1267 1267 return bool(changes), False, bool(missing)
1268 1268
1269 1269 def dirty(self, ignoreupdate=False, missing=False):
1270 1270 wcchanged = self._wcchanged()
1271 1271 changed = wcchanged[0] or (missing and wcchanged[2])
1272 1272 if not changed:
1273 1273 if self._state[1] in self._wcrevs() or ignoreupdate:
1274 1274 return False
1275 1275 return True
1276 1276
1277 1277 def basestate(self):
1278 1278 lastrev, rev = self._wcrevs()
1279 1279 if lastrev != rev:
1280 1280 # Last committed rev is not the same than rev. We would
1281 1281 # like to take lastrev but we do not know if the subrepo
1282 1282 # URL exists at lastrev. Test it and fallback to rev it
1283 1283 # is not there.
1284 1284 try:
1285 1285 self._svncommand(['list', '%s@%s' % (self._state[0], lastrev)])
1286 1286 return lastrev
1287 1287 except error.Abort:
1288 1288 pass
1289 1289 return rev
1290 1290
1291 1291 @annotatesubrepoerror
1292 1292 def commit(self, text, user, date):
1293 1293 # user and date are out of our hands since svn is centralized
1294 1294 changed, extchanged, missing = self._wcchanged()
1295 1295 if not changed:
1296 1296 return self.basestate()
1297 1297 if extchanged:
1298 1298 # Do not try to commit externals
1299 1299 raise error.Abort(_('cannot commit svn externals'))
1300 1300 if missing:
1301 1301 # svn can commit with missing entries but aborting like hg
1302 1302 # seems a better approach.
1303 1303 raise error.Abort(_('cannot commit missing svn entries'))
1304 1304 commitinfo, err = self._svncommand(['commit', '-m', text])
1305 1305 self.ui.status(commitinfo)
1306 1306 newrev = re.search('Committed revision ([0-9]+).', commitinfo)
1307 1307 if not newrev:
1308 1308 if not commitinfo.strip():
1309 1309 # Sometimes, our definition of "changed" differs from
1310 1310 # svn one. For instance, svn ignores missing files
1311 1311 # when committing. If there are only missing files, no
1312 1312 # commit is made, no output and no error code.
1313 1313 raise error.Abort(_('failed to commit svn changes'))
1314 1314 raise error.Abort(commitinfo.splitlines()[-1])
1315 1315 newrev = newrev.groups()[0]
1316 1316 self.ui.status(self._svncommand(['update', '-r', newrev])[0])
1317 1317 return newrev
1318 1318
1319 1319 @annotatesubrepoerror
1320 1320 def remove(self):
1321 1321 if self.dirty():
1322 1322 self.ui.warn(_('not removing repo %s because '
1323 1323 'it has changes.\n') % self._path)
1324 1324 return
1325 1325 self.ui.note(_('removing subrepo %s\n') % self._path)
1326 1326
1327 1327 self.wvfs.rmtree(forcibly=True)
1328 1328 try:
1329 1329 pwvfs = self._ctx.repo().wvfs
1330 1330 pwvfs.removedirs(pwvfs.dirname(self._path))
1331 1331 except OSError:
1332 1332 pass
1333 1333
1334 1334 @annotatesubrepoerror
1335 1335 def get(self, state, overwrite=False):
1336 1336 if overwrite:
1337 1337 self._svncommand(['revert', '--recursive'])
1338 1338 args = ['checkout']
1339 1339 if self._svnversion >= (1, 5):
1340 1340 args.append('--force')
1341 1341 # The revision must be specified at the end of the URL to properly
1342 1342 # update to a directory which has since been deleted and recreated.
1343 1343 args.append('%s@%s' % (state[0], state[1]))
1344 1344
1345 1345 # SEC: check that the ssh url is safe
1346 1346 util.checksafessh(state[0])
1347 1347
1348 1348 status, err = self._svncommand(args, failok=True)
1349 1349 _sanitize(self.ui, self.wvfs, '.svn')
1350 1350 if not re.search('Checked out revision [0-9]+.', status):
1351 1351 if ('is already a working copy for a different URL' in err
1352 1352 and (self._wcchanged()[:2] == (False, False))):
1353 1353 # obstructed but clean working copy, so just blow it away.
1354 1354 self.remove()
1355 1355 self.get(state, overwrite=False)
1356 1356 return
1357 1357 raise error.Abort((status or err).splitlines()[-1])
1358 1358 self.ui.status(status)
1359 1359
1360 1360 @annotatesubrepoerror
1361 1361 def merge(self, state):
1362 1362 old = self._state[1]
1363 1363 new = state[1]
1364 1364 wcrev = self._wcrev()
1365 1365 if new != wcrev:
1366 1366 dirty = old == wcrev or self._wcchanged()[0]
1367 1367 if _updateprompt(self.ui, self, dirty, wcrev, new):
1368 1368 self.get(state, False)
1369 1369
1370 1370 def push(self, opts):
1371 1371 # push is a no-op for SVN
1372 1372 return True
1373 1373
1374 1374 @annotatesubrepoerror
1375 1375 def files(self):
1376 1376 output = self._svncommand(['list', '--recursive', '--xml'])[0]
1377 1377 doc = xml.dom.minidom.parseString(output)
1378 1378 paths = []
1379 1379 for e in doc.getElementsByTagName('entry'):
1380 1380 kind = str(e.getAttribute('kind'))
1381 1381 if kind != 'file':
1382 1382 continue
1383 1383 name = ''.join(c.data for c
1384 1384 in e.getElementsByTagName('name')[0].childNodes
1385 1385 if c.nodeType == c.TEXT_NODE)
1386 1386 paths.append(name.encode('utf-8'))
1387 1387 return paths
1388 1388
1389 1389 def filedata(self, name, decode):
1390 1390 return self._svncommand(['cat'], name)[0]
1391 1391
1392 1392
1393 1393 class gitsubrepo(abstractsubrepo):
1394 1394 def __init__(self, ctx, path, state, allowcreate):
1395 1395 super(gitsubrepo, self).__init__(ctx, path)
1396 1396 self._state = state
1397 1397 self._abspath = ctx.repo().wjoin(path)
1398 1398 self._subparent = ctx.repo()
1399 1399 self._ensuregit()
1400 1400
1401 1401 def _ensuregit(self):
1402 1402 try:
1403 1403 self._gitexecutable = 'git'
1404 1404 out, err = self._gitnodir(['--version'])
1405 1405 except OSError as e:
1406 1406 genericerror = _("error executing git for subrepo '%s': %s")
1407 1407 notfoundhint = _("check git is installed and in your PATH")
1408 1408 if e.errno != errno.ENOENT:
1409 1409 raise error.Abort(genericerror % (
1410 1410 self._path, encoding.strtolocal(e.strerror)))
1411 1411 elif pycompat.iswindows:
1412 1412 try:
1413 1413 self._gitexecutable = 'git.cmd'
1414 1414 out, err = self._gitnodir(['--version'])
1415 1415 except OSError as e2:
1416 1416 if e2.errno == errno.ENOENT:
1417 1417 raise error.Abort(_("couldn't find 'git' or 'git.cmd'"
1418 1418 " for subrepo '%s'") % self._path,
1419 1419 hint=notfoundhint)
1420 1420 else:
1421 1421 raise error.Abort(genericerror % (self._path,
1422 1422 encoding.strtolocal(e2.strerror)))
1423 1423 else:
1424 1424 raise error.Abort(_("couldn't find git for subrepo '%s'")
1425 1425 % self._path, hint=notfoundhint)
1426 1426 versionstatus = self._checkversion(out)
1427 1427 if versionstatus == 'unknown':
1428 1428 self.ui.warn(_('cannot retrieve git version\n'))
1429 1429 elif versionstatus == 'abort':
1430 1430 raise error.Abort(_('git subrepo requires at least 1.6.0 or later'))
1431 1431 elif versionstatus == 'warning':
1432 1432 self.ui.warn(_('git subrepo requires at least 1.6.0 or later\n'))
1433 1433
1434 1434 @staticmethod
1435 1435 def _gitversion(out):
1436 1436 m = re.search(br'^git version (\d+)\.(\d+)\.(\d+)', out)
1437 1437 if m:
1438 1438 return (int(m.group(1)), int(m.group(2)), int(m.group(3)))
1439 1439
1440 1440 m = re.search(br'^git version (\d+)\.(\d+)', out)
1441 1441 if m:
1442 1442 return (int(m.group(1)), int(m.group(2)), 0)
1443 1443
1444 1444 return -1
1445 1445
1446 1446 @staticmethod
1447 1447 def _checkversion(out):
1448 1448 '''ensure git version is new enough
1449 1449
1450 1450 >>> _checkversion = gitsubrepo._checkversion
1451 1451 >>> _checkversion(b'git version 1.6.0')
1452 1452 'ok'
1453 1453 >>> _checkversion(b'git version 1.8.5')
1454 1454 'ok'
1455 1455 >>> _checkversion(b'git version 1.4.0')
1456 1456 'abort'
1457 1457 >>> _checkversion(b'git version 1.5.0')
1458 1458 'warning'
1459 1459 >>> _checkversion(b'git version 1.9-rc0')
1460 1460 'ok'
1461 1461 >>> _checkversion(b'git version 1.9.0.265.g81cdec2')
1462 1462 'ok'
1463 1463 >>> _checkversion(b'git version 1.9.0.GIT')
1464 1464 'ok'
1465 1465 >>> _checkversion(b'git version 12345')
1466 1466 'unknown'
1467 1467 >>> _checkversion(b'no')
1468 1468 'unknown'
1469 1469 '''
1470 1470 version = gitsubrepo._gitversion(out)
1471 1471 # git 1.4.0 can't work at all, but 1.5.X can in at least some cases,
1472 1472 # despite the docstring comment. For now, error on 1.4.0, warn on
1473 1473 # 1.5.0 but attempt to continue.
1474 1474 if version == -1:
1475 1475 return 'unknown'
1476 1476 if version < (1, 5, 0):
1477 1477 return 'abort'
1478 1478 elif version < (1, 6, 0):
1479 1479 return 'warning'
1480 1480 return 'ok'
1481 1481
1482 1482 def _gitcommand(self, commands, env=None, stream=False):
1483 1483 return self._gitdir(commands, env=env, stream=stream)[0]
1484 1484
1485 1485 def _gitdir(self, commands, env=None, stream=False):
1486 1486 return self._gitnodir(commands, env=env, stream=stream,
1487 1487 cwd=self._abspath)
1488 1488
1489 1489 def _gitnodir(self, commands, env=None, stream=False, cwd=None):
1490 1490 """Calls the git command
1491 1491
1492 1492 The methods tries to call the git command. versions prior to 1.6.0
1493 1493 are not supported and very probably fail.
1494 1494 """
1495 1495 self.ui.debug('%s: git %s\n' % (self._relpath, ' '.join(commands)))
1496 1496 if env is None:
1497 1497 env = encoding.environ.copy()
1498 1498 # disable localization for Git output (issue5176)
1499 1499 env['LC_ALL'] = 'C'
1500 1500 # fix for Git CVE-2015-7545
1501 1501 if 'GIT_ALLOW_PROTOCOL' not in env:
1502 1502 env['GIT_ALLOW_PROTOCOL'] = 'file:git:http:https:ssh'
1503 1503 # unless ui.quiet is set, print git's stderr,
1504 1504 # which is mostly progress and useful info
1505 1505 errpipe = None
1506 1506 if self.ui.quiet:
1507 1507 errpipe = open(os.devnull, 'w')
1508 1508 if self.ui._colormode and len(commands) and commands[0] == "diff":
1509 1509 # insert the argument in the front,
1510 1510 # the end of git diff arguments is used for paths
1511 1511 commands.insert(1, '--color')
1512 1512 p = subprocess.Popen([self._gitexecutable] + commands, bufsize=-1,
1513 1513 cwd=cwd, env=env, close_fds=util.closefds,
1514 1514 stdout=subprocess.PIPE, stderr=errpipe)
1515 1515 if stream:
1516 1516 return p.stdout, None
1517 1517
1518 1518 retdata = p.stdout.read().strip()
1519 1519 # wait for the child to exit to avoid race condition.
1520 1520 p.wait()
1521 1521
1522 1522 if p.returncode != 0 and p.returncode != 1:
1523 1523 # there are certain error codes that are ok
1524 1524 command = commands[0]
1525 1525 if command in ('cat-file', 'symbolic-ref'):
1526 1526 return retdata, p.returncode
1527 1527 # for all others, abort
1528 1528 raise error.Abort(_('git %s error %d in %s') %
1529 1529 (command, p.returncode, self._relpath))
1530 1530
1531 1531 return retdata, p.returncode
1532 1532
1533 1533 def _gitmissing(self):
1534 1534 return not self.wvfs.exists('.git')
1535 1535
1536 1536 def _gitstate(self):
1537 1537 return self._gitcommand(['rev-parse', 'HEAD'])
1538 1538
1539 1539 def _gitcurrentbranch(self):
1540 1540 current, err = self._gitdir(['symbolic-ref', 'HEAD', '--quiet'])
1541 1541 if err:
1542 1542 current = None
1543 1543 return current
1544 1544
1545 1545 def _gitremote(self, remote):
1546 1546 out = self._gitcommand(['remote', 'show', '-n', remote])
1547 1547 line = out.split('\n')[1]
1548 1548 i = line.index('URL: ') + len('URL: ')
1549 1549 return line[i:]
1550 1550
1551 1551 def _githavelocally(self, revision):
1552 1552 out, code = self._gitdir(['cat-file', '-e', revision])
1553 1553 return code == 0
1554 1554
1555 1555 def _gitisancestor(self, r1, r2):
1556 1556 base = self._gitcommand(['merge-base', r1, r2])
1557 1557 return base == r1
1558 1558
1559 1559 def _gitisbare(self):
1560 1560 return self._gitcommand(['config', '--bool', 'core.bare']) == 'true'
1561 1561
1562 1562 def _gitupdatestat(self):
1563 1563 """This must be run before git diff-index.
1564 1564 diff-index only looks at changes to file stat;
1565 1565 this command looks at file contents and updates the stat."""
1566 1566 self._gitcommand(['update-index', '-q', '--refresh'])
1567 1567
1568 1568 def _gitbranchmap(self):
1569 1569 '''returns 2 things:
1570 1570 a map from git branch to revision
1571 1571 a map from revision to branches'''
1572 1572 branch2rev = {}
1573 1573 rev2branch = {}
1574 1574
1575 1575 out = self._gitcommand(['for-each-ref', '--format',
1576 1576 '%(objectname) %(refname)'])
1577 1577 for line in out.split('\n'):
1578 1578 revision, ref = line.split(' ')
1579 1579 if (not ref.startswith('refs/heads/') and
1580 1580 not ref.startswith('refs/remotes/')):
1581 1581 continue
1582 1582 if ref.startswith('refs/remotes/') and ref.endswith('/HEAD'):
1583 1583 continue # ignore remote/HEAD redirects
1584 1584 branch2rev[ref] = revision
1585 1585 rev2branch.setdefault(revision, []).append(ref)
1586 1586 return branch2rev, rev2branch
1587 1587
1588 1588 def _gittracking(self, branches):
1589 1589 'return map of remote branch to local tracking branch'
1590 1590 # assumes no more than one local tracking branch for each remote
1591 1591 tracking = {}
1592 1592 for b in branches:
1593 1593 if b.startswith('refs/remotes/'):
1594 1594 continue
1595 1595 bname = b.split('/', 2)[2]
1596 1596 remote = self._gitcommand(['config', 'branch.%s.remote' % bname])
1597 1597 if remote:
1598 1598 ref = self._gitcommand(['config', 'branch.%s.merge' % bname])
1599 1599 tracking['refs/remotes/%s/%s' %
1600 1600 (remote, ref.split('/', 2)[2])] = b
1601 1601 return tracking
1602 1602
1603 1603 def _abssource(self, source):
1604 1604 if '://' not in source:
1605 1605 # recognize the scp syntax as an absolute source
1606 1606 colon = source.find(':')
1607 1607 if colon != -1 and '/' not in source[:colon]:
1608 1608 return source
1609 1609 self._subsource = source
1610 1610 return _abssource(self)
1611 1611
1612 1612 def _fetch(self, source, revision):
1613 1613 if self._gitmissing():
1614 1614 # SEC: check for safe ssh url
1615 1615 util.checksafessh(source)
1616 1616
1617 1617 source = self._abssource(source)
1618 1618 self.ui.status(_('cloning subrepo %s from %s\n') %
1619 1619 (self._relpath, source))
1620 1620 self._gitnodir(['clone', source, self._abspath])
1621 1621 if self._githavelocally(revision):
1622 1622 return
1623 1623 self.ui.status(_('pulling subrepo %s from %s\n') %
1624 1624 (self._relpath, self._gitremote('origin')))
1625 1625 # try only origin: the originally cloned repo
1626 1626 self._gitcommand(['fetch'])
1627 1627 if not self._githavelocally(revision):
1628 1628 raise error.Abort(_('revision %s does not exist in subrepository '
1629 1629 '"%s"\n') % (revision, self._relpath))
1630 1630
1631 1631 @annotatesubrepoerror
1632 1632 def dirty(self, ignoreupdate=False, missing=False):
1633 1633 if self._gitmissing():
1634 1634 return self._state[1] != ''
1635 1635 if self._gitisbare():
1636 1636 return True
1637 1637 if not ignoreupdate and self._state[1] != self._gitstate():
1638 1638 # different version checked out
1639 1639 return True
1640 1640 # check for staged changes or modified files; ignore untracked files
1641 1641 self._gitupdatestat()
1642 1642 out, code = self._gitdir(['diff-index', '--quiet', 'HEAD'])
1643 1643 return code == 1
1644 1644
1645 1645 def basestate(self):
1646 1646 return self._gitstate()
1647 1647
1648 1648 @annotatesubrepoerror
1649 1649 def get(self, state, overwrite=False):
1650 1650 source, revision, kind = state
1651 1651 if not revision:
1652 1652 self.remove()
1653 1653 return
1654 1654 self._fetch(source, revision)
1655 1655 # if the repo was set to be bare, unbare it
1656 1656 if self._gitisbare():
1657 1657 self._gitcommand(['config', 'core.bare', 'false'])
1658 1658 if self._gitstate() == revision:
1659 1659 self._gitcommand(['reset', '--hard', 'HEAD'])
1660 1660 return
1661 1661 elif self._gitstate() == revision:
1662 1662 if overwrite:
1663 1663 # first reset the index to unmark new files for commit, because
1664 1664 # reset --hard will otherwise throw away files added for commit,
1665 1665 # not just unmark them.
1666 1666 self._gitcommand(['reset', 'HEAD'])
1667 1667 self._gitcommand(['reset', '--hard', 'HEAD'])
1668 1668 return
1669 1669 branch2rev, rev2branch = self._gitbranchmap()
1670 1670
1671 1671 def checkout(args):
1672 1672 cmd = ['checkout']
1673 1673 if overwrite:
1674 1674 # first reset the index to unmark new files for commit, because
1675 1675 # the -f option will otherwise throw away files added for
1676 1676 # commit, not just unmark them.
1677 1677 self._gitcommand(['reset', 'HEAD'])
1678 1678 cmd.append('-f')
1679 1679 self._gitcommand(cmd + args)
1680 1680 _sanitize(self.ui, self.wvfs, '.git')
1681 1681
1682 1682 def rawcheckout():
1683 1683 # no branch to checkout, check it out with no branch
1684 1684 self.ui.warn(_('checking out detached HEAD in '
1685 1685 'subrepository "%s"\n') % self._relpath)
1686 1686 self.ui.warn(_('check out a git branch if you intend '
1687 1687 'to make changes\n'))
1688 1688 checkout(['-q', revision])
1689 1689
1690 1690 if revision not in rev2branch:
1691 1691 rawcheckout()
1692 1692 return
1693 1693 branches = rev2branch[revision]
1694 1694 firstlocalbranch = None
1695 1695 for b in branches:
1696 1696 if b == 'refs/heads/master':
1697 1697 # master trumps all other branches
1698 1698 checkout(['refs/heads/master'])
1699 1699 return
1700 1700 if not firstlocalbranch and not b.startswith('refs/remotes/'):
1701 1701 firstlocalbranch = b
1702 1702 if firstlocalbranch:
1703 1703 checkout([firstlocalbranch])
1704 1704 return
1705 1705
1706 1706 tracking = self._gittracking(branch2rev.keys())
1707 1707 # choose a remote branch already tracked if possible
1708 1708 remote = branches[0]
1709 1709 if remote not in tracking:
1710 1710 for b in branches:
1711 1711 if b in tracking:
1712 1712 remote = b
1713 1713 break
1714 1714
1715 1715 if remote not in tracking:
1716 1716 # create a new local tracking branch
1717 1717 local = remote.split('/', 3)[3]
1718 1718 checkout(['-b', local, remote])
1719 1719 elif self._gitisancestor(branch2rev[tracking[remote]], remote):
1720 1720 # When updating to a tracked remote branch,
1721 1721 # if the local tracking branch is downstream of it,
1722 1722 # a normal `git pull` would have performed a "fast-forward merge"
1723 1723 # which is equivalent to updating the local branch to the remote.
1724 1724 # Since we are only looking at branching at update, we need to
1725 1725 # detect this situation and perform this action lazily.
1726 1726 if tracking[remote] != self._gitcurrentbranch():
1727 1727 checkout([tracking[remote]])
1728 1728 self._gitcommand(['merge', '--ff', remote])
1729 1729 _sanitize(self.ui, self.wvfs, '.git')
1730 1730 else:
1731 1731 # a real merge would be required, just checkout the revision
1732 1732 rawcheckout()
1733 1733
1734 1734 @annotatesubrepoerror
1735 1735 def commit(self, text, user, date):
1736 1736 if self._gitmissing():
1737 1737 raise error.Abort(_("subrepo %s is missing") % self._relpath)
1738 1738 cmd = ['commit', '-a', '-m', text]
1739 1739 env = encoding.environ.copy()
1740 1740 if user:
1741 1741 cmd += ['--author', user]
1742 1742 if date:
1743 1743 # git's date parser silently ignores when seconds < 1e9
1744 1744 # convert to ISO8601
1745 1745 env['GIT_AUTHOR_DATE'] = util.datestr(date,
1746 1746 '%Y-%m-%dT%H:%M:%S %1%2')
1747 1747 self._gitcommand(cmd, env=env)
1748 1748 # make sure commit works otherwise HEAD might not exist under certain
1749 1749 # circumstances
1750 1750 return self._gitstate()
1751 1751
1752 1752 @annotatesubrepoerror
1753 1753 def merge(self, state):
1754 1754 source, revision, kind = state
1755 1755 self._fetch(source, revision)
1756 1756 base = self._gitcommand(['merge-base', revision, self._state[1]])
1757 1757 self._gitupdatestat()
1758 1758 out, code = self._gitdir(['diff-index', '--quiet', 'HEAD'])
1759 1759
1760 1760 def mergefunc():
1761 1761 if base == revision:
1762 1762 self.get(state) # fast forward merge
1763 1763 elif base != self._state[1]:
1764 1764 self._gitcommand(['merge', '--no-commit', revision])
1765 1765 _sanitize(self.ui, self.wvfs, '.git')
1766 1766
1767 1767 if self.dirty():
1768 1768 if self._gitstate() != revision:
1769 1769 dirty = self._gitstate() == self._state[1] or code != 0
1770 1770 if _updateprompt(self.ui, self, dirty,
1771 1771 self._state[1][:7], revision[:7]):
1772 1772 mergefunc()
1773 1773 else:
1774 1774 mergefunc()
1775 1775
1776 1776 @annotatesubrepoerror
1777 1777 def push(self, opts):
1778 1778 force = opts.get('force')
1779 1779
1780 1780 if not self._state[1]:
1781 1781 return True
1782 1782 if self._gitmissing():
1783 1783 raise error.Abort(_("subrepo %s is missing") % self._relpath)
1784 1784 # if a branch in origin contains the revision, nothing to do
1785 1785 branch2rev, rev2branch = self._gitbranchmap()
1786 1786 if self._state[1] in rev2branch:
1787 1787 for b in rev2branch[self._state[1]]:
1788 1788 if b.startswith('refs/remotes/origin/'):
1789 1789 return True
1790 1790 for b, revision in branch2rev.iteritems():
1791 1791 if b.startswith('refs/remotes/origin/'):
1792 1792 if self._gitisancestor(self._state[1], revision):
1793 1793 return True
1794 1794 # otherwise, try to push the currently checked out branch
1795 1795 cmd = ['push']
1796 1796 if force:
1797 1797 cmd.append('--force')
1798 1798
1799 1799 current = self._gitcurrentbranch()
1800 1800 if current:
1801 1801 # determine if the current branch is even useful
1802 1802 if not self._gitisancestor(self._state[1], current):
1803 1803 self.ui.warn(_('unrelated git branch checked out '
1804 1804 'in subrepository "%s"\n') % self._relpath)
1805 1805 return False
1806 1806 self.ui.status(_('pushing branch %s of subrepository "%s"\n') %
1807 1807 (current.split('/', 2)[2], self._relpath))
1808 1808 ret = self._gitdir(cmd + ['origin', current])
1809 1809 return ret[1] == 0
1810 1810 else:
1811 1811 self.ui.warn(_('no branch checked out in subrepository "%s"\n'
1812 1812 'cannot push revision %s\n') %
1813 1813 (self._relpath, self._state[1]))
1814 1814 return False
1815 1815
1816 1816 @annotatesubrepoerror
1817 1817 def add(self, ui, match, prefix, explicitonly, **opts):
1818 1818 if self._gitmissing():
1819 1819 return []
1820 1820
1821 1821 (modified, added, removed,
1822 1822 deleted, unknown, ignored, clean) = self.status(None, unknown=True,
1823 1823 clean=True)
1824 1824
1825 1825 tracked = set()
1826 1826 # dirstates 'amn' warn, 'r' is added again
1827 1827 for l in (modified, added, deleted, clean):
1828 1828 tracked.update(l)
1829 1829
1830 1830 # Unknown files not of interest will be rejected by the matcher
1831 1831 files = unknown
1832 1832 files.extend(match.files())
1833 1833
1834 1834 rejected = []
1835 1835
1836 1836 files = [f for f in sorted(set(files)) if match(f)]
1837 1837 for f in files:
1838 1838 exact = match.exact(f)
1839 1839 command = ["add"]
1840 1840 if exact:
1841 1841 command.append("-f") #should be added, even if ignored
1842 1842 if ui.verbose or not exact:
1843 1843 ui.status(_('adding %s\n') % match.rel(f))
1844 1844
1845 1845 if f in tracked: # hg prints 'adding' even if already tracked
1846 1846 if exact:
1847 1847 rejected.append(f)
1848 1848 continue
1849 1849 if not opts.get(r'dry_run'):
1850 1850 self._gitcommand(command + [f])
1851 1851
1852 1852 for f in rejected:
1853 1853 ui.warn(_("%s already tracked!\n") % match.abs(f))
1854 1854
1855 1855 return rejected
1856 1856
1857 1857 @annotatesubrepoerror
1858 1858 def remove(self):
1859 1859 if self._gitmissing():
1860 1860 return
1861 1861 if self.dirty():
1862 1862 self.ui.warn(_('not removing repo %s because '
1863 1863 'it has changes.\n') % self._relpath)
1864 1864 return
1865 1865 # we can't fully delete the repository as it may contain
1866 1866 # local-only history
1867 1867 self.ui.note(_('removing subrepo %s\n') % self._relpath)
1868 1868 self._gitcommand(['config', 'core.bare', 'true'])
1869 1869 for f, kind in self.wvfs.readdir():
1870 1870 if f == '.git':
1871 1871 continue
1872 1872 if kind == stat.S_IFDIR:
1873 1873 self.wvfs.rmtree(f)
1874 1874 else:
1875 1875 self.wvfs.unlink(f)
1876 1876
1877 1877 def archive(self, archiver, prefix, match=None, decode=True):
1878 1878 total = 0
1879 1879 source, revision = self._state
1880 1880 if not revision:
1881 1881 return total
1882 1882 self._fetch(source, revision)
1883 1883
1884 1884 # Parse git's native archive command.
1885 1885 # This should be much faster than manually traversing the trees
1886 1886 # and objects with many subprocess calls.
1887 1887 tarstream = self._gitcommand(['archive', revision], stream=True)
1888 1888 tar = tarfile.open(fileobj=tarstream, mode='r|')
1889 1889 relpath = subrelpath(self)
1890 1890 self.ui.progress(_('archiving (%s)') % relpath, 0, unit=_('files'))
1891 1891 for i, info in enumerate(tar):
1892 1892 if info.isdir():
1893 1893 continue
1894 1894 if match and not match(info.name):
1895 1895 continue
1896 1896 if info.issym():
1897 1897 data = info.linkname
1898 1898 else:
1899 1899 data = tar.extractfile(info).read()
1900 1900 archiver.addfile(prefix + self._path + '/' + info.name,
1901 1901 info.mode, info.issym(), data)
1902 1902 total += 1
1903 1903 self.ui.progress(_('archiving (%s)') % relpath, i + 1,
1904 1904 unit=_('files'))
1905 1905 self.ui.progress(_('archiving (%s)') % relpath, None)
1906 1906 return total
1907 1907
1908 1908
1909 1909 @annotatesubrepoerror
1910 1910 def cat(self, match, fm, fntemplate, prefix, **opts):
1911 1911 rev = self._state[1]
1912 1912 if match.anypats():
1913 1913 return 1 #No support for include/exclude yet
1914 1914
1915 1915 if not match.files():
1916 1916 return 1
1917 1917
1918 1918 # TODO: add support for non-plain formatter (see cmdutil.cat())
1919 1919 for f in match.files():
1920 1920 output = self._gitcommand(["show", "%s:%s" % (rev, f)])
1921 1921 fp = cmdutil.makefileobj(self._subparent, fntemplate,
1922 1922 self._ctx.node(),
1923 1923 pathname=self.wvfs.reljoin(prefix, f))
1924 1924 fp.write(output)
1925 1925 fp.close()
1926 1926 return 0
1927 1927
1928 1928
1929 1929 @annotatesubrepoerror
1930 1930 def status(self, rev2, **opts):
1931 1931 rev1 = self._state[1]
1932 1932 if self._gitmissing() or not rev1:
1933 1933 # if the repo is missing, return no results
1934 1934 return scmutil.status([], [], [], [], [], [], [])
1935 1935 modified, added, removed = [], [], []
1936 1936 self._gitupdatestat()
1937 1937 if rev2:
1938 1938 command = ['diff-tree', '--no-renames', '-r', rev1, rev2]
1939 1939 else:
1940 1940 command = ['diff-index', '--no-renames', rev1]
1941 1941 out = self._gitcommand(command)
1942 1942 for line in out.split('\n'):
1943 1943 tab = line.find('\t')
1944 1944 if tab == -1:
1945 1945 continue
1946 1946 status, f = line[tab - 1], line[tab + 1:]
1947 1947 if status == 'M':
1948 1948 modified.append(f)
1949 1949 elif status == 'A':
1950 1950 added.append(f)
1951 1951 elif status == 'D':
1952 1952 removed.append(f)
1953 1953
1954 1954 deleted, unknown, ignored, clean = [], [], [], []
1955 1955
1956 1956 command = ['status', '--porcelain', '-z']
1957 1957 if opts.get(r'unknown'):
1958 1958 command += ['--untracked-files=all']
1959 1959 if opts.get(r'ignored'):
1960 1960 command += ['--ignored']
1961 1961 out = self._gitcommand(command)
1962 1962
1963 1963 changedfiles = set()
1964 1964 changedfiles.update(modified)
1965 1965 changedfiles.update(added)
1966 1966 changedfiles.update(removed)
1967 1967 for line in out.split('\0'):
1968 1968 if not line:
1969 1969 continue
1970 1970 st = line[0:2]
1971 1971 #moves and copies show 2 files on one line
1972 1972 if line.find('\0') >= 0:
1973 1973 filename1, filename2 = line[3:].split('\0')
1974 1974 else:
1975 1975 filename1 = line[3:]
1976 1976 filename2 = None
1977 1977
1978 1978 changedfiles.add(filename1)
1979 1979 if filename2:
1980 1980 changedfiles.add(filename2)
1981 1981
1982 1982 if st == '??':
1983 1983 unknown.append(filename1)
1984 1984 elif st == '!!':
1985 1985 ignored.append(filename1)
1986 1986
1987 1987 if opts.get(r'clean'):
1988 1988 out = self._gitcommand(['ls-files'])
1989 1989 for f in out.split('\n'):
1990 1990 if not f in changedfiles:
1991 1991 clean.append(f)
1992 1992
1993 1993 return scmutil.status(modified, added, removed, deleted,
1994 1994 unknown, ignored, clean)
1995 1995
1996 1996 @annotatesubrepoerror
1997 1997 def diff(self, ui, diffopts, node2, match, prefix, **opts):
1998 1998 node1 = self._state[1]
1999 1999 cmd = ['diff', '--no-renames']
2000 2000 if opts[r'stat']:
2001 2001 cmd.append('--stat')
2002 2002 else:
2003 2003 # for Git, this also implies '-p'
2004 2004 cmd.append('-U%d' % diffopts.context)
2005 2005
2006 2006 gitprefix = self.wvfs.reljoin(prefix, self._path)
2007 2007
2008 2008 if diffopts.noprefix:
2009 2009 cmd.extend(['--src-prefix=%s/' % gitprefix,
2010 2010 '--dst-prefix=%s/' % gitprefix])
2011 2011 else:
2012 2012 cmd.extend(['--src-prefix=a/%s/' % gitprefix,
2013 2013 '--dst-prefix=b/%s/' % gitprefix])
2014 2014
2015 2015 if diffopts.ignorews:
2016 2016 cmd.append('--ignore-all-space')
2017 2017 if diffopts.ignorewsamount:
2018 2018 cmd.append('--ignore-space-change')
2019 2019 if self._gitversion(self._gitcommand(['--version'])) >= (1, 8, 4) \
2020 2020 and diffopts.ignoreblanklines:
2021 2021 cmd.append('--ignore-blank-lines')
2022 2022
2023 2023 cmd.append(node1)
2024 2024 if node2:
2025 2025 cmd.append(node2)
2026 2026
2027 2027 output = ""
2028 2028 if match.always():
2029 2029 output += self._gitcommand(cmd) + '\n'
2030 2030 else:
2031 2031 st = self.status(node2)[:3]
2032 2032 files = [f for sublist in st for f in sublist]
2033 2033 for f in files:
2034 2034 if match(f):
2035 2035 output += self._gitcommand(cmd + ['--', f]) + '\n'
2036 2036
2037 2037 if output.strip():
2038 2038 ui.write(output)
2039 2039
2040 2040 @annotatesubrepoerror
2041 2041 def revert(self, substate, *pats, **opts):
2042 2042 self.ui.status(_('reverting subrepo %s\n') % substate[0])
2043 2043 if not opts.get(r'no_backup'):
2044 2044 status = self.status(None)
2045 2045 names = status.modified
2046 2046 for name in names:
2047 2047 bakname = scmutil.origpath(self.ui, self._subparent, name)
2048 2048 self.ui.note(_('saving current version of %s as %s\n') %
2049 2049 (name, bakname))
2050 2050 self.wvfs.rename(name, bakname)
2051 2051
2052 2052 if not opts.get(r'dry_run'):
2053 2053 self.get(substate, overwrite=True)
2054 2054 return []
2055 2055
2056 2056 def shortid(self, revid):
2057 2057 return revid[:7]
2058 2058
2059 2059 types = {
2060 2060 'hg': hgsubrepo,
2061 2061 'svn': svnsubrepo,
2062 2062 'git': gitsubrepo,
2063 2063 }
General Comments 0
You need to be logged in to leave comments. Login now