commands.py 236 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

8
from node import hex, bin, nullid, nullrev, short
9
from lock import release
10
from i18n import _
11
import os, re, difflib, time, tempfile, errno, shlex
12
import sys, socket
13
import hg, scmutil, util, revlog, copies, error, bookmarks
14
import patch, help, encoding, templatekw, discovery
15
import archival, changegroup, cmdutil, hbisect
Gregory Szorc's avatar
Gregory Szorc committed
16
import sshserver, hgweb
17
import extensions
18
from hgweb import server as hgweb_server
19
import merge as mergemod
20
import minirst, revset, fileset
21
import dagparser, context, simplemerge, graphmod, copies
22
import random, operator
23
import setdiscovery, treediscovery, dagutil, pvec, localrepo
24
import phases, obsolete, exchange, bundle2, repair, lock as lockmod
25
import ui as uimod
26

27 28 29 30
table = {}

command = cmdutil.command(table)

31 32 33
# Space delimited list of commands that don't require local repositories.
# This should be populated by passing norepo=True into the @command decorator.
norepo = ''
34 35 36 37
# Space delimited list of commands that optionally require local repositories.
# This should be populated by passing optionalrepo=True into the @command
# decorator.
optionalrepo = ''
38 39 40 41 42
# Space delimited list of commands that will examine arguments looking for
# a repository. This should be populated by passing inferrepo=True into the
# @command decorator.
inferrepo = ''

43 44 45 46 47 48
# label constants
# until 3.5, bookmarks.current was the advertised name, not
# bookmarks.active, so we must use both to avoid breaking old
# custom styles
activebookmarklabel = 'bookmarks.active bookmarks.current'

49 50 51 52 53 54 55 56 57
# common command options

globalopts = [
    ('R', 'repository', '',
     _('repository root directory or name of overlay bundle file'),
     _('REPO')),
    ('', 'cwd', '',
     _('change working directory'), _('DIR')),
    ('y', 'noninteractive', None,
58
     _('do not prompt, automatically pick the first choice for all prompts')),
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
    ('q', 'quiet', None, _('suppress output')),
    ('v', 'verbose', None, _('enable additional output')),
    ('', 'config', [],
     _('set/override config option (use \'section.name=value\')'),
     _('CONFIG')),
    ('', 'debug', None, _('enable debugging output')),
    ('', 'debugger', None, _('start debugger')),
    ('', 'encoding', encoding.encoding, _('set the charset encoding'),
     _('ENCODE')),
    ('', 'encodingmode', encoding.encodingmode,
     _('set the charset encoding mode'), _('MODE')),
    ('', 'traceback', None, _('always print a traceback on exception')),
    ('', 'time', None, _('time how long the command takes')),
    ('', 'profile', None, _('print command execution profile')),
    ('', 'version', None, _('output version information and exit')),
    ('h', 'help', None, _('display help and exit')),
75
    ('', 'hidden', False, _('consider hidden changesets')),
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
]

dryrunopts = [('n', 'dry-run', None,
               _('do not perform actions, just print output'))]

remoteopts = [
    ('e', 'ssh', '',
     _('specify ssh command to use'), _('CMD')),
    ('', 'remotecmd', '',
     _('specify hg command to run on the remote side'), _('CMD')),
    ('', 'insecure', None,
     _('do not verify server certificate (ignoring web.cacerts config)')),
]

walkopts = [
    ('I', 'include', [],
     _('include names matching the given patterns'), _('PATTERN')),
    ('X', 'exclude', [],
     _('exclude names matching the given patterns'), _('PATTERN')),
]

commitopts = [
    ('m', 'message', '',
     _('use text as commit message'), _('TEXT')),
    ('l', 'logfile', '',
     _('read commit message from file'), _('FILE')),
]

commitopts2 = [
    ('d', 'date', '',
     _('record the specified date as commit date'), _('DATE')),
    ('u', 'user', '',
     _('record the specified user as committer'), _('USER')),
]

111 112 113
# hidden for now
formatteropts = [
    ('T', 'template', '',
114
     _('display with template (EXPERIMENTAL)'), _('TEMPLATE')),
115 116
]

117 118
templateopts = [
    ('', 'style', '',
119
     _('display using template map file (DEPRECATED)'), _('STYLE')),
120
    ('T', 'template', '',
121 122 123 124 125 126 127 128 129 130
     _('display with template'), _('TEMPLATE')),
]

