commands.py 247 KB
Newer Older
mpm@selenic.com's avatar
mpm@selenic.com committed
1 2
# commands.py - command processing for mercurial
#
3
# Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
mpm@selenic.com's avatar
mpm@selenic.com committed
4
#
5
# This software may be used and distributed according to the terms of the
Matt Mackall's avatar
Matt Mackall committed
6
# GNU General Public License version 2 or any later version.
mpm@selenic.com's avatar
mpm@selenic.com committed
7

Gregory Szorc's avatar
Gregory Szorc committed
8 9 10 11 12
from __future__ import absolute_import

import errno
import os
import re
13
import sys
Gregory Szorc's avatar
Gregory Szorc committed
14 15 16 17 18 19 20

from .i18n import _
from .node import (
    hex,
    nullid,
    nullrev,
    short,
21 22
    wdirhex,
    wdirrev,
Gregory Szorc's avatar
Gregory Szorc committed
23
)
24
from .pycompat import open
Gregory Szorc's avatar
Gregory Szorc committed
25 26 27 28 29 30 31
from . import (
    archival,
    bookmarks,
    bundle2,
    changegroup,
    cmdutil,
    copies,
32
    debugcommands as debugcommandsmod,
Gregory Szorc's avatar
Gregory Szorc committed
33
    destutil,
34
    dirstateguard,
Gregory Szorc's avatar
Gregory Szorc committed
35 36 37 38 39
    discovery,
    encoding,
    error,
    exchange,
    extensions,
40
    filemerge,
Yuya Nishihara's avatar
Yuya Nishihara committed
41
    formatter,
Gregory Szorc's avatar
Gregory Szorc committed
42
    graphmod,
43
    grep as grepmod,
Gregory Szorc's avatar
Gregory Szorc committed
44 45 46
    hbisect,
    help,
    hg,
47
    logcmdutil,
Gregory Szorc's avatar
Gregory Szorc committed
48
    merge as mergemod,
49
    mergestate as mergestatemod,
50
    narrowspec,
Gregory Szorc's avatar
Gregory Szorc committed
51
    obsolete,
52
    obsutil,
Gregory Szorc's avatar
Gregory Szorc committed
53 54
    patch,
    phases,
55
    pycompat,
56
    rcutil,
57
    registrar,
58
    requirements,
59
    revsetlang,
60
    rewriteutil,
Gregory Szorc's avatar
Gregory Szorc committed
61
    scmutil,
62
    server,
63
    shelve as shelvemod,
64
    state as statemod,
Gregory Szorc's avatar
Gregory Szorc committed
65
    streamclone,
66
    tags as tagsmod,
Gregory Szorc's avatar
Gregory Szorc committed
67 68
    ui as uimod,
    util,
69
    verify as verifymod,
70
    vfs as vfsmod,
71
    wireprotoserver,
Gregory Szorc's avatar
Gregory Szorc committed
72
)
73 74 75 76
from .utils import (
    dateutil,
    stringutil,
)
Gregory Szorc's avatar
Gregory Szorc committed
77

78
table = {}
79
table.update(debugcommandsmod.command._table)
80

81
command = registrar.command(table)
82
INTENT_READONLY = registrar.INTENT_READONLY
83 84 85 86

# common command options

globalopts = [
87
    (
88 89 90 91 92
        b'R',
        b'repository',
        b'',
        _(b'repository root directory or name of overlay bundle file'),
        _(b'REPO'),
93
    ),
94
    (b'', b'cwd', b'', _(b'change working directory'), _(b'DIR')),
95
    (
96 97
        b'y',
        b'noninteractive',
98
        None,
99 100 101
        _(
            b'do not prompt, automatically pick the first choice for all prompts'
        ),
102
    ),
103 104
    (b'q', b'quiet', None, _(b'suppress output')),
    (b'v', b'verbose', None, _(b'enable additional output')),
105
    (
106 107 108
        b'',
        b'color',
        b'',
109 110
        # i18n: 'always', 'auto', 'never', and 'debug' are keywords
        # and should not be translated
111 112
        _(b"when to colorize (boolean, always, auto, never, or debug)"),
        _(b'TYPE'),
113 114
    ),
    (
115 116
        b'',
        b'config',
117
        [],
118 119
        _(b'set/override config option (use \'section.name=value\')'),
        _(b'CONFIG'),
120
    ),
121 122
    (b'', b'debug', None, _(b'enable debugging output')),
    (b'', b'debugger', None, _(b'start debugger')),
123
    (
124 125
        b'',
        b'encoding',
126
        encoding.encoding,
127 128
        _(b'set the charset encoding'),
        _(b'ENCODE'),
129 130
    ),
    (
131 132
        b'',
        b'encodingmode',
133
        encoding.encodingmode,
134 135
        _(b'set the charset encoding mode'),
        _(b'MODE'),
136
    ),
137 138 139 140 141 142
    (b'', b'traceback', None, _(b'always print a traceback on exception')),
    (b'', b'time', None, _(b'time how long the command takes')),
    (b'', b'profile', None, _(b'print command execution profile')),
    (b'', b'version', None, _(b'output version information and exit')),
    (b'h', b'help', None, _(b'display help and exit')),
    (b'', b'hidden', False, _(b'consider hidden changesets')),
143
    (
144 145 146 147 148
        b'',
        b'pager',
        b'auto',
        _(b"when to paginate (boolean, always, auto, or never)"),
        _(b'TYPE'),
149
    ),
150 151
]

