##// END OF EJS Templates
update: accept --merge to allow merging across topo branches (issue5125)
Martin von Zweigbergk -
r31166:fad5e299 default
parent child Browse files
Show More
@@ -1,5434 +1,5447
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
15 15 from .i18n import _
16 16 from .node import (
17 17 hex,
18 18 nullid,
19 19 nullrev,
20 20 short,
21 21 )
22 22 from . import (
23 23 archival,
24 24 bookmarks,
25 25 bundle2,
26 26 changegroup,
27 27 cmdutil,
28 28 copies,
29 29 destutil,
30 30 dirstateguard,
31 31 discovery,
32 32 encoding,
33 33 error,
34 34 exchange,
35 35 extensions,
36 36 graphmod,
37 37 hbisect,
38 38 help,
39 39 hg,
40 40 lock as lockmod,
41 41 merge as mergemod,
42 42 obsolete,
43 43 patch,
44 44 phases,
45 45 pycompat,
46 46 revsetlang,
47 47 scmutil,
48 48 server,
49 49 sshserver,
50 50 streamclone,
51 51 templatekw,
52 52 ui as uimod,
53 53 util,
54 54 )
55 55
56 56 release = lockmod.release
57 57
58 58 table = {}
59 59
60 60 command = cmdutil.command(table)
61 61
62 62 # label constants
63 63 # until 3.5, bookmarks.current was the advertised name, not
64 64 # bookmarks.active, so we must use both to avoid breaking old
65 65 # custom styles
66 66 activebookmarklabel = 'bookmarks.active bookmarks.current'
67 67
68 68 # common command options
69 69
70 70 globalopts = [
71 71 ('R', 'repository', '',
72 72 _('repository root directory or name of overlay bundle file'),
73 73 _('REPO')),
74 74 ('', 'cwd', '',
75 75 _('change working directory'), _('DIR')),
76 76 ('y', 'noninteractive', None,
77 77 _('do not prompt, automatically pick the first choice for all prompts')),
78 78 ('q', 'quiet', None, _('suppress output')),
79 79 ('v', 'verbose', None, _('enable additional output')),
80 80 ('', 'color', '',
81 81 # i18n: 'always', 'auto', 'never', and 'debug' are keywords
82 82 # and should not be translated
83 83 _("when to colorize (boolean, always, auto, never, or debug)"),
84 84 _('TYPE')),
85 85 ('', 'config', [],
86 86 _('set/override config option (use \'section.name=value\')'),
87 87 _('CONFIG')),
88 88 ('', 'debug', None, _('enable debugging output')),
89 89 ('', 'debugger', None, _('start debugger')),
90 90 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
91 91 _('ENCODE')),
92 92 ('', 'encodingmode', encoding.encodingmode,
93 93 _('set the charset encoding mode'), _('MODE')),
94 94 ('', 'traceback', None, _('always print a traceback on exception')),
95 95 ('', 'time', None, _('time how long the command takes')),
96 96 ('', 'profile', None, _('print command execution profile')),
97 97 ('', 'version', None, _('output version information and exit')),
98 98 ('h', 'help', None, _('display help and exit')),
99 99 ('', 'hidden', False, _('consider hidden changesets')),
100 100 ('', 'pager', 'auto',
101 101 _("when to paginate (boolean, always, auto, or never)"), _('TYPE')),
102 102 ]
103 103
104 104 dryrunopts = [('n', 'dry-run', None,
105 105 _('do not perform actions, just print output'))]
106 106
107 107 remoteopts = [
108 108 ('e', 'ssh', '',
109 109 _('specify ssh command to use'), _('CMD')),
110 110 ('', 'remotecmd', '',
111 111 _('specify hg command to run on the remote side'), _('CMD')),
112 112 ('', 'insecure', None,
113 113 _('do not verify server certificate (ignoring web.cacerts config)')),
114 114 ]
115 115
116 116 walkopts = [
117 117 ('I', 'include', [],
118 118 _('include names matching the given patterns'), _('PATTERN')),
119 119 ('X', 'exclude', [],
120 120 _('exclude names matching the given patterns'), _('PATTERN')),
121 121 ]
122 122
123 123 commitopts = [
124 124 ('m', 'message', '',
125 125 _('use text as commit message'), _('TEXT')),
126 126 ('l', 'logfile', '',
127 127 _('read commit message from file'), _('FILE')),
128 128 ]
129 129
130 130 commitopts2 = [
131 131 ('d', 'date', '',
132 132 _('record the specified date as commit date'), _('DATE')),
133 133 ('u', 'user', '',
134 134 _('record the specified user as committer'), _('USER')),
135 135 ]
136 136
137 137 # hidden for now
138 138 formatteropts = [
139 139 ('T', 'template', '',
140 140 _('display with template (EXPERIMENTAL)'), _('TEMPLATE')),
141 141 ]
142 142
143 143 templateopts = [
144 144 ('', 'style', '',
145 145 _('display using template map file (DEPRECATED)'), _('STYLE')),
146 146 ('T', 'template', '',
147 147 _('display with template'), _('TEMPLATE')),
148 148 ]
149 149
150 150 logopts = [
151 151 ('p', 'patch', None, _('show patch')),
152 152 ('g', 'git', None, _('use git extended diff format')),
153 153 ('l', 'limit', '',
154 154 _('limit number of changes displayed'), _('NUM')),
155 155 ('M', 'no-merges', None, _('do not show merges')),
156 156 ('', 'stat', None, _('output diffstat-style summary of changes')),
157 157 ('G', 'graph', None, _("show the revision DAG")),
158 158 ] + templateopts
159 159
160 160 diffopts = [
161 161 ('a', 'text', None, _('treat all files as text')),
162 162 ('g', 'git', None, _('use git extended diff format')),
163 163 ('', 'nodates', None, _('omit dates from diff headers'))
164 164 ]
165 165
166 166 diffwsopts = [
167 167 ('w', 'ignore-all-space', None,
168 168 _('ignore white space when comparing lines')),
169 169 ('b', 'ignore-space-change', None,
170 170 _('ignore changes in the amount of white space')),
171 171 ('B', 'ignore-blank-lines', None,
172 172 _('ignore changes whose lines are all blank')),
173 173 ]
174 174
175 175 diffopts2 = [
176 176 ('', 'noprefix', None, _('omit a/ and b/ prefixes from filenames')),
177 177 ('p', 'show-function', None, _('show which function each change is in')),
178 178 ('', 'reverse', None, _('produce a diff that undoes the changes')),
179 179 ] + diffwsopts + [
180 180 ('U', 'unified', '',
181 181 _('number of lines of context to show'), _('NUM')),
182 182 ('', 'stat', None, _('output diffstat-style summary of changes')),
183 183 ('', 'root', '', _('produce diffs relative to subdirectory'), _('DIR')),
184 184 ]
185 185
186 186 mergetoolopts = [
187 187 ('t', 'tool', '', _('specify merge tool')),
188 188 ]
189 189
190 190 similarityopts = [
191 191 ('s', 'similarity', '',
192 192 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
193 193 ]
194 194
195 195 subrepoopts = [
196 196 ('S', 'subrepos', None,
197 197 _('recurse into subrepositories'))
198 198 ]
199 199
200 200 debugrevlogopts = [
201 201 ('c', 'changelog', False, _('open changelog')),
202 202 ('m', 'manifest', False, _('open manifest')),
203 203 ('', 'dir', '', _('open directory manifest')),
204 204 ]
205 205
206 206 # Commands start here, listed alphabetically
207 207
208 208 @command('^add',
209 209 walkopts + subrepoopts + dryrunopts,
210 210 _('[OPTION]... [FILE]...'),
211 211 inferrepo=True)
212 212 def add(ui, repo, *pats, **opts):
213 213 """add the specified files on the next commit
214 214
215 215 Schedule files to be version controlled and added to the
216 216 repository.
217 217
218 218 The files will be added to the repository at the next commit. To
219 219 undo an add before that, see :hg:`forget`.
220 220
221 221 If no names are given, add all files to the repository (except
222 222 files matching ``.hgignore``).
223 223
224 224 .. container:: verbose
225 225
226 226 Examples:
227 227
228 228 - New (unknown) files are added
229 229 automatically by :hg:`add`::
230 230
231 231 $ ls
232 232 foo.c
233 233 $ hg status
234 234 ? foo.c
235 235 $ hg add
236 236 adding foo.c
237 237 $ hg status
238 238 A foo.c
239 239
240 240 - Specific files to be added can be specified::
241 241
242 242 $ ls
243 243 bar.c foo.c
244 244 $ hg status
245 245 ? bar.c
246 246 ? foo.c
247 247 $ hg add bar.c
248 248 $ hg status
249 249 A bar.c
250 250 ? foo.c
251 251
252 252 Returns 0 if all files are successfully added.
253 253 """
254 254
255 255 m = scmutil.match(repo[None], pats, opts)
256 256 rejected = cmdutil.add(ui, repo, m, "", False, **opts)
257 257 return rejected and 1 or 0
258 258
259 259 @command('addremove',
260 260 similarityopts + subrepoopts + walkopts + dryrunopts,
261 261 _('[OPTION]... [FILE]...'),
262 262 inferrepo=True)
263 263 def addremove(ui, repo, *pats, **opts):
264 264 """add all new files, delete all missing files
265 265
266 266 Add all new files and remove all missing files from the
267 267 repository.
268 268
269 269 Unless names are given, new files are ignored if they match any of
270 270 the patterns in ``.hgignore``. As with add, these changes take
271 271 effect at the next commit.
272 272
273 273 Use the -s/--similarity option to detect renamed files. This
274 274 option takes a percentage between 0 (disabled) and 100 (files must
275 275 be identical) as its parameter. With a parameter greater than 0,
276 276 this compares every removed file with every added file and records
277 277 those similar enough as renames. Detecting renamed files this way
278 278 can be expensive. After using this option, :hg:`status -C` can be
279 279 used to check which files were identified as moved or renamed. If
280 280 not specified, -s/--similarity defaults to 100 and only renames of
281 281 identical files are detected.
282 282
283 283 .. container:: verbose
284 284
285 285 Examples:
286 286
287 287 - A number of files (bar.c and foo.c) are new,
288 288 while foobar.c has been removed (without using :hg:`remove`)
289 289 from the repository::
290 290
291 291 $ ls
292 292 bar.c foo.c
293 293 $ hg status
294 294 ! foobar.c
295 295 ? bar.c
296 296 ? foo.c
297 297 $ hg addremove
298 298 adding bar.c
299 299 adding foo.c
300 300 removing foobar.c
301 301 $ hg status
302 302 A bar.c
303 303 A foo.c
304 304 R foobar.c
305 305
306 306 - A file foobar.c was moved to foo.c without using :hg:`rename`.
307 307 Afterwards, it was edited slightly::
308 308
309 309 $ ls
310 310 foo.c
311 311 $ hg status
312 312 ! foobar.c
313 313 ? foo.c
314 314 $ hg addremove --similarity 90
315 315 removing foobar.c
316 316 adding foo.c
317 317 recording removal of foobar.c as rename to foo.c (94% similar)
318 318 $ hg status -C
319 319 A foo.c
320 320 foobar.c
321 321 R foobar.c
322 322
323 323 Returns 0 if all files are successfully added.
324 324 """
325 325 try:
326 326 sim = float(opts.get('similarity') or 100)
327 327 except ValueError:
328 328 raise error.Abort(_('similarity must be a number'))
329 329 if sim < 0 or sim > 100:
330 330 raise error.Abort(_('similarity must be between 0 and 100'))
331 331 matcher = scmutil.match(repo[None], pats, opts)
332 332 return scmutil.addremove(repo, matcher, "", opts, similarity=sim / 100.0)
333 333
334 334 @command('^annotate|blame',
335 335 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
336 336 ('', 'follow', None,
337 337 _('follow copies/renames and list the filename (DEPRECATED)')),
338 338 ('', 'no-follow', None, _("don't follow copies and renames")),
339 339 ('a', 'text', None, _('treat all files as text')),
340 340 ('u', 'user', None, _('list the author (long with -v)')),
341 341 ('f', 'file', None, _('list the filename')),
342 342 ('d', 'date', None, _('list the date (short with -q)')),
343 343 ('n', 'number', None, _('list the revision number (default)')),
344 344 ('c', 'changeset', None, _('list the changeset')),
345 345 ('l', 'line-number', None, _('show line number at the first appearance'))
346 346 ] + diffwsopts + walkopts + formatteropts,
347 347 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'),
348 348 inferrepo=True)
349 349 def annotate(ui, repo, *pats, **opts):
350 350 """show changeset information by line for each file
351 351
352 352 List changes in files, showing the revision id responsible for
353 353 each line.
354 354
355 355 This command is useful for discovering when a change was made and
356 356 by whom.
357 357
358 358 If you include --file, --user, or --date, the revision number is
359 359 suppressed unless you also include --number.
360 360
361 361 Without the -a/--text option, annotate will avoid processing files
362 362 it detects as binary. With -a, annotate will annotate the file
363 363 anyway, although the results will probably be neither useful
364 364 nor desirable.
365 365
366 366 Returns 0 on success.
367 367 """
368 368 if not pats:
369 369 raise error.Abort(_('at least one filename or pattern is required'))
370 370
371 371 if opts.get('follow'):
372 372 # --follow is deprecated and now just an alias for -f/--file
373 373 # to mimic the behavior of Mercurial before version 1.5
374 374 opts['file'] = True
375 375
376 376 ctx = scmutil.revsingle(repo, opts.get('rev'))
377 377
378 378 fm = ui.formatter('annotate', opts)
379 379 if ui.quiet:
380 380 datefunc = util.shortdate
381 381 else:
382 382 datefunc = util.datestr
383 383 if ctx.rev() is None:
384 384 def hexfn(node):
385 385 if node is None:
386 386 return None
387 387 else:
388 388 return fm.hexfunc(node)
389 389 if opts.get('changeset'):
390 390 # omit "+" suffix which is appended to node hex
391 391 def formatrev(rev):
392 392 if rev is None:
393 393 return '%d' % ctx.p1().rev()
394 394 else:
395 395 return '%d' % rev
396 396 else:
397 397 def formatrev(rev):
398 398 if rev is None:
399 399 return '%d+' % ctx.p1().rev()
400 400 else:
401 401 return '%d ' % rev
402 402 def formathex(hex):
403 403 if hex is None:
404 404 return '%s+' % fm.hexfunc(ctx.p1().node())
405 405 else:
406 406 return '%s ' % hex
407 407 else:
408 408 hexfn = fm.hexfunc
409 409 formatrev = formathex = str
410 410
411 411 opmap = [('user', ' ', lambda x: x[0].user(), ui.shortuser),
412 412 ('number', ' ', lambda x: x[0].rev(), formatrev),
413 413 ('changeset', ' ', lambda x: hexfn(x[0].node()), formathex),
414 414 ('date', ' ', lambda x: x[0].date(), util.cachefunc(datefunc)),
415 415 ('file', ' ', lambda x: x[0].path(), str),
416 416 ('line_number', ':', lambda x: x[1], str),
417 417 ]
418 418 fieldnamemap = {'number': 'rev', 'changeset': 'node'}
419 419
420 420 if (not opts.get('user') and not opts.get('changeset')
421 421 and not opts.get('date') and not opts.get('file')):
422 422 opts['number'] = True
423 423
424 424 linenumber = opts.get('line_number') is not None
425 425 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
426 426 raise error.Abort(_('at least one of -n/-c is required for -l'))
427 427
428 428 ui.pager('annotate')
429 429
430 430 if fm.isplain():
431 431 def makefunc(get, fmt):
432 432 return lambda x: fmt(get(x))
433 433 else:
434 434 def makefunc(get, fmt):
435 435 return get
436 436 funcmap = [(makefunc(get, fmt), sep) for op, sep, get, fmt in opmap
437 437 if opts.get(op)]
438 438 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
439 439 fields = ' '.join(fieldnamemap.get(op, op) for op, sep, get, fmt in opmap
440 440 if opts.get(op))
441 441
442 442 def bad(x, y):
443 443 raise error.Abort("%s: %s" % (x, y))
444 444
445 445 m = scmutil.match(ctx, pats, opts, badfn=bad)
446 446
447 447 follow = not opts.get('no_follow')
448 448 diffopts = patch.difffeatureopts(ui, opts, section='annotate',
449 449 whitespace=True)
450 450 for abs in ctx.walk(m):
451 451 fctx = ctx[abs]
452 452 if not opts.get('text') and util.binary(fctx.data()):
453 453 fm.plain(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
454 454 continue
455 455
456 456 lines = fctx.annotate(follow=follow, linenumber=linenumber,
457 457 diffopts=diffopts)
458 458 if not lines:
459 459 continue
460 460 formats = []
461 461 pieces = []
462 462
463 463 for f, sep in funcmap:
464 464 l = [f(n) for n, dummy in lines]
465 465 if fm.isplain():
466 466 sizes = [encoding.colwidth(x) for x in l]
467 467 ml = max(sizes)
468 468 formats.append([sep + ' ' * (ml - w) + '%s' for w in sizes])
469 469 else:
470 470 formats.append(['%s' for x in l])
471 471 pieces.append(l)
472 472
473 473 for f, p, l in zip(zip(*formats), zip(*pieces), lines):
474 474 fm.startitem()
475 475 fm.write(fields, "".join(f), *p)
476 476 fm.write('line', ": %s", l[1])
477 477
478 478 if not lines[-1][1].endswith('\n'):
479 479 fm.plain('\n')
480 480
481 481 fm.end()
482 482
483 483 @command('archive',
484 484 [('', 'no-decode', None, _('do not pass files through decoders')),
485 485 ('p', 'prefix', '', _('directory prefix for files in archive'),
486 486 _('PREFIX')),
487 487 ('r', 'rev', '', _('revision to distribute'), _('REV')),
488 488 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
489 489 ] + subrepoopts + walkopts,
490 490 _('[OPTION]... DEST'))
491 491 def archive(ui, repo, dest, **opts):
492 492 '''create an unversioned archive of a repository revision
493 493
494 494 By default, the revision used is the parent of the working
495 495 directory; use -r/--rev to specify a different revision.
496 496
497 497 The archive type is automatically detected based on file
498 498 extension (to override, use -t/--type).
499 499
500 500 .. container:: verbose
501 501
502 502 Examples:
503 503
504 504 - create a zip file containing the 1.0 release::
505 505
506 506 hg archive -r 1.0 project-1.0.zip
507 507
508 508 - create a tarball excluding .hg files::
509 509
510 510 hg archive project.tar.gz -X ".hg*"
511 511
512 512 Valid types are:
513 513
514 514 :``files``: a directory full of files (default)
515 515 :``tar``: tar archive, uncompressed
516 516 :``tbz2``: tar archive, compressed using bzip2
517 517 :``tgz``: tar archive, compressed using gzip
518 518 :``uzip``: zip archive, uncompressed
519 519 :``zip``: zip archive, compressed using deflate
520 520
521 521 The exact name of the destination archive or directory is given
522 522 using a format string; see :hg:`help export` for details.
523 523
524 524 Each member added to an archive file has a directory prefix
525 525 prepended. Use -p/--prefix to specify a format string for the
526 526 prefix. The default is the basename of the archive, with suffixes
527 527 removed.
528 528
529 529 Returns 0 on success.
530 530 '''
531 531
532 532 ctx = scmutil.revsingle(repo, opts.get('rev'))
533 533 if not ctx:
534 534 raise error.Abort(_('no working directory: please specify a revision'))
535 535 node = ctx.node()
536 536 dest = cmdutil.makefilename(repo, dest, node)
537 537 if os.path.realpath(dest) == repo.root:
538 538 raise error.Abort(_('repository root cannot be destination'))
539 539
540 540 kind = opts.get('type') or archival.guesskind(dest) or 'files'
541 541 prefix = opts.get('prefix')
542 542
543 543 if dest == '-':
544 544 if kind == 'files':
545 545 raise error.Abort(_('cannot archive plain files to stdout'))
546 546 dest = cmdutil.makefileobj(repo, dest)
547 547 if not prefix:
548 548 prefix = os.path.basename(repo.root) + '-%h'
549 549
550 550 prefix = cmdutil.makefilename(repo, prefix, node)
551 551 matchfn = scmutil.match(ctx, [], opts)
552 552 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
553 553 matchfn, prefix, subrepos=opts.get('subrepos'))
554 554
555 555 @command('backout',
556 556 [('', 'merge', None, _('merge with old dirstate parent after backout')),
557 557 ('', 'commit', None,
558 558 _('commit if no conflicts were encountered (DEPRECATED)')),
559 559 ('', 'no-commit', None, _('do not commit')),
560 560 ('', 'parent', '',
561 561 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
562 562 ('r', 'rev', '', _('revision to backout'), _('REV')),
563 563 ('e', 'edit', False, _('invoke editor on commit messages')),
564 564 ] + mergetoolopts + walkopts + commitopts + commitopts2,
565 565 _('[OPTION]... [-r] REV'))
566 566 def backout(ui, repo, node=None, rev=None, **opts):
567 567 '''reverse effect of earlier changeset
568 568
569 569 Prepare a new changeset with the effect of REV undone in the
570 570 current working directory. If no conflicts were encountered,
571 571 it will be committed immediately.
572 572
573 573 If REV is the parent of the working directory, then this new changeset
574 574 is committed automatically (unless --no-commit is specified).
575 575
576 576 .. note::
577 577
578 578 :hg:`backout` cannot be used to fix either an unwanted or
579 579 incorrect merge.
580 580
581 581 .. container:: verbose
582 582
583 583 Examples:
584 584
585 585 - Reverse the effect of the parent of the working directory.
586 586 This backout will be committed immediately::
587 587
588 588 hg backout -r .
589 589
590 590 - Reverse the effect of previous bad revision 23::
591 591
592 592 hg backout -r 23
593 593
594 594 - Reverse the effect of previous bad revision 23 and
595 595 leave changes uncommitted::
596 596
597 597 hg backout -r 23 --no-commit
598 598 hg commit -m "Backout revision 23"
599 599
600 600 By default, the pending changeset will have one parent,
601 601 maintaining a linear history. With --merge, the pending
602 602 changeset will instead have two parents: the old parent of the
603 603 working directory and a new child of REV that simply undoes REV.
604 604
605 605 Before version 1.7, the behavior without --merge was equivalent
606 606 to specifying --merge followed by :hg:`update --clean .` to
607 607 cancel the merge and leave the child of REV as a head to be
608 608 merged separately.
609 609
610 610 See :hg:`help dates` for a list of formats valid for -d/--date.
611 611
612 612 See :hg:`help revert` for a way to restore files to the state
613 613 of another revision.
614 614
615 615 Returns 0 on success, 1 if nothing to backout or there are unresolved
616 616 files.
617 617 '''
618 618 wlock = lock = None
619 619 try:
620 620 wlock = repo.wlock()
621 621 lock = repo.lock()
622 622 return _dobackout(ui, repo, node, rev, **opts)
623 623 finally:
624 624 release(lock, wlock)
625 625
626 626 def _dobackout(ui, repo, node=None, rev=None, **opts):
627 627 if opts.get('commit') and opts.get('no_commit'):
628 628 raise error.Abort(_("cannot use --commit with --no-commit"))
629 629 if opts.get('merge') and opts.get('no_commit'):
630 630 raise error.Abort(_("cannot use --merge with --no-commit"))
631 631
632 632 if rev and node:
633 633 raise error.Abort(_("please specify just one revision"))
634 634
635 635 if not rev:
636 636 rev = node
637 637
638 638 if not rev:
639 639 raise error.Abort(_("please specify a revision to backout"))
640 640
641 641 date = opts.get('date')
642 642 if date:
643 643 opts['date'] = util.parsedate(date)
644 644
645 645 cmdutil.checkunfinished(repo)
646 646 cmdutil.bailifchanged(repo)
647 647 node = scmutil.revsingle(repo, rev).node()
648 648
649 649 op1, op2 = repo.dirstate.parents()
650 650 if not repo.changelog.isancestor(node, op1):
651 651 raise error.Abort(_('cannot backout change that is not an ancestor'))
652 652
653 653 p1, p2 = repo.changelog.parents(node)
654 654 if p1 == nullid:
655 655 raise error.Abort(_('cannot backout a change with no parents'))
656 656 if p2 != nullid:
657 657 if not opts.get('parent'):
658 658 raise error.Abort(_('cannot backout a merge changeset'))
659 659 p = repo.lookup(opts['parent'])
660 660 if p not in (p1, p2):
661 661 raise error.Abort(_('%s is not a parent of %s') %
662 662 (short(p), short(node)))
663 663 parent = p
664 664 else:
665 665 if opts.get('parent'):
666 666 raise error.Abort(_('cannot use --parent on non-merge changeset'))
667 667 parent = p1
668 668
669 669 # the backout should appear on the same branch
670 670 branch = repo.dirstate.branch()
671 671 bheads = repo.branchheads(branch)
672 672 rctx = scmutil.revsingle(repo, hex(parent))
673 673 if not opts.get('merge') and op1 != node:
674 674 dsguard = dirstateguard.dirstateguard(repo, 'backout')
675 675 try:
676 676 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
677 677 'backout')
678 678 stats = mergemod.update(repo, parent, True, True, node, False)
679 679 repo.setparents(op1, op2)
680 680 dsguard.close()
681 681 hg._showstats(repo, stats)
682 682 if stats[3]:
683 683 repo.ui.status(_("use 'hg resolve' to retry unresolved "
684 684 "file merges\n"))
685 685 return 1
686 686 finally:
687 687 ui.setconfig('ui', 'forcemerge', '', '')
688 688 lockmod.release(dsguard)
689 689 else:
690 690 hg.clean(repo, node, show_stats=False)
691 691 repo.dirstate.setbranch(branch)
692 692 cmdutil.revert(ui, repo, rctx, repo.dirstate.parents())
693 693
694 694 if opts.get('no_commit'):
695 695 msg = _("changeset %s backed out, "
696 696 "don't forget to commit.\n")
697 697 ui.status(msg % short(node))
698 698 return 0
699 699
700 700 def commitfunc(ui, repo, message, match, opts):
701 701 editform = 'backout'
702 702 e = cmdutil.getcommiteditor(editform=editform, **opts)
703 703 if not message:
704 704 # we don't translate commit messages
705 705 message = "Backed out changeset %s" % short(node)
706 706 e = cmdutil.getcommiteditor(edit=True, editform=editform)
707 707 return repo.commit(message, opts.get('user'), opts.get('date'),
708 708 match, editor=e)
709 709 newnode = cmdutil.commit(ui, repo, commitfunc, [], opts)
710 710 if not newnode:
711 711 ui.status(_("nothing changed\n"))
712 712 return 1
713 713 cmdutil.commitstatus(repo, newnode, branch, bheads)
714 714
715 715 def nice(node):
716 716 return '%d:%s' % (repo.changelog.rev(node), short(node))
717 717 ui.status(_('changeset %s backs out changeset %s\n') %
718 718 (nice(repo.changelog.tip()), nice(node)))
719 719 if opts.get('merge') and op1 != node:
720 720 hg.clean(repo, op1, show_stats=False)
721 721 ui.status(_('merging with changeset %s\n')
722 722 % nice(repo.changelog.tip()))
723 723 try:
724 724 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
725 725 'backout')
726 726 return hg.merge(repo, hex(repo.changelog.tip()))
727 727 finally:
728 728 ui.setconfig('ui', 'forcemerge', '', '')
729 729 return 0
730 730
731 731 @command('bisect',
732 732 [('r', 'reset', False, _('reset bisect state')),
733 733 ('g', 'good', False, _('mark changeset good')),
734 734 ('b', 'bad', False, _('mark changeset bad')),
735 735 ('s', 'skip', False, _('skip testing changeset')),
736 736 ('e', 'extend', False, _('extend the bisect range')),
737 737 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
738 738 ('U', 'noupdate', False, _('do not update to target'))],
739 739 _("[-gbsr] [-U] [-c CMD] [REV]"))
740 740 def bisect(ui, repo, rev=None, extra=None, command=None,
741 741 reset=None, good=None, bad=None, skip=None, extend=None,
742 742 noupdate=None):
743 743 """subdivision search of changesets
744 744
745 745 This command helps to find changesets which introduce problems. To
746 746 use, mark the earliest changeset you know exhibits the problem as
747 747 bad, then mark the latest changeset which is free from the problem
748 748 as good. Bisect will update your working directory to a revision
749 749 for testing (unless the -U/--noupdate option is specified). Once
750 750 you have performed tests, mark the working directory as good or
751 751 bad, and bisect will either update to another candidate changeset
752 752 or announce that it has found the bad revision.
753 753
754 754 As a shortcut, you can also use the revision argument to mark a
755 755 revision as good or bad without checking it out first.
756 756
757 757 If you supply a command, it will be used for automatic bisection.
758 758 The environment variable HG_NODE will contain the ID of the
759 759 changeset being tested. The exit status of the command will be
760 760 used to mark revisions as good or bad: status 0 means good, 125
761 761 means to skip the revision, 127 (command not found) will abort the
762 762 bisection, and any other non-zero exit status means the revision
763 763 is bad.
764 764
765 765 .. container:: verbose
766 766
767 767 Some examples:
768 768
769 769 - start a bisection with known bad revision 34, and good revision 12::
770 770
771 771 hg bisect --bad 34
772 772 hg bisect --good 12
773 773
774 774 - advance the current bisection by marking current revision as good or
775 775 bad::
776 776
777 777 hg bisect --good
778 778 hg bisect --bad
779 779
780 780 - mark the current revision, or a known revision, to be skipped (e.g. if
781 781 that revision is not usable because of another issue)::
782 782
783 783 hg bisect --skip
784 784 hg bisect --skip 23
785 785
786 786 - skip all revisions that do not touch directories ``foo`` or ``bar``::
787 787
788 788 hg bisect --skip "!( file('path:foo') & file('path:bar') )"
789 789
790 790 - forget the current bisection::
791 791
792 792 hg bisect --reset
793 793
794 794 - use 'make && make tests' to automatically find the first broken
795 795 revision::
796 796
797 797 hg bisect --reset
798 798 hg bisect --bad 34
799 799 hg bisect --good 12
800 800 hg bisect --command "make && make tests"
801 801
802 802 - see all changesets whose states are already known in the current
803 803 bisection::
804 804
805 805 hg log -r "bisect(pruned)"
806 806
807 807 - see the changeset currently being bisected (especially useful
808 808 if running with -U/--noupdate)::
809 809
810 810 hg log -r "bisect(current)"
811 811
812 812 - see all changesets that took part in the current bisection::
813 813
814 814 hg log -r "bisect(range)"
815 815
816 816 - you can even get a nice graph::
817 817
818 818 hg log --graph -r "bisect(range)"
819 819
820 820 See :hg:`help revisions.bisect` for more about the `bisect()` predicate.
821 821
822 822 Returns 0 on success.
823 823 """
824 824 # backward compatibility
825 825 if rev in "good bad reset init".split():
826 826 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
827 827 cmd, rev, extra = rev, extra, None
828 828 if cmd == "good":
829 829 good = True
830 830 elif cmd == "bad":
831 831 bad = True
832 832 else:
833 833 reset = True
834 834 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
835 835 raise error.Abort(_('incompatible arguments'))
836 836
837 837 cmdutil.checkunfinished(repo)
838 838
839 839 if reset:
840 840 hbisect.resetstate(repo)
841 841 return
842 842
843 843 state = hbisect.load_state(repo)
844 844
845 845 # update state
846 846 if good or bad or skip:
847 847 if rev:
848 848 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
849 849 else:
850 850 nodes = [repo.lookup('.')]
851 851 if good:
852 852 state['good'] += nodes
853 853 elif bad:
854 854 state['bad'] += nodes
855 855 elif skip:
856 856 state['skip'] += nodes
857 857 hbisect.save_state(repo, state)
858 858 if not (state['good'] and state['bad']):
859 859 return
860 860
861 861 def mayupdate(repo, node, show_stats=True):
862 862 """common used update sequence"""
863 863 if noupdate:
864 864 return
865 865 cmdutil.bailifchanged(repo)
866 866 return hg.clean(repo, node, show_stats=show_stats)
867 867
868 868 displayer = cmdutil.show_changeset(ui, repo, {})
869 869
870 870 if command:
871 871 changesets = 1
872 872 if noupdate:
873 873 try:
874 874 node = state['current'][0]
875 875 except LookupError:
876 876 raise error.Abort(_('current bisect revision is unknown - '
877 877 'start a new bisect to fix'))
878 878 else:
879 879 node, p2 = repo.dirstate.parents()
880 880 if p2 != nullid:
881 881 raise error.Abort(_('current bisect revision is a merge'))
882 882 if rev:
883 883 node = repo[scmutil.revsingle(repo, rev, node)].node()
884 884 try:
885 885 while changesets:
886 886 # update state
887 887 state['current'] = [node]
888 888 hbisect.save_state(repo, state)
889 889 status = ui.system(command, environ={'HG_NODE': hex(node)})
890 890 if status == 125:
891 891 transition = "skip"
892 892 elif status == 0:
893 893 transition = "good"
894 894 # status < 0 means process was killed
895 895 elif status == 127:
896 896 raise error.Abort(_("failed to execute %s") % command)
897 897 elif status < 0:
898 898 raise error.Abort(_("%s killed") % command)
899 899 else:
900 900 transition = "bad"
901 901 state[transition].append(node)
902 902 ctx = repo[node]
903 903 ui.status(_('changeset %d:%s: %s\n') % (ctx, ctx, transition))
904 904 hbisect.checkstate(state)
905 905 # bisect
906 906 nodes, changesets, bgood = hbisect.bisect(repo.changelog, state)
907 907 # update to next check
908 908 node = nodes[0]
909 909 mayupdate(repo, node, show_stats=False)
910 910 finally:
911 911 state['current'] = [node]
912 912 hbisect.save_state(repo, state)
913 913 hbisect.printresult(ui, repo, state, displayer, nodes, bgood)
914 914 return
915 915
916 916 hbisect.checkstate(state)
917 917
918 918 # actually bisect
919 919 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
920 920 if extend:
921 921 if not changesets:
922 922 extendnode = hbisect.extendrange(repo, state, nodes, good)
923 923 if extendnode is not None:
924 924 ui.write(_("Extending search to changeset %d:%s\n")
925 925 % (extendnode.rev(), extendnode))
926 926 state['current'] = [extendnode.node()]
927 927 hbisect.save_state(repo, state)
928 928 return mayupdate(repo, extendnode.node())
929 929 raise error.Abort(_("nothing to extend"))
930 930
931 931 if changesets == 0:
932 932 hbisect.printresult(ui, repo, state, displayer, nodes, good)
933 933 else:
934 934 assert len(nodes) == 1 # only a single node can be tested next
935 935 node = nodes[0]
936 936 # compute the approximate number of remaining tests
937 937 tests, size = 0, 2
938 938 while size <= changesets:
939 939 tests, size = tests + 1, size * 2
940 940 rev = repo.changelog.rev(node)
941 941 ui.write(_("Testing changeset %d:%s "
942 942 "(%d changesets remaining, ~%d tests)\n")
943 943 % (rev, short(node), changesets, tests))
944 944 state['current'] = [node]
945 945 hbisect.save_state(repo, state)
946 946 return mayupdate(repo, node)
947 947
948 948 @command('bookmarks|bookmark',
949 949 [('f', 'force', False, _('force')),
950 950 ('r', 'rev', '', _('revision for bookmark action'), _('REV')),
951 951 ('d', 'delete', False, _('delete a given bookmark')),
952 952 ('m', 'rename', '', _('rename a given bookmark'), _('OLD')),
953 953 ('i', 'inactive', False, _('mark a bookmark inactive')),
954 954 ] + formatteropts,
955 955 _('hg bookmarks [OPTIONS]... [NAME]...'))
956 956 def bookmark(ui, repo, *names, **opts):
957 957 '''create a new bookmark or list existing bookmarks
958 958
959 959 Bookmarks are labels on changesets to help track lines of development.
960 960 Bookmarks are unversioned and can be moved, renamed and deleted.
961 961 Deleting or moving a bookmark has no effect on the associated changesets.
962 962
963 963 Creating or updating to a bookmark causes it to be marked as 'active'.
964 964 The active bookmark is indicated with a '*'.
965 965 When a commit is made, the active bookmark will advance to the new commit.
966 966 A plain :hg:`update` will also advance an active bookmark, if possible.
967 967 Updating away from a bookmark will cause it to be deactivated.
968 968
969 969 Bookmarks can be pushed and pulled between repositories (see
970 970 :hg:`help push` and :hg:`help pull`). If a shared bookmark has
971 971 diverged, a new 'divergent bookmark' of the form 'name@path' will
972 972 be created. Using :hg:`merge` will resolve the divergence.
973 973
974 974 A bookmark named '@' has the special property that :hg:`clone` will
975 975 check it out by default if it exists.
976 976
977 977 .. container:: verbose
978 978
979 979 Examples:
980 980
981 981 - create an active bookmark for a new line of development::
982 982
983 983 hg book new-feature
984 984
985 985 - create an inactive bookmark as a place marker::
986 986
987 987 hg book -i reviewed
988 988
989 989 - create an inactive bookmark on another changeset::
990 990
991 991 hg book -r .^ tested
992 992
993 993 - rename bookmark turkey to dinner::
994 994
995 995 hg book -m turkey dinner
996 996
997 997 - move the '@' bookmark from another branch::
998 998
999 999 hg book -f @
1000 1000 '''
1001 1001 force = opts.get('force')
1002 1002 rev = opts.get('rev')
1003 1003 delete = opts.get('delete')
1004 1004 rename = opts.get('rename')
1005 1005 inactive = opts.get('inactive')
1006 1006
1007 1007 def checkformat(mark):
1008 1008 mark = mark.strip()
1009 1009 if not mark:
1010 1010 raise error.Abort(_("bookmark names cannot consist entirely of "
1011 1011 "whitespace"))
1012 1012 scmutil.checknewlabel(repo, mark, 'bookmark')
1013 1013 return mark
1014 1014
1015 1015 def checkconflict(repo, mark, cur, force=False, target=None):
1016 1016 if mark in marks and not force:
1017 1017 if target:
1018 1018 if marks[mark] == target and target == cur:
1019 1019 # re-activating a bookmark
1020 1020 return
1021 1021 anc = repo.changelog.ancestors([repo[target].rev()])
1022 1022 bmctx = repo[marks[mark]]
1023 1023 divs = [repo[b].node() for b in marks
1024 1024 if b.split('@', 1)[0] == mark.split('@', 1)[0]]
1025 1025
1026 1026 # allow resolving a single divergent bookmark even if moving
1027 1027 # the bookmark across branches when a revision is specified
1028 1028 # that contains a divergent bookmark
1029 1029 if bmctx.rev() not in anc and target in divs:
1030 1030 bookmarks.deletedivergent(repo, [target], mark)
1031 1031 return
1032 1032
1033 1033 deletefrom = [b for b in divs
1034 1034 if repo[b].rev() in anc or b == target]
1035 1035 bookmarks.deletedivergent(repo, deletefrom, mark)
1036 1036 if bookmarks.validdest(repo, bmctx, repo[target]):
1037 1037 ui.status(_("moving bookmark '%s' forward from %s\n") %
1038 1038 (mark, short(bmctx.node())))
1039 1039 return
1040 1040 raise error.Abort(_("bookmark '%s' already exists "
1041 1041 "(use -f to force)") % mark)
1042 1042 if ((mark in repo.branchmap() or mark == repo.dirstate.branch())
1043 1043 and not force):
1044 1044 raise error.Abort(
1045 1045 _("a bookmark cannot have the name of an existing branch"))
1046 1046
1047 1047 if delete and rename:
1048 1048 raise error.Abort(_("--delete and --rename are incompatible"))
1049 1049 if delete and rev:
1050 1050 raise error.Abort(_("--rev is incompatible with --delete"))
1051 1051 if rename and rev:
1052 1052 raise error.Abort(_("--rev is incompatible with --rename"))
1053 1053 if not names and (delete or rev):
1054 1054 raise error.Abort(_("bookmark name required"))
1055 1055
1056 1056 if delete or rename or names or inactive:
1057 1057 wlock = lock = tr = None
1058 1058 try:
1059 1059 wlock = repo.wlock()
1060 1060 lock = repo.lock()
1061 1061 cur = repo.changectx('.').node()
1062 1062 marks = repo._bookmarks
1063 1063 if delete:
1064 1064 tr = repo.transaction('bookmark')
1065 1065 for mark in names:
1066 1066 if mark not in marks:
1067 1067 raise error.Abort(_("bookmark '%s' does not exist") %
1068 1068 mark)
1069 1069 if mark == repo._activebookmark:
1070 1070 bookmarks.deactivate(repo)
1071 1071 del marks[mark]
1072 1072
1073 1073 elif rename:
1074 1074 tr = repo.transaction('bookmark')
1075 1075 if not names:
1076 1076 raise error.Abort(_("new bookmark name required"))
1077 1077 elif len(names) > 1:
1078 1078 raise error.Abort(_("only one new bookmark name allowed"))
1079 1079 mark = checkformat(names[0])
1080 1080 if rename not in marks:
1081 1081 raise error.Abort(_("bookmark '%s' does not exist")
1082 1082 % rename)
1083 1083 checkconflict(repo, mark, cur, force)
1084 1084 marks[mark] = marks[rename]
1085 1085 if repo._activebookmark == rename and not inactive:
1086 1086 bookmarks.activate(repo, mark)
1087 1087 del marks[rename]
1088 1088 elif names:
1089 1089 tr = repo.transaction('bookmark')
1090 1090 newact = None
1091 1091 for mark in names:
1092 1092 mark = checkformat(mark)
1093 1093 if newact is None:
1094 1094 newact = mark
1095 1095 if inactive and mark == repo._activebookmark:
1096 1096 bookmarks.deactivate(repo)
1097 1097 return
1098 1098 tgt = cur
1099 1099 if rev:
1100 1100 tgt = scmutil.revsingle(repo, rev).node()
1101 1101 checkconflict(repo, mark, cur, force, tgt)
1102 1102 marks[mark] = tgt
1103 1103 if not inactive and cur == marks[newact] and not rev:
1104 1104 bookmarks.activate(repo, newact)
1105 1105 elif cur != tgt and newact == repo._activebookmark:
1106 1106 bookmarks.deactivate(repo)
1107 1107 elif inactive:
1108 1108 if len(marks) == 0:
1109 1109 ui.status(_("no bookmarks set\n"))
1110 1110 elif not repo._activebookmark:
1111 1111 ui.status(_("no active bookmark\n"))
1112 1112 else:
1113 1113 bookmarks.deactivate(repo)
1114 1114 if tr is not None:
1115 1115 marks.recordchange(tr)
1116 1116 tr.close()
1117 1117 finally:
1118 1118 lockmod.release(tr, lock, wlock)
1119 1119 else: # show bookmarks
1120 1120 fm = ui.formatter('bookmarks', opts)
1121 1121 hexfn = fm.hexfunc
1122 1122 marks = repo._bookmarks
1123 1123 if len(marks) == 0 and fm.isplain():
1124 1124 ui.status(_("no bookmarks set\n"))
1125 1125 for bmark, n in sorted(marks.iteritems()):
1126 1126 active = repo._activebookmark
1127 1127 if bmark == active:
1128 1128 prefix, label = '*', activebookmarklabel
1129 1129 else:
1130 1130 prefix, label = ' ', ''
1131 1131
1132 1132 fm.startitem()
1133 1133 if not ui.quiet:
1134 1134 fm.plain(' %s ' % prefix, label=label)
1135 1135 fm.write('bookmark', '%s', bmark, label=label)
1136 1136 pad = " " * (25 - encoding.colwidth(bmark))
1137 1137 fm.condwrite(not ui.quiet, 'rev node', pad + ' %d:%s',
1138 1138 repo.changelog.rev(n), hexfn(n), label=label)
1139 1139 fm.data(active=(bmark == active))
1140 1140 fm.plain('\n')
1141 1141 fm.end()
1142 1142
1143 1143 @command('branch',
1144 1144 [('f', 'force', None,
1145 1145 _('set branch name even if it shadows an existing branch')),
1146 1146 ('C', 'clean', None, _('reset branch name to parent branch name'))],
1147 1147 _('[-fC] [NAME]'))
1148 1148 def branch(ui, repo, label=None, **opts):
1149 1149 """set or show the current branch name
1150 1150
1151 1151 .. note::
1152 1152
1153 1153 Branch names are permanent and global. Use :hg:`bookmark` to create a
1154 1154 light-weight bookmark instead. See :hg:`help glossary` for more
1155 1155 information about named branches and bookmarks.
1156 1156
1157 1157 With no argument, show the current branch name. With one argument,
1158 1158 set the working directory branch name (the branch will not exist
1159 1159 in the repository until the next commit). Standard practice
1160 1160 recommends that primary development take place on the 'default'
1161 1161 branch.
1162 1162
1163 1163 Unless -f/--force is specified, branch will not let you set a
1164 1164 branch name that already exists.
1165 1165
1166 1166 Use -C/--clean to reset the working directory branch to that of
1167 1167 the parent of the working directory, negating a previous branch
1168 1168 change.
1169 1169
1170 1170 Use the command :hg:`update` to switch to an existing branch. Use
1171 1171 :hg:`commit --close-branch` to mark this branch head as closed.
1172 1172 When all heads of a branch are closed, the branch will be
1173 1173 considered closed.
1174 1174
1175 1175 Returns 0 on success.
1176 1176 """
1177 1177 if label:
1178 1178 label = label.strip()
1179 1179
1180 1180 if not opts.get('clean') and not label:
1181 1181 ui.write("%s\n" % repo.dirstate.branch())
1182 1182 return
1183 1183
1184 1184 with repo.wlock():
1185 1185 if opts.get('clean'):
1186 1186 label = repo[None].p1().branch()
1187 1187 repo.dirstate.setbranch(label)
1188 1188 ui.status(_('reset working directory to branch %s\n') % label)
1189 1189 elif label:
1190 1190 if not opts.get('force') and label in repo.branchmap():
1191 1191 if label not in [p.branch() for p in repo[None].parents()]:
1192 1192 raise error.Abort(_('a branch of the same name already'
1193 1193 ' exists'),
1194 1194 # i18n: "it" refers to an existing branch
1195 1195 hint=_("use 'hg update' to switch to it"))
1196 1196 scmutil.checknewlabel(repo, label, 'branch')
1197 1197 repo.dirstate.setbranch(label)
1198 1198 ui.status(_('marked working directory as branch %s\n') % label)
1199 1199
1200 1200 # find any open named branches aside from default
1201 1201 others = [n for n, h, t, c in repo.branchmap().iterbranches()
1202 1202 if n != "default" and not c]
1203 1203 if not others:
1204 1204 ui.status(_('(branches are permanent and global, '
1205 1205 'did you want a bookmark?)\n'))
1206 1206
1207 1207 @command('branches',
1208 1208 [('a', 'active', False,
1209 1209 _('show only branches that have unmerged heads (DEPRECATED)')),
1210 1210 ('c', 'closed', False, _('show normal and closed branches')),
1211 1211 ] + formatteropts,
1212 1212 _('[-c]'))
1213 1213 def branches(ui, repo, active=False, closed=False, **opts):
1214 1214 """list repository named branches
1215 1215
1216 1216 List the repository's named branches, indicating which ones are
1217 1217 inactive. If -c/--closed is specified, also list branches which have
1218 1218 been marked closed (see :hg:`commit --close-branch`).
1219 1219
1220 1220 Use the command :hg:`update` to switch to an existing branch.
1221 1221
1222 1222 Returns 0.
1223 1223 """
1224 1224
1225 1225 fm = ui.formatter('branches', opts)
1226 1226 hexfunc = fm.hexfunc
1227 1227
1228 1228 allheads = set(repo.heads())
1229 1229 branches = []
1230 1230 for tag, heads, tip, isclosed in repo.branchmap().iterbranches():
1231 1231 isactive = not isclosed and bool(set(heads) & allheads)
1232 1232 branches.append((tag, repo[tip], isactive, not isclosed))
1233 1233 branches.sort(key=lambda i: (i[2], i[1].rev(), i[0], i[3]),
1234 1234 reverse=True)
1235 1235
1236 1236 for tag, ctx, isactive, isopen in branches:
1237 1237 if active and not isactive:
1238 1238 continue
1239 1239 if isactive:
1240 1240 label = 'branches.active'
1241 1241 notice = ''
1242 1242 elif not isopen:
1243 1243 if not closed:
1244 1244 continue
1245 1245 label = 'branches.closed'
1246 1246 notice = _(' (closed)')
1247 1247 else:
1248 1248 label = 'branches.inactive'
1249 1249 notice = _(' (inactive)')
1250 1250 current = (tag == repo.dirstate.branch())
1251 1251 if current:
1252 1252 label = 'branches.current'
1253 1253
1254 1254 fm.startitem()
1255 1255 fm.write('branch', '%s', tag, label=label)
1256 1256 rev = ctx.rev()
1257 1257 padsize = max(31 - len(str(rev)) - encoding.colwidth(tag), 0)
1258 1258 fmt = ' ' * padsize + ' %d:%s'
1259 1259 fm.condwrite(not ui.quiet, 'rev node', fmt, rev, hexfunc(ctx.node()),
1260 1260 label='log.changeset changeset.%s' % ctx.phasestr())
1261 1261 fm.data(active=isactive, closed=not isopen, current=current)
1262 1262 if not ui.quiet:
1263 1263 fm.plain(notice)
1264 1264 fm.plain('\n')
1265 1265 fm.end()
1266 1266
1267 1267 @command('bundle',
1268 1268 [('f', 'force', None, _('run even when the destination is unrelated')),
1269 1269 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
1270 1270 _('REV')),
1271 1271 ('b', 'branch', [], _('a specific branch you would like to bundle'),
1272 1272 _('BRANCH')),
1273 1273 ('', 'base', [],
1274 1274 _('a base changeset assumed to be available at the destination'),
1275 1275 _('REV')),
1276 1276 ('a', 'all', None, _('bundle all changesets in the repository')),
1277 1277 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
1278 1278 ] + remoteopts,
1279 1279 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
1280 1280 def bundle(ui, repo, fname, dest=None, **opts):
1281 1281 """create a changegroup file
1282 1282
1283 1283 Generate a changegroup file collecting changesets to be added
1284 1284 to a repository.
1285 1285
1286 1286 To create a bundle containing all changesets, use -a/--all
1287 1287 (or --base null). Otherwise, hg assumes the destination will have
1288 1288 all the nodes you specify with --base parameters. Otherwise, hg
1289 1289 will assume the repository has all the nodes in destination, or
1290 1290 default-push/default if no destination is specified.
1291 1291
1292 1292 You can change bundle format with the -t/--type option. You can
1293 1293 specify a compression, a bundle version or both using a dash
1294 1294 (comp-version). The available compression methods are: none, bzip2,
1295 1295 and gzip (by default, bundles are compressed using bzip2). The
1296 1296 available formats are: v1, v2 (default to most suitable).
1297 1297
1298 1298 The bundle file can then be transferred using conventional means
1299 1299 and applied to another repository with the unbundle or pull
1300 1300 command. This is useful when direct push and pull are not
1301 1301 available or when exporting an entire repository is undesirable.
1302 1302
1303 1303 Applying bundles preserves all changeset contents including
1304 1304 permissions, copy/rename information, and revision history.
1305 1305
1306 1306 Returns 0 on success, 1 if no changes found.
1307 1307 """
1308 1308 revs = None
1309 1309 if 'rev' in opts:
1310 1310 revstrings = opts['rev']
1311 1311 revs = scmutil.revrange(repo, revstrings)
1312 1312 if revstrings and not revs:
1313 1313 raise error.Abort(_('no commits to bundle'))
1314 1314
1315 1315 bundletype = opts.get('type', 'bzip2').lower()
1316 1316 try:
1317 1317 bcompression, cgversion, params = exchange.parsebundlespec(
1318 1318 repo, bundletype, strict=False)
1319 1319 except error.UnsupportedBundleSpecification as e:
1320 1320 raise error.Abort(str(e),
1321 1321 hint=_("see 'hg help bundle' for supported "
1322 1322 "values for --type"))
1323 1323
1324 1324 # Packed bundles are a pseudo bundle format for now.
1325 1325 if cgversion == 's1':
1326 1326 raise error.Abort(_('packed bundles cannot be produced by "hg bundle"'),
1327 1327 hint=_("use 'hg debugcreatestreamclonebundle'"))
1328 1328
1329 1329 if opts.get('all'):
1330 1330 if dest:
1331 1331 raise error.Abort(_("--all is incompatible with specifying "
1332 1332 "a destination"))
1333 1333 if opts.get('base'):
1334 1334 ui.warn(_("ignoring --base because --all was specified\n"))
1335 1335 base = ['null']
1336 1336 else:
1337 1337 base = scmutil.revrange(repo, opts.get('base'))
1338 1338 # TODO: get desired bundlecaps from command line.
1339 1339 bundlecaps = None
1340 1340 if cgversion not in changegroup.supportedoutgoingversions(repo):
1341 1341 raise error.Abort(_("repository does not support bundle version %s") %
1342 1342 cgversion)
1343 1343
1344 1344 if base:
1345 1345 if dest:
1346 1346 raise error.Abort(_("--base is incompatible with specifying "
1347 1347 "a destination"))
1348 1348 common = [repo.lookup(rev) for rev in base]
1349 1349 heads = revs and map(repo.lookup, revs) or None
1350 1350 outgoing = discovery.outgoing(repo, common, heads)
1351 1351 cg = changegroup.getchangegroup(repo, 'bundle', outgoing,
1352 1352 bundlecaps=bundlecaps,
1353 1353 version=cgversion)
1354 1354 outgoing = None
1355 1355 else:
1356 1356 dest = ui.expandpath(dest or 'default-push', dest or 'default')
1357 1357 dest, branches = hg.parseurl(dest, opts.get('branch'))
1358 1358 other = hg.peer(repo, opts, dest)
1359 1359 revs, checkout = hg.addbranchrevs(repo, repo, branches, revs)
1360 1360 heads = revs and map(repo.lookup, revs) or revs
1361 1361 outgoing = discovery.findcommonoutgoing(repo, other,
1362 1362 onlyheads=heads,
1363 1363 force=opts.get('force'),
1364 1364 portable=True)
1365 1365 cg = changegroup.getlocalchangegroup(repo, 'bundle', outgoing,
1366 1366 bundlecaps, version=cgversion)
1367 1367 if not cg:
1368 1368 scmutil.nochangesfound(ui, repo, outgoing and outgoing.excluded)
1369 1369 return 1
1370 1370
1371 1371 if cgversion == '01': #bundle1
1372 1372 if bcompression is None:
1373 1373 bcompression = 'UN'
1374 1374 bversion = 'HG10' + bcompression
1375 1375 bcompression = None
1376 1376 else:
1377 1377 assert cgversion == '02'
1378 1378 bversion = 'HG20'
1379 1379
1380 1380 # TODO compression options should be derived from bundlespec parsing.
1381 1381 # This is a temporary hack to allow adjusting bundle compression
1382 1382 # level without a) formalizing the bundlespec changes to declare it
1383 1383 # b) introducing a command flag.
1384 1384 compopts = {}
1385 1385 complevel = ui.configint('experimental', 'bundlecomplevel')
1386 1386 if complevel is not None:
1387 1387 compopts['level'] = complevel
1388 1388
1389 1389 bundle2.writebundle(ui, cg, fname, bversion, compression=bcompression,
1390 1390 compopts=compopts)
1391 1391
1392 1392 @command('cat',
1393 1393 [('o', 'output', '',
1394 1394 _('print output to file with formatted name'), _('FORMAT')),
1395 1395 ('r', 'rev', '', _('print the given revision'), _('REV')),
1396 1396 ('', 'decode', None, _('apply any matching decode filter')),
1397 1397 ] + walkopts,
1398 1398 _('[OPTION]... FILE...'),
1399 1399 inferrepo=True)
1400 1400 def cat(ui, repo, file1, *pats, **opts):
1401 1401 """output the current or given revision of files
1402 1402
1403 1403 Print the specified files as they were at the given revision. If
1404 1404 no revision is given, the parent of the working directory is used.
1405 1405
1406 1406 Output may be to a file, in which case the name of the file is
1407 1407 given using a format string. The formatting rules as follows:
1408 1408
1409 1409 :``%%``: literal "%" character
1410 1410 :``%s``: basename of file being printed
1411 1411 :``%d``: dirname of file being printed, or '.' if in repository root
1412 1412 :``%p``: root-relative path name of file being printed
1413 1413 :``%H``: changeset hash (40 hexadecimal digits)
1414 1414 :``%R``: changeset revision number
1415 1415 :``%h``: short-form changeset hash (12 hexadecimal digits)
1416 1416 :``%r``: zero-padded changeset revision number
1417 1417 :``%b``: basename of the exporting repository
1418 1418
1419 1419 Returns 0 on success.
1420 1420 """
1421 1421 ctx = scmutil.revsingle(repo, opts.get('rev'))
1422 1422 m = scmutil.match(ctx, (file1,) + pats, opts)
1423 1423
1424 1424 ui.pager('cat')
1425 1425 return cmdutil.cat(ui, repo, ctx, m, '', **opts)
1426 1426
1427 1427 @command('^clone',
1428 1428 [('U', 'noupdate', None, _('the clone will include an empty working '
1429 1429 'directory (only a repository)')),
1430 1430 ('u', 'updaterev', '', _('revision, tag, or branch to check out'),
1431 1431 _('REV')),
1432 1432 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
1433 1433 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
1434 1434 ('', 'pull', None, _('use pull protocol to copy metadata')),
1435 1435 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
1436 1436 ] + remoteopts,
1437 1437 _('[OPTION]... SOURCE [DEST]'),
1438 1438 norepo=True)
1439 1439 def clone(ui, source, dest=None, **opts):
1440 1440 """make a copy of an existing repository
1441 1441
1442 1442 Create a copy of an existing repository in a new directory.
1443 1443
1444 1444 If no destination directory name is specified, it defaults to the
1445 1445 basename of the source.
1446 1446
1447 1447 The location of the source is added to the new repository's
1448 1448 ``.hg/hgrc`` file, as the default to be used for future pulls.
1449 1449
1450 1450 Only local paths and ``ssh://`` URLs are supported as
1451 1451 destinations. For ``ssh://`` destinations, no working directory or
1452 1452 ``.hg/hgrc`` will be created on the remote side.
1453 1453
1454 1454 If the source repository has a bookmark called '@' set, that
1455 1455 revision will be checked out in the new repository by default.
1456 1456
1457 1457 To check out a particular version, use -u/--update, or
1458 1458 -U/--noupdate to create a clone with no working directory.
1459 1459
1460 1460 To pull only a subset of changesets, specify one or more revisions
1461 1461 identifiers with -r/--rev or branches with -b/--branch. The
1462 1462 resulting clone will contain only the specified changesets and
1463 1463 their ancestors. These options (or 'clone src#rev dest') imply
1464 1464 --pull, even for local source repositories.
1465 1465
1466 1466 .. note::
1467 1467
1468 1468 Specifying a tag will include the tagged changeset but not the
1469 1469 changeset containing the tag.
1470 1470
1471 1471 .. container:: verbose
1472 1472
1473 1473 For efficiency, hardlinks are used for cloning whenever the
1474 1474 source and destination are on the same filesystem (note this
1475 1475 applies only to the repository data, not to the working
1476 1476 directory). Some filesystems, such as AFS, implement hardlinking
1477 1477 incorrectly, but do not report errors. In these cases, use the
1478 1478 --pull option to avoid hardlinking.
1479 1479
1480 1480 In some cases, you can clone repositories and the working
1481 1481 directory using full hardlinks with ::
1482 1482
1483 1483 $ cp -al REPO REPOCLONE
1484 1484
1485 1485 This is the fastest way to clone, but it is not always safe. The
1486 1486 operation is not atomic (making sure REPO is not modified during
1487 1487 the operation is up to you) and you have to make sure your
1488 1488 editor breaks hardlinks (Emacs and most Linux Kernel tools do
1489 1489 so). Also, this is not compatible with certain extensions that
1490 1490 place their metadata under the .hg directory, such as mq.
1491 1491
1492 1492 Mercurial will update the working directory to the first applicable
1493 1493 revision from this list:
1494 1494
1495 1495 a) null if -U or the source repository has no changesets
1496 1496 b) if -u . and the source repository is local, the first parent of
1497 1497 the source repository's working directory
1498 1498 c) the changeset specified with -u (if a branch name, this means the
1499 1499 latest head of that branch)
1500 1500 d) the changeset specified with -r
1501 1501 e) the tipmost head specified with -b
1502 1502 f) the tipmost head specified with the url#branch source syntax
1503 1503 g) the revision marked with the '@' bookmark, if present
1504 1504 h) the tipmost head of the default branch
1505 1505 i) tip
1506 1506
1507 1507 When cloning from servers that support it, Mercurial may fetch
1508 1508 pre-generated data from a server-advertised URL. When this is done,
1509 1509 hooks operating on incoming changesets and changegroups may fire twice,
1510 1510 once for the bundle fetched from the URL and another for any additional
1511 1511 data not fetched from this URL. In addition, if an error occurs, the
1512 1512 repository may be rolled back to a partial clone. This behavior may
1513 1513 change in future releases. See :hg:`help -e clonebundles` for more.
1514 1514
1515 1515 Examples:
1516 1516
1517 1517 - clone a remote repository to a new directory named hg/::
1518 1518
1519 1519 hg clone https://www.mercurial-scm.org/repo/hg/
1520 1520
1521 1521 - create a lightweight local clone::
1522 1522
1523 1523 hg clone project/ project-feature/
1524 1524
1525 1525 - clone from an absolute path on an ssh server (note double-slash)::
1526 1526
1527 1527 hg clone ssh://user@server//home/projects/alpha/
1528 1528
1529 1529 - do a high-speed clone over a LAN while checking out a
1530 1530 specified version::
1531 1531
1532 1532 hg clone --uncompressed http://server/repo -u 1.5
1533 1533
1534 1534 - create a repository without changesets after a particular revision::
1535 1535
1536 1536 hg clone -r 04e544 experimental/ good/
1537 1537
1538 1538 - clone (and track) a particular named branch::
1539 1539
1540 1540 hg clone https://www.mercurial-scm.org/repo/hg/#stable
1541 1541
1542 1542 See :hg:`help urls` for details on specifying URLs.
1543 1543
1544 1544 Returns 0 on success.
1545 1545 """
1546 1546 if opts.get('noupdate') and opts.get('updaterev'):
1547 1547 raise error.Abort(_("cannot specify both --noupdate and --updaterev"))
1548 1548
1549 1549 r = hg.clone(ui, opts, source, dest,
1550 1550 pull=opts.get('pull'),
1551 1551 stream=opts.get('uncompressed'),
1552 1552 rev=opts.get('rev'),
1553 1553 update=opts.get('updaterev') or not opts.get('noupdate'),
1554 1554 branch=opts.get('branch'),
1555 1555 shareopts=opts.get('shareopts'))
1556 1556
1557 1557 return r is None
1558 1558
1559 1559 @command('^commit|ci',
1560 1560 [('A', 'addremove', None,
1561 1561 _('mark new/missing files as added/removed before committing')),
1562 1562 ('', 'close-branch', None,
1563 1563 _('mark a branch head as closed')),
1564 1564 ('', 'amend', None, _('amend the parent of the working directory')),
1565 1565 ('s', 'secret', None, _('use the secret phase for committing')),
1566 1566 ('e', 'edit', None, _('invoke editor on commit messages')),
1567 1567 ('i', 'interactive', None, _('use interactive mode')),
1568 1568 ] + walkopts + commitopts + commitopts2 + subrepoopts,
1569 1569 _('[OPTION]... [FILE]...'),
1570 1570 inferrepo=True)
1571 1571 def commit(ui, repo, *pats, **opts):
1572 1572 """commit the specified files or all outstanding changes
1573 1573
1574 1574 Commit changes to the given files into the repository. Unlike a
1575 1575 centralized SCM, this operation is a local operation. See
1576 1576 :hg:`push` for a way to actively distribute your changes.
1577 1577
1578 1578 If a list of files is omitted, all changes reported by :hg:`status`
1579 1579 will be committed.
1580 1580
1581 1581 If you are committing the result of a merge, do not provide any
1582 1582 filenames or -I/-X filters.
1583 1583
1584 1584 If no commit message is specified, Mercurial starts your
1585 1585 configured editor where you can enter a message. In case your
1586 1586 commit fails, you will find a backup of your message in
1587 1587 ``.hg/last-message.txt``.
1588 1588
1589 1589 The --close-branch flag can be used to mark the current branch
1590 1590 head closed. When all heads of a branch are closed, the branch
1591 1591 will be considered closed and no longer listed.
1592 1592
1593 1593 The --amend flag can be used to amend the parent of the
1594 1594 working directory with a new commit that contains the changes
1595 1595 in the parent in addition to those currently reported by :hg:`status`,
1596 1596 if there are any. The old commit is stored in a backup bundle in
1597 1597 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
1598 1598 on how to restore it).
1599 1599
1600 1600 Message, user and date are taken from the amended commit unless
1601 1601 specified. When a message isn't specified on the command line,
1602 1602 the editor will open with the message of the amended commit.
1603 1603
1604 1604 It is not possible to amend public changesets (see :hg:`help phases`)
1605 1605 or changesets that have children.
1606 1606
1607 1607 See :hg:`help dates` for a list of formats valid for -d/--date.
1608 1608
1609 1609 Returns 0 on success, 1 if nothing changed.
1610 1610
1611 1611 .. container:: verbose
1612 1612
1613 1613 Examples:
1614 1614
1615 1615 - commit all files ending in .py::
1616 1616
1617 1617 hg commit --include "set:**.py"
1618 1618
1619 1619 - commit all non-binary files::
1620 1620
1621 1621 hg commit --exclude "set:binary()"
1622 1622
1623 1623 - amend the current commit and set the date to now::
1624 1624
1625 1625 hg commit --amend --date now
1626 1626 """
1627 1627 wlock = lock = None
1628 1628 try:
1629 1629 wlock = repo.wlock()
1630 1630 lock = repo.lock()
1631 1631 return _docommit(ui, repo, *pats, **opts)
1632 1632 finally:
1633 1633 release(lock, wlock)
1634 1634
1635 1635 def _docommit(ui, repo, *pats, **opts):
1636 1636 if opts.get('interactive'):
1637 1637 opts.pop('interactive')
1638 1638 ret = cmdutil.dorecord(ui, repo, commit, None, False,
1639 1639 cmdutil.recordfilter, *pats, **opts)
1640 1640 # ret can be 0 (no changes to record) or the value returned by
1641 1641 # commit(), 1 if nothing changed or None on success.
1642 1642 return 1 if ret == 0 else ret
1643 1643
1644 1644 if opts.get('subrepos'):
1645 1645 if opts.get('amend'):
1646 1646 raise error.Abort(_('cannot amend with --subrepos'))
1647 1647 # Let --subrepos on the command line override config setting.
1648 1648 ui.setconfig('ui', 'commitsubrepos', True, 'commit')
1649 1649
1650 1650 cmdutil.checkunfinished(repo, commit=True)
1651 1651
1652 1652 branch = repo[None].branch()
1653 1653 bheads = repo.branchheads(branch)
1654 1654
1655 1655 extra = {}
1656 1656 if opts.get('close_branch'):
1657 1657 extra['close'] = 1
1658 1658
1659 1659 if not bheads:
1660 1660 raise error.Abort(_('can only close branch heads'))
1661 1661 elif opts.get('amend'):
1662 1662 if repo[None].parents()[0].p1().branch() != branch and \
1663 1663 repo[None].parents()[0].p2().branch() != branch:
1664 1664 raise error.Abort(_('can only close branch heads'))
1665 1665
1666 1666 if opts.get('amend'):
1667 1667 if ui.configbool('ui', 'commitsubrepos'):
1668 1668 raise error.Abort(_('cannot amend with ui.commitsubrepos enabled'))
1669 1669
1670 1670 old = repo['.']
1671 1671 if not old.mutable():
1672 1672 raise error.Abort(_('cannot amend public changesets'))
1673 1673 if len(repo[None].parents()) > 1:
1674 1674 raise error.Abort(_('cannot amend while merging'))
1675 1675 allowunstable = obsolete.isenabled(repo, obsolete.allowunstableopt)
1676 1676 if not allowunstable and old.children():
1677 1677 raise error.Abort(_('cannot amend changeset with children'))
1678 1678
1679 1679 # Currently histedit gets confused if an amend happens while histedit
1680 1680 # is in progress. Since we have a checkunfinished command, we are
1681 1681 # temporarily honoring it.
1682 1682 #
1683 1683 # Note: eventually this guard will be removed. Please do not expect
1684 1684 # this behavior to remain.
1685 1685 if not obsolete.isenabled(repo, obsolete.createmarkersopt):
1686 1686 cmdutil.checkunfinished(repo)
1687 1687
1688 1688 # commitfunc is used only for temporary amend commit by cmdutil.amend
1689 1689 def commitfunc(ui, repo, message, match, opts):
1690 1690 return repo.commit(message,
1691 1691 opts.get('user') or old.user(),
1692 1692 opts.get('date') or old.date(),
1693 1693 match,
1694 1694 extra=extra)
1695 1695
1696 1696 node = cmdutil.amend(ui, repo, commitfunc, old, extra, pats, opts)
1697 1697 if node == old.node():
1698 1698 ui.status(_("nothing changed\n"))
1699 1699 return 1
1700 1700 else:
1701 1701 def commitfunc(ui, repo, message, match, opts):
1702 1702 backup = ui.backupconfig('phases', 'new-commit')
1703 1703 baseui = repo.baseui
1704 1704 basebackup = baseui.backupconfig('phases', 'new-commit')
1705 1705 try:
1706 1706 if opts.get('secret'):
1707 1707 ui.setconfig('phases', 'new-commit', 'secret', 'commit')
1708 1708 # Propagate to subrepos
1709 1709 baseui.setconfig('phases', 'new-commit', 'secret', 'commit')
1710 1710
1711 1711 editform = cmdutil.mergeeditform(repo[None], 'commit.normal')
1712 1712 editor = cmdutil.getcommiteditor(editform=editform, **opts)
1713 1713 return repo.commit(message, opts.get('user'), opts.get('date'),
1714 1714 match,
1715 1715 editor=editor,
1716 1716 extra=extra)
1717 1717 finally:
1718 1718 ui.restoreconfig(backup)
1719 1719 repo.baseui.restoreconfig(basebackup)
1720 1720
1721 1721
1722 1722 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1723 1723
1724 1724 if not node:
1725 1725 stat = cmdutil.postcommitstatus(repo, pats, opts)
1726 1726 if stat[3]:
1727 1727 ui.status(_("nothing changed (%d missing files, see "
1728 1728 "'hg status')\n") % len(stat[3]))
1729 1729 else:
1730 1730 ui.status(_("nothing changed\n"))
1731 1731 return 1
1732 1732
1733 1733 cmdutil.commitstatus(repo, node, branch, bheads, opts)
1734 1734
1735 1735 @command('config|showconfig|debugconfig',
1736 1736 [('u', 'untrusted', None, _('show untrusted configuration options')),
1737 1737 ('e', 'edit', None, _('edit user config')),
1738 1738 ('l', 'local', None, _('edit repository config')),
1739 1739 ('g', 'global', None, _('edit global config'))] + formatteropts,
1740 1740 _('[-u] [NAME]...'),
1741 1741 optionalrepo=True)
1742 1742 def config(ui, repo, *values, **opts):
1743 1743 """show combined config settings from all hgrc files
1744 1744
1745 1745 With no arguments, print names and values of all config items.
1746 1746
1747 1747 With one argument of the form section.name, print just the value
1748 1748 of that config item.
1749 1749
1750 1750 With multiple arguments, print names and values of all config
1751 1751 items with matching section names.
1752 1752
1753 1753 With --edit, start an editor on the user-level config file. With
1754 1754 --global, edit the system-wide config file. With --local, edit the
1755 1755 repository-level config file.
1756 1756
1757 1757 With --debug, the source (filename and line number) is printed
1758 1758 for each config item.
1759 1759
1760 1760 See :hg:`help config` for more information about config files.
1761 1761
1762 1762 Returns 0 on success, 1 if NAME does not exist.
1763 1763
1764 1764 """
1765 1765
1766 1766 if opts.get('edit') or opts.get('local') or opts.get('global'):
1767 1767 if opts.get('local') and opts.get('global'):
1768 1768 raise error.Abort(_("can't use --local and --global together"))
1769 1769
1770 1770 if opts.get('local'):
1771 1771 if not repo:
1772 1772 raise error.Abort(_("can't use --local outside a repository"))
1773 1773 paths = [repo.join('hgrc')]
1774 1774 elif opts.get('global'):
1775 1775 paths = scmutil.systemrcpath()
1776 1776 else:
1777 1777 paths = scmutil.userrcpath()
1778 1778
1779 1779 for f in paths:
1780 1780 if os.path.exists(f):
1781 1781 break
1782 1782 else:
1783 1783 if opts.get('global'):
1784 1784 samplehgrc = uimod.samplehgrcs['global']
1785 1785 elif opts.get('local'):
1786 1786 samplehgrc = uimod.samplehgrcs['local']
1787 1787 else:
1788 1788 samplehgrc = uimod.samplehgrcs['user']
1789 1789
1790 1790 f = paths[0]
1791 1791 fp = open(f, "w")
1792 1792 fp.write(samplehgrc)
1793 1793 fp.close()
1794 1794
1795 1795 editor = ui.geteditor()
1796 1796 ui.system("%s \"%s\"" % (editor, f),
1797 1797 onerr=error.Abort, errprefix=_("edit failed"))
1798 1798 return
1799 1799 ui.pager('config')
1800 1800 fm = ui.formatter('config', opts)
1801 1801 for f in scmutil.rcpath():
1802 1802 ui.debug('read config from: %s\n' % f)
1803 1803 untrusted = bool(opts.get('untrusted'))
1804 1804 if values:
1805 1805 sections = [v for v in values if '.' not in v]
1806 1806 items = [v for v in values if '.' in v]
1807 1807 if len(items) > 1 or items and sections:
1808 1808 raise error.Abort(_('only one config item permitted'))
1809 1809 matched = False
1810 1810 for section, name, value in ui.walkconfig(untrusted=untrusted):
1811 1811 source = ui.configsource(section, name, untrusted)
1812 1812 value = str(value)
1813 1813 if fm.isplain():
1814 1814 source = source or 'none'
1815 1815 value = value.replace('\n', '\\n')
1816 1816 entryname = section + '.' + name
1817 1817 if values:
1818 1818 for v in values:
1819 1819 if v == section:
1820 1820 fm.startitem()
1821 1821 fm.condwrite(ui.debugflag, 'source', '%s: ', source)
1822 1822 fm.write('name value', '%s=%s\n', entryname, value)
1823 1823 matched = True
1824 1824 elif v == entryname:
1825 1825 fm.startitem()
1826 1826 fm.condwrite(ui.debugflag, 'source', '%s: ', source)
1827 1827 fm.write('value', '%s\n', value)
1828 1828 fm.data(name=entryname)
1829 1829 matched = True
1830 1830 else:
1831 1831 fm.startitem()
1832 1832 fm.condwrite(ui.debugflag, 'source', '%s: ', source)
1833 1833 fm.write('name value', '%s=%s\n', entryname, value)
1834 1834 matched = True
1835 1835 fm.end()
1836 1836 if matched:
1837 1837 return 0
1838 1838 return 1
1839 1839
1840 1840 @command('copy|cp',
1841 1841 [('A', 'after', None, _('record a copy that has already occurred')),
1842 1842 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1843 1843 ] + walkopts + dryrunopts,
1844 1844 _('[OPTION]... [SOURCE]... DEST'))
1845 1845 def copy(ui, repo, *pats, **opts):
1846 1846 """mark files as copied for the next commit
1847 1847
1848 1848 Mark dest as having copies of source files. If dest is a
1849 1849 directory, copies are put in that directory. If dest is a file,
1850 1850 the source must be a single file.
1851 1851
1852 1852 By default, this command copies the contents of files as they
1853 1853 exist in the working directory. If invoked with -A/--after, the
1854 1854 operation is recorded, but no copying is performed.
1855 1855
1856 1856 This command takes effect with the next commit. To undo a copy
1857 1857 before that, see :hg:`revert`.
1858 1858
1859 1859 Returns 0 on success, 1 if errors are encountered.
1860 1860 """
1861 1861 with repo.wlock(False):
1862 1862 return cmdutil.copy(ui, repo, pats, opts)
1863 1863
1864 1864 @command('^diff',
1865 1865 [('r', 'rev', [], _('revision'), _('REV')),
1866 1866 ('c', 'change', '', _('change made by revision'), _('REV'))
1867 1867 ] + diffopts + diffopts2 + walkopts + subrepoopts,
1868 1868 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'),
1869 1869 inferrepo=True)
1870 1870 def diff(ui, repo, *pats, **opts):
1871 1871 """diff repository (or selected files)
1872 1872
1873 1873 Show differences between revisions for the specified files.
1874 1874
1875 1875 Differences between files are shown using the unified diff format.
1876 1876
1877 1877 .. note::
1878 1878
1879 1879 :hg:`diff` may generate unexpected results for merges, as it will
1880 1880 default to comparing against the working directory's first
1881 1881 parent changeset if no revisions are specified.
1882 1882
1883 1883 When two revision arguments are given, then changes are shown
1884 1884 between those revisions. If only one revision is specified then
1885 1885 that revision is compared to the working directory, and, when no
1886 1886 revisions are specified, the working directory files are compared
1887 1887 to its first parent.
1888 1888
1889 1889 Alternatively you can specify -c/--change with a revision to see
1890 1890 the changes in that changeset relative to its first parent.
1891 1891
1892 1892 Without the -a/--text option, diff will avoid generating diffs of
1893 1893 files it detects as binary. With -a, diff will generate a diff
1894 1894 anyway, probably with undesirable results.
1895 1895
1896 1896 Use the -g/--git option to generate diffs in the git extended diff
1897 1897 format. For more information, read :hg:`help diffs`.
1898 1898
1899 1899 .. container:: verbose
1900 1900
1901 1901 Examples:
1902 1902
1903 1903 - compare a file in the current working directory to its parent::
1904 1904
1905 1905 hg diff foo.c
1906 1906
1907 1907 - compare two historical versions of a directory, with rename info::
1908 1908
1909 1909 hg diff --git -r 1.0:1.2 lib/
1910 1910
1911 1911 - get change stats relative to the last change on some date::
1912 1912
1913 1913 hg diff --stat -r "date('may 2')"
1914 1914
1915 1915 - diff all newly-added files that contain a keyword::
1916 1916
1917 1917 hg diff "set:added() and grep(GNU)"
1918 1918
1919 1919 - compare a revision and its parents::
1920 1920
1921 1921 hg diff -c 9353 # compare against first parent
1922 1922 hg diff -r 9353^:9353 # same using revset syntax
1923 1923 hg diff -r 9353^2:9353 # compare against the second parent
1924 1924
1925 1925 Returns 0 on success.
1926 1926 """
1927 1927
1928 1928 revs = opts.get('rev')
1929 1929 change = opts.get('change')
1930 1930 stat = opts.get('stat')
1931 1931 reverse = opts.get('reverse')
1932 1932
1933 1933 if revs and change:
1934 1934 msg = _('cannot specify --rev and --change at the same time')
1935 1935 raise error.Abort(msg)
1936 1936 elif change:
1937 1937 node2 = scmutil.revsingle(repo, change, None).node()
1938 1938 node1 = repo[node2].p1().node()
1939 1939 else:
1940 1940 node1, node2 = scmutil.revpair(repo, revs)
1941 1941
1942 1942 if reverse:
1943 1943 node1, node2 = node2, node1
1944 1944
1945 1945 diffopts = patch.diffallopts(ui, opts)
1946 1946 m = scmutil.match(repo[node2], pats, opts)
1947 1947 ui.pager('diff')
1948 1948 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
1949 1949 listsubrepos=opts.get('subrepos'),
1950 1950 root=opts.get('root'))
1951 1951
1952 1952 @command('^export',
1953 1953 [('o', 'output', '',
1954 1954 _('print output to file with formatted name'), _('FORMAT')),
1955 1955 ('', 'switch-parent', None, _('diff against the second parent')),
1956 1956 ('r', 'rev', [], _('revisions to export'), _('REV')),
1957 1957 ] + diffopts,
1958 1958 _('[OPTION]... [-o OUTFILESPEC] [-r] [REV]...'))
1959 1959 def export(ui, repo, *changesets, **opts):
1960 1960 """dump the header and diffs for one or more changesets
1961 1961
1962 1962 Print the changeset header and diffs for one or more revisions.
1963 1963 If no revision is given, the parent of the working directory is used.
1964 1964
1965 1965 The information shown in the changeset header is: author, date,
1966 1966 branch name (if non-default), changeset hash, parent(s) and commit
1967 1967 comment.
1968 1968
1969 1969 .. note::
1970 1970
1971 1971 :hg:`export` may generate unexpected diff output for merge
1972 1972 changesets, as it will compare the merge changeset against its
1973 1973 first parent only.
1974 1974
1975 1975 Output may be to a file, in which case the name of the file is
1976 1976 given using a format string. The formatting rules are as follows:
1977 1977
1978 1978 :``%%``: literal "%" character
1979 1979 :``%H``: changeset hash (40 hexadecimal digits)
1980 1980 :``%N``: number of patches being generated
1981 1981 :``%R``: changeset revision number
1982 1982 :``%b``: basename of the exporting repository
1983 1983 :``%h``: short-form changeset hash (12 hexadecimal digits)
1984 1984 :``%m``: first line of the commit message (only alphanumeric characters)
1985 1985 :``%n``: zero-padded sequence number, starting at 1
1986 1986 :``%r``: zero-padded changeset revision number
1987 1987
1988 1988 Without the -a/--text option, export will avoid generating diffs
1989 1989 of files it detects as binary. With -a, export will generate a
1990 1990 diff anyway, probably with undesirable results.
1991 1991
1992 1992 Use the -g/--git option to generate diffs in the git extended diff
1993 1993 format. See :hg:`help diffs` for more information.
1994 1994
1995 1995 With the --switch-parent option, the diff will be against the
1996 1996 second parent. It can be useful to review a merge.
1997 1997
1998 1998 .. container:: verbose
1999 1999
2000 2000 Examples:
2001 2001
2002 2002 - use export and import to transplant a bugfix to the current
2003 2003 branch::
2004 2004
2005 2005 hg export -r 9353 | hg import -
2006 2006
2007 2007 - export all the changesets between two revisions to a file with
2008 2008 rename information::
2009 2009
2010 2010 hg export --git -r 123:150 > changes.txt
2011 2011
2012 2012 - split outgoing changes into a series of patches with
2013 2013 descriptive names::
2014 2014
2015 2015 hg export -r "outgoing()" -o "%n-%m.patch"
2016 2016
2017 2017 Returns 0 on success.
2018 2018 """
2019 2019 changesets += tuple(opts.get('rev', []))
2020 2020 if not changesets:
2021 2021 changesets = ['.']
2022 2022 revs = scmutil.revrange(repo, changesets)
2023 2023 if not revs:
2024 2024 raise error.Abort(_("export requires at least one changeset"))
2025 2025 if len(revs) > 1:
2026 2026 ui.note(_('exporting patches:\n'))
2027 2027 else:
2028 2028 ui.note(_('exporting patch:\n'))
2029 2029 ui.pager('export')
2030 2030 cmdutil.export(repo, revs, template=opts.get('output'),
2031 2031 switch_parent=opts.get('switch_parent'),
2032 2032 opts=patch.diffallopts(ui, opts))
2033 2033
2034 2034 @command('files',
2035 2035 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
2036 2036 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
2037 2037 ] + walkopts + formatteropts + subrepoopts,
2038 2038 _('[OPTION]... [FILE]...'))
2039 2039 def files(ui, repo, *pats, **opts):
2040 2040 """list tracked files
2041 2041
2042 2042 Print files under Mercurial control in the working directory or
2043 2043 specified revision for given files (excluding removed files).
2044 2044 Files can be specified as filenames or filesets.
2045 2045
2046 2046 If no files are given to match, this command prints the names
2047 2047 of all files under Mercurial control.
2048 2048
2049 2049 .. container:: verbose
2050 2050
2051 2051 Examples:
2052 2052
2053 2053 - list all files under the current directory::
2054 2054
2055 2055 hg files .
2056 2056
2057 2057 - shows sizes and flags for current revision::
2058 2058
2059 2059 hg files -vr .
2060 2060
2061 2061 - list all files named README::
2062 2062
2063 2063 hg files -I "**/README"
2064 2064
2065 2065 - list all binary files::
2066 2066
2067 2067 hg files "set:binary()"
2068 2068
2069 2069 - find files containing a regular expression::
2070 2070
2071 2071 hg files "set:grep('bob')"
2072 2072
2073 2073 - search tracked file contents with xargs and grep::
2074 2074
2075 2075 hg files -0 | xargs -0 grep foo
2076 2076
2077 2077 See :hg:`help patterns` and :hg:`help filesets` for more information
2078 2078 on specifying file patterns.
2079 2079
2080 2080 Returns 0 if a match is found, 1 otherwise.
2081 2081
2082 2082 """
2083 2083 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
2084 2084
2085 2085 end = '\n'
2086 2086 if opts.get('print0'):
2087 2087 end = '\0'
2088 2088 fmt = '%s' + end
2089 2089
2090 2090 m = scmutil.match(ctx, pats, opts)
2091 2091 ui.pager('files')
2092 2092 with ui.formatter('files', opts) as fm:
2093 2093 return cmdutil.files(ui, ctx, m, fm, fmt, opts.get('subrepos'))
2094 2094
2095 2095 @command('^forget', walkopts, _('[OPTION]... FILE...'), inferrepo=True)
2096 2096 def forget(ui, repo, *pats, **opts):
2097 2097 """forget the specified files on the next commit
2098 2098
2099 2099 Mark the specified files so they will no longer be tracked
2100 2100 after the next commit.
2101 2101
2102 2102 This only removes files from the current branch, not from the
2103 2103 entire project history, and it does not delete them from the
2104 2104 working directory.
2105 2105
2106 2106 To delete the file from the working directory, see :hg:`remove`.
2107 2107
2108 2108 To undo a forget before the next commit, see :hg:`add`.
2109 2109
2110 2110 .. container:: verbose
2111 2111
2112 2112 Examples:
2113 2113
2114 2114 - forget newly-added binary files::
2115 2115
2116 2116 hg forget "set:added() and binary()"
2117 2117
2118 2118 - forget files that would be excluded by .hgignore::
2119 2119
2120 2120 hg forget "set:hgignore()"
2121 2121
2122 2122 Returns 0 on success.
2123 2123 """
2124 2124
2125 2125 if not pats:
2126 2126 raise error.Abort(_('no files specified'))
2127 2127
2128 2128 m = scmutil.match(repo[None], pats, opts)
2129 2129 rejected = cmdutil.forget(ui, repo, m, prefix="", explicitonly=False)[0]
2130 2130 return rejected and 1 or 0
2131 2131
2132 2132 @command(
2133 2133 'graft',
2134 2134 [('r', 'rev', [], _('revisions to graft'), _('REV')),
2135 2135 ('c', 'continue', False, _('resume interrupted graft')),
2136 2136 ('e', 'edit', False, _('invoke editor on commit messages')),
2137 2137 ('', 'log', None, _('append graft info to log message')),
2138 2138 ('f', 'force', False, _('force graft')),
2139 2139 ('D', 'currentdate', False,
2140 2140 _('record the current date as commit date')),
2141 2141 ('U', 'currentuser', False,
2142 2142 _('record the current user as committer'), _('DATE'))]
2143 2143 + commitopts2 + mergetoolopts + dryrunopts,
2144 2144 _('[OPTION]... [-r REV]... REV...'))
2145 2145 def graft(ui, repo, *revs, **opts):
2146 2146 '''copy changes from other branches onto the current branch
2147 2147
2148 2148 This command uses Mercurial's merge logic to copy individual
2149 2149 changes from other branches without merging branches in the
2150 2150 history graph. This is sometimes known as 'backporting' or
2151 2151 'cherry-picking'. By default, graft will copy user, date, and
2152 2152 description from the source changesets.
2153 2153
2154 2154 Changesets that are ancestors of the current revision, that have
2155 2155 already been grafted, or that are merges will be skipped.
2156 2156
2157 2157 If --log is specified, log messages will have a comment appended
2158 2158 of the form::
2159 2159
2160 2160 (grafted from CHANGESETHASH)
2161 2161
2162 2162 If --force is specified, revisions will be grafted even if they
2163 2163 are already ancestors of or have been grafted to the destination.
2164 2164 This is useful when the revisions have since been backed out.
2165 2165
2166 2166 If a graft merge results in conflicts, the graft process is
2167 2167 interrupted so that the current merge can be manually resolved.
2168 2168 Once all conflicts are addressed, the graft process can be
2169 2169 continued with the -c/--continue option.
2170 2170
2171 2171 .. note::
2172 2172
2173 2173 The -c/--continue option does not reapply earlier options, except
2174 2174 for --force.
2175 2175
2176 2176 .. container:: verbose
2177 2177
2178 2178 Examples:
2179 2179
2180 2180 - copy a single change to the stable branch and edit its description::
2181 2181
2182 2182 hg update stable
2183 2183 hg graft --edit 9393
2184 2184
2185 2185 - graft a range of changesets with one exception, updating dates::
2186 2186
2187 2187 hg graft -D "2085::2093 and not 2091"
2188 2188
2189 2189 - continue a graft after resolving conflicts::
2190 2190
2191 2191 hg graft -c
2192 2192
2193 2193 - show the source of a grafted changeset::
2194 2194
2195 2195 hg log --debug -r .
2196 2196
2197 2197 - show revisions sorted by date::
2198 2198
2199 2199 hg log -r "sort(all(), date)"
2200 2200
2201 2201 See :hg:`help revisions` for more about specifying revisions.
2202 2202
2203 2203 Returns 0 on successful completion.
2204 2204 '''
2205 2205 with repo.wlock():
2206 2206 return _dograft(ui, repo, *revs, **opts)
2207 2207
2208 2208 def _dograft(ui, repo, *revs, **opts):
2209 2209 if revs and opts.get('rev'):
2210 2210 ui.warn(_('warning: inconsistent use of --rev might give unexpected '
2211 2211 'revision ordering!\n'))
2212 2212
2213 2213 revs = list(revs)
2214 2214 revs.extend(opts.get('rev'))
2215 2215
2216 2216 if not opts.get('user') and opts.get('currentuser'):
2217 2217 opts['user'] = ui.username()
2218 2218 if not opts.get('date') and opts.get('currentdate'):
2219 2219 opts['date'] = "%d %d" % util.makedate()
2220 2220
2221 2221 editor = cmdutil.getcommiteditor(editform='graft', **opts)
2222 2222
2223 2223 cont = False
2224 2224 if opts.get('continue'):
2225 2225 cont = True
2226 2226 if revs:
2227 2227 raise error.Abort(_("can't specify --continue and revisions"))
2228 2228 # read in unfinished revisions
2229 2229 try:
2230 2230 nodes = repo.vfs.read('graftstate').splitlines()
2231 2231 revs = [repo[node].rev() for node in nodes]
2232 2232 except IOError as inst:
2233 2233 if inst.errno != errno.ENOENT:
2234 2234 raise
2235 2235 cmdutil.wrongtooltocontinue(repo, _('graft'))
2236 2236 else:
2237 2237 cmdutil.checkunfinished(repo)
2238 2238 cmdutil.bailifchanged(repo)
2239 2239 if not revs:
2240 2240 raise error.Abort(_('no revisions specified'))
2241 2241 revs = scmutil.revrange(repo, revs)
2242 2242
2243 2243 skipped = set()
2244 2244 # check for merges
2245 2245 for rev in repo.revs('%ld and merge()', revs):
2246 2246 ui.warn(_('skipping ungraftable merge revision %s\n') % rev)
2247 2247 skipped.add(rev)
2248 2248 revs = [r for r in revs if r not in skipped]
2249 2249 if not revs:
2250 2250 return -1
2251 2251
2252 2252 # Don't check in the --continue case, in effect retaining --force across
2253 2253 # --continues. That's because without --force, any revisions we decided to
2254 2254 # skip would have been filtered out here, so they wouldn't have made their
2255 2255 # way to the graftstate. With --force, any revisions we would have otherwise
2256 2256 # skipped would not have been filtered out, and if they hadn't been applied
2257 2257 # already, they'd have been in the graftstate.
2258 2258 if not (cont or opts.get('force')):
2259 2259 # check for ancestors of dest branch
2260 2260 crev = repo['.'].rev()
2261 2261 ancestors = repo.changelog.ancestors([crev], inclusive=True)
2262 2262 # XXX make this lazy in the future
2263 2263 # don't mutate while iterating, create a copy
2264 2264 for rev in list(revs):
2265 2265 if rev in ancestors:
2266 2266 ui.warn(_('skipping ancestor revision %d:%s\n') %
2267 2267 (rev, repo[rev]))
2268 2268 # XXX remove on list is slow
2269 2269 revs.remove(rev)
2270 2270 if not revs:
2271 2271 return -1
2272 2272
2273 2273 # analyze revs for earlier grafts
2274 2274 ids = {}
2275 2275 for ctx in repo.set("%ld", revs):
2276 2276 ids[ctx.hex()] = ctx.rev()
2277 2277 n = ctx.extra().get('source')
2278 2278 if n:
2279 2279 ids[n] = ctx.rev()
2280 2280
2281 2281 # check ancestors for earlier grafts
2282 2282 ui.debug('scanning for duplicate grafts\n')
2283 2283
2284 2284 for rev in repo.changelog.findmissingrevs(revs, [crev]):
2285 2285 ctx = repo[rev]
2286 2286 n = ctx.extra().get('source')
2287 2287 if n in ids:
2288 2288 try:
2289 2289 r = repo[n].rev()
2290 2290 except error.RepoLookupError:
2291 2291 r = None
2292 2292 if r in revs:
2293 2293 ui.warn(_('skipping revision %d:%s '
2294 2294 '(already grafted to %d:%s)\n')
2295 2295 % (r, repo[r], rev, ctx))
2296 2296 revs.remove(r)
2297 2297 elif ids[n] in revs:
2298 2298 if r is None:
2299 2299 ui.warn(_('skipping already grafted revision %d:%s '
2300 2300 '(%d:%s also has unknown origin %s)\n')
2301 2301 % (ids[n], repo[ids[n]], rev, ctx, n[:12]))
2302 2302 else:
2303 2303 ui.warn(_('skipping already grafted revision %d:%s '
2304 2304 '(%d:%s also has origin %d:%s)\n')
2305 2305 % (ids[n], repo[ids[n]], rev, ctx, r, n[:12]))
2306 2306 revs.remove(ids[n])
2307 2307 elif ctx.hex() in ids:
2308 2308 r = ids[ctx.hex()]
2309 2309 ui.warn(_('skipping already grafted revision %d:%s '
2310 2310 '(was grafted from %d:%s)\n') %
2311 2311 (r, repo[r], rev, ctx))
2312 2312 revs.remove(r)
2313 2313 if not revs:
2314 2314 return -1
2315 2315
2316 2316 for pos, ctx in enumerate(repo.set("%ld", revs)):
2317 2317 desc = '%d:%s "%s"' % (ctx.rev(), ctx,
2318 2318 ctx.description().split('\n', 1)[0])
2319 2319 names = repo.nodetags(ctx.node()) + repo.nodebookmarks(ctx.node())
2320 2320 if names:
2321 2321 desc += ' (%s)' % ' '.join(names)
2322 2322 ui.status(_('grafting %s\n') % desc)
2323 2323 if opts.get('dry_run'):
2324 2324 continue
2325 2325
2326 2326 source = ctx.extra().get('source')
2327 2327 extra = {}
2328 2328 if source:
2329 2329 extra['source'] = source
2330 2330 extra['intermediate-source'] = ctx.hex()
2331 2331 else:
2332 2332 extra['source'] = ctx.hex()
2333 2333 user = ctx.user()
2334 2334 if opts.get('user'):
2335 2335 user = opts['user']
2336 2336 date = ctx.date()
2337 2337 if opts.get('date'):
2338 2338 date = opts['date']
2339 2339 message = ctx.description()
2340 2340 if opts.get('log'):
2341 2341 message += '\n(grafted from %s)' % ctx.hex()
2342 2342
2343 2343 # we don't merge the first commit when continuing
2344 2344 if not cont:
2345 2345 # perform the graft merge with p1(rev) as 'ancestor'
2346 2346 try:
2347 2347 # ui.forcemerge is an internal variable, do not document
2348 2348 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
2349 2349 'graft')
2350 2350 stats = mergemod.graft(repo, ctx, ctx.p1(),
2351 2351 ['local', 'graft'])
2352 2352 finally:
2353 2353 repo.ui.setconfig('ui', 'forcemerge', '', 'graft')
2354 2354 # report any conflicts
2355 2355 if stats and stats[3] > 0:
2356 2356 # write out state for --continue
2357 2357 nodelines = [repo[rev].hex() + "\n" for rev in revs[pos:]]
2358 2358 repo.vfs.write('graftstate', ''.join(nodelines))
2359 2359 extra = ''
2360 2360 if opts.get('user'):
2361 2361 extra += ' --user %s' % util.shellquote(opts['user'])
2362 2362 if opts.get('date'):
2363 2363 extra += ' --date %s' % util.shellquote(opts['date'])
2364 2364 if opts.get('log'):
2365 2365 extra += ' --log'
2366 2366 hint=_("use 'hg resolve' and 'hg graft --continue%s'") % extra
2367 2367 raise error.Abort(
2368 2368 _("unresolved conflicts, can't continue"),
2369 2369 hint=hint)
2370 2370 else:
2371 2371 cont = False
2372 2372
2373 2373 # commit
2374 2374 node = repo.commit(text=message, user=user,
2375 2375 date=date, extra=extra, editor=editor)
2376 2376 if node is None:
2377 2377 ui.warn(
2378 2378 _('note: graft of %d:%s created no changes to commit\n') %
2379 2379 (ctx.rev(), ctx))
2380 2380
2381 2381 # remove state when we complete successfully
2382 2382 if not opts.get('dry_run'):
2383 2383 util.unlinkpath(repo.join('graftstate'), ignoremissing=True)
2384 2384
2385 2385 return 0
2386 2386
2387 2387 @command('grep',
2388 2388 [('0', 'print0', None, _('end fields with NUL')),
2389 2389 ('', 'all', None, _('print all revisions that match')),
2390 2390 ('a', 'text', None, _('treat all files as text')),
2391 2391 ('f', 'follow', None,
2392 2392 _('follow changeset history,'
2393 2393 ' or file history across copies and renames')),
2394 2394 ('i', 'ignore-case', None, _('ignore case when matching')),
2395 2395 ('l', 'files-with-matches', None,
2396 2396 _('print only filenames and revisions that match')),
2397 2397 ('n', 'line-number', None, _('print matching line numbers')),
2398 2398 ('r', 'rev', [],
2399 2399 _('only search files changed within revision range'), _('REV')),
2400 2400 ('u', 'user', None, _('list the author (long with -v)')),
2401 2401 ('d', 'date', None, _('list the date (short with -q)')),
2402 2402 ] + formatteropts + walkopts,
2403 2403 _('[OPTION]... PATTERN [FILE]...'),
2404 2404 inferrepo=True)
2405 2405 def grep(ui, repo, pattern, *pats, **opts):
2406 2406 """search revision history for a pattern in specified files
2407 2407
2408 2408 Search revision history for a regular expression in the specified
2409 2409 files or the entire project.
2410 2410
2411 2411 By default, grep prints the most recent revision number for each
2412 2412 file in which it finds a match. To get it to print every revision
2413 2413 that contains a change in match status ("-" for a match that becomes
2414 2414 a non-match, or "+" for a non-match that becomes a match), use the
2415 2415 --all flag.
2416 2416
2417 2417 PATTERN can be any Python (roughly Perl-compatible) regular
2418 2418 expression.
2419 2419
2420 2420 If no FILEs are specified (and -f/--follow isn't set), all files in
2421 2421 the repository are searched, including those that don't exist in the
2422 2422 current branch or have been deleted in a prior changeset.
2423 2423
2424 2424 Returns 0 if a match is found, 1 otherwise.
2425 2425 """
2426 2426 reflags = re.M
2427 2427 if opts.get('ignore_case'):
2428 2428 reflags |= re.I
2429 2429 try:
2430 2430 regexp = util.re.compile(pattern, reflags)
2431 2431 except re.error as inst:
2432 2432 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
2433 2433 return 1
2434 2434 sep, eol = ':', '\n'
2435 2435 if opts.get('print0'):
2436 2436 sep = eol = '\0'
2437 2437
2438 2438 getfile = util.lrucachefunc(repo.file)
2439 2439
2440 2440 def matchlines(body):
2441 2441 begin = 0
2442 2442 linenum = 0
2443 2443 while begin < len(body):
2444 2444 match = regexp.search(body, begin)
2445 2445 if not match:
2446 2446 break
2447 2447 mstart, mend = match.span()
2448 2448 linenum += body.count('\n', begin, mstart) + 1
2449 2449 lstart = body.rfind('\n', begin, mstart) + 1 or begin
2450 2450 begin = body.find('\n', mend) + 1 or len(body) + 1
2451 2451 lend = begin - 1
2452 2452 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
2453 2453
2454 2454 class linestate(object):
2455 2455 def __init__(self, line, linenum, colstart, colend):
2456 2456 self.line = line
2457 2457 self.linenum = linenum
2458 2458 self.colstart = colstart
2459 2459 self.colend = colend
2460 2460
2461 2461 def __hash__(self):
2462 2462 return hash((self.linenum, self.line))
2463 2463
2464 2464 def __eq__(self, other):
2465 2465 return self.line == other.line
2466 2466
2467 2467 def findpos(self):
2468 2468 """Iterate all (start, end) indices of matches"""
2469 2469 yield self.colstart, self.colend
2470 2470 p = self.colend
2471 2471 while p < len(self.line):
2472 2472 m = regexp.search(self.line, p)
2473 2473 if not m:
2474 2474 break
2475 2475 yield m.span()
2476 2476 p = m.end()
2477 2477
2478 2478 matches = {}
2479 2479 copies = {}
2480 2480 def grepbody(fn, rev, body):
2481 2481 matches[rev].setdefault(fn, [])
2482 2482 m = matches[rev][fn]
2483 2483 for lnum, cstart, cend, line in matchlines(body):
2484 2484 s = linestate(line, lnum, cstart, cend)
2485 2485 m.append(s)
2486 2486
2487 2487 def difflinestates(a, b):
2488 2488 sm = difflib.SequenceMatcher(None, a, b)
2489 2489 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2490 2490 if tag == 'insert':
2491 2491 for i in xrange(blo, bhi):
2492 2492 yield ('+', b[i])
2493 2493 elif tag == 'delete':
2494 2494 for i in xrange(alo, ahi):
2495 2495 yield ('-', a[i])
2496 2496 elif tag == 'replace':
2497 2497 for i in xrange(alo, ahi):
2498 2498 yield ('-', a[i])
2499 2499 for i in xrange(blo, bhi):
2500 2500 yield ('+', b[i])
2501 2501
2502 2502 def display(fm, fn, ctx, pstates, states):
2503 2503 rev = ctx.rev()
2504 2504 if fm.isplain():
2505 2505 formatuser = ui.shortuser
2506 2506 else:
2507 2507 formatuser = str
2508 2508 if ui.quiet:
2509 2509 datefmt = '%Y-%m-%d'
2510 2510 else:
2511 2511 datefmt = '%a %b %d %H:%M:%S %Y %1%2'
2512 2512 found = False
2513 2513 @util.cachefunc
2514 2514 def binary():
2515 2515 flog = getfile(fn)
2516 2516 return util.binary(flog.read(ctx.filenode(fn)))
2517 2517
2518 2518 fieldnamemap = {'filename': 'file', 'linenumber': 'line_number'}
2519 2519 if opts.get('all'):
2520 2520 iter = difflinestates(pstates, states)
2521 2521 else:
2522 2522 iter = [('', l) for l in states]
2523 2523 for change, l in iter:
2524 2524 fm.startitem()
2525 2525 fm.data(node=fm.hexfunc(ctx.node()))
2526 2526 cols = [
2527 2527 ('filename', fn, True),
2528 2528 ('rev', rev, True),
2529 2529 ('linenumber', l.linenum, opts.get('line_number')),
2530 2530 ]
2531 2531 if opts.get('all'):
2532 2532 cols.append(('change', change, True))
2533 2533 cols.extend([
2534 2534 ('user', formatuser(ctx.user()), opts.get('user')),
2535 2535 ('date', fm.formatdate(ctx.date(), datefmt), opts.get('date')),
2536 2536 ])
2537 2537 lastcol = next(name for name, data, cond in reversed(cols) if cond)
2538 2538 for name, data, cond in cols:
2539 2539 field = fieldnamemap.get(name, name)
2540 2540 fm.condwrite(cond, field, '%s', data, label='grep.%s' % name)
2541 2541 if cond and name != lastcol:
2542 2542 fm.plain(sep, label='grep.sep')
2543 2543 if not opts.get('files_with_matches'):
2544 2544 fm.plain(sep, label='grep.sep')
2545 2545 if not opts.get('text') and binary():
2546 2546 fm.plain(_(" Binary file matches"))
2547 2547 else:
2548 2548 displaymatches(fm.nested('texts'), l)
2549 2549 fm.plain(eol)
2550 2550 found = True
2551 2551 if opts.get('files_with_matches'):
2552 2552 break
2553 2553 return found
2554 2554
2555 2555 def displaymatches(fm, l):
2556 2556 p = 0
2557 2557 for s, e in l.findpos():
2558 2558 if p < s:
2559 2559 fm.startitem()
2560 2560 fm.write('text', '%s', l.line[p:s])
2561 2561 fm.data(matched=False)
2562 2562 fm.startitem()
2563 2563 fm.write('text', '%s', l.line[s:e], label='grep.match')
2564 2564 fm.data(matched=True)
2565 2565 p = e
2566 2566 if p < len(l.line):
2567 2567 fm.startitem()
2568 2568 fm.write('text', '%s', l.line[p:])
2569 2569 fm.data(matched=False)
2570 2570 fm.end()
2571 2571
2572 2572 skip = {}
2573 2573 revfiles = {}
2574 2574 matchfn = scmutil.match(repo[None], pats, opts)
2575 2575 found = False
2576 2576 follow = opts.get('follow')
2577 2577
2578 2578 def prep(ctx, fns):
2579 2579 rev = ctx.rev()
2580 2580 pctx = ctx.p1()
2581 2581 parent = pctx.rev()
2582 2582 matches.setdefault(rev, {})
2583 2583 matches.setdefault(parent, {})
2584 2584 files = revfiles.setdefault(rev, [])
2585 2585 for fn in fns:
2586 2586 flog = getfile(fn)
2587 2587 try:
2588 2588 fnode = ctx.filenode(fn)
2589 2589 except error.LookupError:
2590 2590 continue
2591 2591
2592 2592 copied = flog.renamed(fnode)
2593 2593 copy = follow and copied and copied[0]
2594 2594 if copy:
2595 2595 copies.setdefault(rev, {})[fn] = copy
2596 2596 if fn in skip:
2597 2597 if copy:
2598 2598 skip[copy] = True
2599 2599 continue
2600 2600 files.append(fn)
2601 2601
2602 2602 if fn not in matches[rev]:
2603 2603 grepbody(fn, rev, flog.read(fnode))
2604 2604
2605 2605 pfn = copy or fn
2606 2606 if pfn not in matches[parent]:
2607 2607 try:
2608 2608 fnode = pctx.filenode(pfn)
2609 2609 grepbody(pfn, parent, flog.read(fnode))
2610 2610 except error.LookupError:
2611 2611 pass
2612 2612
2613 2613 ui.pager('grep')
2614 2614 fm = ui.formatter('grep', opts)
2615 2615 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
2616 2616 rev = ctx.rev()
2617 2617 parent = ctx.p1().rev()
2618 2618 for fn in sorted(revfiles.get(rev, [])):
2619 2619 states = matches[rev][fn]
2620 2620 copy = copies.get(rev, {}).get(fn)
2621 2621 if fn in skip:
2622 2622 if copy:
2623 2623 skip[copy] = True
2624 2624 continue
2625 2625 pstates = matches.get(parent, {}).get(copy or fn, [])
2626 2626 if pstates or states:
2627 2627 r = display(fm, fn, ctx, pstates, states)
2628 2628 found = found or r
2629 2629 if r and not opts.get('all'):
2630 2630 skip[fn] = True
2631 2631 if copy:
2632 2632 skip[copy] = True
2633 2633 del matches[rev]
2634 2634 del revfiles[rev]
2635 2635 fm.end()
2636 2636
2637 2637 return not found
2638 2638
2639 2639 @command('heads',
2640 2640 [('r', 'rev', '',
2641 2641 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
2642 2642 ('t', 'topo', False, _('show topological heads only')),
2643 2643 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
2644 2644 ('c', 'closed', False, _('show normal and closed branch heads')),
2645 2645 ] + templateopts,
2646 2646 _('[-ct] [-r STARTREV] [REV]...'))
2647 2647 def heads(ui, repo, *branchrevs, **opts):
2648 2648 """show branch heads
2649 2649
2650 2650 With no arguments, show all open branch heads in the repository.
2651 2651 Branch heads are changesets that have no descendants on the
2652 2652 same branch. They are where development generally takes place and
2653 2653 are the usual targets for update and merge operations.
2654 2654
2655 2655 If one or more REVs are given, only open branch heads on the
2656 2656 branches associated with the specified changesets are shown. This
2657 2657 means that you can use :hg:`heads .` to see the heads on the
2658 2658 currently checked-out branch.
2659 2659
2660 2660 If -c/--closed is specified, also show branch heads marked closed
2661 2661 (see :hg:`commit --close-branch`).
2662 2662
2663 2663 If STARTREV is specified, only those heads that are descendants of
2664 2664 STARTREV will be displayed.
2665 2665
2666 2666 If -t/--topo is specified, named branch mechanics will be ignored and only
2667 2667 topological heads (changesets with no children) will be shown.
2668 2668
2669 2669 Returns 0 if matching heads are found, 1 if not.
2670 2670 """
2671 2671
2672 2672 start = None
2673 2673 if 'rev' in opts:
2674 2674 start = scmutil.revsingle(repo, opts['rev'], None).node()
2675 2675
2676 2676 if opts.get('topo'):
2677 2677 heads = [repo[h] for h in repo.heads(start)]
2678 2678 else:
2679 2679 heads = []
2680 2680 for branch in repo.branchmap():
2681 2681 heads += repo.branchheads(branch, start, opts.get('closed'))
2682 2682 heads = [repo[h] for h in heads]
2683 2683
2684 2684 if branchrevs:
2685 2685 branches = set(repo[br].branch() for br in branchrevs)
2686 2686 heads = [h for h in heads if h.branch() in branches]
2687 2687
2688 2688 if opts.get('active') and branchrevs:
2689 2689 dagheads = repo.heads(start)
2690 2690 heads = [h for h in heads if h.node() in dagheads]
2691 2691
2692 2692 if branchrevs:
2693 2693 haveheads = set(h.branch() for h in heads)
2694 2694 if branches - haveheads:
2695 2695 headless = ', '.join(b for b in branches - haveheads)
2696 2696 msg = _('no open branch heads found on branches %s')
2697 2697 if opts.get('rev'):
2698 2698 msg += _(' (started at %s)') % opts['rev']
2699 2699 ui.warn((msg + '\n') % headless)
2700 2700
2701 2701 if not heads:
2702 2702 return 1
2703 2703
2704 2704 heads = sorted(heads, key=lambda x: -x.rev())
2705 2705 displayer = cmdutil.show_changeset(ui, repo, opts)
2706 2706 for ctx in heads:
2707 2707 displayer.show(ctx)
2708 2708 displayer.close()
2709 2709
2710 2710 @command('help',
2711 2711 [('e', 'extension', None, _('show only help for extensions')),
2712 2712 ('c', 'command', None, _('show only help for commands')),
2713 2713 ('k', 'keyword', None, _('show topics matching keyword')),
2714 2714 ('s', 'system', [], _('show help for specific platform(s)')),
2715 2715 ],
2716 2716 _('[-ecks] [TOPIC]'),
2717 2717 norepo=True)
2718 2718 def help_(ui, name=None, **opts):
2719 2719 """show help for a given topic or a help overview
2720 2720
2721 2721 With no arguments, print a list of commands with short help messages.
2722 2722
2723 2723 Given a topic, extension, or command name, print help for that
2724 2724 topic.
2725 2725
2726 2726 Returns 0 if successful.
2727 2727 """
2728 2728
2729 2729 keep = opts.get('system') or []
2730 2730 if len(keep) == 0:
2731 2731 if pycompat.sysplatform.startswith('win'):
2732 2732 keep.append('windows')
2733 2733 elif pycompat.sysplatform == 'OpenVMS':
2734 2734 keep.append('vms')
2735 2735 elif pycompat.sysplatform == 'plan9':
2736 2736 keep.append('plan9')
2737 2737 else:
2738 2738 keep.append('unix')
2739 2739 keep.append(pycompat.sysplatform.lower())
2740 2740 if ui.verbose:
2741 2741 keep.append('verbose')
2742 2742
2743 2743 formatted = help.formattedhelp(ui, name, keep=keep, **opts)
2744 2744 ui.pager('help')
2745 2745 ui.write(formatted)
2746 2746
2747 2747
2748 2748 @command('identify|id',
2749 2749 [('r', 'rev', '',
2750 2750 _('identify the specified revision'), _('REV')),
2751 2751 ('n', 'num', None, _('show local revision number')),
2752 2752 ('i', 'id', None, _('show global revision id')),
2753 2753 ('b', 'branch', None, _('show branch')),
2754 2754 ('t', 'tags', None, _('show tags')),
2755 2755 ('B', 'bookmarks', None, _('show bookmarks')),
2756 2756 ] + remoteopts,
2757 2757 _('[-nibtB] [-r REV] [SOURCE]'),
2758 2758 optionalrepo=True)
2759 2759 def identify(ui, repo, source=None, rev=None,
2760 2760 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
2761 2761 """identify the working directory or specified revision
2762 2762
2763 2763 Print a summary identifying the repository state at REV using one or
2764 2764 two parent hash identifiers, followed by a "+" if the working
2765 2765 directory has uncommitted changes, the branch name (if not default),
2766 2766 a list of tags, and a list of bookmarks.
2767 2767
2768 2768 When REV is not given, print a summary of the current state of the
2769 2769 repository.
2770 2770
2771 2771 Specifying a path to a repository root or Mercurial bundle will
2772 2772 cause lookup to operate on that repository/bundle.
2773 2773
2774 2774 .. container:: verbose
2775 2775
2776 2776 Examples:
2777 2777
2778 2778 - generate a build identifier for the working directory::
2779 2779
2780 2780 hg id --id > build-id.dat
2781 2781
2782 2782 - find the revision corresponding to a tag::
2783 2783
2784 2784 hg id -n -r 1.3
2785 2785
2786 2786 - check the most recent revision of a remote repository::
2787 2787
2788 2788 hg id -r tip https://www.mercurial-scm.org/repo/hg/
2789 2789
2790 2790 See :hg:`log` for generating more information about specific revisions,
2791 2791 including full hash identifiers.
2792 2792
2793 2793 Returns 0 if successful.
2794 2794 """
2795 2795
2796 2796 if not repo and not source:
2797 2797 raise error.Abort(_("there is no Mercurial repository here "
2798 2798 "(.hg not found)"))
2799 2799
2800 2800 if ui.debugflag:
2801 2801 hexfunc = hex
2802 2802 else:
2803 2803 hexfunc = short
2804 2804 default = not (num or id or branch or tags or bookmarks)
2805 2805 output = []
2806 2806 revs = []
2807 2807
2808 2808 if source:
2809 2809 source, branches = hg.parseurl(ui.expandpath(source))
2810 2810 peer = hg.peer(repo or ui, opts, source) # only pass ui when no repo
2811 2811 repo = peer.local()
2812 2812 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
2813 2813
2814 2814 if not repo:
2815 2815 if num or branch or tags:
2816 2816 raise error.Abort(
2817 2817 _("can't query remote revision number, branch, or tags"))
2818 2818 if not rev and revs:
2819 2819 rev = revs[0]
2820 2820 if not rev:
2821 2821 rev = "tip"
2822 2822
2823 2823 remoterev = peer.lookup(rev)
2824 2824 if default or id:
2825 2825 output = [hexfunc(remoterev)]
2826 2826
2827 2827 def getbms():
2828 2828 bms = []
2829 2829
2830 2830 if 'bookmarks' in peer.listkeys('namespaces'):
2831 2831 hexremoterev = hex(remoterev)
2832 2832 bms = [bm for bm, bmr in peer.listkeys('bookmarks').iteritems()
2833 2833 if bmr == hexremoterev]
2834 2834
2835 2835 return sorted(bms)
2836 2836
2837 2837 if bookmarks:
2838 2838 output.extend(getbms())
2839 2839 elif default and not ui.quiet:
2840 2840 # multiple bookmarks for a single parent separated by '/'
2841 2841 bm = '/'.join(getbms())
2842 2842 if bm:
2843 2843 output.append(bm)
2844 2844 else:
2845 2845 ctx = scmutil.revsingle(repo, rev, None)
2846 2846
2847 2847 if ctx.rev() is None:
2848 2848 ctx = repo[None]
2849 2849 parents = ctx.parents()
2850 2850 taglist = []
2851 2851 for p in parents:
2852 2852 taglist.extend(p.tags())
2853 2853
2854 2854 changed = ""
2855 2855 if default or id or num:
2856 2856 if (any(repo.status())
2857 2857 or any(ctx.sub(s).dirty() for s in ctx.substate)):
2858 2858 changed = '+'
2859 2859 if default or id:
2860 2860 output = ["%s%s" %
2861 2861 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
2862 2862 if num:
2863 2863 output.append("%s%s" %
2864 2864 ('+'.join([str(p.rev()) for p in parents]), changed))
2865 2865 else:
2866 2866 if default or id:
2867 2867 output = [hexfunc(ctx.node())]
2868 2868 if num:
2869 2869 output.append(str(ctx.rev()))
2870 2870 taglist = ctx.tags()
2871 2871
2872 2872 if default and not ui.quiet:
2873 2873 b = ctx.branch()
2874 2874 if b != 'default':
2875 2875 output.append("(%s)" % b)
2876 2876
2877 2877 # multiple tags for a single parent separated by '/'
2878 2878 t = '/'.join(taglist)
2879 2879 if t:
2880 2880 output.append(t)
2881 2881
2882 2882 # multiple bookmarks for a single parent separated by '/'
2883 2883 bm = '/'.join(ctx.bookmarks())
2884 2884 if bm:
2885 2885 output.append(bm)
2886 2886 else:
2887 2887 if branch:
2888 2888 output.append(ctx.branch())
2889 2889
2890 2890 if tags:
2891 2891 output.extend(taglist)
2892 2892
2893 2893 if bookmarks:
2894 2894 output.extend(ctx.bookmarks())
2895 2895
2896 2896 ui.write("%s\n" % ' '.join(output))
2897 2897
2898 2898 @command('import|patch',
2899 2899 [('p', 'strip', 1,
2900 2900 _('directory strip option for patch. This has the same '
2901 2901 'meaning as the corresponding patch option'), _('NUM')),
2902 2902 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
2903 2903 ('e', 'edit', False, _('invoke editor on commit messages')),
2904 2904 ('f', 'force', None,
2905 2905 _('skip check for outstanding uncommitted changes (DEPRECATED)')),
2906 2906 ('', 'no-commit', None,
2907 2907 _("don't commit, just update the working directory")),
2908 2908 ('', 'bypass', None,
2909 2909 _("apply patch without touching the working directory")),
2910 2910 ('', 'partial', None,
2911 2911 _('commit even if some hunks fail')),
2912 2912 ('', 'exact', None,
2913 2913 _('abort if patch would apply lossily')),
2914 2914 ('', 'prefix', '',
2915 2915 _('apply patch to subdirectory'), _('DIR')),
2916 2916 ('', 'import-branch', None,
2917 2917 _('use any branch information in patch (implied by --exact)'))] +
2918 2918 commitopts + commitopts2 + similarityopts,
2919 2919 _('[OPTION]... PATCH...'))
2920 2920 def import_(ui, repo, patch1=None, *patches, **opts):
2921 2921 """import an ordered set of patches
2922 2922
2923 2923 Import a list of patches and commit them individually (unless
2924 2924 --no-commit is specified).
2925 2925
2926 2926 To read a patch from standard input (stdin), use "-" as the patch
2927 2927 name. If a URL is specified, the patch will be downloaded from
2928 2928 there.
2929 2929
2930 2930 Import first applies changes to the working directory (unless
2931 2931 --bypass is specified), import will abort if there are outstanding
2932 2932 changes.
2933 2933
2934 2934 Use --bypass to apply and commit patches directly to the
2935 2935 repository, without affecting the working directory. Without
2936 2936 --exact, patches will be applied on top of the working directory
2937 2937 parent revision.
2938 2938
2939 2939 You can import a patch straight from a mail message. Even patches
2940 2940 as attachments work (to use the body part, it must have type
2941 2941 text/plain or text/x-patch). From and Subject headers of email
2942 2942 message are used as default committer and commit message. All
2943 2943 text/plain body parts before first diff are added to the commit
2944 2944 message.
2945 2945
2946 2946 If the imported patch was generated by :hg:`export`, user and
2947 2947 description from patch override values from message headers and
2948 2948 body. Values given on command line with -m/--message and -u/--user
2949 2949 override these.
2950 2950
2951 2951 If --exact is specified, import will set the working directory to
2952 2952 the parent of each patch before applying it, and will abort if the
2953 2953 resulting changeset has a different ID than the one recorded in
2954 2954 the patch. This will guard against various ways that portable
2955 2955 patch formats and mail systems might fail to transfer Mercurial
2956 2956 data or metadata. See :hg:`bundle` for lossless transmission.
2957 2957
2958 2958 Use --partial to ensure a changeset will be created from the patch
2959 2959 even if some hunks fail to apply. Hunks that fail to apply will be
2960 2960 written to a <target-file>.rej file. Conflicts can then be resolved
2961 2961 by hand before :hg:`commit --amend` is run to update the created
2962 2962 changeset. This flag exists to let people import patches that
2963 2963 partially apply without losing the associated metadata (author,
2964 2964 date, description, ...).
2965 2965
2966 2966 .. note::
2967 2967
2968 2968 When no hunks apply cleanly, :hg:`import --partial` will create
2969 2969 an empty changeset, importing only the patch metadata.
2970 2970
2971 2971 With -s/--similarity, hg will attempt to discover renames and
2972 2972 copies in the patch in the same way as :hg:`addremove`.
2973 2973
2974 2974 It is possible to use external patch programs to perform the patch
2975 2975 by setting the ``ui.patch`` configuration option. For the default
2976 2976 internal tool, the fuzz can also be configured via ``patch.fuzz``.
2977 2977 See :hg:`help config` for more information about configuration
2978 2978 files and how to use these options.
2979 2979
2980 2980 See :hg:`help dates` for a list of formats valid for -d/--date.
2981 2981
2982 2982 .. container:: verbose
2983 2983
2984 2984 Examples:
2985 2985
2986 2986 - import a traditional patch from a website and detect renames::
2987 2987
2988 2988 hg import -s 80 http://example.com/bugfix.patch
2989 2989
2990 2990 - import a changeset from an hgweb server::
2991 2991
2992 2992 hg import https://www.mercurial-scm.org/repo/hg/rev/5ca8c111e9aa
2993 2993
2994 2994 - import all the patches in an Unix-style mbox::
2995 2995
2996 2996 hg import incoming-patches.mbox
2997 2997
2998 2998 - import patches from stdin::
2999 2999
3000 3000 hg import -
3001 3001
3002 3002 - attempt to exactly restore an exported changeset (not always
3003 3003 possible)::
3004 3004
3005 3005 hg import --exact proposed-fix.patch
3006 3006
3007 3007 - use an external tool to apply a patch which is too fuzzy for
3008 3008 the default internal tool.
3009 3009
3010 3010 hg import --config ui.patch="patch --merge" fuzzy.patch
3011 3011
3012 3012 - change the default fuzzing from 2 to a less strict 7
3013 3013
3014 3014 hg import --config ui.fuzz=7 fuzz.patch
3015 3015
3016 3016 Returns 0 on success, 1 on partial success (see --partial).
3017 3017 """
3018 3018
3019 3019 if not patch1:
3020 3020 raise error.Abort(_('need at least one patch to import'))
3021 3021
3022 3022 patches = (patch1,) + patches
3023 3023
3024 3024 date = opts.get('date')
3025 3025 if date:
3026 3026 opts['date'] = util.parsedate(date)
3027 3027
3028 3028 exact = opts.get('exact')
3029 3029 update = not opts.get('bypass')
3030 3030 if not update and opts.get('no_commit'):
3031 3031 raise error.Abort(_('cannot use --no-commit with --bypass'))
3032 3032 try:
3033 3033 sim = float(opts.get('similarity') or 0)
3034 3034 except ValueError:
3035 3035 raise error.Abort(_('similarity must be a number'))
3036 3036 if sim < 0 or sim > 100:
3037 3037 raise error.Abort(_('similarity must be between 0 and 100'))
3038 3038 if sim and not update:
3039 3039 raise error.Abort(_('cannot use --similarity with --bypass'))
3040 3040 if exact:
3041 3041 if opts.get('edit'):
3042 3042 raise error.Abort(_('cannot use --exact with --edit'))
3043 3043 if opts.get('prefix'):
3044 3044 raise error.Abort(_('cannot use --exact with --prefix'))
3045 3045
3046 3046 base = opts["base"]
3047 3047 wlock = dsguard = lock = tr = None
3048 3048 msgs = []
3049 3049 ret = 0
3050 3050
3051 3051
3052 3052 try:
3053 3053 wlock = repo.wlock()
3054 3054
3055 3055 if update:
3056 3056 cmdutil.checkunfinished(repo)
3057 3057 if (exact or not opts.get('force')):
3058 3058 cmdutil.bailifchanged(repo)
3059 3059
3060 3060 if not opts.get('no_commit'):
3061 3061 lock = repo.lock()
3062 3062 tr = repo.transaction('import')
3063 3063 else:
3064 3064 dsguard = dirstateguard.dirstateguard(repo, 'import')
3065 3065 parents = repo[None].parents()
3066 3066 for patchurl in patches:
3067 3067 if patchurl == '-':
3068 3068 ui.status(_('applying patch from stdin\n'))
3069 3069 patchfile = ui.fin
3070 3070 patchurl = 'stdin' # for error message
3071 3071 else:
3072 3072 patchurl = os.path.join(base, patchurl)
3073 3073 ui.status(_('applying %s\n') % patchurl)
3074 3074 patchfile = hg.openpath(ui, patchurl)
3075 3075
3076 3076 haspatch = False
3077 3077 for hunk in patch.split(patchfile):
3078 3078 (msg, node, rej) = cmdutil.tryimportone(ui, repo, hunk,
3079 3079 parents, opts,
3080 3080 msgs, hg.clean)
3081 3081 if msg:
3082 3082 haspatch = True
3083 3083 ui.note(msg + '\n')
3084 3084 if update or exact:
3085 3085 parents = repo[None].parents()
3086 3086 else:
3087 3087 parents = [repo[node]]
3088 3088 if rej:
3089 3089 ui.write_err(_("patch applied partially\n"))
3090 3090 ui.write_err(_("(fix the .rej files and run "
3091 3091 "`hg commit --amend`)\n"))
3092 3092 ret = 1
3093 3093 break
3094 3094
3095 3095 if not haspatch:
3096 3096 raise error.Abort(_('%s: no diffs found') % patchurl)
3097 3097
3098 3098 if tr:
3099 3099 tr.close()
3100 3100 if msgs:
3101 3101 repo.savecommitmessage('\n* * *\n'.join(msgs))
3102 3102 if dsguard:
3103 3103 dsguard.close()
3104 3104 return ret
3105 3105 finally:
3106 3106 if tr:
3107 3107 tr.release()
3108 3108 release(lock, dsguard, wlock)
3109 3109
3110 3110 @command('incoming|in',
3111 3111 [('f', 'force', None,
3112 3112 _('run even if remote repository is unrelated')),
3113 3113 ('n', 'newest-first', None, _('show newest record first')),
3114 3114 ('', 'bundle', '',
3115 3115 _('file to store the bundles into'), _('FILE')),
3116 3116 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3117 3117 ('B', 'bookmarks', False, _("compare bookmarks")),
3118 3118 ('b', 'branch', [],
3119 3119 _('a specific branch you would like to pull'), _('BRANCH')),
3120 3120 ] + logopts + remoteopts + subrepoopts,
3121 3121 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3122 3122 def incoming(ui, repo, source="default", **opts):
3123 3123 """show new changesets found in source
3124 3124
3125 3125 Show new changesets found in the specified path/URL or the default
3126 3126 pull location. These are the changesets that would have been pulled
3127 3127 if a pull at the time you issued this command.
3128 3128
3129 3129 See pull for valid source format details.
3130 3130
3131 3131 .. container:: verbose
3132 3132
3133 3133 With -B/--bookmarks, the result of bookmark comparison between
3134 3134 local and remote repositories is displayed. With -v/--verbose,
3135 3135 status is also displayed for each bookmark like below::
3136 3136
3137 3137 BM1 01234567890a added
3138 3138 BM2 1234567890ab advanced
3139 3139 BM3 234567890abc diverged
3140 3140 BM4 34567890abcd changed
3141 3141
3142 3142 The action taken locally when pulling depends on the
3143 3143 status of each bookmark:
3144 3144
3145 3145 :``added``: pull will create it
3146 3146 :``advanced``: pull will update it
3147 3147 :``diverged``: pull will create a divergent bookmark
3148 3148 :``changed``: result depends on remote changesets
3149 3149
3150 3150 From the point of view of pulling behavior, bookmark
3151 3151 existing only in the remote repository are treated as ``added``,
3152 3152 even if it is in fact locally deleted.
3153 3153
3154 3154 .. container:: verbose
3155 3155
3156 3156 For remote repository, using --bundle avoids downloading the
3157 3157 changesets twice if the incoming is followed by a pull.
3158 3158
3159 3159 Examples:
3160 3160
3161 3161 - show incoming changes with patches and full description::
3162 3162
3163 3163 hg incoming -vp
3164 3164
3165 3165 - show incoming changes excluding merges, store a bundle::
3166 3166
3167 3167 hg in -vpM --bundle incoming.hg
3168 3168 hg pull incoming.hg
3169 3169
3170 3170 - briefly list changes inside a bundle::
3171 3171
3172 3172 hg in changes.hg -T "{desc|firstline}\\n"
3173 3173
3174 3174 Returns 0 if there are incoming changes, 1 otherwise.
3175 3175 """
3176 3176 if opts.get('graph'):
3177 3177 cmdutil.checkunsupportedgraphflags([], opts)
3178 3178 def display(other, chlist, displayer):
3179 3179 revdag = cmdutil.graphrevs(other, chlist, opts)
3180 3180 cmdutil.displaygraph(ui, repo, revdag, displayer,
3181 3181 graphmod.asciiedges)
3182 3182
3183 3183 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
3184 3184 return 0
3185 3185
3186 3186 if opts.get('bundle') and opts.get('subrepos'):
3187 3187 raise error.Abort(_('cannot combine --bundle and --subrepos'))
3188 3188
3189 3189 if opts.get('bookmarks'):
3190 3190 source, branches = hg.parseurl(ui.expandpath(source),
3191 3191 opts.get('branch'))
3192 3192 other = hg.peer(repo, opts, source)
3193 3193 if 'bookmarks' not in other.listkeys('namespaces'):
3194 3194 ui.warn(_("remote doesn't support bookmarks\n"))
3195 3195 return 0
3196 3196 ui.pager('incoming')
3197 3197 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3198 3198 return bookmarks.incoming(ui, repo, other)
3199 3199
3200 3200 repo._subtoppath = ui.expandpath(source)
3201 3201 try:
3202 3202 return hg.incoming(ui, repo, source, opts)
3203 3203 finally:
3204 3204 del repo._subtoppath
3205 3205
3206 3206
3207 3207 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'),
3208 3208 norepo=True)
3209 3209 def init(ui, dest=".", **opts):
3210 3210 """create a new repository in the given directory
3211 3211
3212 3212 Initialize a new repository in the given directory. If the given
3213 3213 directory does not exist, it will be created.
3214 3214
3215 3215 If no directory is given, the current directory is used.
3216 3216
3217 3217 It is possible to specify an ``ssh://`` URL as the destination.
3218 3218 See :hg:`help urls` for more information.
3219 3219
3220 3220 Returns 0 on success.
3221 3221 """
3222 3222 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3223 3223
3224 3224 @command('locate',
3225 3225 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3226 3226 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3227 3227 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3228 3228 ] + walkopts,
3229 3229 _('[OPTION]... [PATTERN]...'))
3230 3230 def locate(ui, repo, *pats, **opts):
3231 3231 """locate files matching specific patterns (DEPRECATED)
3232 3232
3233 3233 Print files under Mercurial control in the working directory whose
3234 3234 names match the given patterns.
3235 3235
3236 3236 By default, this command searches all directories in the working
3237 3237 directory. To search just the current directory and its
3238 3238 subdirectories, use "--include .".
3239 3239
3240 3240 If no patterns are given to match, this command prints the names
3241 3241 of all files under Mercurial control in the working directory.
3242 3242
3243 3243 If you want to feed the output of this command into the "xargs"
3244 3244 command, use the -0 option to both this command and "xargs". This
3245 3245 will avoid the problem of "xargs" treating single filenames that
3246 3246 contain whitespace as multiple filenames.
3247 3247
3248 3248 See :hg:`help files` for a more versatile command.
3249 3249
3250 3250 Returns 0 if a match is found, 1 otherwise.
3251 3251 """
3252 3252 if opts.get('print0'):
3253 3253 end = '\0'
3254 3254 else:
3255 3255 end = '\n'
3256 3256 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
3257 3257
3258 3258 ret = 1
3259 3259 ctx = repo[rev]
3260 3260 m = scmutil.match(ctx, pats, opts, default='relglob',
3261 3261 badfn=lambda x, y: False)
3262 3262
3263 3263 ui.pager('locate')
3264 3264 for abs in ctx.matches(m):
3265 3265 if opts.get('fullpath'):
3266 3266 ui.write(repo.wjoin(abs), end)
3267 3267 else:
3268 3268 ui.write(((pats and m.rel(abs)) or abs), end)
3269 3269 ret = 0
3270 3270
3271 3271 return ret
3272 3272
3273 3273 @command('^log|history',
3274 3274 [('f', 'follow', None,
3275 3275 _('follow changeset history, or file history across copies and renames')),
3276 3276 ('', 'follow-first', None,
3277 3277 _('only follow the first parent of merge changesets (DEPRECATED)')),
3278 3278 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3279 3279 ('C', 'copies', None, _('show copied files')),
3280 3280 ('k', 'keyword', [],
3281 3281 _('do case-insensitive search for a given text'), _('TEXT')),
3282 3282 ('r', 'rev', [], _('show the specified revision or revset'), _('REV')),
3283 3283 ('', 'removed', None, _('include revisions where files were removed')),
3284 3284 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
3285 3285 ('u', 'user', [], _('revisions committed by user'), _('USER')),
3286 3286 ('', 'only-branch', [],
3287 3287 _('show only changesets within the given named branch (DEPRECATED)'),
3288 3288 _('BRANCH')),
3289 3289 ('b', 'branch', [],
3290 3290 _('show changesets within the given named branch'), _('BRANCH')),
3291 3291 ('P', 'prune', [],
3292 3292 _('do not display revision or any of its ancestors'), _('REV')),
3293 3293 ] + logopts + walkopts,
3294 3294 _('[OPTION]... [FILE]'),
3295 3295 inferrepo=True)
3296 3296 def log(ui, repo, *pats, **opts):
3297 3297 """show revision history of entire repository or files
3298 3298
3299 3299 Print the revision history of the specified files or the entire
3300 3300 project.
3301 3301
3302 3302 If no revision range is specified, the default is ``tip:0`` unless
3303 3303 --follow is set, in which case the working directory parent is
3304 3304 used as the starting revision.
3305 3305
3306 3306 File history is shown without following rename or copy history of
3307 3307 files. Use -f/--follow with a filename to follow history across
3308 3308 renames and copies. --follow without a filename will only show
3309 3309 ancestors or descendants of the starting revision.
3310 3310
3311 3311 By default this command prints revision number and changeset id,
3312 3312 tags, non-trivial parents, user, date and time, and a summary for
3313 3313 each commit. When the -v/--verbose switch is used, the list of
3314 3314 changed files and full commit message are shown.
3315 3315
3316 3316 With --graph the revisions are shown as an ASCII art DAG with the most
3317 3317 recent changeset at the top.
3318 3318 'o' is a changeset, '@' is a working directory parent, 'x' is obsolete,
3319 3319 and '+' represents a fork where the changeset from the lines below is a
3320 3320 parent of the 'o' merge on the same line.
3321 3321
3322 3322 .. note::
3323 3323
3324 3324 :hg:`log --patch` may generate unexpected diff output for merge
3325 3325 changesets, as it will only compare the merge changeset against
3326 3326 its first parent. Also, only files different from BOTH parents
3327 3327 will appear in files:.
3328 3328
3329 3329 .. note::
3330 3330
3331 3331 For performance reasons, :hg:`log FILE` may omit duplicate changes
3332 3332 made on branches and will not show removals or mode changes. To
3333 3333 see all such changes, use the --removed switch.
3334 3334
3335 3335 .. container:: verbose
3336 3336
3337 3337 Some examples:
3338 3338
3339 3339 - changesets with full descriptions and file lists::
3340 3340
3341 3341 hg log -v
3342 3342
3343 3343 - changesets ancestral to the working directory::
3344 3344
3345 3345 hg log -f
3346 3346
3347 3347 - last 10 commits on the current branch::
3348 3348
3349 3349 hg log -l 10 -b .
3350 3350
3351 3351 - changesets showing all modifications of a file, including removals::
3352 3352
3353 3353 hg log --removed file.c
3354 3354
3355 3355 - all changesets that touch a directory, with diffs, excluding merges::
3356 3356
3357 3357 hg log -Mp lib/
3358 3358
3359 3359 - all revision numbers that match a keyword::
3360 3360
3361 3361 hg log -k bug --template "{rev}\\n"
3362 3362
3363 3363 - the full hash identifier of the working directory parent::
3364 3364
3365 3365 hg log -r . --template "{node}\\n"
3366 3366
3367 3367 - list available log templates::
3368 3368
3369 3369 hg log -T list
3370 3370
3371 3371 - check if a given changeset is included in a tagged release::
3372 3372
3373 3373 hg log -r "a21ccf and ancestor(1.9)"
3374 3374
3375 3375 - find all changesets by some user in a date range::
3376 3376
3377 3377 hg log -k alice -d "may 2008 to jul 2008"
3378 3378
3379 3379 - summary of all changesets after the last tag::
3380 3380
3381 3381 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
3382 3382
3383 3383 See :hg:`help dates` for a list of formats valid for -d/--date.
3384 3384
3385 3385 See :hg:`help revisions` for more about specifying and ordering
3386 3386 revisions.
3387 3387
3388 3388 See :hg:`help templates` for more about pre-packaged styles and
3389 3389 specifying custom templates.
3390 3390
3391 3391 Returns 0 on success.
3392 3392
3393 3393 """
3394 3394 if opts.get('follow') and opts.get('rev'):
3395 3395 opts['rev'] = [revsetlang.formatspec('reverse(::%lr)', opts.get('rev'))]
3396 3396 del opts['follow']
3397 3397
3398 3398 if opts.get('graph'):
3399 3399 return cmdutil.graphlog(ui, repo, *pats, **opts)
3400 3400
3401 3401 revs, expr, filematcher = cmdutil.getlogrevs(repo, pats, opts)
3402 3402 limit = cmdutil.loglimit(opts)
3403 3403 count = 0
3404 3404
3405 3405 getrenamed = None
3406 3406 if opts.get('copies'):
3407 3407 endrev = None
3408 3408 if opts.get('rev'):
3409 3409 endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1
3410 3410 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
3411 3411
3412 3412 ui.pager('log')
3413 3413 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
3414 3414 for rev in revs:
3415 3415 if count == limit:
3416 3416 break
3417 3417 ctx = repo[rev]
3418 3418 copies = None
3419 3419 if getrenamed is not None and rev:
3420 3420 copies = []
3421 3421 for fn in ctx.files():
3422 3422 rename = getrenamed(fn, rev)
3423 3423 if rename:
3424 3424 copies.append((fn, rename[0]))
3425 3425 if filematcher:
3426 3426 revmatchfn = filematcher(ctx.rev())
3427 3427 else:
3428 3428 revmatchfn = None
3429 3429 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
3430 3430 if displayer.flush(ctx):
3431 3431 count += 1
3432 3432
3433 3433 displayer.close()
3434 3434
3435 3435 @command('manifest',
3436 3436 [('r', 'rev', '', _('revision to display'), _('REV')),
3437 3437 ('', 'all', False, _("list files from all revisions"))]
3438 3438 + formatteropts,
3439 3439 _('[-r REV]'))
3440 3440 def manifest(ui, repo, node=None, rev=None, **opts):
3441 3441 """output the current or given revision of the project manifest
3442 3442
3443 3443 Print a list of version controlled files for the given revision.
3444 3444 If no revision is given, the first parent of the working directory
3445 3445 is used, or the null revision if no revision is checked out.
3446 3446
3447 3447 With -v, print file permissions, symlink and executable bits.
3448 3448 With --debug, print file revision hashes.
3449 3449
3450 3450 If option --all is specified, the list of all files from all revisions
3451 3451 is printed. This includes deleted and renamed files.
3452 3452
3453 3453 Returns 0 on success.
3454 3454 """
3455 3455 fm = ui.formatter('manifest', opts)
3456 3456
3457 3457 if opts.get('all'):
3458 3458 if rev or node:
3459 3459 raise error.Abort(_("can't specify a revision with --all"))
3460 3460
3461 3461 res = []
3462 3462 prefix = "data/"
3463 3463 suffix = ".i"
3464 3464 plen = len(prefix)
3465 3465 slen = len(suffix)
3466 3466 with repo.lock():
3467 3467 for fn, b, size in repo.store.datafiles():
3468 3468 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
3469 3469 res.append(fn[plen:-slen])
3470 3470 ui.pager('manifest')
3471 3471 for f in res:
3472 3472 fm.startitem()
3473 3473 fm.write("path", '%s\n', f)
3474 3474 fm.end()
3475 3475 return
3476 3476
3477 3477 if rev and node:
3478 3478 raise error.Abort(_("please specify just one revision"))
3479 3479
3480 3480 if not node:
3481 3481 node = rev
3482 3482
3483 3483 char = {'l': '@', 'x': '*', '': ''}
3484 3484 mode = {'l': '644', 'x': '755', '': '644'}
3485 3485 ctx = scmutil.revsingle(repo, node)
3486 3486 mf = ctx.manifest()
3487 3487 ui.pager('manifest')
3488 3488 for f in ctx:
3489 3489 fm.startitem()
3490 3490 fl = ctx[f].flags()
3491 3491 fm.condwrite(ui.debugflag, 'hash', '%s ', hex(mf[f]))
3492 3492 fm.condwrite(ui.verbose, 'mode type', '%s %1s ', mode[fl], char[fl])
3493 3493 fm.write('path', '%s\n', f)
3494 3494 fm.end()
3495 3495
3496 3496 @command('^merge',
3497 3497 [('f', 'force', None,
3498 3498 _('force a merge including outstanding changes (DEPRECATED)')),
3499 3499 ('r', 'rev', '', _('revision to merge'), _('REV')),
3500 3500 ('P', 'preview', None,
3501 3501 _('review revisions to merge (no merge is performed)'))
3502 3502 ] + mergetoolopts,
3503 3503 _('[-P] [[-r] REV]'))
3504 3504 def merge(ui, repo, node=None, **opts):
3505 3505 """merge another revision into working directory
3506 3506
3507 3507 The current working directory is updated with all changes made in
3508 3508 the requested revision since the last common predecessor revision.
3509 3509
3510 3510 Files that changed between either parent are marked as changed for
3511 3511 the next commit and a commit must be performed before any further
3512 3512 updates to the repository are allowed. The next commit will have
3513 3513 two parents.
3514 3514
3515 3515 ``--tool`` can be used to specify the merge tool used for file
3516 3516 merges. It overrides the HGMERGE environment variable and your
3517 3517 configuration files. See :hg:`help merge-tools` for options.
3518 3518
3519 3519 If no revision is specified, the working directory's parent is a
3520 3520 head revision, and the current branch contains exactly one other
3521 3521 head, the other head is merged with by default. Otherwise, an
3522 3522 explicit revision with which to merge with must be provided.
3523 3523
3524 3524 See :hg:`help resolve` for information on handling file conflicts.
3525 3525
3526 3526 To undo an uncommitted merge, use :hg:`update --clean .` which
3527 3527 will check out a clean copy of the original merge parent, losing
3528 3528 all changes.
3529 3529
3530 3530 Returns 0 on success, 1 if there are unresolved files.
3531 3531 """
3532 3532
3533 3533 if opts.get('rev') and node:
3534 3534 raise error.Abort(_("please specify just one revision"))
3535 3535 if not node:
3536 3536 node = opts.get('rev')
3537 3537
3538 3538 if node:
3539 3539 node = scmutil.revsingle(repo, node).node()
3540 3540
3541 3541 if not node:
3542 3542 node = repo[destutil.destmerge(repo)].node()
3543 3543
3544 3544 if opts.get('preview'):
3545 3545 # find nodes that are ancestors of p2 but not of p1
3546 3546 p1 = repo.lookup('.')
3547 3547 p2 = repo.lookup(node)
3548 3548 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
3549 3549
3550 3550 displayer = cmdutil.show_changeset(ui, repo, opts)
3551 3551 for node in nodes:
3552 3552 displayer.show(repo[node])
3553 3553 displayer.close()
3554 3554 return 0
3555 3555
3556 3556 try:
3557 3557 # ui.forcemerge is an internal variable, do not document
3558 3558 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''), 'merge')
3559 3559 force = opts.get('force')
3560 3560 labels = ['working copy', 'merge rev']
3561 3561 return hg.merge(repo, node, force=force, mergeforce=force,
3562 3562 labels=labels)
3563 3563 finally:
3564 3564 ui.setconfig('ui', 'forcemerge', '', 'merge')
3565 3565
3566 3566 @command('outgoing|out',
3567 3567 [('f', 'force', None, _('run even when the destination is unrelated')),
3568 3568 ('r', 'rev', [],
3569 3569 _('a changeset intended to be included in the destination'), _('REV')),
3570 3570 ('n', 'newest-first', None, _('show newest record first')),
3571 3571 ('B', 'bookmarks', False, _('compare bookmarks')),
3572 3572 ('b', 'branch', [], _('a specific branch you would like to push'),
3573 3573 _('BRANCH')),
3574 3574 ] + logopts + remoteopts + subrepoopts,
3575 3575 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
3576 3576 def outgoing(ui, repo, dest=None, **opts):
3577 3577 """show changesets not found in the destination
3578 3578
3579 3579 Show changesets not found in the specified destination repository
3580 3580 or the default push location. These are the changesets that would
3581 3581 be pushed if a push was requested.
3582 3582
3583 3583 See pull for details of valid destination formats.
3584 3584
3585 3585 .. container:: verbose
3586 3586
3587 3587 With -B/--bookmarks, the result of bookmark comparison between
3588 3588 local and remote repositories is displayed. With -v/--verbose,
3589 3589 status is also displayed for each bookmark like below::
3590 3590
3591 3591 BM1 01234567890a added
3592 3592 BM2 deleted
3593 3593 BM3 234567890abc advanced
3594 3594 BM4 34567890abcd diverged
3595 3595 BM5 4567890abcde changed
3596 3596
3597 3597 The action taken when pushing depends on the
3598 3598 status of each bookmark:
3599 3599
3600 3600 :``added``: push with ``-B`` will create it
3601 3601 :``deleted``: push with ``-B`` will delete it
3602 3602 :``advanced``: push will update it
3603 3603 :``diverged``: push with ``-B`` will update it
3604 3604 :``changed``: push with ``-B`` will update it
3605 3605
3606 3606 From the point of view of pushing behavior, bookmarks
3607 3607 existing only in the remote repository are treated as
3608 3608 ``deleted``, even if it is in fact added remotely.
3609 3609
3610 3610 Returns 0 if there are outgoing changes, 1 otherwise.
3611 3611 """
3612 3612 if opts.get('graph'):
3613 3613 cmdutil.checkunsupportedgraphflags([], opts)
3614 3614 o, other = hg._outgoing(ui, repo, dest, opts)
3615 3615 if not o:
3616 3616 cmdutil.outgoinghooks(ui, repo, other, opts, o)
3617 3617 return
3618 3618
3619 3619 revdag = cmdutil.graphrevs(repo, o, opts)
3620 3620 ui.pager('outgoing')
3621 3621 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
3622 3622 cmdutil.displaygraph(ui, repo, revdag, displayer, graphmod.asciiedges)
3623 3623 cmdutil.outgoinghooks(ui, repo, other, opts, o)
3624 3624 return 0
3625 3625
3626 3626 if opts.get('bookmarks'):
3627 3627 dest = ui.expandpath(dest or 'default-push', dest or 'default')
3628 3628 dest, branches = hg.parseurl(dest, opts.get('branch'))
3629 3629 other = hg.peer(repo, opts, dest)
3630 3630 if 'bookmarks' not in other.listkeys('namespaces'):
3631 3631 ui.warn(_("remote doesn't support bookmarks\n"))
3632 3632 return 0
3633 3633 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
3634 3634 ui.pager('outgoing')
3635 3635 return bookmarks.outgoing(ui, repo, other)
3636 3636
3637 3637 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
3638 3638 try:
3639 3639 return hg.outgoing(ui, repo, dest, opts)
3640 3640 finally:
3641 3641 del repo._subtoppath
3642 3642
3643 3643 @command('parents',
3644 3644 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
3645 3645 ] + templateopts,
3646 3646 _('[-r REV] [FILE]'),
3647 3647 inferrepo=True)
3648 3648 def parents(ui, repo, file_=None, **opts):
3649 3649 """show the parents of the working directory or revision (DEPRECATED)
3650 3650
3651 3651 Print the working directory's parent revisions. If a revision is
3652 3652 given via -r/--rev, the parent of that revision will be printed.
3653 3653 If a file argument is given, the revision in which the file was
3654 3654 last changed (before the working directory revision or the
3655 3655 argument to --rev if given) is printed.
3656 3656
3657 3657 This command is equivalent to::
3658 3658
3659 3659 hg log -r "p1()+p2()" or
3660 3660 hg log -r "p1(REV)+p2(REV)" or
3661 3661 hg log -r "max(::p1() and file(FILE))+max(::p2() and file(FILE))" or
3662 3662 hg log -r "max(::p1(REV) and file(FILE))+max(::p2(REV) and file(FILE))"
3663 3663
3664 3664 See :hg:`summary` and :hg:`help revsets` for related information.
3665 3665
3666 3666 Returns 0 on success.
3667 3667 """
3668 3668
3669 3669 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
3670 3670
3671 3671 if file_:
3672 3672 m = scmutil.match(ctx, (file_,), opts)
3673 3673 if m.anypats() or len(m.files()) != 1:
3674 3674 raise error.Abort(_('can only specify an explicit filename'))
3675 3675 file_ = m.files()[0]
3676 3676 filenodes = []
3677 3677 for cp in ctx.parents():
3678 3678 if not cp:
3679 3679 continue
3680 3680 try:
3681 3681 filenodes.append(cp.filenode(file_))
3682 3682 except error.LookupError:
3683 3683 pass
3684 3684 if not filenodes:
3685 3685 raise error.Abort(_("'%s' not found in manifest!") % file_)
3686 3686 p = []
3687 3687 for fn in filenodes:
3688 3688 fctx = repo.filectx(file_, fileid=fn)
3689 3689 p.append(fctx.node())
3690 3690 else:
3691 3691 p = [cp.node() for cp in ctx.parents()]
3692 3692
3693 3693 displayer = cmdutil.show_changeset(ui, repo, opts)
3694 3694 for n in p:
3695 3695 if n != nullid:
3696 3696 displayer.show(repo[n])
3697 3697 displayer.close()
3698 3698
3699 3699 @command('paths', formatteropts, _('[NAME]'), optionalrepo=True)
3700 3700 def paths(ui, repo, search=None, **opts):
3701 3701 """show aliases for remote repositories
3702 3702
3703 3703 Show definition of symbolic path name NAME. If no name is given,
3704 3704 show definition of all available names.
3705 3705
3706 3706 Option -q/--quiet suppresses all output when searching for NAME
3707 3707 and shows only the path names when listing all definitions.
3708 3708
3709 3709 Path names are defined in the [paths] section of your
3710 3710 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
3711 3711 repository, ``.hg/hgrc`` is used, too.
3712 3712
3713 3713 The path names ``default`` and ``default-push`` have a special
3714 3714 meaning. When performing a push or pull operation, they are used
3715 3715 as fallbacks if no location is specified on the command-line.
3716 3716 When ``default-push`` is set, it will be used for push and
3717 3717 ``default`` will be used for pull; otherwise ``default`` is used
3718 3718 as the fallback for both. When cloning a repository, the clone
3719 3719 source is written as ``default`` in ``.hg/hgrc``.
3720 3720
3721 3721 .. note::
3722 3722
3723 3723 ``default`` and ``default-push`` apply to all inbound (e.g.
3724 3724 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email`
3725 3725 and :hg:`bundle`) operations.
3726 3726
3727 3727 See :hg:`help urls` for more information.
3728 3728
3729 3729 Returns 0 on success.
3730 3730 """
3731 3731 ui.pager('paths')
3732 3732 if search:
3733 3733 pathitems = [(name, path) for name, path in ui.paths.iteritems()
3734 3734 if name == search]
3735 3735 else:
3736 3736 pathitems = sorted(ui.paths.iteritems())
3737 3737
3738 3738 fm = ui.formatter('paths', opts)
3739 3739 if fm.isplain():
3740 3740 hidepassword = util.hidepassword
3741 3741 else:
3742 3742 hidepassword = str
3743 3743 if ui.quiet:
3744 3744 namefmt = '%s\n'
3745 3745 else:
3746 3746 namefmt = '%s = '
3747 3747 showsubopts = not search and not ui.quiet
3748 3748
3749 3749 for name, path in pathitems:
3750 3750 fm.startitem()
3751 3751 fm.condwrite(not search, 'name', namefmt, name)
3752 3752 fm.condwrite(not ui.quiet, 'url', '%s\n', hidepassword(path.rawloc))
3753 3753 for subopt, value in sorted(path.suboptions.items()):
3754 3754 assert subopt not in ('name', 'url')
3755 3755 if showsubopts:
3756 3756 fm.plain('%s:%s = ' % (name, subopt))
3757 3757 fm.condwrite(showsubopts, subopt, '%s\n', value)
3758 3758
3759 3759 fm.end()
3760 3760
3761 3761 if search and not pathitems:
3762 3762 if not ui.quiet:
3763 3763 ui.warn(_("not found!\n"))
3764 3764 return 1
3765 3765 else:
3766 3766 return 0
3767 3767
3768 3768 @command('phase',
3769 3769 [('p', 'public', False, _('set changeset phase to public')),
3770 3770 ('d', 'draft', False, _('set changeset phase to draft')),
3771 3771 ('s', 'secret', False, _('set changeset phase to secret')),
3772 3772 ('f', 'force', False, _('allow to move boundary backward')),
3773 3773 ('r', 'rev', [], _('target revision'), _('REV')),
3774 3774 ],
3775 3775 _('[-p|-d|-s] [-f] [-r] [REV...]'))
3776 3776 def phase(ui, repo, *revs, **opts):
3777 3777 """set or show the current phase name
3778 3778
3779 3779 With no argument, show the phase name of the current revision(s).
3780 3780
3781 3781 With one of -p/--public, -d/--draft or -s/--secret, change the
3782 3782 phase value of the specified revisions.
3783 3783
3784 3784 Unless -f/--force is specified, :hg:`phase` won't move changeset from a
3785 3785 lower phase to an higher phase. Phases are ordered as follows::
3786 3786
3787 3787 public < draft < secret
3788 3788
3789 3789 Returns 0 on success, 1 if some phases could not be changed.
3790 3790
3791 3791 (For more information about the phases concept, see :hg:`help phases`.)
3792 3792 """
3793 3793 # search for a unique phase argument
3794 3794 targetphase = None
3795 3795 for idx, name in enumerate(phases.phasenames):
3796 3796 if opts[name]:
3797 3797 if targetphase is not None:
3798 3798 raise error.Abort(_('only one phase can be specified'))
3799 3799 targetphase = idx
3800 3800
3801 3801 # look for specified revision
3802 3802 revs = list(revs)
3803 3803 revs.extend(opts['rev'])
3804 3804 if not revs:
3805 3805 # display both parents as the second parent phase can influence
3806 3806 # the phase of a merge commit
3807 3807 revs = [c.rev() for c in repo[None].parents()]
3808 3808
3809 3809 revs = scmutil.revrange(repo, revs)
3810 3810
3811 3811 lock = None
3812 3812 ret = 0
3813 3813 if targetphase is None:
3814 3814 # display
3815 3815 for r in revs:
3816 3816 ctx = repo[r]
3817 3817 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
3818 3818 else:
3819 3819 tr = None
3820 3820 lock = repo.lock()
3821 3821 try:
3822 3822 tr = repo.transaction("phase")
3823 3823 # set phase
3824 3824 if not revs:
3825 3825 raise error.Abort(_('empty revision set'))
3826 3826 nodes = [repo[r].node() for r in revs]
3827 3827 # moving revision from public to draft may hide them
3828 3828 # We have to check result on an unfiltered repository
3829 3829 unfi = repo.unfiltered()
3830 3830 getphase = unfi._phasecache.phase
3831 3831 olddata = [getphase(unfi, r) for r in unfi]
3832 3832 phases.advanceboundary(repo, tr, targetphase, nodes)
3833 3833 if opts['force']:
3834 3834 phases.retractboundary(repo, tr, targetphase, nodes)
3835 3835 tr.close()
3836 3836 finally:
3837 3837 if tr is not None:
3838 3838 tr.release()
3839 3839 lock.release()
3840 3840 getphase = unfi._phasecache.phase
3841 3841 newdata = [getphase(unfi, r) for r in unfi]
3842 3842 changes = sum(newdata[r] != olddata[r] for r in unfi)
3843 3843 cl = unfi.changelog
3844 3844 rejected = [n for n in nodes
3845 3845 if newdata[cl.rev(n)] < targetphase]
3846 3846 if rejected:
3847 3847 ui.warn(_('cannot move %i changesets to a higher '
3848 3848 'phase, use --force\n') % len(rejected))
3849 3849 ret = 1
3850 3850 if changes:
3851 3851 msg = _('phase changed for %i changesets\n') % changes
3852 3852 if ret:
3853 3853 ui.status(msg)
3854 3854 else:
3855 3855 ui.note(msg)
3856 3856 else:
3857 3857 ui.warn(_('no phases changed\n'))
3858 3858 return ret
3859 3859
3860 3860 def postincoming(ui, repo, modheads, optupdate, checkout, brev):
3861 3861 """Run after a changegroup has been added via pull/unbundle
3862 3862
3863 3863 This takes arguments below:
3864 3864
3865 3865 :modheads: change of heads by pull/unbundle
3866 3866 :optupdate: updating working directory is needed or not
3867 3867 :checkout: update destination revision (or None to default destination)
3868 3868 :brev: a name, which might be a bookmark to be activated after updating
3869 3869 """
3870 3870 if modheads == 0:
3871 3871 return
3872 3872 if optupdate:
3873 3873 try:
3874 3874 return hg.updatetotally(ui, repo, checkout, brev)
3875 3875 except error.UpdateAbort as inst:
3876 3876 msg = _("not updating: %s") % str(inst)
3877 3877 hint = inst.hint
3878 3878 raise error.UpdateAbort(msg, hint=hint)
3879 3879 if modheads > 1:
3880 3880 currentbranchheads = len(repo.branchheads())
3881 3881 if currentbranchheads == modheads:
3882 3882 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
3883 3883 elif currentbranchheads > 1:
3884 3884 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to "
3885 3885 "merge)\n"))
3886 3886 else:
3887 3887 ui.status(_("(run 'hg heads' to see heads)\n"))
3888 3888 else:
3889 3889 ui.status(_("(run 'hg update' to get a working copy)\n"))
3890 3890
3891 3891 @command('^pull',
3892 3892 [('u', 'update', None,
3893 3893 _('update to new branch head if changesets were pulled')),
3894 3894 ('f', 'force', None, _('run even when remote repository is unrelated')),
3895 3895 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3896 3896 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
3897 3897 ('b', 'branch', [], _('a specific branch you would like to pull'),
3898 3898 _('BRANCH')),
3899 3899 ] + remoteopts,
3900 3900 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
3901 3901 def pull(ui, repo, source="default", **opts):
3902 3902 """pull changes from the specified source
3903 3903
3904 3904 Pull changes from a remote repository to a local one.
3905 3905
3906 3906 This finds all changes from the repository at the specified path
3907 3907 or URL and adds them to a local repository (the current one unless
3908 3908 -R is specified). By default, this does not update the copy of the
3909 3909 project in the working directory.
3910 3910
3911 3911 Use :hg:`incoming` if you want to see what would have been added
3912 3912 by a pull at the time you issued this command. If you then decide
3913 3913 to add those changes to the repository, you should use :hg:`pull
3914 3914 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
3915 3915
3916 3916 If SOURCE is omitted, the 'default' path will be used.
3917 3917 See :hg:`help urls` for more information.
3918 3918
3919 3919 Specifying bookmark as ``.`` is equivalent to specifying the active
3920 3920 bookmark's name.
3921 3921
3922 3922 Returns 0 on success, 1 if an update had unresolved files.
3923 3923 """
3924 3924 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
3925 3925 ui.status(_('pulling from %s\n') % util.hidepassword(source))
3926 3926 other = hg.peer(repo, opts, source)
3927 3927 try:
3928 3928 revs, checkout = hg.addbranchrevs(repo, other, branches,
3929 3929 opts.get('rev'))
3930 3930
3931 3931
3932 3932 pullopargs = {}
3933 3933 if opts.get('bookmark'):
3934 3934 if not revs:
3935 3935 revs = []
3936 3936 # The list of bookmark used here is not the one used to actually
3937 3937 # update the bookmark name. This can result in the revision pulled
3938 3938 # not ending up with the name of the bookmark because of a race
3939 3939 # condition on the server. (See issue 4689 for details)
3940 3940 remotebookmarks = other.listkeys('bookmarks')
3941 3941 pullopargs['remotebookmarks'] = remotebookmarks
3942 3942 for b in opts['bookmark']:
3943 3943 b = repo._bookmarks.expandname(b)
3944 3944 if b not in remotebookmarks:
3945 3945 raise error.Abort(_('remote bookmark %s not found!') % b)
3946 3946 revs.append(remotebookmarks[b])
3947 3947
3948 3948 if revs:
3949 3949 try:
3950 3950 # When 'rev' is a bookmark name, we cannot guarantee that it
3951 3951 # will be updated with that name because of a race condition
3952 3952 # server side. (See issue 4689 for details)
3953 3953 oldrevs = revs
3954 3954 revs = [] # actually, nodes
3955 3955 for r in oldrevs:
3956 3956 node = other.lookup(r)
3957 3957 revs.append(node)
3958 3958 if r == checkout:
3959 3959 checkout = node
3960 3960 except error.CapabilityError:
3961 3961 err = _("other repository doesn't support revision lookup, "
3962 3962 "so a rev cannot be specified.")
3963 3963 raise error.Abort(err)
3964 3964
3965 3965 pullopargs.update(opts.get('opargs', {}))
3966 3966 modheads = exchange.pull(repo, other, heads=revs,
3967 3967 force=opts.get('force'),
3968 3968 bookmarks=opts.get('bookmark', ()),
3969 3969 opargs=pullopargs).cgresult
3970 3970
3971 3971 # brev is a name, which might be a bookmark to be activated at
3972 3972 # the end of the update. In other words, it is an explicit
3973 3973 # destination of the update
3974 3974 brev = None
3975 3975
3976 3976 if checkout:
3977 3977 checkout = str(repo.changelog.rev(checkout))
3978 3978
3979 3979 # order below depends on implementation of
3980 3980 # hg.addbranchrevs(). opts['bookmark'] is ignored,
3981 3981 # because 'checkout' is determined without it.
3982 3982 if opts.get('rev'):
3983 3983 brev = opts['rev'][0]
3984 3984 elif opts.get('branch'):
3985 3985 brev = opts['branch'][0]
3986 3986 else:
3987 3987 brev = branches[0]
3988 3988 repo._subtoppath = source
3989 3989 try:
3990 3990 ret = postincoming(ui, repo, modheads, opts.get('update'),
3991 3991 checkout, brev)
3992 3992
3993 3993 finally:
3994 3994 del repo._subtoppath
3995 3995
3996 3996 finally:
3997 3997 other.close()
3998 3998 return ret
3999 3999
4000 4000 @command('^push',
4001 4001 [('f', 'force', None, _('force push')),
4002 4002 ('r', 'rev', [],
4003 4003 _('a changeset intended to be included in the destination'),
4004 4004 _('REV')),
4005 4005 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4006 4006 ('b', 'branch', [],
4007 4007 _('a specific branch you would like to push'), _('BRANCH')),
4008 4008 ('', 'new-branch', False, _('allow pushing a new branch')),
4009 4009 ] + remoteopts,
4010 4010 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
4011 4011 def push(ui, repo, dest=None, **opts):
4012 4012 """push changes to the specified destination
4013 4013
4014 4014 Push changesets from the local repository to the specified
4015 4015 destination.
4016 4016
4017 4017 This operation is symmetrical to pull: it is identical to a pull
4018 4018 in the destination repository from the current one.
4019 4019
4020 4020 By default, push will not allow creation of new heads at the
4021 4021 destination, since multiple heads would make it unclear which head
4022 4022 to use. In this situation, it is recommended to pull and merge
4023 4023 before pushing.
4024 4024
4025 4025 Use --new-branch if you want to allow push to create a new named
4026 4026 branch that is not present at the destination. This allows you to
4027 4027 only create a new branch without forcing other changes.
4028 4028
4029 4029 .. note::
4030 4030
4031 4031 Extra care should be taken with the -f/--force option,
4032 4032 which will push all new heads on all branches, an action which will
4033 4033 almost always cause confusion for collaborators.
4034 4034
4035 4035 If -r/--rev is used, the specified revision and all its ancestors
4036 4036 will be pushed to the remote repository.
4037 4037
4038 4038 If -B/--bookmark is used, the specified bookmarked revision, its
4039 4039 ancestors, and the bookmark will be pushed to the remote
4040 4040 repository. Specifying ``.`` is equivalent to specifying the active
4041 4041 bookmark's name.
4042 4042
4043 4043 Please see :hg:`help urls` for important details about ``ssh://``
4044 4044 URLs. If DESTINATION is omitted, a default path will be used.
4045 4045
4046 4046 Returns 0 if push was successful, 1 if nothing to push.
4047 4047 """
4048 4048
4049 4049 if opts.get('bookmark'):
4050 4050 ui.setconfig('bookmarks', 'pushing', opts['bookmark'], 'push')
4051 4051 for b in opts['bookmark']:
4052 4052 # translate -B options to -r so changesets get pushed
4053 4053 b = repo._bookmarks.expandname(b)
4054 4054 if b in repo._bookmarks:
4055 4055 opts.setdefault('rev', []).append(b)
4056 4056 else:
4057 4057 # if we try to push a deleted bookmark, translate it to null
4058 4058 # this lets simultaneous -r, -b options continue working
4059 4059 opts.setdefault('rev', []).append("null")
4060 4060
4061 4061 path = ui.paths.getpath(dest, default=('default-push', 'default'))
4062 4062 if not path:
4063 4063 raise error.Abort(_('default repository not configured!'),
4064 4064 hint=_("see 'hg help config.paths'"))
4065 4065 dest = path.pushloc or path.loc
4066 4066 branches = (path.branch, opts.get('branch') or [])
4067 4067 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
4068 4068 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
4069 4069 other = hg.peer(repo, opts, dest)
4070 4070
4071 4071 if revs:
4072 4072 revs = [repo.lookup(r) for r in scmutil.revrange(repo, revs)]
4073 4073 if not revs:
4074 4074 raise error.Abort(_("specified revisions evaluate to an empty set"),
4075 4075 hint=_("use different revision arguments"))
4076 4076 elif path.pushrev:
4077 4077 # It doesn't make any sense to specify ancestor revisions. So limit
4078 4078 # to DAG heads to make discovery simpler.
4079 4079 expr = revsetlang.formatspec('heads(%r)', path.pushrev)
4080 4080 revs = scmutil.revrange(repo, [expr])
4081 4081 revs = [repo[rev].node() for rev in revs]
4082 4082 if not revs:
4083 4083 raise error.Abort(_('default push revset for path evaluates to an '
4084 4084 'empty set'))
4085 4085
4086 4086 repo._subtoppath = dest
4087 4087 try:
4088 4088 # push subrepos depth-first for coherent ordering
4089 4089 c = repo['']
4090 4090 subs = c.substate # only repos that are committed
4091 4091 for s in sorted(subs):
4092 4092 result = c.sub(s).push(opts)
4093 4093 if result == 0:
4094 4094 return not result
4095 4095 finally:
4096 4096 del repo._subtoppath
4097 4097 pushop = exchange.push(repo, other, opts.get('force'), revs=revs,
4098 4098 newbranch=opts.get('new_branch'),
4099 4099 bookmarks=opts.get('bookmark', ()),
4100 4100 opargs=opts.get('opargs'))
4101 4101
4102 4102 result = not pushop.cgresult
4103 4103
4104 4104 if pushop.bkresult is not None:
4105 4105 if pushop.bkresult == 2:
4106 4106 result = 2
4107 4107 elif not result and pushop.bkresult:
4108 4108 result = 2
4109 4109
4110 4110 return result
4111 4111
4112 4112 @command('recover', [])
4113 4113 def recover(ui, repo):
4114 4114 """roll back an interrupted transaction
4115 4115
4116 4116 Recover from an interrupted commit or pull.
4117 4117
4118 4118 This command tries to fix the repository status after an
4119 4119 interrupted operation. It should only be necessary when Mercurial
4120 4120 suggests it.
4121 4121
4122 4122 Returns 0 if successful, 1 if nothing to recover or verify fails.
4123 4123 """
4124 4124 if repo.recover():
4125 4125 return hg.verify(repo)
4126 4126 return 1
4127 4127
4128 4128 @command('^remove|rm',
4129 4129 [('A', 'after', None, _('record delete for missing files')),
4130 4130 ('f', 'force', None,
4131 4131 _('forget added files, delete modified files')),
4132 4132 ] + subrepoopts + walkopts,
4133 4133 _('[OPTION]... FILE...'),
4134 4134 inferrepo=True)
4135 4135 def remove(ui, repo, *pats, **opts):
4136 4136 """remove the specified files on the next commit
4137 4137
4138 4138 Schedule the indicated files for removal from the current branch.
4139 4139
4140 4140 This command schedules the files to be removed at the next commit.
4141 4141 To undo a remove before that, see :hg:`revert`. To undo added
4142 4142 files, see :hg:`forget`.
4143 4143
4144 4144 .. container:: verbose
4145 4145
4146 4146 -A/--after can be used to remove only files that have already
4147 4147 been deleted, -f/--force can be used to force deletion, and -Af
4148 4148 can be used to remove files from the next revision without
4149 4149 deleting them from the working directory.
4150 4150
4151 4151 The following table details the behavior of remove for different
4152 4152 file states (columns) and option combinations (rows). The file
4153 4153 states are Added [A], Clean [C], Modified [M] and Missing [!]
4154 4154 (as reported by :hg:`status`). The actions are Warn, Remove
4155 4155 (from branch) and Delete (from disk):
4156 4156
4157 4157 ========= == == == ==
4158 4158 opt/state A C M !
4159 4159 ========= == == == ==
4160 4160 none W RD W R
4161 4161 -f R RD RD R
4162 4162 -A W W W R
4163 4163 -Af R R R R
4164 4164 ========= == == == ==
4165 4165
4166 4166 .. note::
4167 4167
4168 4168 :hg:`remove` never deletes files in Added [A] state from the
4169 4169 working directory, not even if ``--force`` is specified.
4170 4170
4171 4171 Returns 0 on success, 1 if any warnings encountered.
4172 4172 """
4173 4173
4174 4174 after, force = opts.get('after'), opts.get('force')
4175 4175 if not pats and not after:
4176 4176 raise error.Abort(_('no files specified'))
4177 4177
4178 4178 m = scmutil.match(repo[None], pats, opts)
4179 4179 subrepos = opts.get('subrepos')
4180 4180 return cmdutil.remove(ui, repo, m, "", after, force, subrepos)
4181 4181
4182 4182 @command('rename|move|mv',
4183 4183 [('A', 'after', None, _('record a rename that has already occurred')),
4184 4184 ('f', 'force', None, _('forcibly copy over an existing managed file')),
4185 4185 ] + walkopts + dryrunopts,
4186 4186 _('[OPTION]... SOURCE... DEST'))
4187 4187 def rename(ui, repo, *pats, **opts):
4188 4188 """rename files; equivalent of copy + remove
4189 4189
4190 4190 Mark dest as copies of sources; mark sources for deletion. If dest
4191 4191 is a directory, copies are put in that directory. If dest is a
4192 4192 file, there can only be one source.
4193 4193
4194 4194 By default, this command copies the contents of files as they
4195 4195 exist in the working directory. If invoked with -A/--after, the
4196 4196 operation is recorded, but no copying is performed.
4197 4197
4198 4198 This command takes effect at the next commit. To undo a rename
4199 4199 before that, see :hg:`revert`.
4200 4200
4201 4201 Returns 0 on success, 1 if errors are encountered.
4202 4202 """
4203 4203 with repo.wlock(False):
4204 4204 return cmdutil.copy(ui, repo, pats, opts, rename=True)
4205 4205
4206 4206 @command('resolve',
4207 4207 [('a', 'all', None, _('select all unresolved files')),
4208 4208 ('l', 'list', None, _('list state of files needing merge')),
4209 4209 ('m', 'mark', None, _('mark files as resolved')),
4210 4210 ('u', 'unmark', None, _('mark files as unresolved')),
4211 4211 ('n', 'no-status', None, _('hide status prefix'))]
4212 4212 + mergetoolopts + walkopts + formatteropts,
4213 4213 _('[OPTION]... [FILE]...'),
4214 4214 inferrepo=True)
4215 4215 def resolve(ui, repo, *pats, **opts):
4216 4216 """redo merges or set/view the merge status of files
4217 4217
4218 4218 Merges with unresolved conflicts are often the result of
4219 4219 non-interactive merging using the ``internal:merge`` configuration
4220 4220 setting, or a command-line merge tool like ``diff3``. The resolve
4221 4221 command is used to manage the files involved in a merge, after
4222 4222 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4223 4223 working directory must have two parents). See :hg:`help
4224 4224 merge-tools` for information on configuring merge tools.
4225 4225
4226 4226 The resolve command can be used in the following ways:
4227 4227
4228 4228 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4229 4229 files, discarding any previous merge attempts. Re-merging is not
4230 4230 performed for files already marked as resolved. Use ``--all/-a``
4231 4231 to select all unresolved files. ``--tool`` can be used to specify
4232 4232 the merge tool used for the given files. It overrides the HGMERGE
4233 4233 environment variable and your configuration files. Previous file
4234 4234 contents are saved with a ``.orig`` suffix.
4235 4235
4236 4236 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4237 4237 (e.g. after having manually fixed-up the files). The default is
4238 4238 to mark all unresolved files.
4239 4239
4240 4240 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4241 4241 default is to mark all resolved files.
4242 4242
4243 4243 - :hg:`resolve -l`: list files which had or still have conflicts.
4244 4244 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4245 4245 You can use ``set:unresolved()`` or ``set:resolved()`` to filter
4246 4246 the list. See :hg:`help filesets` for details.
4247 4247
4248 4248 .. note::
4249 4249
4250 4250 Mercurial will not let you commit files with unresolved merge
4251 4251 conflicts. You must use :hg:`resolve -m ...` before you can
4252 4252 commit after a conflicting merge.
4253 4253
4254 4254 Returns 0 on success, 1 if any files fail a resolve attempt.
4255 4255 """
4256 4256
4257 4257 flaglist = 'all mark unmark list no_status'.split()
4258 4258 all, mark, unmark, show, nostatus = \
4259 4259 [opts.get(o) for o in flaglist]
4260 4260
4261 4261 if (show and (mark or unmark)) or (mark and unmark):
4262 4262 raise error.Abort(_("too many options specified"))
4263 4263 if pats and all:
4264 4264 raise error.Abort(_("can't specify --all and patterns"))
4265 4265 if not (all or pats or show or mark or unmark):
4266 4266 raise error.Abort(_('no files or directories specified'),
4267 4267 hint=('use --all to re-merge all unresolved files'))
4268 4268
4269 4269 if show:
4270 4270 ui.pager('resolve')
4271 4271 fm = ui.formatter('resolve', opts)
4272 4272 ms = mergemod.mergestate.read(repo)
4273 4273 m = scmutil.match(repo[None], pats, opts)
4274 4274 for f in ms:
4275 4275 if not m(f):
4276 4276 continue
4277 4277 l = 'resolve.' + {'u': 'unresolved', 'r': 'resolved',
4278 4278 'd': 'driverresolved'}[ms[f]]
4279 4279 fm.startitem()
4280 4280 fm.condwrite(not nostatus, 'status', '%s ', ms[f].upper(), label=l)
4281 4281 fm.write('path', '%s\n', f, label=l)
4282 4282 fm.end()
4283 4283 return 0
4284 4284
4285 4285 with repo.wlock():
4286 4286 ms = mergemod.mergestate.read(repo)
4287 4287
4288 4288 if not (ms.active() or repo.dirstate.p2() != nullid):
4289 4289 raise error.Abort(
4290 4290 _('resolve command not applicable when not merging'))
4291 4291
4292 4292 wctx = repo[None]
4293 4293
4294 4294 if ms.mergedriver and ms.mdstate() == 'u':
4295 4295 proceed = mergemod.driverpreprocess(repo, ms, wctx)
4296 4296 ms.commit()
4297 4297 # allow mark and unmark to go through
4298 4298 if not mark and not unmark and not proceed:
4299 4299 return 1
4300 4300
4301 4301 m = scmutil.match(wctx, pats, opts)
4302 4302 ret = 0
4303 4303 didwork = False
4304 4304 runconclude = False
4305 4305
4306 4306 tocomplete = []
4307 4307 for f in ms:
4308 4308 if not m(f):
4309 4309 continue
4310 4310
4311 4311 didwork = True
4312 4312
4313 4313 # don't let driver-resolved files be marked, and run the conclude
4314 4314 # step if asked to resolve
4315 4315 if ms[f] == "d":
4316 4316 exact = m.exact(f)
4317 4317 if mark:
4318 4318 if exact:
4319 4319 ui.warn(_('not marking %s as it is driver-resolved\n')
4320 4320 % f)
4321 4321 elif unmark:
4322 4322 if exact:
4323 4323 ui.warn(_('not unmarking %s as it is driver-resolved\n')
4324 4324 % f)
4325 4325 else:
4326 4326 runconclude = True
4327 4327 continue
4328 4328
4329 4329 if mark:
4330 4330 ms.mark(f, "r")
4331 4331 elif unmark:
4332 4332 ms.mark(f, "u")
4333 4333 else:
4334 4334 # backup pre-resolve (merge uses .orig for its own purposes)
4335 4335 a = repo.wjoin(f)
4336 4336 try:
4337 4337 util.copyfile(a, a + ".resolve")
4338 4338 except (IOError, OSError) as inst:
4339 4339 if inst.errno != errno.ENOENT:
4340 4340 raise
4341 4341
4342 4342 try:
4343 4343 # preresolve file
4344 4344 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
4345 4345 'resolve')
4346 4346 complete, r = ms.preresolve(f, wctx)
4347 4347 if not complete:
4348 4348 tocomplete.append(f)
4349 4349 elif r:
4350 4350 ret = 1
4351 4351 finally:
4352 4352 ui.setconfig('ui', 'forcemerge', '', 'resolve')
4353 4353 ms.commit()
4354 4354
4355 4355 # replace filemerge's .orig file with our resolve file, but only
4356 4356 # for merges that are complete
4357 4357 if complete:
4358 4358 try:
4359 4359 util.rename(a + ".resolve",
4360 4360 scmutil.origpath(ui, repo, a))
4361 4361 except OSError as inst:
4362 4362 if inst.errno != errno.ENOENT:
4363 4363 raise
4364 4364
4365 4365 for f in tocomplete:
4366 4366 try:
4367 4367 # resolve file
4368 4368 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
4369 4369 'resolve')
4370 4370 r = ms.resolve(f, wctx)
4371 4371 if r:
4372 4372 ret = 1
4373 4373 finally:
4374 4374 ui.setconfig('ui', 'forcemerge', '', 'resolve')
4375 4375 ms.commit()
4376 4376
4377 4377 # replace filemerge's .orig file with our resolve file
4378 4378 a = repo.wjoin(f)
4379 4379 try:
4380 4380 util.rename(a + ".resolve", scmutil.origpath(ui, repo, a))
4381 4381 except OSError as inst:
4382 4382 if inst.errno != errno.ENOENT:
4383 4383 raise
4384 4384
4385 4385 ms.commit()
4386 4386 ms.recordactions()
4387 4387
4388 4388 if not didwork and pats:
4389 4389 hint = None
4390 4390 if not any([p for p in pats if p.find(':') >= 0]):
4391 4391 pats = ['path:%s' % p for p in pats]
4392 4392 m = scmutil.match(wctx, pats, opts)
4393 4393 for f in ms:
4394 4394 if not m(f):
4395 4395 continue
4396 4396 flags = ''.join(['-%s ' % o[0] for o in flaglist
4397 4397 if opts.get(o)])
4398 4398 hint = _("(try: hg resolve %s%s)\n") % (
4399 4399 flags,
4400 4400 ' '.join(pats))
4401 4401 break
4402 4402 ui.warn(_("arguments do not match paths that need resolving\n"))
4403 4403 if hint:
4404 4404 ui.warn(hint)
4405 4405 elif ms.mergedriver and ms.mdstate() != 's':
4406 4406 # run conclude step when either a driver-resolved file is requested
4407 4407 # or there are no driver-resolved files
4408 4408 # we can't use 'ret' to determine whether any files are unresolved
4409 4409 # because we might not have tried to resolve some
4410 4410 if ((runconclude or not list(ms.driverresolved()))
4411 4411 and not list(ms.unresolved())):
4412 4412 proceed = mergemod.driverconclude(repo, ms, wctx)
4413 4413 ms.commit()
4414 4414 if not proceed:
4415 4415 return 1
4416 4416
4417 4417 # Nudge users into finishing an unfinished operation
4418 4418 unresolvedf = list(ms.unresolved())
4419 4419 driverresolvedf = list(ms.driverresolved())
4420 4420 if not unresolvedf and not driverresolvedf:
4421 4421 ui.status(_('(no more unresolved files)\n'))
4422 4422 cmdutil.checkafterresolved(repo)
4423 4423 elif not unresolvedf:
4424 4424 ui.status(_('(no more unresolved files -- '
4425 4425 'run "hg resolve --all" to conclude)\n'))
4426 4426
4427 4427 return ret
4428 4428
4429 4429 @command('revert',
4430 4430 [('a', 'all', None, _('revert all changes when no arguments given')),
4431 4431 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4432 4432 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
4433 4433 ('C', 'no-backup', None, _('do not save backup copies of files')),
4434 4434 ('i', 'interactive', None,
4435 4435 _('interactively select the changes (EXPERIMENTAL)')),
4436 4436 ] + walkopts + dryrunopts,
4437 4437 _('[OPTION]... [-r REV] [NAME]...'))
4438 4438 def revert(ui, repo, *pats, **opts):
4439 4439 """restore files to their checkout state
4440 4440
4441 4441 .. note::
4442 4442
4443 4443 To check out earlier revisions, you should use :hg:`update REV`.
4444 4444 To cancel an uncommitted merge (and lose your changes),
4445 4445 use :hg:`update --clean .`.
4446 4446
4447 4447 With no revision specified, revert the specified files or directories
4448 4448 to the contents they had in the parent of the working directory.
4449 4449 This restores the contents of files to an unmodified
4450 4450 state and unschedules adds, removes, copies, and renames. If the
4451 4451 working directory has two parents, you must explicitly specify a
4452 4452 revision.
4453 4453
4454 4454 Using the -r/--rev or -d/--date options, revert the given files or
4455 4455 directories to their states as of a specific revision. Because
4456 4456 revert does not change the working directory parents, this will
4457 4457 cause these files to appear modified. This can be helpful to "back
4458 4458 out" some or all of an earlier change. See :hg:`backout` for a
4459 4459 related method.
4460 4460
4461 4461 Modified files are saved with a .orig suffix before reverting.
4462 4462 To disable these backups, use --no-backup. It is possible to store
4463 4463 the backup files in a custom directory relative to the root of the
4464 4464 repository by setting the ``ui.origbackuppath`` configuration
4465 4465 option.
4466 4466
4467 4467 See :hg:`help dates` for a list of formats valid for -d/--date.
4468 4468
4469 4469 See :hg:`help backout` for a way to reverse the effect of an
4470 4470 earlier changeset.
4471 4471
4472 4472 Returns 0 on success.
4473 4473 """
4474 4474
4475 4475 if opts.get("date"):
4476 4476 if opts.get("rev"):
4477 4477 raise error.Abort(_("you can't specify a revision and a date"))
4478 4478 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
4479 4479
4480 4480 parent, p2 = repo.dirstate.parents()
4481 4481 if not opts.get('rev') and p2 != nullid:
4482 4482 # revert after merge is a trap for new users (issue2915)
4483 4483 raise error.Abort(_('uncommitted merge with no revision specified'),
4484 4484 hint=_("use 'hg update' or see 'hg help revert'"))
4485 4485
4486 4486 ctx = scmutil.revsingle(repo, opts.get('rev'))
4487 4487
4488 4488 if (not (pats or opts.get('include') or opts.get('exclude') or
4489 4489 opts.get('all') or opts.get('interactive'))):
4490 4490 msg = _("no files or directories specified")
4491 4491 if p2 != nullid:
4492 4492 hint = _("uncommitted merge, use --all to discard all changes,"
4493 4493 " or 'hg update -C .' to abort the merge")
4494 4494 raise error.Abort(msg, hint=hint)
4495 4495 dirty = any(repo.status())
4496 4496 node = ctx.node()
4497 4497 if node != parent:
4498 4498 if dirty:
4499 4499 hint = _("uncommitted changes, use --all to discard all"
4500 4500 " changes, or 'hg update %s' to update") % ctx.rev()
4501 4501 else:
4502 4502 hint = _("use --all to revert all files,"
4503 4503 " or 'hg update %s' to update") % ctx.rev()
4504 4504 elif dirty:
4505 4505 hint = _("uncommitted changes, use --all to discard all changes")
4506 4506 else:
4507 4507 hint = _("use --all to revert all files")
4508 4508 raise error.Abort(msg, hint=hint)
4509 4509
4510 4510 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats, **opts)
4511 4511
4512 4512 @command('rollback', dryrunopts +
4513 4513 [('f', 'force', False, _('ignore safety measures'))])
4514 4514 def rollback(ui, repo, **opts):
4515 4515 """roll back the last transaction (DANGEROUS) (DEPRECATED)
4516 4516
4517 4517 Please use :hg:`commit --amend` instead of rollback to correct
4518 4518 mistakes in the last commit.
4519 4519
4520 4520 This command should be used with care. There is only one level of
4521 4521 rollback, and there is no way to undo a rollback. It will also
4522 4522 restore the dirstate at the time of the last transaction, losing
4523 4523 any dirstate changes since that time. This command does not alter
4524 4524 the working directory.
4525 4525
4526 4526 Transactions are used to encapsulate the effects of all commands
4527 4527 that create new changesets or propagate existing changesets into a
4528 4528 repository.
4529 4529
4530 4530 .. container:: verbose
4531 4531
4532 4532 For example, the following commands are transactional, and their
4533 4533 effects can be rolled back:
4534 4534
4535 4535 - commit
4536 4536 - import
4537 4537 - pull
4538 4538 - push (with this repository as the destination)
4539 4539 - unbundle
4540 4540
4541 4541 To avoid permanent data loss, rollback will refuse to rollback a
4542 4542 commit transaction if it isn't checked out. Use --force to
4543 4543 override this protection.
4544 4544
4545 4545 The rollback command can be entirely disabled by setting the
4546 4546 ``ui.rollback`` configuration setting to false. If you're here
4547 4547 because you want to use rollback and it's disabled, you can
4548 4548 re-enable the command by setting ``ui.rollback`` to true.
4549 4549
4550 4550 This command is not intended for use on public repositories. Once
4551 4551 changes are visible for pull by other users, rolling a transaction
4552 4552 back locally is ineffective (someone else may already have pulled
4553 4553 the changes). Furthermore, a race is possible with readers of the
4554 4554 repository; for example an in-progress pull from the repository
4555 4555 may fail if a rollback is performed.
4556 4556
4557 4557 Returns 0 on success, 1 if no rollback data is available.
4558 4558 """
4559 4559 if not ui.configbool('ui', 'rollback', True):
4560 4560 raise error.Abort(_('rollback is disabled because it is unsafe'),
4561 4561 hint=('see `hg help -v rollback` for information'))
4562 4562 return repo.rollback(dryrun=opts.get('dry_run'),
4563 4563 force=opts.get('force'))
4564 4564
4565 4565 @command('root', [])
4566 4566 def root(ui, repo):
4567 4567 """print the root (top) of the current working directory
4568 4568
4569 4569 Print the root directory of the current repository.
4570 4570
4571 4571 Returns 0 on success.
4572 4572 """
4573 4573 ui.write(repo.root + "\n")
4574 4574
4575 4575 @command('^serve',
4576 4576 [('A', 'accesslog', '', _('name of access log file to write to'),
4577 4577 _('FILE')),
4578 4578 ('d', 'daemon', None, _('run server in background')),
4579 4579 ('', 'daemon-postexec', [], _('used internally by daemon mode')),
4580 4580 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
4581 4581 # use string type, then we can check if something was passed
4582 4582 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
4583 4583 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
4584 4584 _('ADDR')),
4585 4585 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
4586 4586 _('PREFIX')),
4587 4587 ('n', 'name', '',
4588 4588 _('name to show in web pages (default: working directory)'), _('NAME')),
4589 4589 ('', 'web-conf', '',
4590 4590 _("name of the hgweb config file (see 'hg help hgweb')"), _('FILE')),
4591 4591 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
4592 4592 _('FILE')),
4593 4593 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
4594 4594 ('', 'stdio', None, _('for remote clients (ADVANCED)')),
4595 4595 ('', 'cmdserver', '', _('for remote clients (ADVANCED)'), _('MODE')),
4596 4596 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
4597 4597 ('', 'style', '', _('template style to use'), _('STYLE')),
4598 4598 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
4599 4599 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
4600 4600 _('[OPTION]...'),
4601 4601 optionalrepo=True)
4602 4602 def serve(ui, repo, **opts):
4603 4603 """start stand-alone webserver
4604 4604
4605 4605 Start a local HTTP repository browser and pull server. You can use
4606 4606 this for ad-hoc sharing and browsing of repositories. It is
4607 4607 recommended to use a real web server to serve a repository for
4608 4608 longer periods of time.
4609 4609
4610 4610 Please note that the server does not implement access control.
4611 4611 This means that, by default, anybody can read from the server and
4612 4612 nobody can write to it by default. Set the ``web.allow_push``
4613 4613 option to ``*`` to allow everybody to push to the server. You
4614 4614 should use a real web server if you need to authenticate users.
4615 4615
4616 4616 By default, the server logs accesses to stdout and errors to
4617 4617 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
4618 4618 files.
4619 4619
4620 4620 To have the server choose a free port number to listen on, specify
4621 4621 a port number of 0; in this case, the server will print the port
4622 4622 number it uses.
4623 4623
4624 4624 Returns 0 on success.
4625 4625 """
4626 4626
4627 4627 if opts["stdio"] and opts["cmdserver"]:
4628 4628 raise error.Abort(_("cannot use --stdio with --cmdserver"))
4629 4629
4630 4630 if opts["stdio"]:
4631 4631 if repo is None:
4632 4632 raise error.RepoError(_("there is no Mercurial repository here"
4633 4633 " (.hg not found)"))
4634 4634 s = sshserver.sshserver(ui, repo)
4635 4635 s.serve_forever()
4636 4636
4637 4637 service = server.createservice(ui, repo, opts)
4638 4638 return server.runservice(opts, initfn=service.init, runfn=service.run)
4639 4639
4640 4640 @command('^status|st',
4641 4641 [('A', 'all', None, _('show status of all files')),
4642 4642 ('m', 'modified', None, _('show only modified files')),
4643 4643 ('a', 'added', None, _('show only added files')),
4644 4644 ('r', 'removed', None, _('show only removed files')),
4645 4645 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
4646 4646 ('c', 'clean', None, _('show only files without changes')),
4647 4647 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
4648 4648 ('i', 'ignored', None, _('show only ignored files')),
4649 4649 ('n', 'no-status', None, _('hide status prefix')),
4650 4650 ('C', 'copies', None, _('show source of copied files')),
4651 4651 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
4652 4652 ('', 'rev', [], _('show difference from revision'), _('REV')),
4653 4653 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
4654 4654 ] + walkopts + subrepoopts + formatteropts,
4655 4655 _('[OPTION]... [FILE]...'),
4656 4656 inferrepo=True)
4657 4657 def status(ui, repo, *pats, **opts):
4658 4658 """show changed files in the working directory
4659 4659
4660 4660 Show status of files in the repository. If names are given, only
4661 4661 files that match are shown. Files that are clean or ignored or
4662 4662 the source of a copy/move operation, are not listed unless
4663 4663 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
4664 4664 Unless options described with "show only ..." are given, the
4665 4665 options -mardu are used.
4666 4666
4667 4667 Option -q/--quiet hides untracked (unknown and ignored) files
4668 4668 unless explicitly requested with -u/--unknown or -i/--ignored.
4669 4669
4670 4670 .. note::
4671 4671
4672 4672 :hg:`status` may appear to disagree with diff if permissions have
4673 4673 changed or a merge has occurred. The standard diff format does
4674 4674 not report permission changes and diff only reports changes
4675 4675 relative to one merge parent.
4676 4676
4677 4677 If one revision is given, it is used as the base revision.
4678 4678 If two revisions are given, the differences between them are
4679 4679 shown. The --change option can also be used as a shortcut to list
4680 4680 the changed files of a revision from its first parent.
4681 4681
4682 4682 The codes used to show the status of files are::
4683 4683
4684 4684 M = modified
4685 4685 A = added
4686 4686 R = removed
4687 4687 C = clean
4688 4688 ! = missing (deleted by non-hg command, but still tracked)
4689 4689 ? = not tracked
4690 4690 I = ignored
4691 4691 = origin of the previous file (with --copies)
4692 4692
4693 4693 .. container:: verbose
4694 4694
4695 4695 Examples:
4696 4696
4697 4697 - show changes in the working directory relative to a
4698 4698 changeset::
4699 4699
4700 4700 hg status --rev 9353
4701 4701
4702 4702 - show changes in the working directory relative to the
4703 4703 current directory (see :hg:`help patterns` for more information)::
4704 4704
4705 4705 hg status re:
4706 4706
4707 4707 - show all changes including copies in an existing changeset::
4708 4708
4709 4709 hg status --copies --change 9353
4710 4710
4711 4711 - get a NUL separated list of added files, suitable for xargs::
4712 4712
4713 4713 hg status -an0
4714 4714
4715 4715 Returns 0 on success.
4716 4716 """
4717 4717
4718 4718 revs = opts.get('rev')
4719 4719 change = opts.get('change')
4720 4720
4721 4721 if revs and change:
4722 4722 msg = _('cannot specify --rev and --change at the same time')
4723 4723 raise error.Abort(msg)
4724 4724 elif change:
4725 4725 node2 = scmutil.revsingle(repo, change, None).node()
4726 4726 node1 = repo[node2].p1().node()
4727 4727 else:
4728 4728 node1, node2 = scmutil.revpair(repo, revs)
4729 4729
4730 4730 if pats:
4731 4731 cwd = repo.getcwd()
4732 4732 else:
4733 4733 cwd = ''
4734 4734
4735 4735 if opts.get('print0'):
4736 4736 end = '\0'
4737 4737 else:
4738 4738 end = '\n'
4739 4739 copy = {}
4740 4740 states = 'modified added removed deleted unknown ignored clean'.split()
4741 4741 show = [k for k in states if opts.get(k)]
4742 4742 if opts.get('all'):
4743 4743 show += ui.quiet and (states[:4] + ['clean']) or states
4744 4744 if not show:
4745 4745 if ui.quiet:
4746 4746 show = states[:4]
4747 4747 else:
4748 4748 show = states[:5]
4749 4749
4750 4750 m = scmutil.match(repo[node2], pats, opts)
4751 4751 stat = repo.status(node1, node2, m,
4752 4752 'ignored' in show, 'clean' in show, 'unknown' in show,
4753 4753 opts.get('subrepos'))
4754 4754 changestates = zip(states, 'MAR!?IC', stat)
4755 4755
4756 4756 if (opts.get('all') or opts.get('copies')
4757 4757 or ui.configbool('ui', 'statuscopies')) and not opts.get('no_status'):
4758 4758 copy = copies.pathcopies(repo[node1], repo[node2], m)
4759 4759
4760 4760 ui.pager('status')
4761 4761 fm = ui.formatter('status', opts)
4762 4762 fmt = '%s' + end
4763 4763 showchar = not opts.get('no_status')
4764 4764
4765 4765 for state, char, files in changestates:
4766 4766 if state in show:
4767 4767 label = 'status.' + state
4768 4768 for f in files:
4769 4769 fm.startitem()
4770 4770 fm.condwrite(showchar, 'status', '%s ', char, label=label)
4771 4771 fm.write('path', fmt, repo.pathto(f, cwd), label=label)
4772 4772 if f in copy:
4773 4773 fm.write("copy", ' %s' + end, repo.pathto(copy[f], cwd),
4774 4774 label='status.copied')
4775 4775 fm.end()
4776 4776
4777 4777 @command('^summary|sum',
4778 4778 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
4779 4779 def summary(ui, repo, **opts):
4780 4780 """summarize working directory state
4781 4781
4782 4782 This generates a brief summary of the working directory state,
4783 4783 including parents, branch, commit status, phase and available updates.
4784 4784
4785 4785 With the --remote option, this will check the default paths for
4786 4786 incoming and outgoing changes. This can be time-consuming.
4787 4787
4788 4788 Returns 0 on success.
4789 4789 """
4790 4790
4791 4791 ui.pager('summary')
4792 4792 ctx = repo[None]
4793 4793 parents = ctx.parents()
4794 4794 pnode = parents[0].node()
4795 4795 marks = []
4796 4796
4797 4797 ms = None
4798 4798 try:
4799 4799 ms = mergemod.mergestate.read(repo)
4800 4800 except error.UnsupportedMergeRecords as e:
4801 4801 s = ' '.join(e.recordtypes)
4802 4802 ui.warn(
4803 4803 _('warning: merge state has unsupported record types: %s\n') % s)
4804 4804 unresolved = 0
4805 4805 else:
4806 4806 unresolved = [f for f in ms if ms[f] == 'u']
4807 4807
4808 4808 for p in parents:
4809 4809 # label with log.changeset (instead of log.parent) since this
4810 4810 # shows a working directory parent *changeset*:
4811 4811 # i18n: column positioning for "hg summary"
4812 4812 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
4813 4813 label=cmdutil._changesetlabels(p))
4814 4814 ui.write(' '.join(p.tags()), label='log.tag')
4815 4815 if p.bookmarks():
4816 4816 marks.extend(p.bookmarks())
4817 4817 if p.rev() == -1:
4818 4818 if not len(repo):
4819 4819 ui.write(_(' (empty repository)'))
4820 4820 else:
4821 4821 ui.write(_(' (no revision checked out)'))
4822 4822 if p.troubled():
4823 4823 ui.write(' ('
4824 4824 + ', '.join(ui.label(trouble, 'trouble.%s' % trouble)
4825 4825 for trouble in p.troubles())
4826 4826 + ')')
4827 4827 ui.write('\n')
4828 4828 if p.description():
4829 4829 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
4830 4830 label='log.summary')
4831 4831
4832 4832 branch = ctx.branch()
4833 4833 bheads = repo.branchheads(branch)
4834 4834 # i18n: column positioning for "hg summary"
4835 4835 m = _('branch: %s\n') % branch
4836 4836 if branch != 'default':
4837 4837 ui.write(m, label='log.branch')
4838 4838 else:
4839 4839 ui.status(m, label='log.branch')
4840 4840
4841 4841 if marks:
4842 4842 active = repo._activebookmark
4843 4843 # i18n: column positioning for "hg summary"
4844 4844 ui.write(_('bookmarks:'), label='log.bookmark')
4845 4845 if active is not None:
4846 4846 if active in marks:
4847 4847 ui.write(' *' + active, label=activebookmarklabel)
4848 4848 marks.remove(active)
4849 4849 else:
4850 4850 ui.write(' [%s]' % active, label=activebookmarklabel)
4851 4851 for m in marks:
4852 4852 ui.write(' ' + m, label='log.bookmark')
4853 4853 ui.write('\n', label='log.bookmark')
4854 4854
4855 4855 status = repo.status(unknown=True)
4856 4856
4857 4857 c = repo.dirstate.copies()
4858 4858 copied, renamed = [], []
4859 4859 for d, s in c.iteritems():
4860 4860 if s in status.removed:
4861 4861 status.removed.remove(s)
4862 4862 renamed.append(d)
4863 4863 else:
4864 4864 copied.append(d)
4865 4865 if d in status.added:
4866 4866 status.added.remove(d)
4867 4867
4868 4868 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
4869 4869
4870 4870 labels = [(ui.label(_('%d modified'), 'status.modified'), status.modified),
4871 4871 (ui.label(_('%d added'), 'status.added'), status.added),
4872 4872 (ui.label(_('%d removed'), 'status.removed'), status.removed),
4873 4873 (ui.label(_('%d renamed'), 'status.copied'), renamed),
4874 4874 (ui.label(_('%d copied'), 'status.copied'), copied),
4875 4875 (ui.label(_('%d deleted'), 'status.deleted'), status.deleted),
4876 4876 (ui.label(_('%d unknown'), 'status.unknown'), status.unknown),
4877 4877 (ui.label(_('%d unresolved'), 'resolve.unresolved'), unresolved),
4878 4878 (ui.label(_('%d subrepos'), 'status.modified'), subs)]
4879 4879 t = []
4880 4880 for l, s in labels:
4881 4881 if s:
4882 4882 t.append(l % len(s))
4883 4883
4884 4884 t = ', '.join(t)
4885 4885 cleanworkdir = False
4886 4886
4887 4887 if repo.vfs.exists('graftstate'):
4888 4888 t += _(' (graft in progress)')
4889 4889 if repo.vfs.exists('updatestate'):
4890 4890 t += _(' (interrupted update)')
4891 4891 elif len(parents) > 1:
4892 4892 t += _(' (merge)')
4893 4893 elif branch != parents[0].branch():
4894 4894 t += _(' (new branch)')
4895 4895 elif (parents[0].closesbranch() and
4896 4896 pnode in repo.branchheads(branch, closed=True)):
4897 4897 t += _(' (head closed)')
4898 4898 elif not (status.modified or status.added or status.removed or renamed or
4899 4899 copied or subs):
4900 4900 t += _(' (clean)')
4901 4901 cleanworkdir = True
4902 4902 elif pnode not in bheads:
4903 4903 t += _(' (new branch head)')
4904 4904
4905 4905 if parents:
4906 4906 pendingphase = max(p.phase() for p in parents)
4907 4907 else:
4908 4908 pendingphase = phases.public
4909 4909
4910 4910 if pendingphase > phases.newcommitphase(ui):
4911 4911 t += ' (%s)' % phases.phasenames[pendingphase]
4912 4912
4913 4913 if cleanworkdir:
4914 4914 # i18n: column positioning for "hg summary"
4915 4915 ui.status(_('commit: %s\n') % t.strip())
4916 4916 else:
4917 4917 # i18n: column positioning for "hg summary"
4918 4918 ui.write(_('commit: %s\n') % t.strip())
4919 4919
4920 4920 # all ancestors of branch heads - all ancestors of parent = new csets
4921 4921 new = len(repo.changelog.findmissing([pctx.node() for pctx in parents],
4922 4922 bheads))
4923 4923
4924 4924 if new == 0:
4925 4925 # i18n: column positioning for "hg summary"
4926 4926 ui.status(_('update: (current)\n'))
4927 4927 elif pnode not in bheads:
4928 4928 # i18n: column positioning for "hg summary"
4929 4929 ui.write(_('update: %d new changesets (update)\n') % new)
4930 4930 else:
4931 4931 # i18n: column positioning for "hg summary"
4932 4932 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
4933 4933 (new, len(bheads)))
4934 4934
4935 4935 t = []
4936 4936 draft = len(repo.revs('draft()'))
4937 4937 if draft:
4938 4938 t.append(_('%d draft') % draft)
4939 4939 secret = len(repo.revs('secret()'))
4940 4940 if secret:
4941 4941 t.append(_('%d secret') % secret)
4942 4942
4943 4943 if draft or secret:
4944 4944 ui.status(_('phases: %s\n') % ', '.join(t))
4945 4945
4946 4946 if obsolete.isenabled(repo, obsolete.createmarkersopt):
4947 4947 for trouble in ("unstable", "divergent", "bumped"):
4948 4948 numtrouble = len(repo.revs(trouble + "()"))
4949 4949 # We write all the possibilities to ease translation
4950 4950 troublemsg = {
4951 4951 "unstable": _("unstable: %d changesets"),
4952 4952 "divergent": _("divergent: %d changesets"),
4953 4953 "bumped": _("bumped: %d changesets"),
4954 4954 }
4955 4955 if numtrouble > 0:
4956 4956 ui.status(troublemsg[trouble] % numtrouble + "\n")
4957 4957
4958 4958 cmdutil.summaryhooks(ui, repo)
4959 4959
4960 4960 if opts.get('remote'):
4961 4961 needsincoming, needsoutgoing = True, True
4962 4962 else:
4963 4963 needsincoming, needsoutgoing = False, False
4964 4964 for i, o in cmdutil.summaryremotehooks(ui, repo, opts, None):
4965 4965 if i:
4966 4966 needsincoming = True
4967 4967 if o:
4968 4968 needsoutgoing = True
4969 4969 if not needsincoming and not needsoutgoing:
4970 4970 return
4971 4971
4972 4972 def getincoming():
4973 4973 source, branches = hg.parseurl(ui.expandpath('default'))
4974 4974 sbranch = branches[0]
4975 4975 try:
4976 4976 other = hg.peer(repo, {}, source)
4977 4977 except error.RepoError:
4978 4978 if opts.get('remote'):
4979 4979 raise
4980 4980 return source, sbranch, None, None, None
4981 4981 revs, checkout = hg.addbranchrevs(repo, other, branches, None)
4982 4982 if revs:
4983 4983 revs = [other.lookup(rev) for rev in revs]
4984 4984 ui.debug('comparing with %s\n' % util.hidepassword(source))
4985 4985 repo.ui.pushbuffer()
4986 4986 commoninc = discovery.findcommonincoming(repo, other, heads=revs)
4987 4987 repo.ui.popbuffer()
4988 4988 return source, sbranch, other, commoninc, commoninc[1]
4989 4989
4990 4990 if needsincoming:
4991 4991 source, sbranch, sother, commoninc, incoming = getincoming()
4992 4992 else:
4993 4993 source = sbranch = sother = commoninc = incoming = None
4994 4994
4995 4995 def getoutgoing():
4996 4996 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
4997 4997 dbranch = branches[0]
4998 4998 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
4999 4999 if source != dest:
5000 5000 try:
5001 5001 dother = hg.peer(repo, {}, dest)
5002 5002 except error.RepoError:
5003 5003 if opts.get('remote'):
5004 5004 raise
5005 5005 return dest, dbranch, None, None
5006 5006 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5007 5007 elif sother is None:
5008 5008 # there is no explicit destination peer, but source one is invalid
5009 5009 return dest, dbranch, None, None
5010 5010 else:
5011 5011 dother = sother
5012 5012 if (source != dest or (sbranch is not None and sbranch != dbranch)):
5013 5013 common = None
5014 5014 else:
5015 5015 common = commoninc
5016 5016 if revs:
5017 5017 revs = [repo.lookup(rev) for rev in revs]
5018 5018 repo.ui.pushbuffer()
5019 5019 outgoing = discovery.findcommonoutgoing(repo, dother, onlyheads=revs,
5020 5020 commoninc=common)
5021 5021 repo.ui.popbuffer()
5022 5022 return dest, dbranch, dother, outgoing
5023 5023
5024 5024 if needsoutgoing:
5025 5025 dest, dbranch, dother, outgoing = getoutgoing()
5026 5026 else:
5027 5027 dest = dbranch = dother = outgoing = None
5028 5028
5029 5029 if opts.get('remote'):
5030 5030 t = []
5031 5031 if incoming:
5032 5032 t.append(_('1 or more incoming'))
5033 5033 o = outgoing.missing
5034 5034 if o:
5035 5035 t.append(_('%d outgoing') % len(o))
5036 5036 other = dother or sother
5037 5037 if 'bookmarks' in other.listkeys('namespaces'):
5038 5038 counts = bookmarks.summary(repo, other)
5039 5039 if counts[0] > 0:
5040 5040 t.append(_('%d incoming bookmarks') % counts[0])
5041 5041 if counts[1] > 0:
5042 5042 t.append(_('%d outgoing bookmarks') % counts[1])
5043 5043
5044 5044 if t:
5045 5045 # i18n: column positioning for "hg summary"
5046 5046 ui.write(_('remote: %s\n') % (', '.join(t)))
5047 5047 else:
5048 5048 # i18n: column positioning for "hg summary"
5049 5049 ui.status(_('remote: (synced)\n'))
5050 5050
5051 5051 cmdutil.summaryremotehooks(ui, repo, opts,
5052 5052 ((source, sbranch, sother, commoninc),
5053 5053 (dest, dbranch, dother, outgoing)))
5054 5054
5055 5055 @command('tag',
5056 5056 [('f', 'force', None, _('force tag')),
5057 5057 ('l', 'local', None, _('make the tag local')),
5058 5058 ('r', 'rev', '', _('revision to tag'), _('REV')),
5059 5059 ('', 'remove', None, _('remove a tag')),
5060 5060 # -l/--local is already there, commitopts cannot be used
5061 5061 ('e', 'edit', None, _('invoke editor on commit messages')),
5062 5062 ('m', 'message', '', _('use text as commit message'), _('TEXT')),
5063 5063 ] + commitopts2,
5064 5064 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
5065 5065 def tag(ui, repo, name1, *names, **opts):
5066 5066 """add one or more tags for the current or given revision
5067 5067
5068 5068 Name a particular revision using <name>.
5069 5069
5070 5070 Tags are used to name particular revisions of the repository and are
5071 5071 very useful to compare different revisions, to go back to significant
5072 5072 earlier versions or to mark branch points as releases, etc. Changing
5073 5073 an existing tag is normally disallowed; use -f/--force to override.
5074 5074
5075 5075 If no revision is given, the parent of the working directory is
5076 5076 used.
5077 5077
5078 5078 To facilitate version control, distribution, and merging of tags,
5079 5079 they are stored as a file named ".hgtags" which is managed similarly
5080 5080 to other project files and can be hand-edited if necessary. This
5081 5081 also means that tagging creates a new commit. The file
5082 5082 ".hg/localtags" is used for local tags (not shared among
5083 5083 repositories).
5084 5084
5085 5085 Tag commits are usually made at the head of a branch. If the parent
5086 5086 of the working directory is not a branch head, :hg:`tag` aborts; use
5087 5087 -f/--force to force the tag commit to be based on a non-head
5088 5088 changeset.
5089 5089
5090 5090 See :hg:`help dates` for a list of formats valid for -d/--date.
5091 5091
5092 5092 Since tag names have priority over branch names during revision
5093 5093 lookup, using an existing branch name as a tag name is discouraged.
5094 5094
5095 5095 Returns 0 on success.
5096 5096 """
5097 5097 wlock = lock = None
5098 5098 try:
5099 5099 wlock = repo.wlock()
5100 5100 lock = repo.lock()
5101 5101 rev_ = "."
5102 5102 names = [t.strip() for t in (name1,) + names]
5103 5103 if len(names) != len(set(names)):
5104 5104 raise error.Abort(_('tag names must be unique'))
5105 5105 for n in names:
5106 5106 scmutil.checknewlabel(repo, n, 'tag')
5107 5107 if not n:
5108 5108 raise error.Abort(_('tag names cannot consist entirely of '
5109 5109 'whitespace'))
5110 5110 if opts.get('rev') and opts.get('remove'):
5111 5111 raise error.Abort(_("--rev and --remove are incompatible"))
5112 5112 if opts.get('rev'):
5113 5113 rev_ = opts['rev']
5114 5114 message = opts.get('message')
5115 5115 if opts.get('remove'):
5116 5116 if opts.get('local'):
5117 5117 expectedtype = 'local'
5118 5118 else:
5119 5119 expectedtype = 'global'
5120 5120
5121 5121 for n in names:
5122 5122 if not repo.tagtype(n):
5123 5123 raise error.Abort(_("tag '%s' does not exist") % n)
5124 5124 if repo.tagtype(n) != expectedtype:
5125 5125 if expectedtype == 'global':
5126 5126 raise error.Abort(_("tag '%s' is not a global tag") % n)
5127 5127 else:
5128 5128 raise error.Abort(_("tag '%s' is not a local tag") % n)
5129 5129 rev_ = 'null'
5130 5130 if not message:
5131 5131 # we don't translate commit messages
5132 5132 message = 'Removed tag %s' % ', '.join(names)
5133 5133 elif not opts.get('force'):
5134 5134 for n in names:
5135 5135 if n in repo.tags():
5136 5136 raise error.Abort(_("tag '%s' already exists "
5137 5137 "(use -f to force)") % n)
5138 5138 if not opts.get('local'):
5139 5139 p1, p2 = repo.dirstate.parents()
5140 5140 if p2 != nullid:
5141 5141 raise error.Abort(_('uncommitted merge'))
5142 5142 bheads = repo.branchheads()
5143 5143 if not opts.get('force') and bheads and p1 not in bheads:
5144 5144 raise error.Abort(_('working directory is not at a branch head '
5145 5145 '(use -f to force)'))
5146 5146 r = scmutil.revsingle(repo, rev_).node()
5147 5147
5148 5148 if not message:
5149 5149 # we don't translate commit messages
5150 5150 message = ('Added tag %s for changeset %s' %
5151 5151 (', '.join(names), short(r)))
5152 5152
5153 5153 date = opts.get('date')
5154 5154 if date:
5155 5155 date = util.parsedate(date)
5156 5156
5157 5157 if opts.get('remove'):
5158 5158 editform = 'tag.remove'
5159 5159 else:
5160 5160 editform = 'tag.add'
5161 5161 editor = cmdutil.getcommiteditor(editform=editform, **opts)
5162 5162
5163 5163 # don't allow tagging the null rev
5164 5164 if (not opts.get('remove') and
5165 5165 scmutil.revsingle(repo, rev_).rev() == nullrev):
5166 5166 raise error.Abort(_("cannot tag null revision"))
5167 5167
5168 5168 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date,
5169 5169 editor=editor)
5170 5170 finally:
5171 5171 release(lock, wlock)
5172 5172
5173 5173 @command('tags', formatteropts, '')
5174 5174 def tags(ui, repo, **opts):
5175 5175 """list repository tags
5176 5176
5177 5177 This lists both regular and local tags. When the -v/--verbose
5178 5178 switch is used, a third column "local" is printed for local tags.
5179 5179 When the -q/--quiet switch is used, only the tag name is printed.
5180 5180
5181 5181 Returns 0 on success.
5182 5182 """
5183 5183
5184 5184 ui.pager('tags')
5185 5185 fm = ui.formatter('tags', opts)
5186 5186 hexfunc = fm.hexfunc
5187 5187 tagtype = ""
5188 5188
5189 5189 for t, n in reversed(repo.tagslist()):
5190 5190 hn = hexfunc(n)
5191 5191 label = 'tags.normal'
5192 5192 tagtype = ''
5193 5193 if repo.tagtype(t) == 'local':
5194 5194 label = 'tags.local'
5195 5195 tagtype = 'local'
5196 5196
5197 5197 fm.startitem()
5198 5198 fm.write('tag', '%s', t, label=label)
5199 5199 fmt = " " * (30 - encoding.colwidth(t)) + ' %5d:%s'
5200 5200 fm.condwrite(not ui.quiet, 'rev node', fmt,
5201 5201 repo.changelog.rev(n), hn, label=label)
5202 5202 fm.condwrite(ui.verbose and tagtype, 'type', ' %s',
5203 5203 tagtype, label=label)
5204 5204 fm.plain('\n')
5205 5205 fm.end()
5206 5206
5207 5207 @command('tip',
5208 5208 [('p', 'patch', None, _('show patch')),
5209 5209 ('g', 'git', None, _('use git extended diff format')),
5210 5210 ] + templateopts,
5211 5211 _('[-p] [-g]'))
5212 5212 def tip(ui, repo, **opts):
5213 5213 """show the tip revision (DEPRECATED)
5214 5214
5215 5215 The tip revision (usually just called the tip) is the changeset
5216 5216 most recently added to the repository (and therefore the most
5217 5217 recently changed head).
5218 5218
5219 5219 If you have just made a commit, that commit will be the tip. If
5220 5220 you have just pulled changes from another repository, the tip of
5221 5221 that repository becomes the current tip. The "tip" tag is special
5222 5222 and cannot be renamed or assigned to a different changeset.
5223 5223
5224 5224 This command is deprecated, please use :hg:`heads` instead.
5225 5225
5226 5226 Returns 0 on success.
5227 5227 """
5228 5228 displayer = cmdutil.show_changeset(ui, repo, opts)
5229 5229 displayer.show(repo['tip'])
5230 5230 displayer.close()
5231 5231
5232 5232 @command('unbundle',
5233 5233 [('u', 'update', None,
5234 5234 _('update to new branch head if changesets were unbundled'))],
5235 5235 _('[-u] FILE...'))
5236 5236 def unbundle(ui, repo, fname1, *fnames, **opts):
5237 5237 """apply one or more changegroup files
5238 5238
5239 5239 Apply one or more compressed changegroup files generated by the
5240 5240 bundle command.
5241 5241
5242 5242 Returns 0 on success, 1 if an update has unresolved files.
5243 5243 """
5244 5244 fnames = (fname1,) + fnames
5245 5245
5246 5246 with repo.lock():
5247 5247 for fname in fnames:
5248 5248 f = hg.openpath(ui, fname)
5249 5249 gen = exchange.readbundle(ui, f, fname)
5250 5250 if isinstance(gen, bundle2.unbundle20):
5251 5251 tr = repo.transaction('unbundle')
5252 5252 try:
5253 5253 op = bundle2.applybundle(repo, gen, tr, source='unbundle',
5254 5254 url='bundle:' + fname)
5255 5255 tr.close()
5256 5256 except error.BundleUnknownFeatureError as exc:
5257 5257 raise error.Abort(_('%s: unknown bundle feature, %s')
5258 5258 % (fname, exc),
5259 5259 hint=_("see https://mercurial-scm.org/"
5260 5260 "wiki/BundleFeature for more "
5261 5261 "information"))
5262 5262 finally:
5263 5263 if tr:
5264 5264 tr.release()
5265 5265 changes = [r.get('return', 0)
5266 5266 for r in op.records['changegroup']]
5267 5267 modheads = changegroup.combineresults(changes)
5268 5268 elif isinstance(gen, streamclone.streamcloneapplier):
5269 5269 raise error.Abort(
5270 5270 _('packed bundles cannot be applied with '
5271 5271 '"hg unbundle"'),
5272 5272 hint=_('use "hg debugapplystreamclonebundle"'))
5273 5273 else:
5274 5274 modheads = gen.apply(repo, 'unbundle', 'bundle:' + fname)
5275 5275
5276 5276 return postincoming(ui, repo, modheads, opts.get('update'), None, None)
5277 5277
5278 5278 @command('^update|up|checkout|co',
5279 5279 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
5280 5280 ('c', 'check', None, _('require clean working directory')),
5281 ('m', 'merge', None, _('merge uncommitted changes')),
5281 5282 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5282 5283 ('r', 'rev', '', _('revision'), _('REV'))
5283 5284 ] + mergetoolopts,
5284 _('[-C|-c] [-d DATE] [[-r] REV]'))
5285 _('[-C|-c|-m] [-d DATE] [[-r] REV]'))
5285 5286 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False,
5286 tool=None):
5287 merge=None, tool=None):
5287 5288 """update working directory (or switch revisions)
5288 5289
5289 5290 Update the repository's working directory to the specified
5290 5291 changeset. If no changeset is specified, update to the tip of the
5291 5292 current named branch and move the active bookmark (see :hg:`help
5292 5293 bookmarks`).
5293 5294
5294 5295 Update sets the working directory's parent revision to the specified
5295 5296 changeset (see :hg:`help parents`).
5296 5297
5297 5298 If the changeset is not a descendant or ancestor of the working
5298 5299 directory's parent and there are uncommitted changes, the update is
5299 5300 aborted. With the -c/--check option, the working directory is checked
5300 5301 for uncommitted changes; if none are found, the working directory is
5301 5302 updated to the specified changeset.
5302 5303
5303 5304 .. container:: verbose
5304 5305
5305 The -C/--clean and -c/--check options control what happens if the
5306 working directory contains uncommitted changes.
5306 The -C/--clean, -c/--check, and -m/--merge options control what
5307 happens if the working directory contains uncommitted changes.
5307 5308 At most of one of them can be specified.
5308 5309
5309 5310 1. If no option is specified, and if
5310 5311 the requested changeset is an ancestor or descendant of
5311 5312 the working directory's parent, the uncommitted changes
5312 5313 are merged into the requested changeset and the merged
5313 5314 result is left uncommitted. If the requested changeset is
5314 5315 not an ancestor or descendant (that is, it is on another
5315 5316 branch), the update is aborted and the uncommitted changes
5316 5317 are preserved.
5317 5318
5318 2. With the -c/--check option, the update is aborted and the
5319 2. With the -m/--merge option, the update is allowed even if the
5320 requested changeset is not an ancestor or descendant of
5321 the working directory's parent.
5322
5323 3. With the -c/--check option, the update is aborted and the
5319 5324 uncommitted changes are preserved.
5320 5325
5321 3. With the -C/--clean option, uncommitted changes are discarded and
5326 4. With the -C/--clean option, uncommitted changes are discarded and
5322 5327 the working directory is updated to the requested changeset.
5323 5328
5324 5329 To cancel an uncommitted merge (and lose your changes), use
5325 5330 :hg:`update --clean .`.
5326 5331
5327 5332 Use null as the changeset to remove the working directory (like
5328 5333 :hg:`clone -U`).
5329 5334
5330 5335 If you want to revert just one file to an older revision, use
5331 5336 :hg:`revert [-r REV] NAME`.
5332 5337
5333 5338 See :hg:`help dates` for a list of formats valid for -d/--date.
5334 5339
5335 5340 Returns 0 on success, 1 if there are unresolved files.
5336 5341 """
5337 5342 if rev and node:
5338 5343 raise error.Abort(_("please specify just one revision"))
5339 5344
5340 5345 if rev is None or rev == '':
5341 5346 rev = node
5342 5347
5343 5348 if date and rev is not None:
5344 5349 raise error.Abort(_("you can't specify a revision and a date"))
5345 5350
5346 if check and clean:
5347 raise error.Abort(_("cannot specify both -c/--check and -C/--clean"))
5351 if len([x for x in (clean, check, merge) if x]) > 1:
5352 raise error.Abort(_("can only specify one of -C/--clean, -c/--check, "
5353 "or -m/merge"))
5354
5355 updatecheck = None
5356 if check:
5357 updatecheck = 'abort'
5358 elif merge:
5359 updatecheck = 'none'
5348 5360
5349 5361 with repo.wlock():
5350 5362 cmdutil.clearunfinished(repo)
5351 5363
5352 5364 if date:
5353 5365 rev = cmdutil.finddate(ui, repo, date)
5354 5366
5355 5367 # if we defined a bookmark, we have to remember the original name
5356 5368 brev = rev
5357 5369 rev = scmutil.revsingle(repo, rev, rev).rev()
5358 5370
5359 5371 repo.ui.setconfig('ui', 'forcemerge', tool, 'update')
5360 5372
5361 return hg.updatetotally(ui, repo, rev, brev, clean=clean, check=check)
5373 return hg.updatetotally(ui, repo, rev, brev, clean=clean,
5374 updatecheck=updatecheck)
5362 5375
5363 5376 @command('verify', [])
5364 5377 def verify(ui, repo):
5365 5378 """verify the integrity of the repository
5366 5379
5367 5380 Verify the integrity of the current repository.
5368 5381
5369 5382 This will perform an extensive check of the repository's
5370 5383 integrity, validating the hashes and checksums of each entry in
5371 5384 the changelog, manifest, and tracked files, as well as the
5372 5385 integrity of their crosslinks and indices.
5373 5386
5374 5387 Please see https://mercurial-scm.org/wiki/RepositoryCorruption
5375 5388 for more information about recovery from corruption of the
5376 5389 repository.
5377 5390
5378 5391 Returns 0 on success, 1 if errors are encountered.
5379 5392 """
5380 5393 return hg.verify(repo)
5381 5394
5382 5395 @command('version', [] + formatteropts, norepo=True)
5383 5396 def version_(ui, **opts):
5384 5397 """output version and copyright information"""
5385 5398 if ui.verbose:
5386 5399 ui.pager('version')
5387 5400 fm = ui.formatter("version", opts)
5388 5401 fm.startitem()
5389 5402 fm.write("ver", _("Mercurial Distributed SCM (version %s)\n"),
5390 5403 util.version())
5391 5404 license = _(
5392 5405 "(see https://mercurial-scm.org for more information)\n"
5393 5406 "\nCopyright (C) 2005-2017 Matt Mackall and others\n"
5394 5407 "This is free software; see the source for copying conditions. "
5395 5408 "There is NO\nwarranty; "
5396 5409 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5397 5410 )
5398 5411 if not ui.quiet:
5399 5412 fm.plain(license)
5400 5413
5401 5414 if ui.verbose:
5402 5415 fm.plain(_("\nEnabled extensions:\n\n"))
5403 5416 # format names and versions into columns
5404 5417 names = []
5405 5418 vers = []
5406 5419 isinternals = []
5407 5420 for name, module in extensions.extensions():
5408 5421 names.append(name)
5409 5422 vers.append(extensions.moduleversion(module) or None)
5410 5423 isinternals.append(extensions.ismoduleinternal(module))
5411 5424 fn = fm.nested("extensions")
5412 5425 if names:
5413 5426 namefmt = " %%-%ds " % max(len(n) for n in names)
5414 5427 places = [_("external"), _("internal")]
5415 5428 for n, v, p in zip(names, vers, isinternals):
5416 5429 fn.startitem()
5417 5430 fn.condwrite(ui.verbose, "name", namefmt, n)
5418 5431 if ui.verbose:
5419 5432 fn.plain("%s " % places[p])
5420 5433 fn.data(bundled=p)
5421 5434 fn.condwrite(ui.verbose and v, "ver", "%s", v)
5422 5435 if ui.verbose:
5423 5436 fn.plain("\n")
5424 5437 fn.end()
5425 5438 fm.end()
5426 5439
5427 5440 def loadcmdtable(ui, name, cmdtable):
5428 5441 """Load command functions from specified cmdtable
5429 5442 """
5430 5443 overrides = [cmd for cmd in cmdtable if cmd in table]
5431 5444 if overrides:
5432 5445 ui.warn(_("extension '%s' overrides commands: %s\n")
5433 5446 % (name, " ".join(overrides)))
5434 5447 table.update(cmdtable)
@@ -1,1040 +1,1051
1 1 # hg.py - repository classes for mercurial
2 2 #
3 3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 4 # Copyright 2006 Vadim Gelfer <vadim.gelfer@gmail.com>
5 5 #
6 6 # This software may be used and distributed according to the terms of the
7 7 # GNU General Public License version 2 or any later version.
8 8
9 9 from __future__ import absolute_import
10 10
11 11 import errno
12 12 import hashlib
13 13 import os
14 14 import shutil
15 15
16 16 from .i18n import _
17 17 from .node import nullid
18 18
19 19 from . import (
20 20 bookmarks,
21 21 bundlerepo,
22 22 cmdutil,
23 23 destutil,
24 24 discovery,
25 25 error,
26 26 exchange,
27 27 extensions,
28 28 httppeer,
29 29 localrepo,
30 30 lock,
31 31 merge as mergemod,
32 32 node,
33 33 phases,
34 34 repoview,
35 35 scmutil,
36 36 sshpeer,
37 37 statichttprepo,
38 38 ui as uimod,
39 39 unionrepo,
40 40 url,
41 41 util,
42 42 verify as verifymod,
43 43 )
44 44
45 45 release = lock.release
46 46
47 47 # shared features
48 48 sharedbookmarks = 'bookmarks'
49 49
50 50 def _local(path):
51 51 path = util.expandpath(util.urllocalpath(path))
52 52 return (os.path.isfile(path) and bundlerepo or localrepo)
53 53
54 54 def addbranchrevs(lrepo, other, branches, revs):
55 55 peer = other.peer() # a courtesy to callers using a localrepo for other
56 56 hashbranch, branches = branches
57 57 if not hashbranch and not branches:
58 58 x = revs or None
59 59 if util.safehasattr(revs, 'first'):
60 60 y = revs.first()
61 61 elif revs:
62 62 y = revs[0]
63 63 else:
64 64 y = None
65 65 return x, y
66 66 if revs:
67 67 revs = list(revs)
68 68 else:
69 69 revs = []
70 70
71 71 if not peer.capable('branchmap'):
72 72 if branches:
73 73 raise error.Abort(_("remote branch lookup not supported"))
74 74 revs.append(hashbranch)
75 75 return revs, revs[0]
76 76 branchmap = peer.branchmap()
77 77
78 78 def primary(branch):
79 79 if branch == '.':
80 80 if not lrepo:
81 81 raise error.Abort(_("dirstate branch not accessible"))
82 82 branch = lrepo.dirstate.branch()
83 83 if branch in branchmap:
84 84 revs.extend(node.hex(r) for r in reversed(branchmap[branch]))
85 85 return True
86 86 else:
87 87 return False
88 88
89 89 for branch in branches:
90 90 if not primary(branch):
91 91 raise error.RepoLookupError(_("unknown branch '%s'") % branch)
92 92 if hashbranch:
93 93 if not primary(hashbranch):
94 94 revs.append(hashbranch)
95 95 return revs, revs[0]
96 96
97 97 def parseurl(path, branches=None):
98 98 '''parse url#branch, returning (url, (branch, branches))'''
99 99
100 100 u = util.url(path)
101 101 branch = None
102 102 if u.fragment:
103 103 branch = u.fragment
104 104 u.fragment = None
105 105 return str(u), (branch, branches or [])
106 106
107 107 schemes = {
108 108 'bundle': bundlerepo,
109 109 'union': unionrepo,
110 110 'file': _local,
111 111 'http': httppeer,
112 112 'https': httppeer,
113 113 'ssh': sshpeer,
114 114 'static-http': statichttprepo,
115 115 }
116 116
117 117 def _peerlookup(path):
118 118 u = util.url(path)
119 119 scheme = u.scheme or 'file'
120 120 thing = schemes.get(scheme) or schemes['file']
121 121 try:
122 122 return thing(path)
123 123 except TypeError:
124 124 # we can't test callable(thing) because 'thing' can be an unloaded
125 125 # module that implements __call__
126 126 if not util.safehasattr(thing, 'instance'):
127 127 raise
128 128 return thing
129 129
130 130 def islocal(repo):
131 131 '''return true if repo (or path pointing to repo) is local'''
132 132 if isinstance(repo, str):
133 133 try:
134 134 return _peerlookup(repo).islocal(repo)
135 135 except AttributeError:
136 136 return False
137 137 return repo.local()
138 138
139 139 def openpath(ui, path):
140 140 '''open path with open if local, url.open if remote'''
141 141 pathurl = util.url(path, parsequery=False, parsefragment=False)
142 142 if pathurl.islocal():
143 143 return util.posixfile(pathurl.localpath(), 'rb')
144 144 else:
145 145 return url.open(ui, path)
146 146
147 147 # a list of (ui, repo) functions called for wire peer initialization
148 148 wirepeersetupfuncs = []
149 149
150 150 def _peerorrepo(ui, path, create=False):
151 151 """return a repository object for the specified path"""
152 152 obj = _peerlookup(path).instance(ui, path, create)
153 153 ui = getattr(obj, "ui", ui)
154 154 for name, module in extensions.extensions(ui):
155 155 hook = getattr(module, 'reposetup', None)
156 156 if hook:
157 157 hook(ui, obj)
158 158 if not obj.local():
159 159 for f in wirepeersetupfuncs:
160 160 f(ui, obj)
161 161 return obj
162 162
163 163 def repository(ui, path='', create=False):
164 164 """return a repository object for the specified path"""
165 165 peer = _peerorrepo(ui, path, create)
166 166 repo = peer.local()
167 167 if not repo:
168 168 raise error.Abort(_("repository '%s' is not local") %
169 169 (path or peer.url()))
170 170 return repo.filtered('visible')
171 171
172 172 def peer(uiorrepo, opts, path, create=False):
173 173 '''return a repository peer for the specified path'''
174 174 rui = remoteui(uiorrepo, opts)
175 175 return _peerorrepo(rui, path, create).peer()
176 176
177 177 def defaultdest(source):
178 178 '''return default destination of clone if none is given
179 179
180 180 >>> defaultdest('foo')
181 181 'foo'
182 182 >>> defaultdest('/foo/bar')
183 183 'bar'
184 184 >>> defaultdest('/')
185 185 ''
186 186 >>> defaultdest('')
187 187 ''
188 188 >>> defaultdest('http://example.org/')
189 189 ''
190 190 >>> defaultdest('http://example.org/foo/')
191 191 'foo'
192 192 '''
193 193 path = util.url(source).path
194 194 if not path:
195 195 return ''
196 196 return os.path.basename(os.path.normpath(path))
197 197
198 198 def share(ui, source, dest=None, update=True, bookmarks=True, defaultpath=None,
199 199 relative=False):
200 200 '''create a shared repository'''
201 201
202 202 if not islocal(source):
203 203 raise error.Abort(_('can only share local repositories'))
204 204
205 205 if not dest:
206 206 dest = defaultdest(source)
207 207 else:
208 208 dest = ui.expandpath(dest)
209 209
210 210 if isinstance(source, str):
211 211 origsource = ui.expandpath(source)
212 212 source, branches = parseurl(origsource)
213 213 srcrepo = repository(ui, source)
214 214 rev, checkout = addbranchrevs(srcrepo, srcrepo, branches, None)
215 215 else:
216 216 srcrepo = source.local()
217 217 origsource = source = srcrepo.url()
218 218 checkout = None
219 219
220 220 sharedpath = srcrepo.sharedpath # if our source is already sharing
221 221
222 222 destwvfs = scmutil.vfs(dest, realpath=True)
223 223 destvfs = scmutil.vfs(os.path.join(destwvfs.base, '.hg'), realpath=True)
224 224
225 225 if destvfs.lexists():
226 226 raise error.Abort(_('destination already exists'))
227 227
228 228 if not destwvfs.isdir():
229 229 destwvfs.mkdir()
230 230 destvfs.makedir()
231 231
232 232 requirements = ''
233 233 try:
234 234 requirements = srcrepo.vfs.read('requires')
235 235 except IOError as inst:
236 236 if inst.errno != errno.ENOENT:
237 237 raise
238 238
239 239 if relative:
240 240 try:
241 241 sharedpath = os.path.relpath(sharedpath, destvfs.base)
242 242 requirements += 'relshared\n'
243 243 except IOError as e:
244 244 raise error.Abort(_('cannot calculate relative path'),
245 245 hint=str(e))
246 246 else:
247 247 requirements += 'shared\n'
248 248
249 249 destvfs.write('requires', requirements)
250 250 destvfs.write('sharedpath', sharedpath)
251 251
252 252 r = repository(ui, destwvfs.base)
253 253 postshare(srcrepo, r, bookmarks=bookmarks, defaultpath=defaultpath)
254 254 _postshareupdate(r, update, checkout=checkout)
255 255
256 256 def postshare(sourcerepo, destrepo, bookmarks=True, defaultpath=None):
257 257 """Called after a new shared repo is created.
258 258
259 259 The new repo only has a requirements file and pointer to the source.
260 260 This function configures additional shared data.
261 261
262 262 Extensions can wrap this function and write additional entries to
263 263 destrepo/.hg/shared to indicate additional pieces of data to be shared.
264 264 """
265 265 default = defaultpath or sourcerepo.ui.config('paths', 'default')
266 266 if default:
267 267 fp = destrepo.vfs("hgrc", "w", text=True)
268 268 fp.write("[paths]\n")
269 269 fp.write("default = %s\n" % default)
270 270 fp.close()
271 271
272 272 with destrepo.wlock():
273 273 if bookmarks:
274 274 fp = destrepo.vfs('shared', 'w')
275 275 fp.write(sharedbookmarks + '\n')
276 276 fp.close()
277 277
278 278 def _postshareupdate(repo, update, checkout=None):
279 279 """Maybe perform a working directory update after a shared repo is created.
280 280
281 281 ``update`` can be a boolean or a revision to update to.
282 282 """
283 283 if not update:
284 284 return
285 285
286 286 repo.ui.status(_("updating working directory\n"))
287 287 if update is not True:
288 288 checkout = update
289 289 for test in (checkout, 'default', 'tip'):
290 290 if test is None:
291 291 continue
292 292 try:
293 293 uprev = repo.lookup(test)
294 294 break
295 295 except error.RepoLookupError:
296 296 continue
297 297 _update(repo, uprev)
298 298
299 299 def copystore(ui, srcrepo, destpath):
300 300 '''copy files from store of srcrepo in destpath
301 301
302 302 returns destlock
303 303 '''
304 304 destlock = None
305 305 try:
306 306 hardlink = None
307 307 num = 0
308 308 closetopic = [None]
309 309 def prog(topic, pos):
310 310 if pos is None:
311 311 closetopic[0] = topic
312 312 else:
313 313 ui.progress(topic, pos + num)
314 314 srcpublishing = srcrepo.publishing()
315 315 srcvfs = scmutil.vfs(srcrepo.sharedpath)
316 316 dstvfs = scmutil.vfs(destpath)
317 317 for f in srcrepo.store.copylist():
318 318 if srcpublishing and f.endswith('phaseroots'):
319 319 continue
320 320 dstbase = os.path.dirname(f)
321 321 if dstbase and not dstvfs.exists(dstbase):
322 322 dstvfs.mkdir(dstbase)
323 323 if srcvfs.exists(f):
324 324 if f.endswith('data'):
325 325 # 'dstbase' may be empty (e.g. revlog format 0)
326 326 lockfile = os.path.join(dstbase, "lock")
327 327 # lock to avoid premature writing to the target
328 328 destlock = lock.lock(dstvfs, lockfile)
329 329 hardlink, n = util.copyfiles(srcvfs.join(f), dstvfs.join(f),
330 330 hardlink, progress=prog)
331 331 num += n
332 332 if hardlink:
333 333 ui.debug("linked %d files\n" % num)
334 334 if closetopic[0]:
335 335 ui.progress(closetopic[0], None)
336 336 else:
337 337 ui.debug("copied %d files\n" % num)
338 338 if closetopic[0]:
339 339 ui.progress(closetopic[0], None)
340 340 return destlock
341 341 except: # re-raises
342 342 release(destlock)
343 343 raise
344 344
345 345 def clonewithshare(ui, peeropts, sharepath, source, srcpeer, dest, pull=False,
346 346 rev=None, update=True, stream=False):
347 347 """Perform a clone using a shared repo.
348 348
349 349 The store for the repository will be located at <sharepath>/.hg. The
350 350 specified revisions will be cloned or pulled from "source". A shared repo
351 351 will be created at "dest" and a working copy will be created if "update" is
352 352 True.
353 353 """
354 354 revs = None
355 355 if rev:
356 356 if not srcpeer.capable('lookup'):
357 357 raise error.Abort(_("src repository does not support "
358 358 "revision lookup and so doesn't "
359 359 "support clone by revision"))
360 360 revs = [srcpeer.lookup(r) for r in rev]
361 361
362 362 # Obtain a lock before checking for or cloning the pooled repo otherwise
363 363 # 2 clients may race creating or populating it.
364 364 pooldir = os.path.dirname(sharepath)
365 365 # lock class requires the directory to exist.
366 366 try:
367 367 util.makedir(pooldir, False)
368 368 except OSError as e:
369 369 if e.errno != errno.EEXIST:
370 370 raise
371 371
372 372 poolvfs = scmutil.vfs(pooldir)
373 373 basename = os.path.basename(sharepath)
374 374
375 375 with lock.lock(poolvfs, '%s.lock' % basename):
376 376 if os.path.exists(sharepath):
377 377 ui.status(_('(sharing from existing pooled repository %s)\n') %
378 378 basename)
379 379 else:
380 380 ui.status(_('(sharing from new pooled repository %s)\n') % basename)
381 381 # Always use pull mode because hardlinks in share mode don't work
382 382 # well. Never update because working copies aren't necessary in
383 383 # share mode.
384 384 clone(ui, peeropts, source, dest=sharepath, pull=True,
385 385 rev=rev, update=False, stream=stream)
386 386
387 387 # Resolve the value to put in [paths] section for the source.
388 388 if islocal(source):
389 389 defaultpath = os.path.abspath(util.urllocalpath(source))
390 390 else:
391 391 defaultpath = source
392 392
393 393 sharerepo = repository(ui, path=sharepath)
394 394 share(ui, sharerepo, dest=dest, update=False, bookmarks=False,
395 395 defaultpath=defaultpath)
396 396
397 397 # We need to perform a pull against the dest repo to fetch bookmarks
398 398 # and other non-store data that isn't shared by default. In the case of
399 399 # non-existing shared repo, this means we pull from the remote twice. This
400 400 # is a bit weird. But at the time it was implemented, there wasn't an easy
401 401 # way to pull just non-changegroup data.
402 402 destrepo = repository(ui, path=dest)
403 403 exchange.pull(destrepo, srcpeer, heads=revs)
404 404
405 405 _postshareupdate(destrepo, update)
406 406
407 407 return srcpeer, peer(ui, peeropts, dest)
408 408
409 409 def clone(ui, peeropts, source, dest=None, pull=False, rev=None,
410 410 update=True, stream=False, branch=None, shareopts=None):
411 411 """Make a copy of an existing repository.
412 412
413 413 Create a copy of an existing repository in a new directory. The
414 414 source and destination are URLs, as passed to the repository
415 415 function. Returns a pair of repository peers, the source and
416 416 newly created destination.
417 417
418 418 The location of the source is added to the new repository's
419 419 .hg/hgrc file, as the default to be used for future pulls and
420 420 pushes.
421 421
422 422 If an exception is raised, the partly cloned/updated destination
423 423 repository will be deleted.
424 424
425 425 Arguments:
426 426
427 427 source: repository object or URL
428 428
429 429 dest: URL of destination repository to create (defaults to base
430 430 name of source repository)
431 431
432 432 pull: always pull from source repository, even in local case or if the
433 433 server prefers streaming
434 434
435 435 stream: stream raw data uncompressed from repository (fast over
436 436 LAN, slow over WAN)
437 437
438 438 rev: revision to clone up to (implies pull=True)
439 439
440 440 update: update working directory after clone completes, if
441 441 destination is local repository (True means update to default rev,
442 442 anything else is treated as a revision)
443 443
444 444 branch: branches to clone
445 445
446 446 shareopts: dict of options to control auto sharing behavior. The "pool" key
447 447 activates auto sharing mode and defines the directory for stores. The
448 448 "mode" key determines how to construct the directory name of the shared
449 449 repository. "identity" means the name is derived from the node of the first
450 450 changeset in the repository. "remote" means the name is derived from the
451 451 remote's path/URL. Defaults to "identity."
452 452 """
453 453
454 454 if isinstance(source, str):
455 455 origsource = ui.expandpath(source)
456 456 source, branch = parseurl(origsource, branch)
457 457 srcpeer = peer(ui, peeropts, source)
458 458 else:
459 459 srcpeer = source.peer() # in case we were called with a localrepo
460 460 branch = (None, branch or [])
461 461 origsource = source = srcpeer.url()
462 462 rev, checkout = addbranchrevs(srcpeer, srcpeer, branch, rev)
463 463
464 464 if dest is None:
465 465 dest = defaultdest(source)
466 466 if dest:
467 467 ui.status(_("destination directory: %s\n") % dest)
468 468 else:
469 469 dest = ui.expandpath(dest)
470 470
471 471 dest = util.urllocalpath(dest)
472 472 source = util.urllocalpath(source)
473 473
474 474 if not dest:
475 475 raise error.Abort(_("empty destination path is not valid"))
476 476
477 477 destvfs = scmutil.vfs(dest, expandpath=True)
478 478 if destvfs.lexists():
479 479 if not destvfs.isdir():
480 480 raise error.Abort(_("destination '%s' already exists") % dest)
481 481 elif destvfs.listdir():
482 482 raise error.Abort(_("destination '%s' is not empty") % dest)
483 483
484 484 shareopts = shareopts or {}
485 485 sharepool = shareopts.get('pool')
486 486 sharenamemode = shareopts.get('mode')
487 487 if sharepool and islocal(dest):
488 488 sharepath = None
489 489 if sharenamemode == 'identity':
490 490 # Resolve the name from the initial changeset in the remote
491 491 # repository. This returns nullid when the remote is empty. It
492 492 # raises RepoLookupError if revision 0 is filtered or otherwise
493 493 # not available. If we fail to resolve, sharing is not enabled.
494 494 try:
495 495 rootnode = srcpeer.lookup('0')
496 496 if rootnode != node.nullid:
497 497 sharepath = os.path.join(sharepool, node.hex(rootnode))
498 498 else:
499 499 ui.status(_('(not using pooled storage: '
500 500 'remote appears to be empty)\n'))
501 501 except error.RepoLookupError:
502 502 ui.status(_('(not using pooled storage: '
503 503 'unable to resolve identity of remote)\n'))
504 504 elif sharenamemode == 'remote':
505 505 sharepath = os.path.join(
506 506 sharepool, hashlib.sha1(source).hexdigest())
507 507 else:
508 508 raise error.Abort(_('unknown share naming mode: %s') %
509 509 sharenamemode)
510 510
511 511 if sharepath:
512 512 return clonewithshare(ui, peeropts, sharepath, source, srcpeer,
513 513 dest, pull=pull, rev=rev, update=update,
514 514 stream=stream)
515 515
516 516 srclock = destlock = cleandir = None
517 517 srcrepo = srcpeer.local()
518 518 try:
519 519 abspath = origsource
520 520 if islocal(origsource):
521 521 abspath = os.path.abspath(util.urllocalpath(origsource))
522 522
523 523 if islocal(dest):
524 524 cleandir = dest
525 525
526 526 copy = False
527 527 if (srcrepo and srcrepo.cancopy() and islocal(dest)
528 528 and not phases.hassecret(srcrepo)):
529 529 copy = not pull and not rev
530 530
531 531 if copy:
532 532 try:
533 533 # we use a lock here because if we race with commit, we
534 534 # can end up with extra data in the cloned revlogs that's
535 535 # not pointed to by changesets, thus causing verify to
536 536 # fail
537 537 srclock = srcrepo.lock(wait=False)
538 538 except error.LockError:
539 539 copy = False
540 540
541 541 if copy:
542 542 srcrepo.hook('preoutgoing', throw=True, source='clone')
543 543 hgdir = os.path.realpath(os.path.join(dest, ".hg"))
544 544 if not os.path.exists(dest):
545 545 os.mkdir(dest)
546 546 else:
547 547 # only clean up directories we create ourselves
548 548 cleandir = hgdir
549 549 try:
550 550 destpath = hgdir
551 551 util.makedir(destpath, notindexed=True)
552 552 except OSError as inst:
553 553 if inst.errno == errno.EEXIST:
554 554 cleandir = None
555 555 raise error.Abort(_("destination '%s' already exists")
556 556 % dest)
557 557 raise
558 558
559 559 destlock = copystore(ui, srcrepo, destpath)
560 560 # copy bookmarks over
561 561 srcbookmarks = srcrepo.join('bookmarks')
562 562 dstbookmarks = os.path.join(destpath, 'bookmarks')
563 563 if os.path.exists(srcbookmarks):
564 564 util.copyfile(srcbookmarks, dstbookmarks)
565 565
566 566 # Recomputing branch cache might be slow on big repos,
567 567 # so just copy it
568 568 def copybranchcache(fname):
569 569 srcbranchcache = srcrepo.join('cache/%s' % fname)
570 570 dstbranchcache = os.path.join(dstcachedir, fname)
571 571 if os.path.exists(srcbranchcache):
572 572 if not os.path.exists(dstcachedir):
573 573 os.mkdir(dstcachedir)
574 574 util.copyfile(srcbranchcache, dstbranchcache)
575 575
576 576 dstcachedir = os.path.join(destpath, 'cache')
577 577 # In local clones we're copying all nodes, not just served
578 578 # ones. Therefore copy all branch caches over.
579 579 copybranchcache('branch2')
580 580 for cachename in repoview.filtertable:
581 581 copybranchcache('branch2-%s' % cachename)
582 582
583 583 # we need to re-init the repo after manually copying the data
584 584 # into it
585 585 destpeer = peer(srcrepo, peeropts, dest)
586 586 srcrepo.hook('outgoing', source='clone',
587 587 node=node.hex(node.nullid))
588 588 else:
589 589 try:
590 590 destpeer = peer(srcrepo or ui, peeropts, dest, create=True)
591 591 # only pass ui when no srcrepo
592 592 except OSError as inst:
593 593 if inst.errno == errno.EEXIST:
594 594 cleandir = None
595 595 raise error.Abort(_("destination '%s' already exists")
596 596 % dest)
597 597 raise
598 598
599 599 revs = None
600 600 if rev:
601 601 if not srcpeer.capable('lookup'):
602 602 raise error.Abort(_("src repository does not support "
603 603 "revision lookup and so doesn't "
604 604 "support clone by revision"))
605 605 revs = [srcpeer.lookup(r) for r in rev]
606 606 checkout = revs[0]
607 607 local = destpeer.local()
608 608 if local:
609 609 if not stream:
610 610 if pull:
611 611 stream = False
612 612 else:
613 613 stream = None
614 614 # internal config: ui.quietbookmarkmove
615 615 quiet = local.ui.backupconfig('ui', 'quietbookmarkmove')
616 616 try:
617 617 local.ui.setconfig(
618 618 'ui', 'quietbookmarkmove', True, 'clone')
619 619 exchange.pull(local, srcpeer, revs,
620 620 streamclonerequested=stream)
621 621 finally:
622 622 local.ui.restoreconfig(quiet)
623 623 elif srcrepo:
624 624 exchange.push(srcrepo, destpeer, revs=revs,
625 625 bookmarks=srcrepo._bookmarks.keys())
626 626 else:
627 627 raise error.Abort(_("clone from remote to remote not supported")
628 628 )
629 629
630 630 cleandir = None
631 631
632 632 destrepo = destpeer.local()
633 633 if destrepo:
634 634 template = uimod.samplehgrcs['cloned']
635 635 fp = destrepo.vfs("hgrc", "w", text=True)
636 636 u = util.url(abspath)
637 637 u.passwd = None
638 638 defaulturl = str(u)
639 639 fp.write(template % defaulturl)
640 640 fp.close()
641 641
642 642 destrepo.ui.setconfig('paths', 'default', defaulturl, 'clone')
643 643
644 644 if update:
645 645 if update is not True:
646 646 checkout = srcpeer.lookup(update)
647 647 uprev = None
648 648 status = None
649 649 if checkout is not None:
650 650 try:
651 651 uprev = destrepo.lookup(checkout)
652 652 except error.RepoLookupError:
653 653 if update is not True:
654 654 try:
655 655 uprev = destrepo.lookup(update)
656 656 except error.RepoLookupError:
657 657 pass
658 658 if uprev is None:
659 659 try:
660 660 uprev = destrepo._bookmarks['@']
661 661 update = '@'
662 662 bn = destrepo[uprev].branch()
663 663 if bn == 'default':
664 664 status = _("updating to bookmark @\n")
665 665 else:
666 666 status = (_("updating to bookmark @ on branch %s\n")
667 667 % bn)
668 668 except KeyError:
669 669 try:
670 670 uprev = destrepo.branchtip('default')
671 671 except error.RepoLookupError:
672 672 uprev = destrepo.lookup('tip')
673 673 if not status:
674 674 bn = destrepo[uprev].branch()
675 675 status = _("updating to branch %s\n") % bn
676 676 destrepo.ui.status(status)
677 677 _update(destrepo, uprev)
678 678 if update in destrepo._bookmarks:
679 679 bookmarks.activate(destrepo, update)
680 680 finally:
681 681 release(srclock, destlock)
682 682 if cleandir is not None:
683 683 shutil.rmtree(cleandir, True)
684 684 if srcpeer is not None:
685 685 srcpeer.close()
686 686 return srcpeer, destpeer
687 687
688 688 def _showstats(repo, stats, quietempty=False):
689 689 if quietempty and not any(stats):
690 690 return
691 691 repo.ui.status(_("%d files updated, %d files merged, "
692 692 "%d files removed, %d files unresolved\n") % stats)
693 693
694 def updaterepo(repo, node, overwrite):
694 def updaterepo(repo, node, overwrite, updatecheck=None):
695 695 """Update the working directory to node.
696 696
697 697 When overwrite is set, changes are clobbered, merged else
698 698
699 699 returns stats (see pydoc mercurial.merge.applyupdates)"""
700 700 return mergemod.update(repo, node, False, overwrite,
701 labels=['working copy', 'destination'])
701 labels=['working copy', 'destination'],
702 updatecheck=updatecheck)
702 703
703 def update(repo, node, quietempty=False):
704 """update the working directory to node, merging linear changes"""
705 stats = updaterepo(repo, node, False)
704 def update(repo, node, quietempty=False, updatecheck=None):
705 """update the working directory to node"""
706 stats = updaterepo(repo, node, False, updatecheck=updatecheck)
706 707 _showstats(repo, stats, quietempty)
707 708 if stats[3]:
708 709 repo.ui.status(_("use 'hg resolve' to retry unresolved file merges\n"))
709 710 return stats[3] > 0
710 711
711 712 # naming conflict in clone()
712 713 _update = update
713 714
714 715 def clean(repo, node, show_stats=True, quietempty=False):
715 716 """forcibly switch the working directory to node, clobbering changes"""
716 717 stats = updaterepo(repo, node, True)
717 718 util.unlinkpath(repo.join('graftstate'), ignoremissing=True)
718 719 if show_stats:
719 720 _showstats(repo, stats, quietempty)
720 721 return stats[3] > 0
721 722
722 723 # naming conflict in updatetotally()
723 724 _clean = clean
724 725
725 def updatetotally(ui, repo, checkout, brev, clean=False, check=False):
726 def updatetotally(ui, repo, checkout, brev, clean=False, updatecheck=None):
726 727 """Update the working directory with extra care for non-file components
727 728
728 729 This takes care of non-file components below:
729 730
730 731 :bookmark: might be advanced or (in)activated
731 732
732 733 This takes arguments below:
733 734
734 735 :checkout: to which revision the working directory is updated
735 736 :brev: a name, which might be a bookmark to be activated after updating
736 737 :clean: whether changes in the working directory can be discarded
737 :check: whether changes in the working directory should be checked
738 :updatecheck: how to deal with a dirty working directory
739
740 Valid values for updatecheck are (None => linear):
741
742 * abort: abort if the working directory is dirty
743 * none: don't check (merge working directory changes into destination)
744 * linear: check that update is linear before merging working directory
745 changes into destination
738 746
739 747 This returns whether conflict is detected at updating or not.
740 748 """
749 if updatecheck is None:
750 updatecheck = 'linear'
741 751 with repo.wlock():
742 752 movemarkfrom = None
743 753 warndest = False
744 754 if checkout is None:
745 755 updata = destutil.destupdate(repo, clean=clean)
746 756 checkout, movemarkfrom, brev = updata
747 757 warndest = True
748 758
749 759 if clean:
750 760 ret = _clean(repo, checkout)
751 761 else:
752 if check:
762 if updatecheck == 'abort':
753 763 cmdutil.bailifchanged(repo, merge=False)
754 ret = _update(repo, checkout)
764 updatecheck = 'none'
765 ret = _update(repo, checkout, updatecheck=updatecheck)
755 766
756 767 if not ret and movemarkfrom:
757 768 if movemarkfrom == repo['.'].node():
758 769 pass # no-op update
759 770 elif bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
760 771 b = ui.label(repo._activebookmark, 'bookmarks.active')
761 772 ui.status(_("updating bookmark %s\n") % b)
762 773 else:
763 774 # this can happen with a non-linear update
764 775 b = ui.label(repo._activebookmark, 'bookmarks')
765 776 ui.status(_("(leaving bookmark %s)\n") % b)
766 777 bookmarks.deactivate(repo)
767 778 elif brev in repo._bookmarks:
768 779 if brev != repo._activebookmark:
769 780 b = ui.label(brev, 'bookmarks.active')
770 781 ui.status(_("(activating bookmark %s)\n") % b)
771 782 bookmarks.activate(repo, brev)
772 783 elif brev:
773 784 if repo._activebookmark:
774 785 b = ui.label(repo._activebookmark, 'bookmarks')
775 786 ui.status(_("(leaving bookmark %s)\n") % b)
776 787 bookmarks.deactivate(repo)
777 788
778 789 if warndest:
779 790 destutil.statusotherdests(ui, repo)
780 791
781 792 return ret
782 793
783 794 def merge(repo, node, force=None, remind=True, mergeforce=False, labels=None):
784 795 """Branch merge with node, resolving changes. Return true if any
785 796 unresolved conflicts."""
786 797 stats = mergemod.update(repo, node, True, force, mergeforce=mergeforce,
787 798 labels=labels)
788 799 _showstats(repo, stats)
789 800 if stats[3]:
790 801 repo.ui.status(_("use 'hg resolve' to retry unresolved file merges "
791 802 "or 'hg update -C .' to abandon\n"))
792 803 elif remind:
793 804 repo.ui.status(_("(branch merge, don't forget to commit)\n"))
794 805 return stats[3] > 0
795 806
796 807 def _incoming(displaychlist, subreporecurse, ui, repo, source,
797 808 opts, buffered=False):
798 809 """
799 810 Helper for incoming / gincoming.
800 811 displaychlist gets called with
801 812 (remoterepo, incomingchangesetlist, displayer) parameters,
802 813 and is supposed to contain only code that can't be unified.
803 814 """
804 815 source, branches = parseurl(ui.expandpath(source), opts.get('branch'))
805 816 other = peer(repo, opts, source)
806 817 ui.status(_('comparing with %s\n') % util.hidepassword(source))
807 818 revs, checkout = addbranchrevs(repo, other, branches, opts.get('rev'))
808 819
809 820 if revs:
810 821 revs = [other.lookup(rev) for rev in revs]
811 822 other, chlist, cleanupfn = bundlerepo.getremotechanges(ui, repo, other,
812 823 revs, opts["bundle"], opts["force"])
813 824 try:
814 825 if not chlist:
815 826 ui.status(_("no changes found\n"))
816 827 return subreporecurse()
817 828 ui.pager('incoming')
818 829 displayer = cmdutil.show_changeset(ui, other, opts, buffered)
819 830 displaychlist(other, chlist, displayer)
820 831 displayer.close()
821 832 finally:
822 833 cleanupfn()
823 834 subreporecurse()
824 835 return 0 # exit code is zero since we found incoming changes
825 836
826 837 def incoming(ui, repo, source, opts):
827 838 def subreporecurse():
828 839 ret = 1
829 840 if opts.get('subrepos'):
830 841 ctx = repo[None]
831 842 for subpath in sorted(ctx.substate):
832 843 sub = ctx.sub(subpath)
833 844 ret = min(ret, sub.incoming(ui, source, opts))
834 845 return ret
835 846
836 847 def display(other, chlist, displayer):
837 848 limit = cmdutil.loglimit(opts)
838 849 if opts.get('newest_first'):
839 850 chlist.reverse()
840 851 count = 0
841 852 for n in chlist:
842 853 if limit is not None and count >= limit:
843 854 break
844 855 parents = [p for p in other.changelog.parents(n) if p != nullid]
845 856 if opts.get('no_merges') and len(parents) == 2:
846 857 continue
847 858 count += 1
848 859 displayer.show(other[n])
849 860 return _incoming(display, subreporecurse, ui, repo, source, opts)
850 861
851 862 def _outgoing(ui, repo, dest, opts):
852 863 dest = ui.expandpath(dest or 'default-push', dest or 'default')
853 864 dest, branches = parseurl(dest, opts.get('branch'))
854 865 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
855 866 revs, checkout = addbranchrevs(repo, repo, branches, opts.get('rev'))
856 867 if revs:
857 868 revs = [repo.lookup(rev) for rev in scmutil.revrange(repo, revs)]
858 869
859 870 other = peer(repo, opts, dest)
860 871 outgoing = discovery.findcommonoutgoing(repo.unfiltered(), other, revs,
861 872 force=opts.get('force'))
862 873 o = outgoing.missing
863 874 if not o:
864 875 scmutil.nochangesfound(repo.ui, repo, outgoing.excluded)
865 876 return o, other
866 877
867 878 def outgoing(ui, repo, dest, opts):
868 879 def recurse():
869 880 ret = 1
870 881 if opts.get('subrepos'):
871 882 ctx = repo[None]
872 883 for subpath in sorted(ctx.substate):
873 884 sub = ctx.sub(subpath)
874 885 ret = min(ret, sub.outgoing(ui, dest, opts))
875 886 return ret
876 887
877 888 limit = cmdutil.loglimit(opts)
878 889 o, other = _outgoing(ui, repo, dest, opts)
879 890 if not o:
880 891 cmdutil.outgoinghooks(ui, repo, other, opts, o)
881 892 return recurse()
882 893
883 894 if opts.get('newest_first'):
884 895 o.reverse()
885 896 ui.pager('outgoing')
886 897 displayer = cmdutil.show_changeset(ui, repo, opts)
887 898 count = 0
888 899 for n in o:
889 900 if limit is not None and count >= limit:
890 901 break
891 902 parents = [p for p in repo.changelog.parents(n) if p != nullid]
892 903 if opts.get('no_merges') and len(parents) == 2:
893 904 continue
894 905 count += 1
895 906 displayer.show(repo[n])
896 907 displayer.close()
897 908 cmdutil.outgoinghooks(ui, repo, other, opts, o)
898 909 recurse()
899 910 return 0 # exit code is zero since we found outgoing changes
900 911
901 912 def verify(repo):
902 913 """verify the consistency of a repository"""
903 914 ret = verifymod.verify(repo)
904 915
905 916 # Broken subrepo references in hidden csets don't seem worth worrying about,
906 917 # since they can't be pushed/pulled, and --hidden can be used if they are a
907 918 # concern.
908 919
909 920 # pathto() is needed for -R case
910 921 revs = repo.revs("filelog(%s)",
911 922 util.pathto(repo.root, repo.getcwd(), '.hgsubstate'))
912 923
913 924 if revs:
914 925 repo.ui.status(_('checking subrepo links\n'))
915 926 for rev in revs:
916 927 ctx = repo[rev]
917 928 try:
918 929 for subpath in ctx.substate:
919 930 try:
920 931 ret = (ctx.sub(subpath, allowcreate=False).verify()
921 932 or ret)
922 933 except error.RepoError as e:
923 934 repo.ui.warn(('%s: %s\n') % (rev, e))
924 935 except Exception:
925 936 repo.ui.warn(_('.hgsubstate is corrupt in revision %s\n') %
926 937 node.short(ctx.node()))
927 938
928 939 return ret
929 940
930 941 def remoteui(src, opts):
931 942 'build a remote ui from ui or repo and opts'
932 943 if util.safehasattr(src, 'baseui'): # looks like a repository
933 944 dst = src.baseui.copy() # drop repo-specific config
934 945 src = src.ui # copy target options from repo
935 946 else: # assume it's a global ui object
936 947 dst = src.copy() # keep all global options
937 948
938 949 # copy ssh-specific options
939 950 for o in 'ssh', 'remotecmd':
940 951 v = opts.get(o) or src.config('ui', o)
941 952 if v:
942 953 dst.setconfig("ui", o, v, 'copied')
943 954
944 955 # copy bundle-specific options
945 956 r = src.config('bundle', 'mainreporoot')
946 957 if r:
947 958 dst.setconfig('bundle', 'mainreporoot', r, 'copied')
948 959
949 960 # copy selected local settings to the remote ui
950 961 for sect in ('auth', 'hostfingerprints', 'hostsecurity', 'http_proxy'):
951 962 for key, val in src.configitems(sect):
952 963 dst.setconfig(sect, key, val, 'copied')
953 964 v = src.config('web', 'cacerts')
954 965 if v:
955 966 dst.setconfig('web', 'cacerts', util.expandpath(v), 'copied')
956 967
957 968 return dst
958 969
959 970 # Files of interest
960 971 # Used to check if the repository has changed looking at mtime and size of
961 972 # these files.
962 973 foi = [('spath', '00changelog.i'),
963 974 ('spath', 'phaseroots'), # ! phase can change content at the same size
964 975 ('spath', 'obsstore'),
965 976 ('path', 'bookmarks'), # ! bookmark can change content at the same size
966 977 ]
967 978
968 979 class cachedlocalrepo(object):
969 980 """Holds a localrepository that can be cached and reused."""
970 981
971 982 def __init__(self, repo):
972 983 """Create a new cached repo from an existing repo.
973 984
974 985 We assume the passed in repo was recently created. If the
975 986 repo has changed between when it was created and when it was
976 987 turned into a cache, it may not refresh properly.
977 988 """
978 989 assert isinstance(repo, localrepo.localrepository)
979 990 self._repo = repo
980 991 self._state, self.mtime = self._repostate()
981 992 self._filtername = repo.filtername
982 993
983 994 def fetch(self):
984 995 """Refresh (if necessary) and return a repository.
985 996
986 997 If the cached instance is out of date, it will be recreated
987 998 automatically and returned.
988 999
989 1000 Returns a tuple of the repo and a boolean indicating whether a new
990 1001 repo instance was created.
991 1002 """
992 1003 # We compare the mtimes and sizes of some well-known files to
993 1004 # determine if the repo changed. This is not precise, as mtimes
994 1005 # are susceptible to clock skew and imprecise filesystems and
995 1006 # file content can change while maintaining the same size.
996 1007
997 1008 state, mtime = self._repostate()
998 1009 if state == self._state:
999 1010 return self._repo, False
1000 1011
1001 1012 repo = repository(self._repo.baseui, self._repo.url())
1002 1013 if self._filtername:
1003 1014 self._repo = repo.filtered(self._filtername)
1004 1015 else:
1005 1016 self._repo = repo.unfiltered()
1006 1017 self._state = state
1007 1018 self.mtime = mtime
1008 1019
1009 1020 return self._repo, True
1010 1021
1011 1022 def _repostate(self):
1012 1023 state = []
1013 1024 maxmtime = -1
1014 1025 for attr, fname in foi:
1015 1026 prefix = getattr(self._repo, attr)
1016 1027 p = os.path.join(prefix, fname)
1017 1028 try:
1018 1029 st = os.stat(p)
1019 1030 except OSError:
1020 1031 st = os.stat(prefix)
1021 1032 state.append((st.st_mtime, st.st_size))
1022 1033 maxmtime = max(maxmtime, st.st_mtime)
1023 1034
1024 1035 return tuple(state), maxmtime
1025 1036
1026 1037 def copy(self):
1027 1038 """Obtain a copy of this class instance.
1028 1039
1029 1040 A new localrepository instance is obtained. The new instance should be
1030 1041 completely independent of the original.
1031 1042 """
1032 1043 repo = repository(self._repo.baseui, self._repo.origroot)
1033 1044 if self._filtername:
1034 1045 repo = repo.filtered(self._filtername)
1035 1046 else:
1036 1047 repo = repo.unfiltered()
1037 1048 c = cachedlocalrepo(repo)
1038 1049 c._state = self._state
1039 1050 c.mtime = self.mtime
1040 1051 return c
@@ -1,1705 +1,1717
1 1 # merge.py - directory-level update/merge handling for Mercurial
2 2 #
3 3 # Copyright 2006, 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 hashlib
12 12 import os
13 13 import shutil
14 14 import struct
15 15
16 16 from .i18n import _
17 17 from .node import (
18 18 addednodeid,
19 19 bin,
20 20 hex,
21 21 modifiednodeid,
22 22 nullhex,
23 23 nullid,
24 24 nullrev,
25 25 )
26 26 from . import (
27 27 copies,
28 28 error,
29 29 filemerge,
30 30 obsolete,
31 31 pycompat,
32 32 scmutil,
33 33 subrepo,
34 34 util,
35 35 worker,
36 36 )
37 37
38 38 _pack = struct.pack
39 39 _unpack = struct.unpack
40 40
41 41 def _droponode(data):
42 42 # used for compatibility for v1
43 43 bits = data.split('\0')
44 44 bits = bits[:-2] + bits[-1:]
45 45 return '\0'.join(bits)
46 46
47 47 class mergestate(object):
48 48 '''track 3-way merge state of individual files
49 49
50 50 The merge state is stored on disk when needed. Two files are used: one with
51 51 an old format (version 1), and one with a new format (version 2). Version 2
52 52 stores a superset of the data in version 1, including new kinds of records
53 53 in the future. For more about the new format, see the documentation for
54 54 `_readrecordsv2`.
55 55
56 56 Each record can contain arbitrary content, and has an associated type. This
57 57 `type` should be a letter. If `type` is uppercase, the record is mandatory:
58 58 versions of Mercurial that don't support it should abort. If `type` is
59 59 lowercase, the record can be safely ignored.
60 60
61 61 Currently known records:
62 62
63 63 L: the node of the "local" part of the merge (hexified version)
64 64 O: the node of the "other" part of the merge (hexified version)
65 65 F: a file to be merged entry
66 66 C: a change/delete or delete/change conflict
67 67 D: a file that the external merge driver will merge internally
68 68 (experimental)
69 69 m: the external merge driver defined for this merge plus its run state
70 70 (experimental)
71 71 f: a (filename, dictionary) tuple of optional values for a given file
72 72 X: unsupported mandatory record type (used in tests)
73 73 x: unsupported advisory record type (used in tests)
74 74 l: the labels for the parts of the merge.
75 75
76 76 Merge driver run states (experimental):
77 77 u: driver-resolved files unmarked -- needs to be run next time we're about
78 78 to resolve or commit
79 79 m: driver-resolved files marked -- only needs to be run before commit
80 80 s: success/skipped -- does not need to be run any more
81 81
82 82 '''
83 83 statepathv1 = 'merge/state'
84 84 statepathv2 = 'merge/state2'
85 85
86 86 @staticmethod
87 87 def clean(repo, node=None, other=None, labels=None):
88 88 """Initialize a brand new merge state, removing any existing state on
89 89 disk."""
90 90 ms = mergestate(repo)
91 91 ms.reset(node, other, labels)
92 92 return ms
93 93
94 94 @staticmethod
95 95 def read(repo):
96 96 """Initialize the merge state, reading it from disk."""
97 97 ms = mergestate(repo)
98 98 ms._read()
99 99 return ms
100 100
101 101 def __init__(self, repo):
102 102 """Initialize the merge state.
103 103
104 104 Do not use this directly! Instead call read() or clean()."""
105 105 self._repo = repo
106 106 self._dirty = False
107 107 self._labels = None
108 108
109 109 def reset(self, node=None, other=None, labels=None):
110 110 self._state = {}
111 111 self._stateextras = {}
112 112 self._local = None
113 113 self._other = None
114 114 self._labels = labels
115 115 for var in ('localctx', 'otherctx'):
116 116 if var in vars(self):
117 117 delattr(self, var)
118 118 if node:
119 119 self._local = node
120 120 self._other = other
121 121 self._readmergedriver = None
122 122 if self.mergedriver:
123 123 self._mdstate = 's'
124 124 else:
125 125 self._mdstate = 'u'
126 126 shutil.rmtree(self._repo.join('merge'), True)
127 127 self._results = {}
128 128 self._dirty = False
129 129
130 130 def _read(self):
131 131 """Analyse each record content to restore a serialized state from disk
132 132
133 133 This function process "record" entry produced by the de-serialization
134 134 of on disk file.
135 135 """
136 136 self._state = {}
137 137 self._stateextras = {}
138 138 self._local = None
139 139 self._other = None
140 140 for var in ('localctx', 'otherctx'):
141 141 if var in vars(self):
142 142 delattr(self, var)
143 143 self._readmergedriver = None
144 144 self._mdstate = 's'
145 145 unsupported = set()
146 146 records = self._readrecords()
147 147 for rtype, record in records:
148 148 if rtype == 'L':
149 149 self._local = bin(record)
150 150 elif rtype == 'O':
151 151 self._other = bin(record)
152 152 elif rtype == 'm':
153 153 bits = record.split('\0', 1)
154 154 mdstate = bits[1]
155 155 if len(mdstate) != 1 or mdstate not in 'ums':
156 156 # the merge driver should be idempotent, so just rerun it
157 157 mdstate = 'u'
158 158
159 159 self._readmergedriver = bits[0]
160 160 self._mdstate = mdstate
161 161 elif rtype in 'FDC':
162 162 bits = record.split('\0')
163 163 self._state[bits[0]] = bits[1:]
164 164 elif rtype == 'f':
165 165 filename, rawextras = record.split('\0', 1)
166 166 extraparts = rawextras.split('\0')
167 167 extras = {}
168 168 i = 0
169 169 while i < len(extraparts):
170 170 extras[extraparts[i]] = extraparts[i + 1]
171 171 i += 2
172 172
173 173 self._stateextras[filename] = extras
174 174 elif rtype == 'l':
175 175 labels = record.split('\0', 2)
176 176 self._labels = [l for l in labels if len(l) > 0]
177 177 elif not rtype.islower():
178 178 unsupported.add(rtype)
179 179 self._results = {}
180 180 self._dirty = False
181 181
182 182 if unsupported:
183 183 raise error.UnsupportedMergeRecords(unsupported)
184 184
185 185 def _readrecords(self):
186 186 """Read merge state from disk and return a list of record (TYPE, data)
187 187
188 188 We read data from both v1 and v2 files and decide which one to use.
189 189
190 190 V1 has been used by version prior to 2.9.1 and contains less data than
191 191 v2. We read both versions and check if no data in v2 contradicts
192 192 v1. If there is not contradiction we can safely assume that both v1
193 193 and v2 were written at the same time and use the extract data in v2. If
194 194 there is contradiction we ignore v2 content as we assume an old version
195 195 of Mercurial has overwritten the mergestate file and left an old v2
196 196 file around.
197 197
198 198 returns list of record [(TYPE, data), ...]"""
199 199 v1records = self._readrecordsv1()
200 200 v2records = self._readrecordsv2()
201 201 if self._v1v2match(v1records, v2records):
202 202 return v2records
203 203 else:
204 204 # v1 file is newer than v2 file, use it
205 205 # we have to infer the "other" changeset of the merge
206 206 # we cannot do better than that with v1 of the format
207 207 mctx = self._repo[None].parents()[-1]
208 208 v1records.append(('O', mctx.hex()))
209 209 # add place holder "other" file node information
210 210 # nobody is using it yet so we do no need to fetch the data
211 211 # if mctx was wrong `mctx[bits[-2]]` may fails.
212 212 for idx, r in enumerate(v1records):
213 213 if r[0] == 'F':
214 214 bits = r[1].split('\0')
215 215 bits.insert(-2, '')
216 216 v1records[idx] = (r[0], '\0'.join(bits))
217 217 return v1records
218 218
219 219 def _v1v2match(self, v1records, v2records):
220 220 oldv2 = set() # old format version of v2 record
221 221 for rec in v2records:
222 222 if rec[0] == 'L':
223 223 oldv2.add(rec)
224 224 elif rec[0] == 'F':
225 225 # drop the onode data (not contained in v1)
226 226 oldv2.add(('F', _droponode(rec[1])))
227 227 for rec in v1records:
228 228 if rec not in oldv2:
229 229 return False
230 230 else:
231 231 return True
232 232
233 233 def _readrecordsv1(self):
234 234 """read on disk merge state for version 1 file
235 235
236 236 returns list of record [(TYPE, data), ...]
237 237
238 238 Note: the "F" data from this file are one entry short
239 239 (no "other file node" entry)
240 240 """
241 241 records = []
242 242 try:
243 243 f = self._repo.vfs(self.statepathv1)
244 244 for i, l in enumerate(f):
245 245 if i == 0:
246 246 records.append(('L', l[:-1]))
247 247 else:
248 248 records.append(('F', l[:-1]))
249 249 f.close()
250 250 except IOError as err:
251 251 if err.errno != errno.ENOENT:
252 252 raise
253 253 return records
254 254
255 255 def _readrecordsv2(self):
256 256 """read on disk merge state for version 2 file
257 257
258 258 This format is a list of arbitrary records of the form:
259 259
260 260 [type][length][content]
261 261
262 262 `type` is a single character, `length` is a 4 byte integer, and
263 263 `content` is an arbitrary byte sequence of length `length`.
264 264
265 265 Mercurial versions prior to 3.7 have a bug where if there are
266 266 unsupported mandatory merge records, attempting to clear out the merge
267 267 state with hg update --clean or similar aborts. The 't' record type
268 268 works around that by writing out what those versions treat as an
269 269 advisory record, but later versions interpret as special: the first
270 270 character is the 'real' record type and everything onwards is the data.
271 271
272 272 Returns list of records [(TYPE, data), ...]."""
273 273 records = []
274 274 try:
275 275 f = self._repo.vfs(self.statepathv2)
276 276 data = f.read()
277 277 off = 0
278 278 end = len(data)
279 279 while off < end:
280 280 rtype = data[off]
281 281 off += 1
282 282 length = _unpack('>I', data[off:(off + 4)])[0]
283 283 off += 4
284 284 record = data[off:(off + length)]
285 285 off += length
286 286 if rtype == 't':
287 287 rtype, record = record[0], record[1:]
288 288 records.append((rtype, record))
289 289 f.close()
290 290 except IOError as err:
291 291 if err.errno != errno.ENOENT:
292 292 raise
293 293 return records
294 294
295 295 @util.propertycache
296 296 def mergedriver(self):
297 297 # protect against the following:
298 298 # - A configures a malicious merge driver in their hgrc, then
299 299 # pauses the merge
300 300 # - A edits their hgrc to remove references to the merge driver
301 301 # - A gives a copy of their entire repo, including .hg, to B
302 302 # - B inspects .hgrc and finds it to be clean
303 303 # - B then continues the merge and the malicious merge driver
304 304 # gets invoked
305 305 configmergedriver = self._repo.ui.config('experimental', 'mergedriver')
306 306 if (self._readmergedriver is not None
307 307 and self._readmergedriver != configmergedriver):
308 308 raise error.ConfigError(
309 309 _("merge driver changed since merge started"),
310 310 hint=_("revert merge driver change or abort merge"))
311 311
312 312 return configmergedriver
313 313
314 314 @util.propertycache
315 315 def localctx(self):
316 316 if self._local is None:
317 317 raise RuntimeError("localctx accessed but self._local isn't set")
318 318 return self._repo[self._local]
319 319
320 320 @util.propertycache
321 321 def otherctx(self):
322 322 if self._other is None:
323 323 raise RuntimeError("otherctx accessed but self._other isn't set")
324 324 return self._repo[self._other]
325 325
326 326 def active(self):
327 327 """Whether mergestate is active.
328 328
329 329 Returns True if there appears to be mergestate. This is a rough proxy
330 330 for "is a merge in progress."
331 331 """
332 332 # Check local variables before looking at filesystem for performance
333 333 # reasons.
334 334 return bool(self._local) or bool(self._state) or \
335 335 self._repo.vfs.exists(self.statepathv1) or \
336 336 self._repo.vfs.exists(self.statepathv2)
337 337
338 338 def commit(self):
339 339 """Write current state on disk (if necessary)"""
340 340 if self._dirty:
341 341 records = self._makerecords()
342 342 self._writerecords(records)
343 343 self._dirty = False
344 344
345 345 def _makerecords(self):
346 346 records = []
347 347 records.append(('L', hex(self._local)))
348 348 records.append(('O', hex(self._other)))
349 349 if self.mergedriver:
350 350 records.append(('m', '\0'.join([
351 351 self.mergedriver, self._mdstate])))
352 352 for d, v in self._state.iteritems():
353 353 if v[0] == 'd':
354 354 records.append(('D', '\0'.join([d] + v)))
355 355 # v[1] == local ('cd'), v[6] == other ('dc') -- not supported by
356 356 # older versions of Mercurial
357 357 elif v[1] == nullhex or v[6] == nullhex:
358 358 records.append(('C', '\0'.join([d] + v)))
359 359 else:
360 360 records.append(('F', '\0'.join([d] + v)))
361 361 for filename, extras in sorted(self._stateextras.iteritems()):
362 362 rawextras = '\0'.join('%s\0%s' % (k, v) for k, v in
363 363 extras.iteritems())
364 364 records.append(('f', '%s\0%s' % (filename, rawextras)))
365 365 if self._labels is not None:
366 366 labels = '\0'.join(self._labels)
367 367 records.append(('l', labels))
368 368 return records
369 369
370 370 def _writerecords(self, records):
371 371 """Write current state on disk (both v1 and v2)"""
372 372 self._writerecordsv1(records)
373 373 self._writerecordsv2(records)
374 374
375 375 def _writerecordsv1(self, records):
376 376 """Write current state on disk in a version 1 file"""
377 377 f = self._repo.vfs(self.statepathv1, 'w')
378 378 irecords = iter(records)
379 379 lrecords = next(irecords)
380 380 assert lrecords[0] == 'L'
381 381 f.write(hex(self._local) + '\n')
382 382 for rtype, data in irecords:
383 383 if rtype == 'F':
384 384 f.write('%s\n' % _droponode(data))
385 385 f.close()
386 386
387 387 def _writerecordsv2(self, records):
388 388 """Write current state on disk in a version 2 file
389 389
390 390 See the docstring for _readrecordsv2 for why we use 't'."""
391 391 # these are the records that all version 2 clients can read
392 392 whitelist = 'LOF'
393 393 f = self._repo.vfs(self.statepathv2, 'w')
394 394 for key, data in records:
395 395 assert len(key) == 1
396 396 if key not in whitelist:
397 397 key, data = 't', '%s%s' % (key, data)
398 398 format = '>sI%is' % len(data)
399 399 f.write(_pack(format, key, len(data), data))
400 400 f.close()
401 401
402 402 def add(self, fcl, fco, fca, fd):
403 403 """add a new (potentially?) conflicting file the merge state
404 404 fcl: file context for local,
405 405 fco: file context for remote,
406 406 fca: file context for ancestors,
407 407 fd: file path of the resulting merge.
408 408
409 409 note: also write the local version to the `.hg/merge` directory.
410 410 """
411 411 if fcl.isabsent():
412 412 hash = nullhex
413 413 else:
414 414 hash = hashlib.sha1(fcl.path()).hexdigest()
415 415 self._repo.vfs.write('merge/' + hash, fcl.data())
416 416 self._state[fd] = ['u', hash, fcl.path(),
417 417 fca.path(), hex(fca.filenode()),
418 418 fco.path(), hex(fco.filenode()),
419 419 fcl.flags()]
420 420 self._stateextras[fd] = { 'ancestorlinknode' : hex(fca.node()) }
421 421 self._dirty = True
422 422
423 423 def __contains__(self, dfile):
424 424 return dfile in self._state
425 425
426 426 def __getitem__(self, dfile):
427 427 return self._state[dfile][0]
428 428
429 429 def __iter__(self):
430 430 return iter(sorted(self._state))
431 431
432 432 def files(self):
433 433 return self._state.keys()
434 434
435 435 def mark(self, dfile, state):
436 436 self._state[dfile][0] = state
437 437 self._dirty = True
438 438
439 439 def mdstate(self):
440 440 return self._mdstate
441 441
442 442 def unresolved(self):
443 443 """Obtain the paths of unresolved files."""
444 444
445 445 for f, entry in self._state.items():
446 446 if entry[0] == 'u':
447 447 yield f
448 448
449 449 def driverresolved(self):
450 450 """Obtain the paths of driver-resolved files."""
451 451
452 452 for f, entry in self._state.items():
453 453 if entry[0] == 'd':
454 454 yield f
455 455
456 456 def extras(self, filename):
457 457 return self._stateextras.setdefault(filename, {})
458 458
459 459 def _resolve(self, preresolve, dfile, wctx):
460 460 """rerun merge process for file path `dfile`"""
461 461 if self[dfile] in 'rd':
462 462 return True, 0
463 463 stateentry = self._state[dfile]
464 464 state, hash, lfile, afile, anode, ofile, onode, flags = stateentry
465 465 octx = self._repo[self._other]
466 466 extras = self.extras(dfile)
467 467 anccommitnode = extras.get('ancestorlinknode')
468 468 if anccommitnode:
469 469 actx = self._repo[anccommitnode]
470 470 else:
471 471 actx = None
472 472 fcd = self._filectxorabsent(hash, wctx, dfile)
473 473 fco = self._filectxorabsent(onode, octx, ofile)
474 474 # TODO: move this to filectxorabsent
475 475 fca = self._repo.filectx(afile, fileid=anode, changeid=actx)
476 476 # "premerge" x flags
477 477 flo = fco.flags()
478 478 fla = fca.flags()
479 479 if 'x' in flags + flo + fla and 'l' not in flags + flo + fla:
480 480 if fca.node() == nullid and flags != flo:
481 481 if preresolve:
482 482 self._repo.ui.warn(
483 483 _('warning: cannot merge flags for %s '
484 484 'without common ancestor - keeping local flags\n')
485 485 % afile)
486 486 elif flags == fla:
487 487 flags = flo
488 488 if preresolve:
489 489 # restore local
490 490 if hash != nullhex:
491 491 f = self._repo.vfs('merge/' + hash)
492 492 self._repo.wwrite(dfile, f.read(), flags)
493 493 f.close()
494 494 else:
495 495 self._repo.wvfs.unlinkpath(dfile, ignoremissing=True)
496 496 complete, r, deleted = filemerge.premerge(self._repo, self._local,
497 497 lfile, fcd, fco, fca,
498 498 labels=self._labels)
499 499 else:
500 500 complete, r, deleted = filemerge.filemerge(self._repo, self._local,
501 501 lfile, fcd, fco, fca,
502 502 labels=self._labels)
503 503 if r is None:
504 504 # no real conflict
505 505 del self._state[dfile]
506 506 self._stateextras.pop(dfile, None)
507 507 self._dirty = True
508 508 elif not r:
509 509 self.mark(dfile, 'r')
510 510
511 511 if complete:
512 512 action = None
513 513 if deleted:
514 514 if fcd.isabsent():
515 515 # dc: local picked. Need to drop if present, which may
516 516 # happen on re-resolves.
517 517 action = 'f'
518 518 else:
519 519 # cd: remote picked (or otherwise deleted)
520 520 action = 'r'
521 521 else:
522 522 if fcd.isabsent(): # dc: remote picked
523 523 action = 'g'
524 524 elif fco.isabsent(): # cd: local picked
525 525 if dfile in self.localctx:
526 526 action = 'am'
527 527 else:
528 528 action = 'a'
529 529 # else: regular merges (no action necessary)
530 530 self._results[dfile] = r, action
531 531
532 532 return complete, r
533 533
534 534 def _filectxorabsent(self, hexnode, ctx, f):
535 535 if hexnode == nullhex:
536 536 return filemerge.absentfilectx(ctx, f)
537 537 else:
538 538 return ctx[f]
539 539
540 540 def preresolve(self, dfile, wctx):
541 541 """run premerge process for dfile
542 542
543 543 Returns whether the merge is complete, and the exit code."""
544 544 return self._resolve(True, dfile, wctx)
545 545
546 546 def resolve(self, dfile, wctx):
547 547 """run merge process (assuming premerge was run) for dfile
548 548
549 549 Returns the exit code of the merge."""
550 550 return self._resolve(False, dfile, wctx)[1]
551 551
552 552 def counts(self):
553 553 """return counts for updated, merged and removed files in this
554 554 session"""
555 555 updated, merged, removed = 0, 0, 0
556 556 for r, action in self._results.itervalues():
557 557 if r is None:
558 558 updated += 1
559 559 elif r == 0:
560 560 if action == 'r':
561 561 removed += 1
562 562 else:
563 563 merged += 1
564 564 return updated, merged, removed
565 565
566 566 def unresolvedcount(self):
567 567 """get unresolved count for this merge (persistent)"""
568 568 return len([True for f, entry in self._state.iteritems()
569 569 if entry[0] == 'u'])
570 570
571 571 def actions(self):
572 572 """return lists of actions to perform on the dirstate"""
573 573 actions = {'r': [], 'f': [], 'a': [], 'am': [], 'g': []}
574 574 for f, (r, action) in self._results.iteritems():
575 575 if action is not None:
576 576 actions[action].append((f, None, "merge result"))
577 577 return actions
578 578
579 579 def recordactions(self):
580 580 """record remove/add/get actions in the dirstate"""
581 581 branchmerge = self._repo.dirstate.p2() != nullid
582 582 recordupdates(self._repo, self.actions(), branchmerge)
583 583
584 584 def queueremove(self, f):
585 585 """queues a file to be removed from the dirstate
586 586
587 587 Meant for use by custom merge drivers."""
588 588 self._results[f] = 0, 'r'
589 589
590 590 def queueadd(self, f):
591 591 """queues a file to be added to the dirstate
592 592
593 593 Meant for use by custom merge drivers."""
594 594 self._results[f] = 0, 'a'
595 595
596 596 def queueget(self, f):
597 597 """queues a file to be marked modified in the dirstate
598 598
599 599 Meant for use by custom merge drivers."""
600 600 self._results[f] = 0, 'g'
601 601
602 602 def _getcheckunknownconfig(repo, section, name):
603 603 config = repo.ui.config(section, name, default='abort')
604 604 valid = ['abort', 'ignore', 'warn']
605 605 if config not in valid:
606 606 validstr = ', '.join(["'" + v + "'" for v in valid])
607 607 raise error.ConfigError(_("%s.%s not valid "
608 608 "('%s' is none of %s)")
609 609 % (section, name, config, validstr))
610 610 return config
611 611
612 612 def _checkunknownfile(repo, wctx, mctx, f, f2=None):
613 613 if f2 is None:
614 614 f2 = f
615 615 return (repo.wvfs.audit.check(f)
616 616 and repo.wvfs.isfileorlink(f)
617 617 and repo.dirstate.normalize(f) not in repo.dirstate
618 618 and mctx[f2].cmp(wctx[f]))
619 619
620 620 def _checkunknownfiles(repo, wctx, mctx, force, actions, mergeforce):
621 621 """
622 622 Considers any actions that care about the presence of conflicting unknown
623 623 files. For some actions, the result is to abort; for others, it is to
624 624 choose a different action.
625 625 """
626 626 conflicts = set()
627 627 warnconflicts = set()
628 628 abortconflicts = set()
629 629 unknownconfig = _getcheckunknownconfig(repo, 'merge', 'checkunknown')
630 630 ignoredconfig = _getcheckunknownconfig(repo, 'merge', 'checkignored')
631 631 if not force:
632 632 def collectconflicts(conflicts, config):
633 633 if config == 'abort':
634 634 abortconflicts.update(conflicts)
635 635 elif config == 'warn':
636 636 warnconflicts.update(conflicts)
637 637
638 638 for f, (m, args, msg) in actions.iteritems():
639 639 if m in ('c', 'dc'):
640 640 if _checkunknownfile(repo, wctx, mctx, f):
641 641 conflicts.add(f)
642 642 elif m == 'dg':
643 643 if _checkunknownfile(repo, wctx, mctx, f, args[0]):
644 644 conflicts.add(f)
645 645
646 646 ignoredconflicts = set([c for c in conflicts
647 647 if repo.dirstate._ignore(c)])
648 648 unknownconflicts = conflicts - ignoredconflicts
649 649 collectconflicts(ignoredconflicts, ignoredconfig)
650 650 collectconflicts(unknownconflicts, unknownconfig)
651 651 else:
652 652 for f, (m, args, msg) in actions.iteritems():
653 653 if m == 'cm':
654 654 fl2, anc = args
655 655 different = _checkunknownfile(repo, wctx, mctx, f)
656 656 if repo.dirstate._ignore(f):
657 657 config = ignoredconfig
658 658 else:
659 659 config = unknownconfig
660 660
661 661 # The behavior when force is True is described by this table:
662 662 # config different mergeforce | action backup
663 663 # * n * | get n
664 664 # * y y | merge -
665 665 # abort y n | merge - (1)
666 666 # warn y n | warn + get y
667 667 # ignore y n | get y
668 668 #
669 669 # (1) this is probably the wrong behavior here -- we should
670 670 # probably abort, but some actions like rebases currently
671 671 # don't like an abort happening in the middle of
672 672 # merge.update.
673 673 if not different:
674 674 actions[f] = ('g', (fl2, False), "remote created")
675 675 elif mergeforce or config == 'abort':
676 676 actions[f] = ('m', (f, f, None, False, anc),
677 677 "remote differs from untracked local")
678 678 elif config == 'abort':
679 679 abortconflicts.add(f)
680 680 else:
681 681 if config == 'warn':
682 682 warnconflicts.add(f)
683 683 actions[f] = ('g', (fl2, True), "remote created")
684 684
685 685 for f in sorted(abortconflicts):
686 686 repo.ui.warn(_("%s: untracked file differs\n") % f)
687 687 if abortconflicts:
688 688 raise error.Abort(_("untracked files in working directory "
689 689 "differ from files in requested revision"))
690 690
691 691 for f in sorted(warnconflicts):
692 692 repo.ui.warn(_("%s: replacing untracked file\n") % f)
693 693
694 694 for f, (m, args, msg) in actions.iteritems():
695 695 backup = f in conflicts
696 696 if m == 'c':
697 697 flags, = args
698 698 actions[f] = ('g', (flags, backup), msg)
699 699
700 700 def _forgetremoved(wctx, mctx, branchmerge):
701 701 """
702 702 Forget removed files
703 703
704 704 If we're jumping between revisions (as opposed to merging), and if
705 705 neither the working directory nor the target rev has the file,
706 706 then we need to remove it from the dirstate, to prevent the
707 707 dirstate from listing the file when it is no longer in the
708 708 manifest.
709 709
710 710 If we're merging, and the other revision has removed a file
711 711 that is not present in the working directory, we need to mark it
712 712 as removed.
713 713 """
714 714
715 715 actions = {}
716 716 m = 'f'
717 717 if branchmerge:
718 718 m = 'r'
719 719 for f in wctx.deleted():
720 720 if f not in mctx:
721 721 actions[f] = m, None, "forget deleted"
722 722
723 723 if not branchmerge:
724 724 for f in wctx.removed():
725 725 if f not in mctx:
726 726 actions[f] = 'f', None, "forget removed"
727 727
728 728 return actions
729 729
730 730 def _checkcollision(repo, wmf, actions):
731 731 # build provisional merged manifest up
732 732 pmmf = set(wmf)
733 733
734 734 if actions:
735 735 # k, dr, e and rd are no-op
736 736 for m in 'a', 'am', 'f', 'g', 'cd', 'dc':
737 737 for f, args, msg in actions[m]:
738 738 pmmf.add(f)
739 739 for f, args, msg in actions['r']:
740 740 pmmf.discard(f)
741 741 for f, args, msg in actions['dm']:
742 742 f2, flags = args
743 743 pmmf.discard(f2)
744 744 pmmf.add(f)
745 745 for f, args, msg in actions['dg']:
746 746 pmmf.add(f)
747 747 for f, args, msg in actions['m']:
748 748 f1, f2, fa, move, anc = args
749 749 if move:
750 750 pmmf.discard(f1)
751 751 pmmf.add(f)
752 752
753 753 # check case-folding collision in provisional merged manifest
754 754 foldmap = {}
755 755 for f in sorted(pmmf):
756 756 fold = util.normcase(f)
757 757 if fold in foldmap:
758 758 raise error.Abort(_("case-folding collision between %s and %s")
759 759 % (f, foldmap[fold]))
760 760 foldmap[fold] = f
761 761
762 762 # check case-folding of directories
763 763 foldprefix = unfoldprefix = lastfull = ''
764 764 for fold, f in sorted(foldmap.items()):
765 765 if fold.startswith(foldprefix) and not f.startswith(unfoldprefix):
766 766 # the folded prefix matches but actual casing is different
767 767 raise error.Abort(_("case-folding collision between "
768 768 "%s and directory of %s") % (lastfull, f))
769 769 foldprefix = fold + '/'
770 770 unfoldprefix = f + '/'
771 771 lastfull = f
772 772
773 773 def driverpreprocess(repo, ms, wctx, labels=None):
774 774 """run the preprocess step of the merge driver, if any
775 775
776 776 This is currently not implemented -- it's an extension point."""
777 777 return True
778 778
779 779 def driverconclude(repo, ms, wctx, labels=None):
780 780 """run the conclude step of the merge driver, if any
781 781
782 782 This is currently not implemented -- it's an extension point."""
783 783 return True
784 784
785 785 def manifestmerge(repo, wctx, p2, pa, branchmerge, force, matcher,
786 786 acceptremote, followcopies):
787 787 """
788 788 Merge wctx and p2 with ancestor pa and generate merge action list
789 789
790 790 branchmerge and force are as passed in to update
791 791 matcher = matcher to filter file lists
792 792 acceptremote = accept the incoming changes without prompting
793 793 """
794 794 if matcher is not None and matcher.always():
795 795 matcher = None
796 796
797 797 copy, movewithdir, diverge, renamedelete, dirmove = {}, {}, {}, {}, {}
798 798
799 799 # manifests fetched in order are going to be faster, so prime the caches
800 800 [x.manifest() for x in
801 801 sorted(wctx.parents() + [p2, pa], key=lambda x: x.rev())]
802 802
803 803 if followcopies:
804 804 ret = copies.mergecopies(repo, wctx, p2, pa)
805 805 copy, movewithdir, diverge, renamedelete, dirmove = ret
806 806
807 807 repo.ui.note(_("resolving manifests\n"))
808 808 repo.ui.debug(" branchmerge: %s, force: %s, partial: %s\n"
809 809 % (bool(branchmerge), bool(force), bool(matcher)))
810 810 repo.ui.debug(" ancestor: %s, local: %s, remote: %s\n" % (pa, wctx, p2))
811 811
812 812 m1, m2, ma = wctx.manifest(), p2.manifest(), pa.manifest()
813 813 copied = set(copy.values())
814 814 copied.update(movewithdir.values())
815 815
816 816 if '.hgsubstate' in m1:
817 817 # check whether sub state is modified
818 818 if any(wctx.sub(s).dirty() for s in wctx.substate):
819 819 m1['.hgsubstate'] = modifiednodeid
820 820
821 821 # Compare manifests
822 822 if matcher is not None:
823 823 m1 = m1.matches(matcher)
824 824 m2 = m2.matches(matcher)
825 825 diff = m1.diff(m2)
826 826
827 827 actions = {}
828 828 for f, ((n1, fl1), (n2, fl2)) in diff.iteritems():
829 829 if n1 and n2: # file exists on both local and remote side
830 830 if f not in ma:
831 831 fa = copy.get(f, None)
832 832 if fa is not None:
833 833 actions[f] = ('m', (f, f, fa, False, pa.node()),
834 834 "both renamed from " + fa)
835 835 else:
836 836 actions[f] = ('m', (f, f, None, False, pa.node()),
837 837 "both created")
838 838 else:
839 839 a = ma[f]
840 840 fla = ma.flags(f)
841 841 nol = 'l' not in fl1 + fl2 + fla
842 842 if n2 == a and fl2 == fla:
843 843 actions[f] = ('k' , (), "remote unchanged")
844 844 elif n1 == a and fl1 == fla: # local unchanged - use remote
845 845 if n1 == n2: # optimization: keep local content
846 846 actions[f] = ('e', (fl2,), "update permissions")
847 847 else:
848 848 actions[f] = ('g', (fl2, False), "remote is newer")
849 849 elif nol and n2 == a: # remote only changed 'x'
850 850 actions[f] = ('e', (fl2,), "update permissions")
851 851 elif nol and n1 == a: # local only changed 'x'
852 852 actions[f] = ('g', (fl1, False), "remote is newer")
853 853 else: # both changed something
854 854 actions[f] = ('m', (f, f, f, False, pa.node()),
855 855 "versions differ")
856 856 elif n1: # file exists only on local side
857 857 if f in copied:
858 858 pass # we'll deal with it on m2 side
859 859 elif f in movewithdir: # directory rename, move local
860 860 f2 = movewithdir[f]
861 861 if f2 in m2:
862 862 actions[f2] = ('m', (f, f2, None, True, pa.node()),
863 863 "remote directory rename, both created")
864 864 else:
865 865 actions[f2] = ('dm', (f, fl1),
866 866 "remote directory rename - move from " + f)
867 867 elif f in copy:
868 868 f2 = copy[f]
869 869 actions[f] = ('m', (f, f2, f2, False, pa.node()),
870 870 "local copied/moved from " + f2)
871 871 elif f in ma: # clean, a different, no remote
872 872 if n1 != ma[f]:
873 873 if acceptremote:
874 874 actions[f] = ('r', None, "remote delete")
875 875 else:
876 876 actions[f] = ('cd', (f, None, f, False, pa.node()),
877 877 "prompt changed/deleted")
878 878 elif n1 == addednodeid:
879 879 # This extra 'a' is added by working copy manifest to mark
880 880 # the file as locally added. We should forget it instead of
881 881 # deleting it.
882 882 actions[f] = ('f', None, "remote deleted")
883 883 else:
884 884 actions[f] = ('r', None, "other deleted")
885 885 elif n2: # file exists only on remote side
886 886 if f in copied:
887 887 pass # we'll deal with it on m1 side
888 888 elif f in movewithdir:
889 889 f2 = movewithdir[f]
890 890 if f2 in m1:
891 891 actions[f2] = ('m', (f2, f, None, False, pa.node()),
892 892 "local directory rename, both created")
893 893 else:
894 894 actions[f2] = ('dg', (f, fl2),
895 895 "local directory rename - get from " + f)
896 896 elif f in copy:
897 897 f2 = copy[f]
898 898 if f2 in m2:
899 899 actions[f] = ('m', (f2, f, f2, False, pa.node()),
900 900 "remote copied from " + f2)
901 901 else:
902 902 actions[f] = ('m', (f2, f, f2, True, pa.node()),
903 903 "remote moved from " + f2)
904 904 elif f not in ma:
905 905 # local unknown, remote created: the logic is described by the
906 906 # following table:
907 907 #
908 908 # force branchmerge different | action
909 909 # n * * | create
910 910 # y n * | create
911 911 # y y n | create
912 912 # y y y | merge
913 913 #
914 914 # Checking whether the files are different is expensive, so we
915 915 # don't do that when we can avoid it.
916 916 if not force:
917 917 actions[f] = ('c', (fl2,), "remote created")
918 918 elif not branchmerge:
919 919 actions[f] = ('c', (fl2,), "remote created")
920 920 else:
921 921 actions[f] = ('cm', (fl2, pa.node()),
922 922 "remote created, get or merge")
923 923 elif n2 != ma[f]:
924 924 df = None
925 925 for d in dirmove:
926 926 if f.startswith(d):
927 927 # new file added in a directory that was moved
928 928 df = dirmove[d] + f[len(d):]
929 929 break
930 930 if df in m1:
931 931 actions[df] = ('m', (df, f, f, False, pa.node()),
932 932 "local directory rename - respect move from " + f)
933 933 elif acceptremote:
934 934 actions[f] = ('c', (fl2,), "remote recreating")
935 935 else:
936 936 actions[f] = ('dc', (None, f, f, False, pa.node()),
937 937 "prompt deleted/changed")
938 938
939 939 return actions, diverge, renamedelete
940 940
941 941 def _resolvetrivial(repo, wctx, mctx, ancestor, actions):
942 942 """Resolves false conflicts where the nodeid changed but the content
943 943 remained the same."""
944 944
945 945 for f, (m, args, msg) in actions.items():
946 946 if m == 'cd' and f in ancestor and not wctx[f].cmp(ancestor[f]):
947 947 # local did change but ended up with same content
948 948 actions[f] = 'r', None, "prompt same"
949 949 elif m == 'dc' and f in ancestor and not mctx[f].cmp(ancestor[f]):
950 950 # remote did change but ended up with same content
951 951 del actions[f] # don't get = keep local deleted
952 952
953 953 def calculateupdates(repo, wctx, mctx, ancestors, branchmerge, force,
954 954 acceptremote, followcopies, matcher=None,
955 955 mergeforce=False):
956 956 "Calculate the actions needed to merge mctx into wctx using ancestors"
957 957 if len(ancestors) == 1: # default
958 958 actions, diverge, renamedelete = manifestmerge(
959 959 repo, wctx, mctx, ancestors[0], branchmerge, force, matcher,
960 960 acceptremote, followcopies)
961 961 _checkunknownfiles(repo, wctx, mctx, force, actions, mergeforce)
962 962
963 963 else: # only when merge.preferancestor=* - the default
964 964 repo.ui.note(
965 965 _("note: merging %s and %s using bids from ancestors %s\n") %
966 966 (wctx, mctx, _(' and ').join(str(anc) for anc in ancestors)))
967 967
968 968 # Call for bids
969 969 fbids = {} # mapping filename to bids (action method to list af actions)
970 970 diverge, renamedelete = None, None
971 971 for ancestor in ancestors:
972 972 repo.ui.note(_('\ncalculating bids for ancestor %s\n') % ancestor)
973 973 actions, diverge1, renamedelete1 = manifestmerge(
974 974 repo, wctx, mctx, ancestor, branchmerge, force, matcher,
975 975 acceptremote, followcopies)
976 976 _checkunknownfiles(repo, wctx, mctx, force, actions, mergeforce)
977 977
978 978 # Track the shortest set of warning on the theory that bid
979 979 # merge will correctly incorporate more information
980 980 if diverge is None or len(diverge1) < len(diverge):
981 981 diverge = diverge1
982 982 if renamedelete is None or len(renamedelete) < len(renamedelete1):
983 983 renamedelete = renamedelete1
984 984
985 985 for f, a in sorted(actions.iteritems()):
986 986 m, args, msg = a
987 987 repo.ui.debug(' %s: %s -> %s\n' % (f, msg, m))
988 988 if f in fbids:
989 989 d = fbids[f]
990 990 if m in d:
991 991 d[m].append(a)
992 992 else:
993 993 d[m] = [a]
994 994 else:
995 995 fbids[f] = {m: [a]}
996 996
997 997 # Pick the best bid for each file
998 998 repo.ui.note(_('\nauction for merging merge bids\n'))
999 999 actions = {}
1000 1000 dms = [] # filenames that have dm actions
1001 1001 for f, bids in sorted(fbids.items()):
1002 1002 # bids is a mapping from action method to list af actions
1003 1003 # Consensus?
1004 1004 if len(bids) == 1: # all bids are the same kind of method
1005 1005 m, l = bids.items()[0]
1006 1006 if all(a == l[0] for a in l[1:]): # len(bids) is > 1
1007 1007 repo.ui.note(_(" %s: consensus for %s\n") % (f, m))
1008 1008 actions[f] = l[0]
1009 1009 if m == 'dm':
1010 1010 dms.append(f)
1011 1011 continue
1012 1012 # If keep is an option, just do it.
1013 1013 if 'k' in bids:
1014 1014 repo.ui.note(_(" %s: picking 'keep' action\n") % f)
1015 1015 actions[f] = bids['k'][0]
1016 1016 continue
1017 1017 # If there are gets and they all agree [how could they not?], do it.
1018 1018 if 'g' in bids:
1019 1019 ga0 = bids['g'][0]
1020 1020 if all(a == ga0 for a in bids['g'][1:]):
1021 1021 repo.ui.note(_(" %s: picking 'get' action\n") % f)
1022 1022 actions[f] = ga0
1023 1023 continue
1024 1024 # TODO: Consider other simple actions such as mode changes
1025 1025 # Handle inefficient democrazy.
1026 1026 repo.ui.note(_(' %s: multiple bids for merge action:\n') % f)
1027 1027 for m, l in sorted(bids.items()):
1028 1028 for _f, args, msg in l:
1029 1029 repo.ui.note(' %s -> %s\n' % (msg, m))
1030 1030 # Pick random action. TODO: Instead, prompt user when resolving
1031 1031 m, l = bids.items()[0]
1032 1032 repo.ui.warn(_(' %s: ambiguous merge - picked %s action\n') %
1033 1033 (f, m))
1034 1034 actions[f] = l[0]
1035 1035 if m == 'dm':
1036 1036 dms.append(f)
1037 1037 continue
1038 1038 # Work around 'dm' that can cause multiple actions for the same file
1039 1039 for f in dms:
1040 1040 dm, (f0, flags), msg = actions[f]
1041 1041 assert dm == 'dm', dm
1042 1042 if f0 in actions and actions[f0][0] == 'r':
1043 1043 # We have one bid for removing a file and another for moving it.
1044 1044 # These two could be merged as first move and then delete ...
1045 1045 # but instead drop moving and just delete.
1046 1046 del actions[f]
1047 1047 repo.ui.note(_('end of auction\n\n'))
1048 1048
1049 1049 _resolvetrivial(repo, wctx, mctx, ancestors[0], actions)
1050 1050
1051 1051 if wctx.rev() is None:
1052 1052 fractions = _forgetremoved(wctx, mctx, branchmerge)
1053 1053 actions.update(fractions)
1054 1054
1055 1055 return actions, diverge, renamedelete
1056 1056
1057 1057 def batchremove(repo, actions):
1058 1058 """apply removes to the working directory
1059 1059
1060 1060 yields tuples for progress updates
1061 1061 """
1062 1062 verbose = repo.ui.verbose
1063 1063 unlink = util.unlinkpath
1064 1064 wjoin = repo.wjoin
1065 1065 audit = repo.wvfs.audit
1066 1066 try:
1067 1067 cwd = pycompat.getcwd()
1068 1068 except OSError as err:
1069 1069 if err.errno != errno.ENOENT:
1070 1070 raise
1071 1071 cwd = None
1072 1072 i = 0
1073 1073 for f, args, msg in actions:
1074 1074 repo.ui.debug(" %s: %s -> r\n" % (f, msg))
1075 1075 if verbose:
1076 1076 repo.ui.note(_("removing %s\n") % f)
1077 1077 audit(f)
1078 1078 try:
1079 1079 unlink(wjoin(f), ignoremissing=True)
1080 1080 except OSError as inst:
1081 1081 repo.ui.warn(_("update failed to remove %s: %s!\n") %
1082 1082 (f, inst.strerror))
1083 1083 if i == 100:
1084 1084 yield i, f
1085 1085 i = 0
1086 1086 i += 1
1087 1087 if i > 0:
1088 1088 yield i, f
1089 1089 if cwd:
1090 1090 # cwd was present before we started to remove files
1091 1091 # let's check if it is present after we removed them
1092 1092 try:
1093 1093 pycompat.getcwd()
1094 1094 except OSError as err:
1095 1095 if err.errno != errno.ENOENT:
1096 1096 raise
1097 1097 # Print a warning if cwd was deleted
1098 1098 repo.ui.warn(_("current directory was removed\n"
1099 1099 "(consider changing to repo root: %s)\n") %
1100 1100 repo.root)
1101 1101
1102 1102 def batchget(repo, mctx, actions):
1103 1103 """apply gets to the working directory
1104 1104
1105 1105 mctx is the context to get from
1106 1106
1107 1107 yields tuples for progress updates
1108 1108 """
1109 1109 verbose = repo.ui.verbose
1110 1110 fctx = mctx.filectx
1111 1111 wwrite = repo.wwrite
1112 1112 ui = repo.ui
1113 1113 i = 0
1114 1114 with repo.wvfs.backgroundclosing(ui, expectedcount=len(actions)):
1115 1115 for f, (flags, backup), msg in actions:
1116 1116 repo.ui.debug(" %s: %s -> g\n" % (f, msg))
1117 1117 if verbose:
1118 1118 repo.ui.note(_("getting %s\n") % f)
1119 1119
1120 1120 if backup:
1121 1121 absf = repo.wjoin(f)
1122 1122 orig = scmutil.origpath(ui, repo, absf)
1123 1123 try:
1124 1124 if repo.wvfs.isfileorlink(f):
1125 1125 util.rename(absf, orig)
1126 1126 except OSError as e:
1127 1127 if e.errno != errno.ENOENT:
1128 1128 raise
1129 1129
1130 1130 if repo.wvfs.isdir(f) and not repo.wvfs.islink(f):
1131 1131 repo.wvfs.removedirs(f)
1132 1132 wwrite(f, fctx(f).data(), flags, backgroundclose=True)
1133 1133 if i == 100:
1134 1134 yield i, f
1135 1135 i = 0
1136 1136 i += 1
1137 1137 if i > 0:
1138 1138 yield i, f
1139 1139
1140 1140 def applyupdates(repo, actions, wctx, mctx, overwrite, labels=None):
1141 1141 """apply the merge action list to the working directory
1142 1142
1143 1143 wctx is the working copy context
1144 1144 mctx is the context to be merged into the working copy
1145 1145
1146 1146 Return a tuple of counts (updated, merged, removed, unresolved) that
1147 1147 describes how many files were affected by the update.
1148 1148 """
1149 1149
1150 1150 updated, merged, removed = 0, 0, 0
1151 1151 ms = mergestate.clean(repo, wctx.p1().node(), mctx.node(), labels)
1152 1152 moves = []
1153 1153 for m, l in actions.items():
1154 1154 l.sort()
1155 1155
1156 1156 # 'cd' and 'dc' actions are treated like other merge conflicts
1157 1157 mergeactions = sorted(actions['cd'])
1158 1158 mergeactions.extend(sorted(actions['dc']))
1159 1159 mergeactions.extend(actions['m'])
1160 1160 for f, args, msg in mergeactions:
1161 1161 f1, f2, fa, move, anc = args
1162 1162 if f == '.hgsubstate': # merged internally
1163 1163 continue
1164 1164 if f1 is None:
1165 1165 fcl = filemerge.absentfilectx(wctx, fa)
1166 1166 else:
1167 1167 repo.ui.debug(" preserving %s for resolve of %s\n" % (f1, f))
1168 1168 fcl = wctx[f1]
1169 1169 if f2 is None:
1170 1170 fco = filemerge.absentfilectx(mctx, fa)
1171 1171 else:
1172 1172 fco = mctx[f2]
1173 1173 actx = repo[anc]
1174 1174 if fa in actx:
1175 1175 fca = actx[fa]
1176 1176 else:
1177 1177 # TODO: move to absentfilectx
1178 1178 fca = repo.filectx(f1, fileid=nullrev)
1179 1179 ms.add(fcl, fco, fca, f)
1180 1180 if f1 != f and move:
1181 1181 moves.append(f1)
1182 1182
1183 1183 audit = repo.wvfs.audit
1184 1184 _updating = _('updating')
1185 1185 _files = _('files')
1186 1186 progress = repo.ui.progress
1187 1187
1188 1188 # remove renamed files after safely stored
1189 1189 for f in moves:
1190 1190 if os.path.lexists(repo.wjoin(f)):
1191 1191 repo.ui.debug("removing %s\n" % f)
1192 1192 audit(f)
1193 1193 util.unlinkpath(repo.wjoin(f))
1194 1194
1195 1195 numupdates = sum(len(l) for m, l in actions.items() if m != 'k')
1196 1196
1197 1197 if [a for a in actions['r'] if a[0] == '.hgsubstate']:
1198 1198 subrepo.submerge(repo, wctx, mctx, wctx, overwrite, labels)
1199 1199
1200 1200 # remove in parallel (must come first)
1201 1201 z = 0
1202 1202 prog = worker.worker(repo.ui, 0.001, batchremove, (repo,), actions['r'])
1203 1203 for i, item in prog:
1204 1204 z += i
1205 1205 progress(_updating, z, item=item, total=numupdates, unit=_files)
1206 1206 removed = len(actions['r'])
1207 1207
1208 1208 # get in parallel
1209 1209 prog = worker.worker(repo.ui, 0.001, batchget, (repo, mctx), actions['g'])
1210 1210 for i, item in prog:
1211 1211 z += i
1212 1212 progress(_updating, z, item=item, total=numupdates, unit=_files)
1213 1213 updated = len(actions['g'])
1214 1214
1215 1215 if [a for a in actions['g'] if a[0] == '.hgsubstate']:
1216 1216 subrepo.submerge(repo, wctx, mctx, wctx, overwrite, labels)
1217 1217
1218 1218 # forget (manifest only, just log it) (must come first)
1219 1219 for f, args, msg in actions['f']:
1220 1220 repo.ui.debug(" %s: %s -> f\n" % (f, msg))
1221 1221 z += 1
1222 1222 progress(_updating, z, item=f, total=numupdates, unit=_files)
1223 1223
1224 1224 # re-add (manifest only, just log it)
1225 1225 for f, args, msg in actions['a']:
1226 1226 repo.ui.debug(" %s: %s -> a\n" % (f, msg))
1227 1227 z += 1
1228 1228 progress(_updating, z, item=f, total=numupdates, unit=_files)
1229 1229
1230 1230 # re-add/mark as modified (manifest only, just log it)
1231 1231 for f, args, msg in actions['am']:
1232 1232 repo.ui.debug(" %s: %s -> am\n" % (f, msg))
1233 1233 z += 1
1234 1234 progress(_updating, z, item=f, total=numupdates, unit=_files)
1235 1235
1236 1236 # keep (noop, just log it)
1237 1237 for f, args, msg in actions['k']:
1238 1238 repo.ui.debug(" %s: %s -> k\n" % (f, msg))
1239 1239 # no progress
1240 1240
1241 1241 # directory rename, move local
1242 1242 for f, args, msg in actions['dm']:
1243 1243 repo.ui.debug(" %s: %s -> dm\n" % (f, msg))
1244 1244 z += 1
1245 1245 progress(_updating, z, item=f, total=numupdates, unit=_files)
1246 1246 f0, flags = args
1247 1247 repo.ui.note(_("moving %s to %s\n") % (f0, f))
1248 1248 audit(f)
1249 1249 repo.wwrite(f, wctx.filectx(f0).data(), flags)
1250 1250 util.unlinkpath(repo.wjoin(f0))
1251 1251 updated += 1
1252 1252
1253 1253 # local directory rename, get
1254 1254 for f, args, msg in actions['dg']:
1255 1255 repo.ui.debug(" %s: %s -> dg\n" % (f, msg))
1256 1256 z += 1
1257 1257 progress(_updating, z, item=f, total=numupdates, unit=_files)
1258 1258 f0, flags = args
1259 1259 repo.ui.note(_("getting %s to %s\n") % (f0, f))
1260 1260 repo.wwrite(f, mctx.filectx(f0).data(), flags)
1261 1261 updated += 1
1262 1262
1263 1263 # exec
1264 1264 for f, args, msg in actions['e']:
1265 1265 repo.ui.debug(" %s: %s -> e\n" % (f, msg))
1266 1266 z += 1
1267 1267 progress(_updating, z, item=f, total=numupdates, unit=_files)
1268 1268 flags, = args
1269 1269 audit(f)
1270 1270 util.setflags(repo.wjoin(f), 'l' in flags, 'x' in flags)
1271 1271 updated += 1
1272 1272
1273 1273 # the ordering is important here -- ms.mergedriver will raise if the merge
1274 1274 # driver has changed, and we want to be able to bypass it when overwrite is
1275 1275 # True
1276 1276 usemergedriver = not overwrite and mergeactions and ms.mergedriver
1277 1277
1278 1278 if usemergedriver:
1279 1279 ms.commit()
1280 1280 proceed = driverpreprocess(repo, ms, wctx, labels=labels)
1281 1281 # the driver might leave some files unresolved
1282 1282 unresolvedf = set(ms.unresolved())
1283 1283 if not proceed:
1284 1284 # XXX setting unresolved to at least 1 is a hack to make sure we
1285 1285 # error out
1286 1286 return updated, merged, removed, max(len(unresolvedf), 1)
1287 1287 newactions = []
1288 1288 for f, args, msg in mergeactions:
1289 1289 if f in unresolvedf:
1290 1290 newactions.append((f, args, msg))
1291 1291 mergeactions = newactions
1292 1292
1293 1293 # premerge
1294 1294 tocomplete = []
1295 1295 for f, args, msg in mergeactions:
1296 1296 repo.ui.debug(" %s: %s -> m (premerge)\n" % (f, msg))
1297 1297 z += 1
1298 1298 progress(_updating, z, item=f, total=numupdates, unit=_files)
1299 1299 if f == '.hgsubstate': # subrepo states need updating
1300 1300 subrepo.submerge(repo, wctx, mctx, wctx.ancestor(mctx),
1301 1301 overwrite, labels)
1302 1302 continue
1303 1303 audit(f)
1304 1304 complete, r = ms.preresolve(f, wctx)
1305 1305 if not complete:
1306 1306 numupdates += 1
1307 1307 tocomplete.append((f, args, msg))
1308 1308
1309 1309 # merge
1310 1310 for f, args, msg in tocomplete:
1311 1311 repo.ui.debug(" %s: %s -> m (merge)\n" % (f, msg))
1312 1312 z += 1
1313 1313 progress(_updating, z, item=f, total=numupdates, unit=_files)
1314 1314 ms.resolve(f, wctx)
1315 1315
1316 1316 ms.commit()
1317 1317
1318 1318 unresolved = ms.unresolvedcount()
1319 1319
1320 1320 if usemergedriver and not unresolved and ms.mdstate() != 's':
1321 1321 if not driverconclude(repo, ms, wctx, labels=labels):
1322 1322 # XXX setting unresolved to at least 1 is a hack to make sure we
1323 1323 # error out
1324 1324 unresolved = max(unresolved, 1)
1325 1325
1326 1326 ms.commit()
1327 1327
1328 1328 msupdated, msmerged, msremoved = ms.counts()
1329 1329 updated += msupdated
1330 1330 merged += msmerged
1331 1331 removed += msremoved
1332 1332
1333 1333 extraactions = ms.actions()
1334 1334 if extraactions:
1335 1335 mfiles = set(a[0] for a in actions['m'])
1336 1336 for k, acts in extraactions.iteritems():
1337 1337 actions[k].extend(acts)
1338 1338 # Remove these files from actions['m'] as well. This is important
1339 1339 # because in recordupdates, files in actions['m'] are processed
1340 1340 # after files in other actions, and the merge driver might add
1341 1341 # files to those actions via extraactions above. This can lead to a
1342 1342 # file being recorded twice, with poor results. This is especially
1343 1343 # problematic for actions['r'] (currently only possible with the
1344 1344 # merge driver in the initial merge process; interrupted merges
1345 1345 # don't go through this flow).
1346 1346 #
1347 1347 # The real fix here is to have indexes by both file and action so
1348 1348 # that when the action for a file is changed it is automatically
1349 1349 # reflected in the other action lists. But that involves a more
1350 1350 # complex data structure, so this will do for now.
1351 1351 #
1352 1352 # We don't need to do the same operation for 'dc' and 'cd' because
1353 1353 # those lists aren't consulted again.
1354 1354 mfiles.difference_update(a[0] for a in acts)
1355 1355
1356 1356 actions['m'] = [a for a in actions['m'] if a[0] in mfiles]
1357 1357
1358 1358 progress(_updating, None, total=numupdates, unit=_files)
1359 1359
1360 1360 return updated, merged, removed, unresolved
1361 1361
1362 1362 def recordupdates(repo, actions, branchmerge):
1363 1363 "record merge actions to the dirstate"
1364 1364 # remove (must come first)
1365 1365 for f, args, msg in actions.get('r', []):
1366 1366 if branchmerge:
1367 1367 repo.dirstate.remove(f)
1368 1368 else:
1369 1369 repo.dirstate.drop(f)
1370 1370
1371 1371 # forget (must come first)
1372 1372 for f, args, msg in actions.get('f', []):
1373 1373 repo.dirstate.drop(f)
1374 1374
1375 1375 # re-add
1376 1376 for f, args, msg in actions.get('a', []):
1377 1377 repo.dirstate.add(f)
1378 1378
1379 1379 # re-add/mark as modified
1380 1380 for f, args, msg in actions.get('am', []):
1381 1381 if branchmerge:
1382 1382 repo.dirstate.normallookup(f)
1383 1383 else:
1384 1384 repo.dirstate.add(f)
1385 1385
1386 1386 # exec change
1387 1387 for f, args, msg in actions.get('e', []):
1388 1388 repo.dirstate.normallookup(f)
1389 1389
1390 1390 # keep
1391 1391 for f, args, msg in actions.get('k', []):
1392 1392 pass
1393 1393
1394 1394 # get
1395 1395 for f, args, msg in actions.get('g', []):
1396 1396 if branchmerge:
1397 1397 repo.dirstate.otherparent(f)
1398 1398 else:
1399 1399 repo.dirstate.normal(f)
1400 1400
1401 1401 # merge
1402 1402 for f, args, msg in actions.get('m', []):
1403 1403 f1, f2, fa, move, anc = args
1404 1404 if branchmerge:
1405 1405 # We've done a branch merge, mark this file as merged
1406 1406 # so that we properly record the merger later
1407 1407 repo.dirstate.merge(f)
1408 1408 if f1 != f2: # copy/rename
1409 1409 if move:
1410 1410 repo.dirstate.remove(f1)
1411 1411 if f1 != f:
1412 1412 repo.dirstate.copy(f1, f)
1413 1413 else:
1414 1414 repo.dirstate.copy(f2, f)
1415 1415 else:
1416 1416 # We've update-merged a locally modified file, so
1417 1417 # we set the dirstate to emulate a normal checkout
1418 1418 # of that file some time in the past. Thus our
1419 1419 # merge will appear as a normal local file
1420 1420 # modification.
1421 1421 if f2 == f: # file not locally copied/moved
1422 1422 repo.dirstate.normallookup(f)
1423 1423 if move:
1424 1424 repo.dirstate.drop(f1)
1425 1425
1426 1426 # directory rename, move local
1427 1427 for f, args, msg in actions.get('dm', []):
1428 1428 f0, flag = args
1429 1429 if branchmerge:
1430 1430 repo.dirstate.add(f)
1431 1431 repo.dirstate.remove(f0)
1432 1432 repo.dirstate.copy(f0, f)
1433 1433 else:
1434 1434 repo.dirstate.normal(f)
1435 1435 repo.dirstate.drop(f0)
1436 1436
1437 1437 # directory rename, get
1438 1438 for f, args, msg in actions.get('dg', []):
1439 1439 f0, flag = args
1440 1440 if branchmerge:
1441 1441 repo.dirstate.add(f)
1442 1442 repo.dirstate.copy(f0, f)
1443 1443 else:
1444 1444 repo.dirstate.normal(f)
1445 1445
1446 1446 def update(repo, node, branchmerge, force, ancestor=None,
1447 mergeancestor=False, labels=None, matcher=None, mergeforce=False):
1447 mergeancestor=False, labels=None, matcher=None, mergeforce=False,
1448 updatecheck=None):
1448 1449 """
1449 1450 Perform a merge between the working directory and the given node
1450 1451
1451 1452 node = the node to update to
1452 1453 branchmerge = whether to merge between branches
1453 1454 force = whether to force branch merging or file overwriting
1454 1455 matcher = a matcher to filter file lists (dirstate not updated)
1455 1456 mergeancestor = whether it is merging with an ancestor. If true,
1456 1457 we should accept the incoming changes for any prompts that occur.
1457 1458 If false, merging with an ancestor (fast-forward) is only allowed
1458 1459 between different named branches. This flag is used by rebase extension
1459 1460 as a temporary fix and should be avoided in general.
1460 1461 labels = labels to use for base, local and other
1461 1462 mergeforce = whether the merge was run with 'merge --force' (deprecated): if
1462 1463 this is True, then 'force' should be True as well.
1463 1464
1464 1465 The table below shows all the behaviors of the update command
1465 1466 given the -c and -C or no options, whether the working directory
1466 1467 is dirty, whether a revision is specified, and the relationship of
1467 1468 the parent rev to the target rev (linear or not). Match from top first.
1468 1469
1469 1470 This logic is tested by test-update-branches.t.
1470 1471
1471 -c -C dirty rev linear | result
1472 y y * * * | (1)
1473 * * * n n | x
1474 * * n * * | ok
1475 n n y * y | merge
1476 n n y y n | (2)
1477 n y y * * | discard
1478 y n y * * | (3)
1472 -c -C -m dirty rev linear | result
1473 y y * * * * | (1)
1474 y * y * * * | (1)
1475 * y y * * * | (1)
1476 * * * * n n | x
1477 * * * n * * | ok
1478 n n n y * y | merge
1479 n n n y y n | (2)
1480 n n y y * * | merge
1481 n y n y * * | discard
1482 y n n y * * | (3)
1479 1483
1480 1484 x = can't happen
1481 1485 * = don't-care
1482 1486 1 = incompatible options (checked in commands.py)
1483 1487 2 = abort: uncommitted changes (commit or update --clean to discard changes)
1484 1488 3 = abort: uncommitted changes (checked in commands.py)
1485 1489
1486 1490 Return the same tuple as applyupdates().
1487 1491 """
1488 1492
1489 # This functon used to find the default destination if node was None, but
1493 # This function used to find the default destination if node was None, but
1490 1494 # that's now in destutil.py.
1491 1495 assert node is not None
1496 if not branchmerge and not force:
1497 # TODO: remove the default once all callers that pass branchmerge=False
1498 # and force=False pass a value for updatecheck. We may want to allow
1499 # updatecheck='abort' to better suppport some of these callers.
1500 if updatecheck is None:
1501 updatecheck = 'linear'
1502 assert updatecheck in ('none', 'linear')
1492 1503 # If we're doing a partial update, we need to skip updating
1493 1504 # the dirstate, so make a note of any partial-ness to the
1494 1505 # update here.
1495 1506 if matcher is None or matcher.always():
1496 1507 partial = False
1497 1508 else:
1498 1509 partial = True
1499 1510 with repo.wlock():
1500 1511 wc = repo[None]
1501 1512 pl = wc.parents()
1502 1513 p1 = pl[0]
1503 1514 pas = [None]
1504 1515 if ancestor is not None:
1505 1516 pas = [repo[ancestor]]
1506 1517
1507 1518 overwrite = force and not branchmerge
1508 1519
1509 1520 p2 = repo[node]
1510 1521 if pas[0] is None:
1511 1522 if repo.ui.configlist('merge', 'preferancestor', ['*']) == ['*']:
1512 1523 cahs = repo.changelog.commonancestorsheads(p1.node(), p2.node())
1513 1524 pas = [repo[anc] for anc in (sorted(cahs) or [nullid])]
1514 1525 else:
1515 1526 pas = [p1.ancestor(p2, warn=branchmerge)]
1516 1527
1517 1528 fp1, fp2, xp1, xp2 = p1.node(), p2.node(), str(p1), str(p2)
1518 1529
1519 1530 ### check phase
1520 1531 if not overwrite:
1521 1532 if len(pl) > 1:
1522 1533 raise error.Abort(_("outstanding uncommitted merge"))
1523 1534 ms = mergestate.read(repo)
1524 1535 if list(ms.unresolved()):
1525 1536 raise error.Abort(_("outstanding merge conflicts"))
1526 1537 if branchmerge:
1527 1538 if pas == [p2]:
1528 1539 raise error.Abort(_("merging with a working directory ancestor"
1529 1540 " has no effect"))
1530 1541 elif pas == [p1]:
1531 1542 if not mergeancestor and p1.branch() == p2.branch():
1532 1543 raise error.Abort(_("nothing to merge"),
1533 1544 hint=_("use 'hg update' "
1534 1545 "or check 'hg heads'"))
1535 1546 if not force and (wc.files() or wc.deleted()):
1536 1547 raise error.Abort(_("uncommitted changes"),
1537 1548 hint=_("use 'hg status' to list changes"))
1538 1549 for s in sorted(wc.substate):
1539 1550 wc.sub(s).bailifchanged()
1540 1551
1541 1552 elif not overwrite:
1542 1553 if p1 == p2: # no-op update
1543 1554 # call the hooks and exit early
1544 1555 repo.hook('preupdate', throw=True, parent1=xp2, parent2='')
1545 1556 repo.hook('update', parent1=xp2, parent2='', error=0)
1546 1557 return 0, 0, 0, 0
1547 1558
1548 if pas not in ([p1], [p2]): # nonlinear
1559 if (updatecheck == 'linear' and
1560 pas not in ([p1], [p2])): # nonlinear
1549 1561 dirty = wc.dirty(missing=True)
1550 1562 if dirty:
1551 1563 # Branching is a bit strange to ensure we do the minimal
1552 1564 # amount of call to obsolete.foreground.
1553 1565 foreground = obsolete.foreground(repo, [p1.node()])
1554 1566 # note: the <node> variable contains a random identifier
1555 1567 if repo[node].node() in foreground:
1556 1568 pass # allow updating to successors
1557 1569 else:
1558 1570 msg = _("uncommitted changes")
1559 1571 hint = _("commit or update --clean to discard changes")
1560 1572 raise error.UpdateAbort(msg, hint=hint)
1561 1573 else:
1562 1574 # Allow jumping branches if clean and specific rev given
1563 1575 pass
1564 1576
1565 1577 if overwrite:
1566 1578 pas = [wc]
1567 1579 elif not branchmerge:
1568 1580 pas = [p1]
1569 1581
1570 1582 # deprecated config: merge.followcopies
1571 1583 followcopies = repo.ui.configbool('merge', 'followcopies', True)
1572 1584 if overwrite:
1573 1585 followcopies = False
1574 1586 elif not pas[0]:
1575 1587 followcopies = False
1576 1588 if not branchmerge and not wc.dirty(missing=True):
1577 1589 followcopies = False
1578 1590
1579 1591 ### calculate phase
1580 1592 actionbyfile, diverge, renamedelete = calculateupdates(
1581 1593 repo, wc, p2, pas, branchmerge, force, mergeancestor,
1582 1594 followcopies, matcher=matcher, mergeforce=mergeforce)
1583 1595
1584 1596 # Prompt and create actions. Most of this is in the resolve phase
1585 1597 # already, but we can't handle .hgsubstate in filemerge or
1586 1598 # subrepo.submerge yet so we have to keep prompting for it.
1587 1599 if '.hgsubstate' in actionbyfile:
1588 1600 f = '.hgsubstate'
1589 1601 m, args, msg = actionbyfile[f]
1590 1602 prompts = filemerge.partextras(labels)
1591 1603 prompts['f'] = f
1592 1604 if m == 'cd':
1593 1605 if repo.ui.promptchoice(
1594 1606 _("local%(l)s changed %(f)s which other%(o)s deleted\n"
1595 1607 "use (c)hanged version or (d)elete?"
1596 1608 "$$ &Changed $$ &Delete") % prompts, 0):
1597 1609 actionbyfile[f] = ('r', None, "prompt delete")
1598 1610 elif f in p1:
1599 1611 actionbyfile[f] = ('am', None, "prompt keep")
1600 1612 else:
1601 1613 actionbyfile[f] = ('a', None, "prompt keep")
1602 1614 elif m == 'dc':
1603 1615 f1, f2, fa, move, anc = args
1604 1616 flags = p2[f2].flags()
1605 1617 if repo.ui.promptchoice(
1606 1618 _("other%(o)s changed %(f)s which local%(l)s deleted\n"
1607 1619 "use (c)hanged version or leave (d)eleted?"
1608 1620 "$$ &Changed $$ &Deleted") % prompts, 0) == 0:
1609 1621 actionbyfile[f] = ('g', (flags, False), "prompt recreating")
1610 1622 else:
1611 1623 del actionbyfile[f]
1612 1624
1613 1625 # Convert to dictionary-of-lists format
1614 1626 actions = dict((m, []) for m in 'a am f g cd dc r dm dg m e k'.split())
1615 1627 for f, (m, args, msg) in actionbyfile.iteritems():
1616 1628 if m not in actions:
1617 1629 actions[m] = []
1618 1630 actions[m].append((f, args, msg))
1619 1631
1620 1632 if not util.fscasesensitive(repo.path):
1621 1633 # check collision between files only in p2 for clean update
1622 1634 if (not branchmerge and
1623 1635 (force or not wc.dirty(missing=True, branch=False))):
1624 1636 _checkcollision(repo, p2.manifest(), None)
1625 1637 else:
1626 1638 _checkcollision(repo, wc.manifest(), actions)
1627 1639
1628 1640 # divergent renames
1629 1641 for f, fl in sorted(diverge.iteritems()):
1630 1642 repo.ui.warn(_("note: possible conflict - %s was renamed "
1631 1643 "multiple times to:\n") % f)
1632 1644 for nf in fl:
1633 1645 repo.ui.warn(" %s\n" % nf)
1634 1646
1635 1647 # rename and delete
1636 1648 for f, fl in sorted(renamedelete.iteritems()):
1637 1649 repo.ui.warn(_("note: possible conflict - %s was deleted "
1638 1650 "and renamed to:\n") % f)
1639 1651 for nf in fl:
1640 1652 repo.ui.warn(" %s\n" % nf)
1641 1653
1642 1654 ### apply phase
1643 1655 if not branchmerge: # just jump to the new rev
1644 1656 fp1, fp2, xp1, xp2 = fp2, nullid, xp2, ''
1645 1657 if not partial:
1646 1658 repo.hook('preupdate', throw=True, parent1=xp1, parent2=xp2)
1647 1659 # note that we're in the middle of an update
1648 1660 repo.vfs.write('updatestate', p2.hex())
1649 1661
1650 1662 stats = applyupdates(repo, actions, wc, p2, overwrite, labels=labels)
1651 1663
1652 1664 if not partial:
1653 1665 repo.dirstate.beginparentchange()
1654 1666 repo.setparents(fp1, fp2)
1655 1667 recordupdates(repo, actions, branchmerge)
1656 1668 # update completed, clear state
1657 1669 util.unlink(repo.join('updatestate'))
1658 1670
1659 1671 if not branchmerge:
1660 1672 repo.dirstate.setbranch(p2.branch())
1661 1673 repo.dirstate.endparentchange()
1662 1674
1663 1675 if not partial:
1664 1676 repo.hook('update', parent1=xp1, parent2=xp2, error=stats[3])
1665 1677 return stats
1666 1678
1667 1679 def graft(repo, ctx, pctx, labels, keepparent=False):
1668 1680 """Do a graft-like merge.
1669 1681
1670 1682 This is a merge where the merge ancestor is chosen such that one
1671 1683 or more changesets are grafted onto the current changeset. In
1672 1684 addition to the merge, this fixes up the dirstate to include only
1673 1685 a single parent (if keepparent is False) and tries to duplicate any
1674 1686 renames/copies appropriately.
1675 1687
1676 1688 ctx - changeset to rebase
1677 1689 pctx - merge base, usually ctx.p1()
1678 1690 labels - merge labels eg ['local', 'graft']
1679 1691 keepparent - keep second parent if any
1680 1692
1681 1693 """
1682 1694 # If we're grafting a descendant onto an ancestor, be sure to pass
1683 1695 # mergeancestor=True to update. This does two things: 1) allows the merge if
1684 1696 # the destination is the same as the parent of the ctx (so we can use graft
1685 1697 # to copy commits), and 2) informs update that the incoming changes are
1686 1698 # newer than the destination so it doesn't prompt about "remote changed foo
1687 1699 # which local deleted".
1688 1700 mergeancestor = repo.changelog.isancestor(repo['.'].node(), ctx.node())
1689 1701
1690 1702 stats = update(repo, ctx.node(), True, True, pctx.node(),
1691 1703 mergeancestor=mergeancestor, labels=labels)
1692 1704
1693 1705 pother = nullid
1694 1706 parents = ctx.parents()
1695 1707 if keepparent and len(parents) == 2 and pctx in parents:
1696 1708 parents.remove(pctx)
1697 1709 pother = parents[0].node()
1698 1710
1699 1711 repo.dirstate.beginparentchange()
1700 1712 repo.setparents(repo['.'].node(), pother)
1701 1713 repo.dirstate.write(repo.currenttransaction())
1702 1714 # fix up dirstate for copies and renames
1703 1715 copies.duplicatecopies(repo, ctx.rev(), pctx.rev())
1704 1716 repo.dirstate.endparentchange()
1705 1717 return stats
@@ -1,360 +1,360
1 1 Show all commands except debug commands
2 2 $ hg debugcomplete
3 3 add
4 4 addremove
5 5 annotate
6 6 archive
7 7 backout
8 8 bisect
9 9 bookmarks
10 10 branch
11 11 branches
12 12 bundle
13 13 cat
14 14 clone
15 15 commit
16 16 config
17 17 copy
18 18 diff
19 19 export
20 20 files
21 21 forget
22 22 graft
23 23 grep
24 24 heads
25 25 help
26 26 identify
27 27 import
28 28 incoming
29 29 init
30 30 locate
31 31 log
32 32 manifest
33 33 merge
34 34 outgoing
35 35 parents
36 36 paths
37 37 phase
38 38 pull
39 39 push
40 40 recover
41 41 remove
42 42 rename
43 43 resolve
44 44 revert
45 45 rollback
46 46 root
47 47 serve
48 48 status
49 49 summary
50 50 tag
51 51 tags
52 52 tip
53 53 unbundle
54 54 update
55 55 verify
56 56 version
57 57
58 58 Show all commands that start with "a"
59 59 $ hg debugcomplete a
60 60 add
61 61 addremove
62 62 annotate
63 63 archive
64 64
65 65 Do not show debug commands if there are other candidates
66 66 $ hg debugcomplete d
67 67 diff
68 68
69 69 Show debug commands if there are no other candidates
70 70 $ hg debugcomplete debug
71 71 debugancestor
72 72 debugapplystreamclonebundle
73 73 debugbuilddag
74 74 debugbundle
75 75 debugcheckstate
76 76 debugcolor
77 77 debugcommands
78 78 debugcomplete
79 79 debugconfig
80 80 debugcreatestreamclonebundle
81 81 debugdag
82 82 debugdata
83 83 debugdate
84 84 debugdeltachain
85 85 debugdirstate
86 86 debugdiscovery
87 87 debugextensions
88 88 debugfileset
89 89 debugfsinfo
90 90 debuggetbundle
91 91 debugignore
92 92 debugindex
93 93 debugindexdot
94 94 debuginstall
95 95 debugknown
96 96 debuglabelcomplete
97 97 debuglocks
98 98 debugmergestate
99 99 debugnamecomplete
100 100 debugobsolete
101 101 debugpathcomplete
102 102 debugpushkey
103 103 debugpvec
104 104 debugrebuilddirstate
105 105 debugrebuildfncache
106 106 debugrename
107 107 debugrevlog
108 108 debugrevspec
109 109 debugsetparents
110 110 debugsub
111 111 debugsuccessorssets
112 112 debugtemplate
113 113 debugupgraderepo
114 114 debugwalk
115 115 debugwireargs
116 116
117 117 Do not show the alias of a debug command if there are other candidates
118 118 (this should hide rawcommit)
119 119 $ hg debugcomplete r
120 120 recover
121 121 remove
122 122 rename
123 123 resolve
124 124 revert
125 125 rollback
126 126 root
127 127 Show the alias of a debug command if there are no other candidates
128 128 $ hg debugcomplete rawc
129 129
130 130
131 131 Show the global options
132 132 $ hg debugcomplete --options | sort
133 133 --color
134 134 --config
135 135 --cwd
136 136 --debug
137 137 --debugger
138 138 --encoding
139 139 --encodingmode
140 140 --help
141 141 --hidden
142 142 --noninteractive
143 143 --pager
144 144 --profile
145 145 --quiet
146 146 --repository
147 147 --time
148 148 --traceback
149 149 --verbose
150 150 --version
151 151 -R
152 152 -h
153 153 -q
154 154 -v
155 155 -y
156 156
157 157 Show the options for the "serve" command
158 158 $ hg debugcomplete --options serve | sort
159 159 --accesslog
160 160 --address
161 161 --certificate
162 162 --cmdserver
163 163 --color
164 164 --config
165 165 --cwd
166 166 --daemon
167 167 --daemon-postexec
168 168 --debug
169 169 --debugger
170 170 --encoding
171 171 --encodingmode
172 172 --errorlog
173 173 --help
174 174 --hidden
175 175 --ipv6
176 176 --name
177 177 --noninteractive
178 178 --pager
179 179 --pid-file
180 180 --port
181 181 --prefix
182 182 --profile
183 183 --quiet
184 184 --repository
185 185 --stdio
186 186 --style
187 187 --templates
188 188 --time
189 189 --traceback
190 190 --verbose
191 191 --version
192 192 --web-conf
193 193 -6
194 194 -A
195 195 -E
196 196 -R
197 197 -a
198 198 -d
199 199 -h
200 200 -n
201 201 -p
202 202 -q
203 203 -t
204 204 -v
205 205 -y
206 206
207 207 Show an error if we use --options with an ambiguous abbreviation
208 208 $ hg debugcomplete --options s
209 209 hg: command 's' is ambiguous:
210 210 serve showconfig status summary
211 211 [255]
212 212
213 213 Show all commands + options
214 214 $ hg debugcommands
215 215 add: include, exclude, subrepos, dry-run
216 216 annotate: rev, follow, no-follow, text, user, file, date, number, changeset, line-number, ignore-all-space, ignore-space-change, ignore-blank-lines, include, exclude, template
217 217 clone: noupdate, updaterev, rev, branch, pull, uncompressed, ssh, remotecmd, insecure
218 218 commit: addremove, close-branch, amend, secret, edit, interactive, include, exclude, message, logfile, date, user, subrepos
219 219 diff: rev, change, text, git, nodates, noprefix, show-function, reverse, ignore-all-space, ignore-space-change, ignore-blank-lines, unified, stat, root, include, exclude, subrepos
220 220 export: output, switch-parent, rev, text, git, nodates
221 221 forget: include, exclude
222 222 init: ssh, remotecmd, insecure
223 223 log: follow, follow-first, date, copies, keyword, rev, removed, only-merges, user, only-branch, branch, prune, patch, git, limit, no-merges, stat, graph, style, template, include, exclude
224 224 merge: force, rev, preview, tool
225 225 pull: update, force, rev, bookmark, branch, ssh, remotecmd, insecure
226 226 push: force, rev, bookmark, branch, new-branch, ssh, remotecmd, insecure
227 227 remove: after, force, subrepos, include, exclude
228 228 serve: accesslog, daemon, daemon-postexec, errorlog, port, address, prefix, name, web-conf, webdir-conf, pid-file, stdio, cmdserver, templates, style, ipv6, certificate
229 229 status: all, modified, added, removed, deleted, clean, unknown, ignored, no-status, copies, print0, rev, change, include, exclude, subrepos, template
230 230 summary: remote
231 update: clean, check, date, rev, tool
231 update: clean, check, merge, date, rev, tool
232 232 addremove: similarity, subrepos, include, exclude, dry-run
233 233 archive: no-decode, prefix, rev, type, subrepos, include, exclude
234 234 backout: merge, commit, no-commit, parent, rev, edit, tool, include, exclude, message, logfile, date, user
235 235 bisect: reset, good, bad, skip, extend, command, noupdate
236 236 bookmarks: force, rev, delete, rename, inactive, template
237 237 branch: force, clean
238 238 branches: active, closed, template
239 239 bundle: force, rev, branch, base, all, type, ssh, remotecmd, insecure
240 240 cat: output, rev, decode, include, exclude
241 241 config: untrusted, edit, local, global, template
242 242 copy: after, force, include, exclude, dry-run
243 243 debugancestor:
244 244 debugapplystreamclonebundle:
245 245 debugbuilddag: mergeable-file, overwritten-file, new-file
246 246 debugbundle: all, spec
247 247 debugcheckstate:
248 248 debugcolor: style
249 249 debugcommands:
250 250 debugcomplete: options
251 251 debugcreatestreamclonebundle:
252 252 debugdag: tags, branches, dots, spaces
253 253 debugdata: changelog, manifest, dir
254 254 debugdate: extended
255 255 debugdeltachain: changelog, manifest, dir, template
256 256 debugdirstate: nodates, datesort
257 257 debugdiscovery: old, nonheads, ssh, remotecmd, insecure
258 258 debugextensions: template
259 259 debugfileset: rev
260 260 debugfsinfo:
261 261 debuggetbundle: head, common, type
262 262 debugignore:
263 263 debugindex: changelog, manifest, dir, format
264 264 debugindexdot: changelog, manifest, dir
265 265 debuginstall: template
266 266 debugknown:
267 267 debuglabelcomplete:
268 268 debuglocks: force-lock, force-wlock
269 269 debugmergestate:
270 270 debugnamecomplete:
271 271 debugobsolete: flags, record-parents, rev, index, delete, date, user, template
272 272 debugpathcomplete: full, normal, added, removed
273 273 debugpushkey:
274 274 debugpvec:
275 275 debugrebuilddirstate: rev, minimal
276 276 debugrebuildfncache:
277 277 debugrename: rev
278 278 debugrevlog: changelog, manifest, dir, dump
279 279 debugrevspec: optimize, show-stage, no-optimized, verify-optimized
280 280 debugsetparents:
281 281 debugsub: rev
282 282 debugsuccessorssets:
283 283 debugtemplate: rev, define
284 284 debugupgraderepo: optimize, run
285 285 debugwalk: include, exclude
286 286 debugwireargs: three, four, five, ssh, remotecmd, insecure
287 287 files: rev, print0, include, exclude, template, subrepos
288 288 graft: rev, continue, edit, log, force, currentdate, currentuser, date, user, tool, dry-run
289 289 grep: print0, all, text, follow, ignore-case, files-with-matches, line-number, rev, user, date, template, include, exclude
290 290 heads: rev, topo, active, closed, style, template
291 291 help: extension, command, keyword, system
292 292 identify: rev, num, id, branch, tags, bookmarks, ssh, remotecmd, insecure
293 293 import: strip, base, edit, force, no-commit, bypass, partial, exact, prefix, import-branch, message, logfile, date, user, similarity
294 294 incoming: force, newest-first, bundle, rev, bookmarks, branch, patch, git, limit, no-merges, stat, graph, style, template, ssh, remotecmd, insecure, subrepos
295 295 locate: rev, print0, fullpath, include, exclude
296 296 manifest: rev, all, template
297 297 outgoing: force, rev, newest-first, bookmarks, branch, patch, git, limit, no-merges, stat, graph, style, template, ssh, remotecmd, insecure, subrepos
298 298 parents: rev, style, template
299 299 paths: template
300 300 phase: public, draft, secret, force, rev
301 301 recover:
302 302 rename: after, force, include, exclude, dry-run
303 303 resolve: all, list, mark, unmark, no-status, tool, include, exclude, template
304 304 revert: all, date, rev, no-backup, interactive, include, exclude, dry-run
305 305 rollback: dry-run, force
306 306 root:
307 307 tag: force, local, rev, remove, edit, message, date, user
308 308 tags: template
309 309 tip: patch, git, style, template
310 310 unbundle: update
311 311 verify:
312 312 version: template
313 313
314 314 $ hg init a
315 315 $ cd a
316 316 $ echo fee > fee
317 317 $ hg ci -q -Amfee
318 318 $ hg tag fee
319 319 $ mkdir fie
320 320 $ echo dead > fie/dead
321 321 $ echo live > fie/live
322 322 $ hg bookmark fo
323 323 $ hg branch -q fie
324 324 $ hg ci -q -Amfie
325 325 $ echo fo > fo
326 326 $ hg branch -qf default
327 327 $ hg ci -q -Amfo
328 328 $ echo Fum > Fum
329 329 $ hg ci -q -AmFum
330 330 $ hg bookmark Fum
331 331
332 332 Test debugpathcomplete
333 333
334 334 $ hg debugpathcomplete f
335 335 fee
336 336 fie
337 337 fo
338 338 $ hg debugpathcomplete -f f
339 339 fee
340 340 fie/dead
341 341 fie/live
342 342 fo
343 343
344 344 $ hg rm Fum
345 345 $ hg debugpathcomplete -r F
346 346 Fum
347 347
348 348 Test debugnamecomplete
349 349
350 350 $ hg debugnamecomplete
351 351 Fum
352 352 default
353 353 fee
354 354 fie
355 355 fo
356 356 tip
357 357 $ hg debugnamecomplete f
358 358 fee
359 359 fie
360 360 fo
@@ -1,414 +1,434
1 1 # Construct the following history tree:
2 2 #
3 3 # @ 5:e1bb631146ca b1
4 4 # |
5 5 # o 4:a4fdb3b883c4 0:b608b9236435 b1
6 6 # |
7 7 # | o 3:4b57d2520816 1:44592833ba9f
8 8 # | |
9 9 # | | o 2:063f31070f65
10 10 # | |/
11 11 # | o 1:44592833ba9f
12 12 # |/
13 13 # o 0:b608b9236435
14 14
15 15 $ mkdir b1
16 16 $ cd b1
17 17 $ hg init
18 18 $ echo foo > foo
19 19 $ echo zero > a
20 20 $ hg init sub
21 21 $ echo suba > sub/suba
22 22 $ hg --cwd sub ci -Am addsuba
23 23 adding suba
24 24 $ echo 'sub = sub' > .hgsub
25 25 $ hg ci -qAm0
26 26 $ echo one > a ; hg ci -m1
27 27 $ echo two > a ; hg ci -m2
28 28 $ hg up -q 1
29 29 $ echo three > a ; hg ci -qm3
30 30 $ hg up -q 0
31 31 $ hg branch -q b1
32 32 $ echo four > a ; hg ci -qm4
33 33 $ echo five > a ; hg ci -qm5
34 34
35 35 Initial repo state:
36 36
37 37 $ hg log -G --template '{rev}:{node|short} {parents} {branches}\n'
38 38 @ 5:ff252e8273df b1
39 39 |
40 40 o 4:d047485b3896 0:60829823a42a b1
41 41 |
42 42 | o 3:6efa171f091b 1:0786582aa4b1
43 43 | |
44 44 | | o 2:bd10386d478c
45 45 | |/
46 46 | o 1:0786582aa4b1
47 47 |/
48 48 o 0:60829823a42a
49 49
50 50
51 51 Make sure update doesn't assume b1 is a repository if invoked from outside:
52 52
53 53 $ cd ..
54 54 $ hg update b1
55 55 abort: no repository found in '$TESTTMP' (.hg not found)!
56 56 [255]
57 57 $ cd b1
58 58
59 59 Test helper functions:
60 60
61 61 $ revtest () {
62 62 > msg=$1
63 63 > dirtyflag=$2 # 'clean', 'dirty' or 'dirtysub'
64 64 > startrev=$3
65 65 > targetrev=$4
66 66 > opt=$5
67 67 > hg up -qC $startrev
68 68 > test $dirtyflag = dirty && echo dirty > foo
69 69 > test $dirtyflag = dirtysub && echo dirty > sub/suba
70 70 > hg up $opt $targetrev
71 71 > hg parent --template 'parent={rev}\n'
72 72 > hg stat -S
73 73 > }
74 74
75 75 $ norevtest () {
76 76 > msg=$1
77 77 > dirtyflag=$2 # 'clean', 'dirty' or 'dirtysub'
78 78 > startrev=$3
79 79 > opt=$4
80 80 > hg up -qC $startrev
81 81 > test $dirtyflag = dirty && echo dirty > foo
82 82 > test $dirtyflag = dirtysub && echo dirty > sub/suba
83 83 > hg up $opt
84 84 > hg parent --template 'parent={rev}\n'
85 85 > hg stat -S
86 86 > }
87 87
88 88 Test cases are documented in a table in the update function of merge.py.
89 89 Cases are run as shown in that table, row by row.
90 90
91 91 $ norevtest 'none clean linear' clean 4
92 92 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
93 93 parent=5
94 94
95 95 $ norevtest 'none clean same' clean 2
96 96 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
97 97 1 other heads for branch "default"
98 98 parent=2
99 99
100 100
101 101 $ revtest 'none clean linear' clean 1 2
102 102 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
103 103 parent=2
104 104
105 105 $ revtest 'none clean same' clean 2 3
106 106 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
107 107 parent=3
108 108
109 109 $ revtest 'none clean cross' clean 3 4
110 110 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
111 111 parent=4
112 112
113 113
114 114 $ revtest 'none dirty linear' dirty 1 2
115 115 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
116 116 parent=2
117 117 M foo
118 118
119 119 $ revtest 'none dirtysub linear' dirtysub 1 2
120 120 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
121 121 parent=2
122 122 M sub/suba
123 123
124 124 $ revtest 'none dirty same' dirty 2 3
125 125 abort: uncommitted changes
126 126 (commit or update --clean to discard changes)
127 127 parent=2
128 128 M foo
129 129
130 130 $ revtest 'none dirtysub same' dirtysub 2 3
131 131 abort: uncommitted changes
132 132 (commit or update --clean to discard changes)
133 133 parent=2
134 134 M sub/suba
135 135
136 136 $ revtest 'none dirty cross' dirty 3 4
137 137 abort: uncommitted changes
138 138 (commit or update --clean to discard changes)
139 139 parent=3
140 140 M foo
141 141
142 142 $ norevtest 'none dirty cross' dirty 2
143 143 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
144 144 1 other heads for branch "default"
145 145 parent=2
146 146 M foo
147 147
148 148 $ revtest 'none dirtysub cross' dirtysub 3 4
149 149 abort: uncommitted changes
150 150 (commit or update --clean to discard changes)
151 151 parent=3
152 152 M sub/suba
153 153
154 154 $ revtest '-C dirty linear' dirty 1 2 -C
155 155 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
156 156 parent=2
157 157
158 158 $ revtest '-c dirty linear' dirty 1 2 -c
159 159 abort: uncommitted changes
160 160 parent=1
161 161 M foo
162 162
163 $ revtest '-m dirty linear' dirty 1 2 -m
164 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
165 parent=2
166 M foo
167
168 $ revtest '-m dirty cross' dirty 3 4 -m
169 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
170 parent=4
171 M foo
172
163 173 $ revtest '-c dirtysub linear' dirtysub 1 2 -c
164 174 abort: uncommitted changes in subrepository 'sub'
165 175 parent=1
166 176 M sub/suba
167 177
168 178 $ norevtest '-c clean same' clean 2 -c
169 179 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
170 180 1 other heads for branch "default"
171 181 parent=2
172 182
173 183 $ revtest '-cC dirty linear' dirty 1 2 -cC
174 abort: cannot specify both -c/--check and -C/--clean
184 abort: can only specify one of -C/--clean, -c/--check, or -m/merge
185 parent=1
186 M foo
187
188 $ revtest '-mc dirty linear' dirty 1 2 -mc
189 abort: can only specify one of -C/--clean, -c/--check, or -m/merge
190 parent=1
191 M foo
192
193 $ revtest '-mC dirty linear' dirty 1 2 -mC
194 abort: can only specify one of -C/--clean, -c/--check, or -m/merge
175 195 parent=1
176 196 M foo
177 197
178 198 $ cd ..
179 199
180 200 Test updating to null revision
181 201
182 202 $ hg init null-repo
183 203 $ cd null-repo
184 204 $ echo a > a
185 205 $ hg add a
186 206 $ hg ci -m a
187 207 $ hg up -qC 0
188 208 $ echo b > b
189 209 $ hg add b
190 210 $ hg up null
191 211 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
192 212 $ hg st
193 213 A b
194 214 $ hg up -q 0
195 215 $ hg st
196 216 A b
197 217 $ hg up -qC null
198 218 $ hg st
199 219 ? b
200 220 $ cd ..
201 221
202 222 Test updating with closed head
203 223 ---------------------------------------------------------------------
204 224
205 225 $ hg clone -U -q b1 closed-heads
206 226 $ cd closed-heads
207 227
208 228 Test updating if at least one non-closed branch head exists
209 229
210 230 if on the closed branch head:
211 231 - update to "."
212 232 - "updated to a closed branch head ...." message is displayed
213 233 - "N other heads for ...." message is displayed
214 234
215 235 $ hg update -q -C 3
216 236 $ hg commit --close-branch -m 6
217 237 $ norevtest "on closed branch head" clean 6
218 238 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
219 239 no open descendant heads on branch "default", updating to a closed head
220 240 (committing will reopen the head, use 'hg heads .' to see 1 other heads)
221 241 parent=6
222 242
223 243 if descendant non-closed branch head exists, and it is only one branch head:
224 244 - update to it, even if its revision is less than closed one
225 245 - "N other heads for ...." message isn't displayed
226 246
227 247 $ norevtest "non-closed 2 should be chosen" clean 1
228 248 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
229 249 parent=2
230 250
231 251 if all descendant branch heads are closed, but there is another branch head:
232 252 - update to the tipmost descendant head
233 253 - "updated to a closed branch head ...." message is displayed
234 254 - "N other heads for ...." message is displayed
235 255
236 256 $ norevtest "all descendant branch heads are closed" clean 3
237 257 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
238 258 no open descendant heads on branch "default", updating to a closed head
239 259 (committing will reopen the head, use 'hg heads .' to see 1 other heads)
240 260 parent=6
241 261
242 262 Test updating if all branch heads are closed
243 263
244 264 if on the closed branch head:
245 265 - update to "."
246 266 - "updated to a closed branch head ...." message is displayed
247 267 - "all heads of branch ...." message is displayed
248 268
249 269 $ hg update -q -C 2
250 270 $ hg commit --close-branch -m 7
251 271 $ norevtest "all heads of branch default are closed" clean 6
252 272 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
253 273 no open descendant heads on branch "default", updating to a closed head
254 274 (committing will reopen branch "default")
255 275 parent=6
256 276
257 277 if not on the closed branch head:
258 278 - update to the tipmost descendant (closed) head
259 279 - "updated to a closed branch head ...." message is displayed
260 280 - "all heads of branch ...." message is displayed
261 281
262 282 $ norevtest "all heads of branch default are closed" clean 1
263 283 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
264 284 no open descendant heads on branch "default", updating to a closed head
265 285 (committing will reopen branch "default")
266 286 parent=7
267 287
268 288 $ cd ..
269 289
270 290 Test updating if "default" branch doesn't exist and no revision is
271 291 checked out (= "default" is used as current branch)
272 292
273 293 $ hg init no-default-branch
274 294 $ cd no-default-branch
275 295
276 296 $ hg branch foobar
277 297 marked working directory as branch foobar
278 298 (branches are permanent and global, did you want a bookmark?)
279 299 $ echo a > a
280 300 $ hg commit -m "#0" -A
281 301 adding a
282 302 $ echo 1 >> a
283 303 $ hg commit -m "#1"
284 304 $ hg update -q 0
285 305 $ echo 3 >> a
286 306 $ hg commit -m "#2"
287 307 created new head
288 308 $ hg commit --close-branch -m "#3"
289 309
290 310 if there is at least one non-closed branch head:
291 311 - update to the tipmost branch head
292 312
293 313 $ norevtest "non-closed 1 should be chosen" clean null
294 314 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
295 315 parent=1
296 316
297 317 if all branch heads are closed
298 318 - update to "tip"
299 319 - "updated to a closed branch head ...." message is displayed
300 320 - "all heads for branch "XXXX" are closed" message is displayed
301 321
302 322 $ hg update -q -C 1
303 323 $ hg commit --close-branch -m "#4"
304 324
305 325 $ norevtest "all branches are closed" clean null
306 326 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
307 327 no open descendant heads on branch "foobar", updating to a closed head
308 328 (committing will reopen branch "foobar")
309 329 parent=4
310 330
311 331 $ cd ../b1
312 332
313 333 Test obsolescence behavior
314 334 ---------------------------------------------------------------------
315 335
316 336 successors should be taken in account when checking head destination
317 337
318 338 $ cat << EOF >> $HGRCPATH
319 339 > [ui]
320 340 > logtemplate={rev}:{node|short} {desc|firstline}
321 341 > [experimental]
322 342 > evolution=createmarkers
323 343 > EOF
324 344
325 345 Test no-argument update to a successor of an obsoleted changeset
326 346
327 347 $ hg log -G
328 348 o 5:ff252e8273df 5
329 349 |
330 350 o 4:d047485b3896 4
331 351 |
332 352 | o 3:6efa171f091b 3
333 353 | |
334 354 | | o 2:bd10386d478c 2
335 355 | |/
336 356 | @ 1:0786582aa4b1 1
337 357 |/
338 358 o 0:60829823a42a 0
339 359
340 360 $ hg book bm -r 3
341 361 $ hg status
342 362 M foo
343 363
344 364 We add simple obsolescence marker between 3 and 4 (indirect successors)
345 365
346 366 $ hg id --debug -i -r 3
347 367 6efa171f091b00a3c35edc15d48c52a498929953
348 368 $ hg id --debug -i -r 4
349 369 d047485b3896813b2a624e86201983520f003206
350 370 $ hg debugobsolete 6efa171f091b00a3c35edc15d48c52a498929953 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
351 371 $ hg debugobsolete aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa d047485b3896813b2a624e86201983520f003206
352 372
353 373 Test that 5 is detected as a valid destination from 3 and also accepts moving
354 374 the bookmark (issue4015)
355 375
356 376 $ hg up --quiet --hidden 3
357 377 $ hg up 5
358 378 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
359 379 $ hg book bm
360 380 moving bookmark 'bm' forward from 6efa171f091b
361 381 $ hg bookmarks
362 382 * bm 5:ff252e8273df
363 383
364 384 Test that 4 is detected as the no-argument destination from 3 and also moves
365 385 the bookmark with it
366 386 $ hg up --quiet 0 # we should be able to update to 3 directly
367 387 $ hg up --quiet --hidden 3 # but not implemented yet.
368 388 $ hg book -f bm
369 389 $ hg up
370 390 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
371 391 updating bookmark bm
372 392 $ hg book
373 393 * bm 4:d047485b3896
374 394
375 395 Test that 5 is detected as a valid destination from 1
376 396 $ hg up --quiet 0 # we should be able to update to 3 directly
377 397 $ hg up --quiet --hidden 3 # but not implemented yet.
378 398 $ hg up 5
379 399 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
380 400
381 401 Test that 5 is not detected as a valid destination from 2
382 402 $ hg up --quiet 0
383 403 $ hg up --quiet 2
384 404 $ hg up 5
385 405 abort: uncommitted changes
386 406 (commit or update --clean to discard changes)
387 407 [255]
388 408
389 409 Test that we don't crash when updating from a pruned changeset (i.e. has no
390 410 successors). Behavior should probably be that we update to the first
391 411 non-obsolete parent but that will be decided later.
392 412 $ hg id --debug -r 2
393 413 bd10386d478cd5a9faf2e604114c8e6da62d3889
394 414 $ hg up --quiet 0
395 415 $ hg up --quiet 2
396 416 $ hg debugobsolete bd10386d478cd5a9faf2e604114c8e6da62d3889
397 417 $ hg up
398 418 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
399 419
400 420 Test experimental revset support
401 421
402 422 $ hg log -r '_destupdate()'
403 423 2:bd10386d478c 2 (no-eol)
404 424
405 425 Test that boolean flags allow --no-flag specification to override [defaults]
406 426 $ cat >> $HGRCPATH <<EOF
407 427 > [defaults]
408 428 > update = --check
409 429 > EOF
410 430 $ hg co 2
411 431 abort: uncommitted changes
412 432 [255]
413 433 $ hg co --no-check 2
414 434 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
General Comments 0
You need to be logged in to leave comments. Login now