logopts = [
    ('p', 'patch', None, _('show patch')),
    ('g', 'git', None, _('use git extended diff format')),
    ('l', 'limit', '',
     _('limit number of changes displayed'), _('NUM')),
    ('M', 'no-merges', None, _('do not show merges')),
    ('', 'stat', None, _('output diffstat-style summary of changes')),
131
    ('G', 'graph', None, _("show the revision DAG")),
132 133 134 135 136 137 138 139
] + templateopts

diffopts = [
    ('a', 'text', None, _('treat all files as text')),
    ('g', 'git', None, _('use git extended diff format')),
    ('', 'nodates', None, _('omit dates from diff headers'))
]

140
diffwsopts = [
141 142 143 144 145 146
    ('w', 'ignore-all-space', None,
     _('ignore white space when comparing lines')),
    ('b', 'ignore-space-change', None,
     _('ignore changes in the amount of white space')),
    ('B', 'ignore-blank-lines', None,
     _('ignore changes whose lines are all blank')),
147 148 149
    ]

diffopts2 = [
150
    ('', 'noprefix', None, _('omit a/ and b/ prefixes from filenames')),
151 152 153
    ('p', 'show-function', None, _('show which function each change is in')),
    ('', 'reverse', None, _('produce a diff that undoes the changes')),
    ] + diffwsopts + [
154 155 156
    ('U', 'unified', '',
     _('number of lines of context to show'), _('NUM')),
    ('', 'stat', None, _('output diffstat-style summary of changes')),
157
    ('', 'root', '', _('produce diffs relative to subdirectory'), _('DIR')),
158 159
]

160 161 162 163
mergetoolopts = [
    ('t', 'tool', '', _('specify merge tool')),
]