152 153 154 155 156
dryrunopts = cmdutil.dryrunopts
remoteopts = cmdutil.remoteopts
walkopts = cmdutil.walkopts
commitopts = cmdutil.commitopts
commitopts2 = cmdutil.commitopts2
157
commitopts3 = cmdutil.commitopts3
158 159 160 161 162 163 164 165 166 167
formatteropts = cmdutil.formatteropts
templateopts = cmdutil.templateopts
logopts = cmdutil.logopts
diffopts = cmdutil.diffopts
diffwsopts = cmdutil.diffwsopts
diffopts2 = cmdutil.diffopts2
mergetoolopts = cmdutil.mergetoolopts
similarityopts = cmdutil.similarityopts
subrepoopts = cmdutil.subrepoopts
debugrevlogopts = cmdutil.debugrevlogopts
168

mpm@selenic.com's avatar
mpm@selenic.com committed
169
# Commands start here, listed alphabetically
170

171 172

@command(
173
    b'abort',
174 175 176 177
    dryrunopts,
    helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
    helpbasic=True,
)
178 179 180 181 182 183 184 185
def abort(ui, repo, **opts):
    """abort an unfinished operation (EXPERIMENTAL)

    Aborts a multistep operation like graft, histedit, rebase, merge,
    and unshelve if they are in an unfinished state.

    use --dry-run/-n to dry run the command.
    """
186
    dryrun = opts.get('dry_run')
187 188
    abortstate = cmdutil.getunfinishedstate(repo)
    if not abortstate:
189
        raise error.Abort(_(b'no operation in progress'))
190
    if not abortstate.abortfunc:
191 192
        raise error.Abort(
            (
193
                _(b"%s in progress but does not support 'hg abort'")
194 195 196 197
                % (abortstate._opname)
            ),
            hint=abortstate.hint(),
        )
198
    if dryrun:
199 200 201
        ui.status(
            _(b'%s in progress, will be aborted\n') % (abortstate._opname)
        )
202 203 204
        return
    return abortstate.abortfunc(ui, repo)

205 206

@command(
207
    b'add',
208
    walkopts + subrepoopts + dryrunopts,
209
    _(b'[OPTION]... [FILE]...'),
210
    helpcategory=command.CATEGORY_WORKING_DIRECTORY,
211 212 213
    helpbasic=True,
    inferrepo=True,
)
214
def add(ui, repo, *pats, **opts):
215 216
    """add the specified files on the next commit

217 218
    Schedule files to be version controlled and added to the
    repository.
219

220
    The files will be added to the repository at the next commit. To
221
    undo an add before that, see :hg:`forget`.
222

timeless's avatar
timeless committed
223 224
    If no names are given, add all files to the repository (except
    files matching ``.hgignore``).
225 226 227

    .. container:: verbose

228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
       Examples:

         - New (unknown) files are added
           automatically by :hg:`add`::

             $ ls
             foo.c
             $ hg status
             ? foo.c
             $ hg add
             adding foo.c
             $ hg status
             A foo.c

         - Specific files to be added can be specified::

             $ ls
             bar.c  foo.c
             $ hg status
             ? bar.c
             ? foo.c
             $ hg add bar.c
             $ hg status
             A bar.c
             ? foo.c
253 254

    Returns 0 if all files are successfully added.
255 256
    """

257
    m = scmutil.match(repo[None], pats, pycompat.byteskwargs(opts))
258
    uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