164 165 166 167 168 169 170 171 172 173
similarityopts = [
    ('s', 'similarity', '',
     _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
]

subrepoopts = [
    ('S', 'subrepos', None,
     _('recurse into subrepositories'))
]

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

176 177
@command('^add',
    walkopts + subrepoopts + dryrunopts,
178 179
    _('[OPTION]... [FILE]...'),
    inferrepo=True)
180
def add(ui, repo, *pats, **opts):
181 182
    """add the specified files on the next commit

183 184
    Schedule files to be version controlled and added to the
    repository.
185

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

189
    If no names are given, add all files to the repository.
190 191 192 193

    .. container:: verbose

       An example showing how new (unknown) files are added
Martin Geisler's avatar
Martin Geisler committed
194
       automatically by :hg:`add`::
195 196 197 198 199 200 201 202

         $ ls
         foo.c
         $ hg status
         ? foo.c
         $ hg add
         adding foo.c
         $ hg status
203
         A foo.c
204 205

    Returns 0 if all files are successfully added.
206 207
    """

208
    m = scmutil.match(repo[None], pats, opts)
209
    rejected = cmdutil.add(ui, repo, m, "", False, **opts)
210
    return rejected and 1 or 0
211

212
@command('addremove',
213
    similarityopts + subrepoopts + walkopts + dryrunopts,
214 215
    _('[OPTION]... [FILE]...'),
    inferrepo=True)
216
def addremove(ui, repo, *pats, **opts):
217
    """add all new files, delete all missing files
218

219 220
    Add all new files and remove all missing files from the
    repository.
221

222
    New files are ignored if they match any of the patterns in
223
    ``.hgignore``. As with add, these changes take effect at the next
224
    commit.
225

226
    Use the -s/--similarity option to detect renamed files. This
227
    option takes a percentage between 0 (disabled) and 100 (files must
228 229 230
    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
231
    can be expensive. After using this option, :hg:`status -C` can be
232 233 234
    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.
235 236

    Returns 0 if all files are successfully added.
237
    """
238
    try:
239
        sim = float(opts.get('similarity') or 100)
240 241
    except ValueError:
        raise util.Abort(_('similarity must be a number'))
242 243
    if sim < 0 or sim > 100:
        raise util.Abort(_('similarity must be between 0 and 100'))
244
    matcher = scmutil.match(repo[None], pats, opts)
245
    return scmutil.addremove(repo, matcher, "", opts, similarity=sim / 100.0)
246

247 248 249 250 251 252 253 254 255 256 257 258
@command('^annotate|blame',
    [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
    ('', 'follow', None,
     _('follow copies/renames and list the filename (DEPRECATED)')),
    ('', 'no-follow', None, _("don't follow copies and renames")),
    ('a', 'text', None, _('treat all files as text')),
    ('u', 'user', None, _('list the author (long with -v)')),
    ('f', 'file', None, _('list the filename')),
    ('d', 'date', None, _('list the date (short with -q)')),
    ('n', 'number', None, _('list the revision number (default)')),
    ('c', 'changeset', None, _('list the changeset')),
    ('l', 'line-number', None, _('show line number at the first appearance'))
259
    ] + diffwsopts + walkopts + formatteropts,
260 261
    _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'),
    inferrepo=True)
262
def annotate(ui, repo, *pats, **opts):
263
    """show changeset information by line for each file
264

265 266
    List changes in files, showing the revision id responsible for
    each line
267

268 269
    This command is useful for discovering when a change was made and
    by whom.
270

271 272 273 274
    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.
275 276

    Returns 0 on success.
277
    """
278 279 280
    if not pats:
        raise util.Abort(_('at least one filename or pattern is required'))

281 282 283
    if opts.get('follow'):
        # --follow is deprecated and now just an alias for -f/--file
        # to mimic the behavior of Mercurial before version 1.5
284
        opts['file'] = True
285

286 287
    ctx = scmutil.revsingle(repo, opts.get('rev'))

288
    fm = ui.formatter('annotate', opts)
289 290 291 292
    if ui.quiet:
        datefunc = util.shortdate
    else:
        datefunc = util.datestr
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
    if ctx.rev() is None:
        def hexfn(node):
            if node is None:
                return None
            else:
                return fm.hexfunc(node)
        if opts.get('changeset'):
            # omit "+" suffix which is appended to node hex
            def formatrev(rev):
                if rev is None:
                    return '%d' % ctx.p1().rev()
                else:
                    return '%d' % rev
        else:
            def formatrev(rev):
                if rev is None:
                    return '%d+' % ctx.p1().rev()
                else:
                    return '%d ' % rev
        def formathex(hex):
            if hex is None:
                return '%s+' % fm.hexfunc(ctx.p1().node())
            else:
                return '%s ' % hex
    else:
        hexfn = fm.hexfunc
        formatrev = formathex = str
320

321
    opmap = [('user', ' ', lambda x: x[0].user(), ui.shortuser),
322 323
             ('number', ' ', lambda x: x[0].rev(), formatrev),
             ('changeset', ' ', lambda x: hexfn(x[0].node()), formathex),
324 325 326
             ('date', ' ', lambda x: x[0].date(), util.cachefunc(datefunc)),
             ('file', ' ', lambda x: x[0].path(), str),
             ('line_number', ':', lambda x: x[1], str),
327
            ]
328
    fieldnamemap = {'number': 'rev', 'changeset': 'node'}
329

330
    if (not opts.get('user') and not opts.get('changeset')
331
        and not opts.get('date') and not opts.get('file')):
332
        opts['number'] = True
333

334
    linenumber = opts.get('line_number') is not None
335
    if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
336 337
        raise util.Abort(_('at least one of -n/-c is required for -l'))

338 339 340 341 342 343
    if fm:
        def makefunc(get, fmt):
            return get
    else:
        def makefunc(get, fmt):
            return lambda x: fmt(get(x))
344 345
    funcmap = [(makefunc(get, fmt), sep) for op, sep, get, fmt in opmap
               if opts.get(op)]
346
    funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
347 348
    fields = ' '.join(fieldnamemap.get(op, op) for op, sep, get, fmt in opmap
                      if opts.get(op))
349

350 351 352
    def bad(x, y):
        raise util.Abort("%s: %s" % (x, y))

353 354
    m = scmutil.match(ctx, pats, opts, badfn=bad)

355
    follow = not opts.get('no_follow')
356 357
    diffopts = patch.difffeatureopts(ui, opts, section='annotate',
                                     whitespace=True)
Matt Mackall's avatar
Matt Mackall committed
358 359
    for abs in ctx.walk(m):
        fctx = ctx[abs]
360
        if not opts.get('text') and util.binary(fctx.data()):
361
            fm.plain(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
362 363
            continue

364 365
        lines = fctx.annotate(follow=follow, linenumber=linenumber,
                              diffopts=diffopts)
366
        formats = []
367 368
        pieces = []

369
        for f, sep in funcmap:
370 371
            l = [f(n) for n, dummy in lines]
            if l:
372 373 374 375 376 377
                if fm:
                    formats.append(['%s' for x in l])
                else:
                    sizes = [encoding.colwidth(x) for x in l]
                    ml = max(sizes)
                    formats.append([sep + ' ' * (ml - w) + '%s' for w in sizes])
378
                pieces.append(l)
379

380
        for f, p, l in zip(zip(*formats), zip(*pieces), lines):
381 382 383
            fm.startitem()
            fm.write(fields, "".join(f), *p)
            fm.write('line', ": %s", l[1])
384

385
        if lines and not lines[-1][1].endswith('\n'):
386 387 388
            fm.plain('\n')

    fm.end()
389

390 391 392 393 394 395 396 397
@command('archive',
    [('', 'no-decode', None, _('do not pass files through decoders')),
    ('p', 'prefix', '', _('directory prefix for files in archive'),
     _('PREFIX')),
    ('r', 'rev', '', _('revision to distribute'), _('REV')),
    ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
    ] + subrepoopts + walkopts,
    _('[OPTION]... DEST'))
398
def archive(ui, repo, dest, **opts):
399
    '''create an unversioned archive of a repository revision
400

401 402
    By default, the revision used is the parent of the working
    directory; use -r/--rev to specify a different revision.
403

404 405 406
    The archive type is automatically detected based on file
    extension (or override using -t/--type).

Matt Mackall's avatar
Matt Mackall committed
407 408 409 410 411 412 413 414 415 416 417 418
    .. 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*"

419
    Valid types are:
420

421 422 423 424 425 426
    :``files``: a directory full of files (default)
    :``tar``:   tar archive, uncompressed
    :``tbz2``:  tar archive, compressed using bzip2
    :``tgz``:   tar archive, compressed using gzip
    :``uzip``:  zip archive, uncompressed
    :``zip``:   zip archive, compressed using deflate
427

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

431 432 433 434
    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.
435 436

    Returns 0 on success.
437 438
    '''

439
    ctx = scmutil.revsingle(repo, opts.get('rev'))
440
    if not ctx:
441
        raise util.Abort(_('no working directory: please specify a revision'))
442
    node = ctx.node()
443
    dest = cmdutil.makefilename(repo, dest, node)
444
    if os.path.realpath(dest) == repo.root:
445
        raise util.Abort(_('repository root cannot be destination'))
446

447
    kind = opts.get('type') or archival.guesskind(dest) or 'files'
448
    prefix = opts.get('prefix')
449

450 451 452
    if dest == '-':
        if kind == 'files':
            raise util.Abort(_('cannot archive plain files to stdout'))
453
        dest = cmdutil.makefileobj(repo, dest)
454 455
        if not prefix:
            prefix = os.path.basename(repo.root) + '-%h'
456

457
    prefix = cmdutil.makefilename(repo, prefix, node)
458
    matchfn = scmutil.match(ctx, [], opts)
459
    archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
460
                     matchfn, prefix, subrepos=opts.get('subrepos'))
461

462 463
@command('backout',
    [('', 'merge', None, _('merge with old dirstate parent after backout')),
Mateusz Kwapich's avatar
Mateusz Kwapich committed
464
    ('', 'commit', None, _('commit if no conflicts were encountered')),
465 466
    ('', 'parent', '',
     _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
467
    ('r', 'rev', '', _('revision to backout'), _('REV')),
468
    ('e', 'edit', False, _('invoke editor on commit messages')),
469
    ] + mergetoolopts + walkopts + commitopts + commitopts2,
470
    _('[OPTION]... [-r] REV'))
Mateusz Kwapich's avatar
Mateusz Kwapich committed
471
def backout(ui, repo, node=None, rev=None, commit=False, **opts):
Vadim Gelfer's avatar
Vadim Gelfer committed
472 473
    '''reverse effect of earlier changeset

474 475 476
    Prepare a new changeset with the effect of REV undone in the
    current working directory.

477
    If REV is the parent of the working directory, then this new changeset
478 479 480
    is committed automatically. Otherwise, hg needs to merge the
    changes and the merged result is left uncommitted.

481
    .. note::
482

483 484 485
      backout cannot be used to fix either an unwanted or
      incorrect merge.

Matt Mackall's avatar
Matt Mackall committed
486 487 488 489 490 491 492 493 494 495 496
    .. container:: verbose

      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.
497

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

500 501
    Returns 0 on success, 1 if nothing to backout or there are unresolved
    files.
502
    '''
Daniel Holth's avatar
Daniel Holth committed
503 504 505 506 507
    if rev and node:
        raise util.Abort(_("please specify just one revision"))

    if not rev:
        rev = node
Vadim Gelfer's avatar
Vadim Gelfer committed
508

509 510 511
    if not rev:
        raise util.Abort(_("please specify a revision to backout"))

512 513 514 515
    date = opts.get('date')
    if date:
        opts['date'] = util.parsedate(date)

516
    cmdutil.checkunfinished(repo)
517
    cmdutil.bailifchanged(repo)
518
    node = scmutil.revsingle(repo, rev).node()
519

520
    op1, op2 = repo.dirstate.parents()
521
    if not repo.changelog.isancestor(node, op1):
522
        raise util.Abort(_('cannot backout change that is not an ancestor'))
523

524 525
    p1, p2 = repo.changelog.parents(node)
    if p1 == nullid:
526
        raise util.Abort(_('cannot backout a change with no parents'))
Vadim Gelfer's avatar
Vadim Gelfer committed
527
    if p2 != nullid:
528
        if not opts.get('parent'):
529
            raise util.Abort(_('cannot backout a merge changeset'))
530 531
        p = repo.lookup(opts['parent'])
        if p not in (p1, p2):
532
            raise util.Abort(_('%s is not a parent of %s') %
533
                             (short(p), short(node)))
534 535
        parent = p
    else:
536
        if opts.get('parent'):
537 538
            raise util.Abort(_('cannot use --parent on non-merge changeset'))
        parent = p1
539

540
    # the backout should appear on the same branch
541 542 543
    wlock = repo.wlock()
    try:
        branch = repo.dirstate.branch()
544
        bheads = repo.branchheads(branch)
545
        rctx = scmutil.revsingle(repo, hex(parent))
546 547
        if not opts.get('merge') and op1 != node:
            try:
548 549
                ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
                             'backout')
550
                repo.dirstate.beginparentchange()
551 552
                stats = mergemod.update(repo, parent, True, True, False,
                                        node, False)
553
                repo.setparents(op1, op2)
554
                repo.dirstate.endparentchange()
555 556
                hg._showstats(repo, stats)
                if stats[3]:
557 558
                    repo.ui.status(_("use 'hg resolve' to retry unresolved "
                                     "file merges\n"))
Mateusz Kwapich's avatar
Mateusz Kwapich committed
559 560
                    return 1
                elif not commit:
561 562 563
                    msg = _("changeset %s backed out, "
                            "don't forget to commit.\n")
                    ui.status(msg % short(node))
Mateusz Kwapich's avatar
Mateusz Kwapich committed
564
                    return 0
565
            finally:
566
                ui.setconfig('ui', 'forcemerge', '', '')
567 568 569 570 571
        else:
            hg.clean(repo, node, show_stats=False)
            repo.dirstate.setbranch(branch)
            cmdutil.revert(ui, repo, rctx, repo.dirstate.parents())

572

573
        def commitfunc(ui, repo, message, match, opts):
574 575
            editform = 'backout'
            e = cmdutil.getcommiteditor(editform=editform, **opts)
576 577 578
            if not message:
                # we don't translate commit messages
                message = "Backed out changeset %s" % short(node)
579
                e = cmdutil.getcommiteditor(edit=True, editform=editform)
580 581 582
            return repo.commit(message, opts.get('user'), opts.get('date'),
                               match, editor=e)
        newnode = cmdutil.commit(ui, repo, commitfunc, [], opts)
583 584 585
        if not newnode:
            ui.status(_("nothing changed\n"))
            return 1
586
        cmdutil.commitstatus(repo, newnode, branch, bheads)
587

588 589 590 591 592 593 594 595 596
        def nice(node):
            return '%d:%s' % (repo.changelog.rev(node), short(node))
        ui.status(_('changeset %s backs out changeset %s\n') %
                  (nice(repo.changelog.tip()), nice(node)))
        if opts.get('merge') and op1 != node:
            hg.clean(repo, op1, show_stats=False)
            ui.status(_('merging with changeset %s\n')
                      % nice(repo.changelog.tip()))
            try:
597 598
                ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
                             'backout')