259
    rejected = cmdutil.add(ui, repo, m, b"", uipathfn, False, **opts)
260
    return rejected and 1 or 0
261

262 263

@command(
264
    b'addremove',
265
    similarityopts + subrepoopts + walkopts + dryrunopts,
266
    _(b'[OPTION]... [FILE]...'),
267
    helpcategory=command.CATEGORY_WORKING_DIRECTORY,
268 269
    inferrepo=True,
)
270
def addremove(ui, repo, *pats, **opts):
271
    """add all new files, delete all missing files
272

273 274
    Add all new files and remove all missing files from the
    repository.
275

timeless's avatar
timeless committed
276 277 278
    Unless names are given, new files are ignored if they match any of
    the patterns in ``.hgignore``. As with add, these changes take
    effect at the next commit.
279

280
    Use the -s/--similarity option to detect renamed files. This
281
    option takes a percentage between 0 (disabled) and 100 (files must
282 283 284
    be identical) as its parameter. With a parameter greater than 0,
    this compares every removed file with every added file and records
    those similar enough as renames. Detecting renamed files this way
285
    can be expensive. After using this option, :hg:`status -C` can be
286 287 288
    used to check which files were identified as moved or renamed. If
    not specified, -s/--similarity defaults to 100 and only renames of
    identical files are detected.
289

290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
    .. container:: verbose

       Examples:

         - A number of files (bar.c and foo.c) are new,
           while foobar.c has been removed (without using :hg:`remove`)
           from the repository::

             $ ls
             bar.c foo.c
             $ hg status
             ! foobar.c
             ? bar.c
             ? foo.c
             $ hg addremove
             adding bar.c
             adding foo.c
             removing foobar.c
             $ hg status
             A bar.c
             A foo.c
             R foobar.c

         - A file foobar.c was moved to foo.c without using :hg:`rename`.
           Afterwards, it was edited slightly::

             $ ls
             foo.c
             $ hg status
             ! foobar.c
             ? foo.c
             $ hg addremove --similarity 90
             removing foobar.c
             adding foo.c
             recording removal of foobar.c as rename to foo.c (94% similar)
             $ hg status -C
             A foo.c
               foobar.c
             R foobar.c

330
    Returns 0 if all files are successfully added.
331
    """
332
    opts = pycompat.byteskwargs(opts)
333 334
    if not opts.get(b'similarity'):
        opts[b'similarity'] = b'100'
335
    matcher = scmutil.match(repo[None], pats, opts)
336
    relative = scmutil.anypats(pats, opts)
337
    uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=relative)
338
    return scmutil.addremove(repo, matcher, b"", uipathfn, opts)
339

340 341

@command(
342
    b'annotate|blame',
343
    [
344
        (b'r', b'rev', b'', _(b'annotate the specified revision'), _(b'REV')),
345
        (
346 347
            b'',
            b'follow',
348
            None,
349
            _(b'follow copies/renames and list the filename (DEPRECATED)'),
350
        ),
351 352 353 354 355 356 357
        (b'', b'no-follow', None, _(b"don't follow copies and renames")),
        (b'a', b'text', None, _(b'treat all files as text')),
        (b'u', b'user', None, _(b'list the author (long with -v)')),
        (b'f', b'file', None, _(b'list the filename')),
        (b'd', b'date', None, _(b'list the date (short with -q)')),
        (b'n', b'number', None, _(b'list the revision number (default)')),
        (b'c', b'changeset', None, _(b'list the changeset')),
358
        (
359 360
            b'l',
            b'line-number',
361
            None,
362 363 364 365 366 367
            _(b'show line number at the first appearance'),
        ),
        (
            b'',
            b'skip',
            [],
368
            _(b'revset to not display (EXPERIMENTAL)'),
369
            _(b'REV'),
370 371 372 373 374
        ),
    ]
    + diffwsopts
    + walkopts
    + formatteropts,
375
    _(b'[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'),
376
    helpcategory=command.CATEGORY_FILE_CONTENTS,
377 378 379
    helpbasic=True,
    inferrepo=True,
)
380
def annotate(ui, repo, *pats, **opts):
381
    """show changeset information by line for each file
382

383
    List changes in files, showing the revision id responsible for
384
    each line.
385

386 387
    This command is useful for discovering when a change was made and
    by whom.
388

389 390 391
    If you include --file, --user, or --date, the revision number is
    suppressed unless you also include --number.

392 393 394 395
    Without the -a/--text option, annotate will avoid processing files
    it detects as binary. With -a, annotate will annotate the file
    anyway, although the results will probably be neither useful
    nor desirable.
396

397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
    .. container:: verbose

      Template:

      The following keywords are supported in addition to the common template
      keywords and functions. See also :hg:`help templates`.

      :lines:   List of lines with annotation data.
      :path:    String. Repository-absolute path of the specified file.

      And each entry of ``{lines}`` provides the following sub-keywords in
      addition to ``{date}``, ``{node}``, ``{rev}``, ``{user}``, etc.

      :line:    String. Line content.
      :lineno:  Integer. Line number at that revision.
      :path:    String. Repository-absolute path of the file at that revision.

      See :hg:`help templates.operators` for the list expansion syntax.

416
    Returns 0 on success.
417
    """
418
    opts = pycompat.byteskwargs(opts)
419
    if not pats:
420
        raise error.Abort(_(b'at least one filename or pattern is required'))
421

422
    if opts.get(b'follow'):
423 424
        # --follow is deprecated and now just an alias for -f/--file
        # to mimic the behavior of Mercurial before version 1.5
425
        opts[b'file'] = True
426

427
    if (
428 429 430 431
        not opts.get(b'user')
        and not opts.get(b'changeset')
        and not opts.get(b'date')
        and not opts.get(b'file')
432
    ):
433
        opts[b'number'] = True
434

435 436 437 438 439 440 441
    linenumber = opts.get(b'line_number') is not None
    if (
        linenumber
        and (not opts.get(b'changeset'))
        and (not opts.get(b'number'))
    ):
        raise error.Abort(_(b'at least one of -n/-c is required for -l'))
442

443
    rev = opts.get(b'rev')
444
    if rev:
445
        repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
446
    ctx = scmutil.revsingle(repo, rev)
447

448 449
    ui.pager(b'annotate')
    rootfm = ui.formatter(b'annotate', opts)
450 451 452
    if ui.debugflag:
        shorthex = pycompat.identity
    else:
453

454 455
        def shorthex(h):
            return h[:12]
456

457
    if ui.quiet:
458
        datefunc = dateutil.shortdate
459
    else:
460
        datefunc = dateutil.datestr
461
    if ctx.rev() is None:
462
        if opts.get(b'changeset'):
463 464
            # omit "+" suffix which is appended to node hex
            def formatrev(rev):
465
                if rev == wdirrev:
466
                    return b'%d' % ctx.p1().rev()
467
                else:
468
                    return b'%d' % rev
469

470
        else:
471

472
            def formatrev(rev):
473
                if rev == wdirrev:
474
                    return b'%d+' % ctx.p1().rev()
475
                else:
476
                    return b'%d ' % rev
477

478
        def formathex(h):
479
            if h == wdirhex:
480
                return b'%s+' % shorthex(hex(ctx.p1().node()))
481
            else:
482
                return b'%s ' % shorthex(h)
483

484
    else:
485 486
        formatrev = b'%d'.__mod__
        formathex = shorthex
487

488
    opmap = [
489 490 491 492 493 494
        (b'user', b' ', lambda x: x.fctx.user(), ui.shortuser),
        (b'rev', b' ', lambda x: scmutil.intrev(x.fctx), formatrev),
        (b'node', b' ', lambda x: hex(scmutil.binnode(x.fctx)), formathex),
        (b'date', b' ', lambda x: x.fctx.date(), util.cachefunc(datefunc)),
        (b'path', b' ', lambda x: x.fctx.path(), pycompat.bytestr),
        (b'lineno', b':', lambda x: x.lineno, pycompat.bytestr),
495 496
    ]
    opnamemap = {
497 498 499 500
        b'rev': b'number',
        b'node': b'changeset',
        b'path': b'file',
        b'lineno': b'line_number',
501
    }
502

503
    if rootfm.isplain():
504

505
        def makefunc(get, fmt):
506
            return lambda x: fmt(get(x))
507

508
    else:
509

510
        def makefunc(get, fmt):
511
            return get
512

513
    datahint = rootfm.datahint()
514 515 516 517 518
    funcmap = [
        (makefunc(get, fmt), sep)
        for fn, sep, get, fmt in opmap
        if opts.get(opnamemap.get(fn, fn)) or fn in datahint
    ]
519 520
    funcmap[0] = (funcmap[0][0], b'')  # no separator in front of first column
    fields = b' '.join(
521 522 523 524
        fn
        for fn, sep, get, fmt in opmap
        if opts.get(opnamemap.get(fn, fn)) or fn in datahint
    )