599 600
                return hg.merge(repo, hex(repo.changelog.tip()))
            finally:
601
                ui.setconfig('ui', 'forcemerge', '', '')
602 603
    finally:
        wlock.release()
604
    return 0
Vadim Gelfer's avatar
Vadim Gelfer committed
605

606 607 608 609 610 611 612 613 614
@command('bisect',
    [('r', 'reset', False, _('reset bisect state')),
    ('g', 'good', False, _('mark changeset good')),
    ('b', 'bad', False, _('mark changeset bad')),
    ('s', 'skip', False, _('skip testing changeset')),
    ('e', 'extend', False, _('extend the bisect range')),
    ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
    ('U', 'noupdate', False, _('do not update to target'))],
    _("[-gbsr] [-U] [-c CMD] [REV]"))
615
def bisect(ui, repo, rev=None, extra=None, command=None,
616 617
               reset=None, good=None, bad=None, skip=None, extend=None,
               noupdate=None):
618 619
    """subdivision search of changesets

620 621 622 623 624 625 626 627 628 629 630 631 632
    This command helps to find changesets which introduce problems. To
    use, mark the earliest changeset you know exhibits the problem as
    bad, then mark the latest changeset which is free from the problem
    as good. Bisect will update your working directory to a revision
    for testing (unless the -U/--noupdate option is specified). Once
    you have performed tests, mark the working directory as good or
    bad, and bisect will either update to another candidate changeset
    or announce that it has found the bad revision.

    As a shortcut, you can also use the revision argument to mark a
    revision as good or bad without checking it out first.

    If you supply a command, it will be used for automatic bisection.
633 634 635 636 637 638
    The environment variable HG_NODE will contain the ID of the
    changeset being tested. The exit status of the command will be
    used to mark revisions as good or bad: status 0 means good, 125
    means to skip the revision, 127 (command not found) will abort the
    bisection, and any other non-zero exit status means the revision
    is bad.
639

640 641 642 643
    .. container:: verbose

      Some examples:

644
      - start a bisection with known bad revision 34, and good revision 12::
645 646 647 648 649 650 651 652 653 654

          hg bisect --bad 34
          hg bisect --good 12

      - advance the current bisection by marking current revision as good or
        bad::

          hg bisect --good
          hg bisect --bad

kiilerix's avatar
kiilerix committed
655
      - mark the current revision, or a known revision, to be skipped (e.g. if
656 657 658 659 660
        that revision is not usable because of another issue)::

          hg bisect --skip
          hg bisect --skip 23

661
      - skip all revisions that do not touch directories ``foo`` or ``bar``::
662

663
          hg bisect --skip "!( file('path:foo') & file('path:bar') )"
664

665 666 667 668 669 670 671 672 673 674
      - forget the current bisection::

          hg bisect --reset

      - use 'make && make tests' to automatically find the first broken
        revision::

          hg bisect --reset
          hg bisect --bad 34
          hg bisect --good 12
675
          hg bisect --command "make && make tests"
676 677 678 679 680 681

      - see all changesets whose states are already known in the current
        bisection::

          hg log -r "bisect(pruned)"

682 683 684 685 686
      - see the changeset currently being bisected (especially useful
        if running with -U/--noupdate)::

          hg log -r "bisect(current)"

687 688 689 690
      - see all changesets that took part in the current bisection::

          hg log -r "bisect(range)"

691
      - you can even get a nice graph::
692 693 694

          hg log --graph -r "bisect(range)"

695 696
      See :hg:`help revsets` for more about the `bisect()` keyword.

697
    Returns 0 on success.
698
    """