525

526
    def bad(x, y):
527
        raise error.Abort(b"%s: %s" % (x, y))
528

529 530
    m = scmutil.match(ctx, pats, opts, badfn=bad)

531
    follow = not opts.get(b'no_follow')
532
    diffopts = patch.difffeatureopts(
533
        ui, opts, section=b'annotate', whitespace=True
534
    )
535
    skiprevs = opts.get(b'skip')
536 537 538
    if skiprevs:
        skiprevs = scmutil.revrange(repo, skiprevs)

539
    uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
Matt Mackall's avatar
Matt Mackall committed
540 541
    for abs in ctx.walk(m):
        fctx = ctx[abs]
542
        rootfm.startitem()
543
        rootfm.data(path=abs)
544 545
        if not opts.get(b'text') and fctx.isbinary():
            rootfm.plain(_(b"%s: binary file\n") % uipathfn(abs))
546 547
            continue

548
        fm = rootfm.nested(b'lines', tmpl=b'{rev}: {line}')
549 550 551
        lines = fctx.annotate(
            follow=follow, skiprevs=skiprevs, diffopts=diffopts
        )
552
        if not lines:
553
            fm.end()
554
            continue
555
        formats = []
556 557
        pieces = []

558
        for f, sep in funcmap:
559
            l = [f(n) for n in lines]
560
            if fm.isplain():
561 562
                sizes = [encoding.colwidth(x) for x in l]
                ml = max(sizes)
563
                formats.append([sep + b' ' * (ml - w) + b'%s' for w in sizes])
564
            else:
565
                formats.append([b'%s'] * len(l))
566
            pieces.append(l)
567

568
        for f, p, n in zip(zip(*formats), zip(*pieces), lines):
569
            fm.startitem()
570
            fm.context(fctx=n.fctx)
571
            fm.write(fields, b"".join(f), *p)
572
            if n.skip:
573
                fmt = b"* %s"
574
            else:
575 576
                fmt = b": %s"
            fm.write(b'line', fmt, n.text)
577

578 579
        if not lines[-1].text.endswith(b'\n'):
            fm.plain(b'\n')
580
        fm.end()
581

582
    rootfm.end()
583

584 585

@command(
586
    b'archive',
587
    [
588
        (b'', b'no-decode', None, _(b'do not pass files through decoders')),
589
        (
590 591 592 593 594
            b'p',
            b'prefix',
            b'',
            _(b'directory prefix for files in archive'),
            _(b'PREFIX'),
595
        ),
596 597
        (b'r', b'rev', b'', _(b'revision to distribute'), _(b'REV')),
        (b't', b'type', b'', _(b'type of distribution to create'), _(b'TYPE')),
598 599 600
    ]
    + subrepoopts
    + walkopts,
601
    _(b'[OPTION]... DEST'),
602 603
    helpcategory=command.CATEGORY_IMPORT_EXPORT,
)
604
def archive(ui, repo, dest, **opts):
605
    '''create an unversioned archive of a repository revision
606

607 608
    By default, the revision used is the parent of the working
    directory; use -r/--rev to specify a different revision.
609

610
    The archive type is automatically detected based on file
timeless's avatar
timeless committed
611
    extension (to override, use -t/--type).
612

Matt Mackall's avatar
Matt Mackall committed
613 614 615 616 617 618 619 620 621 622 623 624
    .. container:: verbose

      Examples:

      - create a zip file containing the 1.0 release::

          hg archive -r 1.0 project-1.0.zip

      - create a tarball excluding .hg files::

          hg archive project.tar.gz -X ".hg*"

625
    Valid types are:
626

627 628 629 630
    :``files``: a directory full of files (default)
    :``tar``:   tar archive, uncompressed
    :``tbz2``:  tar archive, compressed using bzip2
    :``tgz``:   tar archive, compressed using gzip
631
    :``txz``:   tar archive, compressed using lzma (only in Python 3)
632 633
    :``uzip``:  zip archive, uncompressed
    :``zip``:   zip archive, compressed using deflate
634

635
    The exact name of the destination archive or directory is given
Martin Geisler's avatar
Martin Geisler committed
636
    using a format string; see :hg:`help export` for details.
637

638 639 640 641
    Each member added to an archive file has a directory prefix
    prepended. Use -p/--prefix to specify a format string for the
    prefix. The default is the basename of the archive, with suffixes
    removed.
642 643

    Returns 0 on success.
644 645
    '''