699 700 701 702 703
    def extendbisectrange(nodes, good):
        # bisect is incomplete when it ends on a merge node and
        # one of the parent was not checked.
        parents = repo[nodes[0]].parents()
        if len(parents) > 1:
704 705 706 707
            if good:
                side = state['bad']
            else:
                side = state['good']
708 709
            num = len(set(i.node() for i in parents) & set(side))
            if num == 1:
Yuya Nishihara's avatar
Yuya Nishihara committed
710
                return parents[0].ancestor(parents[1])
711 712
        return None

713 714 715 716
    def print_result(nodes, good):
        displayer = cmdutil.show_changeset(ui, repo, {})
        if len(nodes) == 1:
            # narrowed it down to a single revision
717 718 719 720
            if good:
                ui.write(_("The first good revision is:\n"))
            else:
                ui.write(_("The first bad revision is:\n"))
721
            displayer.show(repo[nodes[0]])
722 723 724 725 726
            extendnode = extendbisectrange(nodes, good)
            if extendnode is not None:
                ui.write(_('Not all ancestors of this changeset have been'
                           ' checked.\nUse bisect --extend to continue the '
                           'bisection from\nthe common ancestor, %s.\n')
727
                         % extendnode)
728 729
        else:
            # multiple possible revisions
730 731 732 733 734 735
            if good:
                ui.write(_("Due to skipped revisions, the first "
                        "good revision could be any of:\n"))
            else:
                ui.write(_("Due to skipped revisions, the first "
                        "bad revision could be any of:\n"))
736
            for n in nodes:
737
                displayer.show(repo[n])
738
        displayer.close()
739 740 741 742 743 744 745 746 747 748 749

    def check_state(state, interactive=True):
        if not state['good'] or not state['bad']:
            if (good or bad or skip or reset) and interactive:
                return
            if not state['good']:
                raise util.Abort(_('cannot bisect (no known good revisions)'))
            else:
                raise util.Abort(_('cannot bisect (no known bad revisions)'))
        return True

750 751 752 753 754 755 756 757 758 759
    # backward compatibility
    if rev in "good bad reset init".split():
        ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
        cmd, rev, extra = rev, extra, None
        if cmd == "good":
            good = True
        elif cmd == "bad":
            bad = True
        else:
            reset = True
760
    elif extra or good + bad + skip + reset + extend + bool(command) > 1:
761
        raise util.Abort(_('incompatible arguments'))
762

763 764
    cmdutil.checkunfinished(repo)

765 766 767 768 769 770
    if reset:
        p = repo.join("bisect.state")
        if os.path.exists(p):
            os.unlink(p)
        return

771 772 773 774
    state = hbisect.load_state(repo)

    if command:
        changesets = 1
775 776 777 778
        if noupdate:
            try:
                node = state['current'][0]
            except LookupError:
779 780
                raise util.Abort(_('current bisect revision is unknown - '
                                   'start a new bisect to fix'))