646
    opts = pycompat.byteskwargs(opts)
647
    rev = opts.get(b'rev')
648
    if rev:
649
        repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
650
    ctx = scmutil.revsingle(repo, rev)
651
    if not ctx:
652
        raise error.Abort(_(b'no working directory: please specify a revision'))
653
    node = ctx.node()
654
    dest = cmdutil.makefilename(ctx, dest)
655
    if os.path.realpath(dest) == repo.root:
656
        raise error.Abort(_(b'repository root cannot be destination'))
657

658 659
    kind = opts.get(b'type') or archival.guesskind(dest) or b'files'
    prefix = opts.get(b'prefix')
660

661 662 663
    if dest == b'-':
        if kind == b'files':
            raise error.Abort(_(b'cannot archive plain files to stdout'))
664
        dest = cmdutil.makefileobj(ctx, dest)
665
        if not prefix:
666
            prefix = os.path.basename(repo.root) + b'-%h'
667

668
    prefix = cmdutil.makefilename(ctx, prefix)
669
    match = scmutil.match(ctx, [], opts)
670 671 672 673 674
    archival.archive(
        repo,
        dest,
        node,
        kind,
675
        not opts.get(b'no_decode'),
676 677
        match,
        prefix,
678
        subrepos=opts.get(b'subrepos'),
679 680 681 682
    )


@command(
683
    b'backout',
684 685
    [
        (
686 687 688 689 690 691 692 693
            b'',
            b'merge',
            None,
            _(b'merge with old dirstate parent after backout'),
        ),
        (
            b'',
            b'commit',
694
            None,
695
            _(b'commit if no conflicts were encountered (DEPRECATED)'),
696
        ),
697
        (b'', b'no-commit', None, _(b'do not commit')),
698
        (
699 700 701 702 703
            b'',
            b'parent',
            b'',
            _(b'parent to choose when backing out merge (DEPRECATED)'),
            _(b'REV'),
704
        ),
705 706
        (b'r', b'rev', b'', _(b'revision to backout'), _(b'REV')),
        (b'e', b'edit', False, _(b'invoke editor on commit messages')),
707 708 709 710 711
    ]
    + mergetoolopts
    + walkopts
    + commitopts
    + commitopts2,
712
    _(b'[OPTION]... [-r] REV'),
713 714
    helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
)
715
def backout(ui, repo, node=None, rev=None, **opts):
Vadim Gelfer's avatar
Vadim Gelfer committed
716 717
    '''reverse effect of earlier changeset

718
    Prepare a new changeset with the effect of REV undone in the
719 720
    current working directory. If no conflicts were encountered,
    it will be committed immediately.
721

722
    If REV is the parent of the working directory, then this new changeset
723
    is committed automatically (unless --no-commit is specified).
724

725
    .. note::
726

727
       :hg:`backout` cannot be used to fix either an unwanted or
728
       incorrect merge.
729

Matt Mackall's avatar
Matt Mackall committed
730 731
    .. container:: verbose

732 733 734 735 736 737 738 739 740 741 742 743
      Examples:

      - Reverse the effect of the parent of the working directory.
        This backout will be committed immediately::

          hg backout -r .

      - Reverse the effect of previous bad revision 23::

          hg backout -r 23

      - Reverse the effect of previous bad revision 23 and
744
        leave changes uncommitted::
745

746 747
          hg backout -r 23 --no-commit
          hg commit -m "Backout revision 23"
748

Matt Mackall's avatar
Matt Mackall committed
749 750 751 752 753 754 755 756 757
      By default, the pending changeset will have one parent,
      maintaining a linear history. With --merge, the pending
      changeset will instead have two parents: the old parent of the
      working directory and a new child of REV that simply undoes REV.

      Before version 1.7, the behavior without --merge was equivalent
      to specifying --merge followed by :hg:`update --clean .` to
      cancel the merge and leave the child of REV as a head to be
      merged separately.
758

Martin Geisler's avatar
Martin Geisler committed
759
    See :hg:`help dates` for a list of formats valid for -d/--date.
760

761 762 763
    See :hg:`help revert` for a way to restore files to the state
    of another revision.

764 765
    Returns 0 on success, 1 if nothing to backout or there are unresolved
    files.
766
    '''
767
    with repo.wlock(), repo.lock():
768
        return _dobackout(ui, repo, node, rev, **opts)
769

770