781
        else:
782 783 784
            node, p2 = repo.dirstate.parents()
            if p2 != nullid:
                raise util.Abort(_('current bisect revision is a merge'))
785 786 787
        try:
            while changesets:
                # update state
788
                state['current'] = [node]
789
                hbisect.save_state(repo, state)
790
                status = ui.system(command, environ={'HG_NODE': hex(node)})
791 792 793 794 795 796 797 798 799 800 801
                if status == 125:
                    transition = "skip"
                elif status == 0:
                    transition = "good"
                # status < 0 means process was killed
                elif status == 127:
                    raise util.Abort(_("failed to execute %s") % command)
                elif status < 0:
                    raise util.Abort(_("%s killed") % command)
                else:
                    transition = "bad"
802
                ctx = scmutil.revsingle(repo, rev, node)
803
                rev = None # clear for future iterations
804
                state[transition].append(ctx.node())
805
                ui.status(_('changeset %d:%s: %s\n') % (ctx, ctx, transition))
806 807
                check_state(state, interactive=False)
                # bisect
808
                nodes, changesets, bgood = hbisect.bisect(repo.changelog, state)
809
                # update to next check
810 811 812 813
                node = nodes[0]
                if not noupdate:
                    cmdutil.bailifchanged(repo)
                    hg.clean(repo, node, show_stats=False)
814
        finally:
815
            state['current'] = [node]
816
            hbisect.save_state(repo, state)
817
        print_result(nodes, bgood)
818
        return
819 820

    # update state
821 822

    if rev:
823
        nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
824 825 826
    else:
        nodes = [repo.lookup('.')]

827 828
    if good or bad or skip:
        if good:
829
            state['good'] += nodes
830
        elif bad:
831
            state['bad'] += nodes
832
        elif skip:
833
            state['skip'] += nodes
834
        hbisect.save_state(repo, state)
835

836 837
    if not check_state(state):
        return
838 839

    # actually bisect
840
    nodes, changesets, good = hbisect.bisect(repo.changelog, state)
841 842 843 844
    if extend:
        if not changesets:
            extendnode = extendbisectrange(nodes, good)
            if extendnode is not None:
845 846
                ui.write(_("Extending search to changeset %d:%s\n")
                         % (extendnode.rev(), extendnode))
847