commands.py 138 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, nullid, nullrev, short
9
from lock import release
10
from i18n import _, gettext
Benoit Boissinot's avatar
Benoit Boissinot committed
11 12
import os, re, sys, difflib, time, tempfile
import hg, util, revlog, bundlerepo, extensions, copies, error
13
import patch, help, mdiff, url, encoding, templatekw
14 15
import archival, changegroup, cmdutil, sshserver, hbisect
from hgweb import server
Matt Mackall's avatar
Matt Mackall committed
16
import merge as merge_
17
import minirst
18

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

21
def add(ui, repo, *pats, **opts):
22 23
    """add the specified files on the next commit

24 25
    Schedule files to be version controlled and added to the
    repository.
26

27 28
    The files will be added to the repository at the next commit. To
    undo an add before that, see hg forget.
29

30
    If no names are given, add all files to the repository.
31 32
    """

33
    bad = []
34
    names = []
35
    m = cmdutil.match(repo, pats, opts)
36
    oldbad = m.bad
37
    m.bad = lambda x, y: bad.append(x) or oldbad(x, y)
38 39 40 41 42 43 44

    for f in repo.walk(m):
        exact = m.exact(f)
        if exact or f not in repo.dirstate:
            names.append(f)
            if ui.verbose or not exact:
                ui.status(_('adding %s\n') % m.rel(f))
45
    if not opts.get('dry_run'):
46 47
        bad += [f for f in repo.add(names) if f in m.files()]
    return bad and 1 or 0
48

49
def addremove(ui, repo, *pats, **opts):
50
    """add all new files, delete all missing files
51

52 53
    Add all new files and remove all missing files from the
    repository.
54

55 56 57
    New files are ignored if they match any of the patterns in
    .hgignore. As with add, these changes take effect at the next
    commit.
58

59 60 61 62 63 64
    Use the -s/--similarity option to detect renamed files. With a
    parameter greater than 0, this compares every removed file with
    every added file and records those similar enough as renames. This
    option takes a percentage between 0 (disabled) and 100 (files must
    be identical) as its parameter. Detecting renamed files this way
    can be expensive.
65
    """
66 67 68 69
    try:
        sim = float(opts.get('similarity') or 0)
    except ValueError:
        raise util.Abort(_('similarity must be a number'))
70 71
    if sim < 0 or sim > 100:
        raise util.Abort(_('similarity must be between 0 and 100'))
72
    return cmdutil.addremove(repo, pats, opts, similarity=sim / 100.0)
73

74
def annotate(ui, repo, *pats, **opts):
75
    """show changeset information by line for each file
76

77 78
    List changes in files, showing the revision id responsible for
    each line
79

80 81
    This command is useful for discovering when a change was made and
    by whom.
82

83 84 85 86
    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.
87
    """
88 89
    datefunc = ui.quiet and util.shortdate or util.datestr
    getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
90

91
    if not pats:
92
        raise util.Abort(_('at least one filename or pattern is required'))
93

94 95 96 97
    opmap = [('user', lambda x: ui.shortuser(x[0].user())),
             ('number', lambda x: str(x[0].rev())),
             ('changeset', lambda x: short(x[0].node())),
             ('date', getdate),
98
             ('file', lambda x: x[0].path()),
99 100
            ]

101
    if (not opts.get('user') and not opts.get('changeset')
102
        and not opts.get('date') and not opts.get('file')):
103
        opts['number'] = 1
104

105
    linenumber = opts.get('line_number') is not None
106
    if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
107 108 109 110 111 112 113
        raise util.Abort(_('at least one of -n/-c is required for -l'))

    funcmap = [func for op, func in opmap if opts.get(op)]
    if linenumber:
        lastfunc = funcmap[-1]
        funcmap[-1] = lambda x: "%s:%s" % (lastfunc(x), x[1])

114
    ctx = repo[opts.get('rev')]
115
    m = cmdutil.match(repo, pats, opts)
116
    follow = not opts.get('no_follow')
Matt Mackall's avatar
Matt Mackall committed
117 118
    for abs in ctx.walk(m):
        fctx = ctx[abs]
119
        if not opts.get('text') and util.binary(fctx.data()):
120
            ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
121 122
            continue

123
        lines = fctx.annotate(follow=follow, linenumber=linenumber)
124 125
        pieces = []

126 127 128
        for f in funcmap:
            l = [f(n) for n, dummy in lines]
            if l:
129 130
                ml = max(map(len, l))
                pieces.append(["%*s" % (ml, x) for x in l])
131

mpm@selenic.com's avatar
mpm@selenic.com committed
132 133 134
        if pieces:
            for p, l in zip(zip(*pieces), lines):
                ui.write("%s: %s" % (" ".join(p), l[1]))
135

136
def archive(ui, repo, dest, **opts):
137
    '''create an unversioned archive of a repository revision
138

139 140
    By default, the revision used is the parent of the working
    directory; use -r/--rev to specify a different revision.
141

142
    To specify the type of archive to create, use -t/--type. Valid
143
    types are:
144

145 146 147 148 149 150
    :``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
151

152 153
    The exact name of the destination archive or directory is given
    using a format string; see 'hg help export' for details.
154

155 156 157 158
    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.
159 160
    '''

161
    ctx = repo[opts.get('rev')]
162
    if not ctx:
163
        raise util.Abort(_('no working directory: please specify a revision'))
164
    node = ctx.node()
Vadim Gelfer's avatar
Vadim Gelfer committed
165
    dest = cmdutil.make_filename(repo, dest, node)
166 167
    if os.path.realpath(dest) == repo.root:
        raise util.Abort(_('repository root cannot be destination'))
168
    matchfn = cmdutil.match(repo, [], opts)
169
    kind = opts.get('type') or 'files'
170
    prefix = opts.get('prefix')
171 172 173 174
    if dest == '-':
        if kind == 'files':
            raise util.Abort(_('cannot archive plain files to stdout'))
        dest = sys.stdout
175 176
        if not prefix:
            prefix = os.path.basename(repo.root) + '-%h'
Vadim Gelfer's avatar
Vadim Gelfer committed
177
    prefix = cmdutil.make_filename(repo, prefix, node)
178
    archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
179
                     matchfn, prefix)
180

Daniel Holth's avatar
Daniel Holth committed
181
def backout(ui, repo, node=None, rev=None, **opts):
Vadim Gelfer's avatar
Vadim Gelfer committed
182 183
    '''reverse effect of earlier changeset

184 185
    Commit the backed out changes as a new changeset. The new
    changeset is a child of the backed out changeset.
Vadim Gelfer's avatar
Vadim Gelfer committed
186

187 188 189
    If you backout a changeset other than the tip, a new head is
    created. This head will be the new tip and you should merge this
    backout changeset with another head.
Vadim Gelfer's avatar
Vadim Gelfer committed
190

191 192 193 194
    The --merge option remembers the parent of the working directory
    before starting the backout, then merges the new head with that
    changeset afterwards. This saves you from doing the merge by hand.
    The result of this merge is not committed, as with a normal merge.
195

196
    See 'hg help dates' for a list of formats valid for -d/--date.
197
    '''
Daniel Holth's avatar
Daniel Holth committed
198 199 200 201 202
    if rev and node:
        raise util.Abort(_("please specify just one revision"))

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

204 205 206
    if not rev:
        raise util.Abort(_("please specify a revision to backout"))

207 208 209 210
    date = opts.get('date')
    if date:
        opts['date'] = util.parsedate(date)

211
    cmdutil.bail_if_changed(repo)
Vadim Gelfer's avatar
Vadim Gelfer committed
212
    node = repo.lookup(rev)
213

214
    op1, op2 = repo.dirstate.parents()
215 216
    a = repo.changelog.ancestor(op1, node)
    if a != node:
217
        raise util.Abort(_('cannot backout change on a different branch'))
218

219 220
    p1, p2 = repo.changelog.parents(node)
    if p1 == nullid:
221
        raise util.Abort(_('cannot backout a change with no parents'))
Vadim Gelfer's avatar
Vadim Gelfer committed
222
    if p2 != nullid:
223
        if not opts.get('parent'):
224
            raise util.Abort(_('cannot backout a merge changeset without '
225 226 227
                               '--parent'))
        p = repo.lookup(opts['parent'])
        if p not in (p1, p2):
228
            raise util.Abort(_('%s is not a parent of %s') %
229
                             (short(p), short(node)))
230 231
        parent = p
    else:
232
        if opts.get('parent'):
233 234
            raise util.Abort(_('cannot use --parent on non-merge changeset'))
        parent = p1
235

236 237
    # the backout should appear on the same branch
    branch = repo.dirstate.branch()
238
    hg.clean(repo, node, show_stats=False)
239
    repo.dirstate.setbranch(branch)
Vadim Gelfer's avatar
Vadim Gelfer committed
240
    revert_opts = opts.copy()
241
    revert_opts['date'] = None
242
    revert_opts['all'] = True
Vadim Gelfer's avatar
Vadim Gelfer committed
243
    revert_opts['rev'] = hex(parent)
244
    revert_opts['no_backup'] = None
Vadim Gelfer's avatar
Vadim Gelfer committed
245 246 247
    revert(ui, repo, **revert_opts)
    commit_opts = opts.copy()
    commit_opts['addremove'] = False
248
    if not commit_opts['message'] and not commit_opts['logfile']:
249
        # we don't translate commit messages
250
        commit_opts['message'] = "Backed out changeset %s" % short(node)
251
        commit_opts['force_editor'] = True
Vadim Gelfer's avatar
Vadim Gelfer committed
252 253 254 255 256
    commit(ui, repo, **commit_opts)
    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)))
257
    if op1 != node:
258
        hg.clean(repo, op1, show_stats=False)
259
        if opts.get('merge'):
260 261
            ui.status(_('merging with changeset %s\n')
                      % nice(repo.changelog.tip()))
262
            hg.merge(repo, hex(repo.changelog.tip()))
263 264 265
        else:
            ui.status(_('the backout changeset is a new head - '
                        'do not forget to merge\n'))
266 267
            ui.status(_('(use "backout --merge" '
                        'if you want to auto-merge)\n'))
Vadim Gelfer's avatar
Vadim Gelfer committed
268

269
def bisect(ui, repo, rev=None, extra=None, command=None,
270 271 272
               reset=None, good=None, bad=None, skip=None, noupdate=None):
    """subdivision search of changesets

273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
    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.
    Its exit status 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.
290
    """
291 292 293 294
    def print_result(nodes, good):
        displayer = cmdutil.show_changeset(ui, repo, {})
        if len(nodes) == 1:
            # narrowed it down to a single revision
295 296 297 298
            if good:
                ui.write(_("The first good revision is:\n"))
            else:
                ui.write(_("The first bad revision is:\n"))
299
            displayer.show(repo[nodes[0]])
300 301
        else:
            # multiple possible revisions
302 303 304 305 306 307
            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"))
308
            for n in nodes:
309
                displayer.show(repo[n])
310
        displayer.close()
311 312 313 314 315 316 317 318 319 320 321

    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

322 323 324 325 326 327 328 329 330 331
    # 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
332
    elif extra or good + bad + skip + reset + bool(command) > 1:
333
        raise util.Abort(_('incompatible arguments'))
334 335 336 337 338 339 340

    if reset:
        p = repo.join("bisect.state")
        if os.path.exists(p):
            os.unlink(p)
        return

341 342 343 344
    state = hbisect.load_state(repo)

    if command:
        changesets = 1
345 346 347
        try:
            while changesets:
                # update state
348
                status = util.system(command)
349 350 351 352 353 354 355 356 357 358 359
                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"
360 361 362
                ctx = repo[rev or '.']
                state[transition].append(ctx.node())
                ui.status(_('Changeset %d:%s: %s\n') % (ctx, ctx, transition))
363 364 365 366 367 368 369 370
                check_state(state, interactive=False)
                # bisect
                nodes, changesets, good = hbisect.bisect(repo.changelog, state)
                # update to next check
                cmdutil.bail_if_changed(repo)
                hg.clean(repo, nodes[0], show_stats=False)
        finally:
            hbisect.save_state(repo, state)
371
        return print_result(nodes, good)
372 373 374

    # update state
    node = repo.lookup(rev or '.')
375 376 377 378 379 380 381 382
    if good or bad or skip:
        if good:
            state['good'].append(node)
        elif bad:
            state['bad'].append(node)
        elif skip:
            state['skip'].append(node)
        hbisect.save_state(repo, state)
383

384 385
    if not check_state(state):
        return
386 387

    # actually bisect
388
    nodes, changesets, good = hbisect.bisect(repo.changelog, state)
389
    if changesets == 0:
390
        print_result(nodes, good)
391 392 393
    else:
        assert len(nodes) == 1 # only a single node can be tested next
        node = nodes[0]
394 395 396 397 398
        # compute the approximate number of remaining tests
        tests, size = 0, 2
        while size <= changesets:
            tests, size = tests + 1, size * 2
        rev = repo.changelog.rev(node)
399 400
        ui.write(_("Testing changeset %d:%s "
                   "(%d changesets remaining, ~%d tests)\n")
401
                 % (rev, short(node), changesets, tests))
402 403 404 405
        if not noupdate:
            cmdutil.bail_if_changed(repo)
            return hg.clean(repo, node)

406
def branch(ui, repo, label=None, **opts):
407 408
    """set or show the current branch name

409 410 411 412 413
    With no argument, show the current branch name. With one argument,
    set the working directory branch name (the branch will not exist
    in the repository until the next commit). Standard practice
    recommends that primary development take place on the 'default'
    branch.
414

415 416
    Unless -f/--force is specified, branch will not let you set a
    branch name that already exists, even if it's inactive.
417

418 419 420
    Use -C/--clean to reset the working directory branch to that of
    the parent of the working directory, negating a previous branch
    change.
421

422 423
    Use the command 'hg update' to switch to an existing branch. Use
    'hg commit --close-branch' to mark this branch as closed.
424 425
    """

426 427 428 429 430
    if opts.get('clean'):
        label = repo[None].parents()[0].branch()
        repo.dirstate.setbranch(label)
        ui.status(_('reset working directory to branch %s\n') % label)
    elif label:
431 432
        utflabel = encoding.fromlocal(label)
        if not opts.get('force') and utflabel in repo.branchtags():
433
            if label not in [p.branch() for p in repo.parents()]:
434 435
                raise util.Abort(_('a branch of the same name already exists'
                                   ' (use --force to override)'))
436
        repo.dirstate.setbranch(utflabel)
437
        ui.status(_('marked working directory as branch %s\n') % label)
438
    else:
439
        ui.write("%s\n" % encoding.tolocal(repo.dirstate.branch()))
440

441
def branches(ui, repo, active=False, closed=False):
442 443
    """list repository named branches

444 445 446
    List the repository's named branches, indicating which ones are
    inactive. If -c/--closed is specified, also list branches which have
    been marked closed (see hg commit --close-branch).
447

448 449
    If -a/--active is specified, only show active branches. A branch
    is considered active if it contains repository heads.
450 451

    Use the command 'hg update' to switch to an existing branch.
452
    """
453

454
    hexfunc = ui.debugflag and hex or short
455
    activebranches = [repo[n].branch() for n in repo.heads()]
456 457 458 459 460
    def testactive(tag, node):
        realhead = tag in activebranches
        open = node in repo.branchheads(tag, closed=False)
        return realhead and open
    branches = sorted([(testactive(tag, node), repo.changelog.rev(node), tag)
461 462
                          for tag, node in repo.branchtags().items()],
                      reverse=True)
463 464 465

    for isactive, node, tag in branches:
        if (not active) or isactive:
466
            encodedtag = encoding.tolocal(tag)
467
            if ui.quiet:
468
                ui.write("%s\n" % encodedtag)
469
            else:
470 471 472 473
                hn = repo.lookup(node)
                if isactive:
                    notice = ''
                elif hn not in repo.branchheads(tag, closed=False):
474 475
                    if not closed:
                        continue
476
                    notice = _(' (closed)')
477
                else:
478
                    notice = _(' (inactive)')
479 480
                rev = str(node).rjust(31 - encoding.colwidth(encodedtag))
                data = encodedtag, rev, hexfunc(hn), notice
481
                ui.write("%s %s:%s%s\n" % data)
482

483
def bundle(ui, repo, fname, dest=None, **opts):
484 485
    """create a changegroup file

486 487
    Generate a compressed changegroup file collecting changesets not
    known to be in another repository.
488

timeless's avatar
timeless committed
489 490
    If you omit the destination repository, then hg assumes the
    destination will have all the nodes you specify with --base
491 492
    parameters. To create a bundle containing all changesets, use
    -a/--all (or --base null).
493

494 495 496
    You can change compression method with the -t/--type option.
    The available compression methods are: none, bzip2, and
    gzip (by default, bundles are compressed using bzip2).
497

498 499 500 501
    The bundle file can then be transferred using conventional means
    and applied to another repository with the unbundle or pull
    command. This is useful when direct push and pull are not
    available or when exporting an entire repository is undesirable.
502

503 504
    Applying bundles preserves all changeset contents including
    permissions, copy/rename information, and revision history.
505
    """
506 507 508
    revs = opts.get('rev') or None
    if revs:
        revs = [repo.lookup(rev) for rev in revs]
509 510 511 512
    if opts.get('all'):
        base = ['null']
    else:
        base = opts.get('base')
513 514
    if base:
        if dest:
515
            raise util.Abort(_("--base is incompatible with specifying "
516
                               "a destination"))
517 518 519
        base = [repo.lookup(rev) for rev in base]
        # create the right base
        # XXX: nodesbetween / changegroup* should be "fixed" instead
520
        o = []
521
        has = set((nullid,))
522
        for n in base:
Matt Mackall's avatar
Matt Mackall committed
523
            has.update(repo.changelog.reachable(n))
524
        if revs:
525
            visit = list(revs)
526
        else:
527
            visit = repo.changelog.heads()
Matt Mackall's avatar
Matt Mackall committed
528
        seen = {}
529 530
        while visit:
            n = visit.pop(0)
Matt Mackall's avatar
Matt Mackall committed
531
            parents = [p for p in repo.changelog.parents(n) if p not in has]
532 533 534
            if len(parents) == 0:
                o.insert(0, n)
            else:
535 536
                for p in parents:
                    if p not in seen:
Matt Mackall's avatar
Matt Mackall committed
537
                        seen[p] = 1
538
                        visit.append(p)
539
    else:
540
        dest = ui.expandpath(dest or 'default-push', dest or 'default')
541
        dest, branches = hg.parseurl(dest, opts.get('branch'))
Matt Mackall's avatar
Matt Mackall committed
542
        other = hg.repository(cmdutil.remoteui(repo, opts), dest)
543
        revs, checkout = hg.addbranchrevs(repo, other, branches, revs)
544
        o = repo.findoutgoing(other, force=opts.get('force'))
545 546 547 548 549

    if revs:
        cg = repo.changegroupsubset(o, revs, 'bundle')
    else:
        cg = repo.changegroup(o, 'bundle')
550 551 552 553 554 555 556 557

    bundletype = opts.get('type', 'bzip2').lower()
    btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
    bundletype = btypes.get(bundletype)
    if bundletype not in changegroup.bundletypes:
        raise util.Abort(_('unknown bundle type specified with --type'))

    changegroup.writebundle(cg, fname, bundletype)
558

559
def cat(ui, repo, file1, *pats, **opts):
560
    """output the current or given revision of files
561

562 563 564
    Print the specified files as they were at the given revision. If
    no revision is given, the parent of the working directory is used,
    or tip if no revision is checked out.
565

566 567
    Output may be to a file, in which case the name of the file is
    given using a format string. The formatting rules are the same as
568
    for the export command, with the following additions:
569

570 571 572
    :``%s``: basename of file being printed
    :``%d``: dirname of file being printed, or '.' if in repository root
    :``%p``: root-relative path name of file being printed
573
    """
574
    ctx = repo[opts.get('rev')]
Matt Mackall's avatar
Matt Mackall committed
575
    err = 1
576
    m = cmdutil.match(repo, (file1,) + pats, opts)
Matt Mackall's avatar
Matt Mackall committed
577
    for abs in ctx.walk(m):
578
        fp = cmdutil.make_file(repo, opts.get('output'), ctx.node(), pathname=abs)
Matt Mackall's avatar
Matt Mackall committed
579
        data = ctx[abs].data()
580
        if opts.get('decode'):
581 582
            data = repo.wwritedata(abs, data)
        fp.write(data)
Matt Mackall's avatar
Matt Mackall committed
583 584
        err = 0
    return err
mpm@selenic.com's avatar
mpm@selenic.com committed
585

586
def clone(ui, source, dest=None, **opts):
587 588 589 590
    """make a copy of an existing repository

    Create a copy of an existing repository in a new directory.

591 592
    If no destination directory name is specified, it defaults to the
    basename of the source.
593

594 595
    The location of the source is added to the new repository's
    .hg/hgrc file, as the default to be used for future pulls.
596

597 598
    See 'hg help urls' for valid source format details.

599
    It is possible to specify an ``ssh://`` URL as the destination, but no
600
    .hg/hgrc and working directory will be created on the remote side.
601
    Please see 'hg help urls' for important details about ``ssh://`` URLs.
602

603 604 605
    If the -U/--noupdate option is specified, the new clone will contain
    only a repository (.hg) and no working copy (the working copy parent
    will be the null changeset). Otherwise, clone will initially check
606
    out (in order of precedence):
607

608 609
    a) the changeset, tag or branch specified with -u/--updaterev
    b) the changeset, tag or branch given with the first -r/--rev
610 611 612
    c) the branch given with the first -b/--branch
    d) the branch given with the url#branch source syntax
    e) the head of the default branch
613 614 615 616 617 618 619 620

    Use 'hg clone -u . src dst' to checkout the source repository's
    parent changeset (applicable for local source repositories only).

    A set of changesets (tags, or branch names) to pull may be specified
    by listing each changeset (tag, or branch name) with -r/--rev.
    If -r/--rev is used, the cloned repository will contain only a subset
    of the changesets of the source repository. Only the set of changesets
Wagner Bruna's avatar
Wagner Bruna committed
621 622
    defined by all -r/--rev options (including all their ancestors)
    will be pulled into the destination repository.
623 624 625 626 627 628
    No subsequent changesets (including subsequent tags) will be present
    in the destination.

    Using -r/--rev (or 'clone src#rev dest') implies --pull, even for
    local source repositories.

629 630 631 632 633 634
    For efficiency, hardlinks are used for cloning whenever the source
    and destination are on the same filesystem (note this applies only
    to the repository data, not to the checked out files). Some
    filesystems, such as AFS, implement hardlinking incorrectly, but
    do not report errors. In these cases, use the --pull option to
    avoid hardlinking.
635

636 637
    In some cases, you can clone repositories and checked out files
    using full hardlinks with ::
638 639 640

      $ cp -al REPO REPOCLONE

641 642 643 644 645 646
    This is the fastest way to clone, but it is not always safe. The
    operation is not atomic (making sure REPO is not modified during
    the operation is up to you) and you have to make sure your editor
    breaks hardlinks (Emacs and most Linux Kernel tools do so). Also,
    this is not compatible with certain extensions that place their
    metadata under the .hg directory, such as mq.
647
    """
648 649 650
    if opts.get('noupdate') and opts.get('updaterev'):
        raise util.Abort(_("cannot specify both --noupdate and --updaterev"))

Matt Mackall's avatar
Matt Mackall committed
651
    hg.clone(cmdutil.remoteui(ui, opts), source, dest,
652 653 654
             pull=opts.get('pull'),
             stream=opts.get('uncompressed'),
             rev=opts.get('rev'),
655 656
             update=opts.get('updaterev') or not opts.get('noupdate'),
             branch=opts.get('branch'))
mpm@selenic.com's avatar
mpm@selenic.com committed
657

658
def commit(ui, repo, *pats, **opts):
659 660
    """commit the specified files or all outstanding changes

661
    Commit changes to the given files into the repository. Unlike a
662 663
    centralized RCS, this operation is a local operation. See hg push
    for a way to actively distribute your changes.
664

665 666
    If a list of files is omitted, all changes reported by "hg status"
    will be committed.
667

668 669
    If you are committing the result of a merge, do not provide any
    filenames or -I/-X filters.
670

671 672
    If no commit message is specified, the configured editor is
    started to prompt you for a message.
673 674

    See 'hg help dates' for a list of formats valid for -d/--date.
675
    """
676 677 678
    extra = {}
    if opts.get('close_branch'):
        extra['close'] = 1
679 680 681 682
    e = cmdutil.commiteditor
    if opts.get('force_editor'):
        e = cmdutil.commitforceeditor

683
    def commitfunc(ui, repo, message, match, opts):
684 685
        return repo.commit(message, opts.get('user'), opts.get('date'), match,
                           editor=e, extra=extra)
686

687 688
    node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
    if not node:
689
        ui.status(_("nothing changed\n"))
690 691 692 693 694 695
        return
    cl = repo.changelog
    rev = cl.rev(node)
    parents = cl.parentrevs(rev)
    if rev - 1 in parents:
        # one of the parents was the old tip
696 697 698 699
        pass
    elif (parents == (nullrev, nullrev) or
          len(cl.heads(cl.node(parents[0]))) > 1 and
          (parents[1] == nullrev or len(cl.heads(cl.node(parents[1]))) > 1)):
700
        ui.status(_('created new head\n'))
Bryan O'Sullivan's avatar
Bryan O'Sullivan committed
701

702
    if ui.debugflag:
703
        ui.write(_('committed changeset %d:%s\n') % (rev, hex(node)))
704
    elif ui.verbose:
705
        ui.write(_('committed changeset %d:%s\n') % (rev, short(node)))
706

Bryan O'Sullivan's avatar
Bryan O'Sullivan committed
707
def copy(ui, repo, *pats, **opts):
708 709
    """mark files as copied for the next commit

710 711 712
    Mark dest as having copies of source files. If dest is a
    directory, copies are put in that directory. If dest is a file,
    the source must be a single file.
713

714 715 716
    By default, this command copies the contents of files as they
    exist in the working directory. If invoked with -A/--after, the
    operation is recorded, but no copying is performed.
717

718 719
    This command takes effect with the next commit. To undo a copy
    before that, see hg revert.
720
    """
Matt Mackall's avatar
Matt Mackall committed
721
    wlock = repo.wlock(False)
722
    try:
Matt Mackall's avatar
Matt Mackall committed
723
        return cmdutil.copy(ui, repo, pats, opts)
724
    finally:
725
        wlock.release()
mpm@selenic.com's avatar
mpm@selenic.com committed
726

727
def debugancestor(ui, repo, *args):
mpm@selenic.com's avatar
mpm@selenic.com committed
728
    """find the ancestor revision of two revisions in a given index"""
729 730
    if len(args) == 3:
        index, rev1, rev2 = args
731
        r = revlog.revlog(util.opener(os.getcwd(), audit=False), index)
732
        lookup = r.lookup
733
    elif len(args) == 2:
734 735 736
        if not repo:
            raise util.Abort(_("There is no Mercurial repository here "
                               "(.hg not found)"))
737
        rev1, rev2 = args
738
        r = repo.changelog
739
        lookup = repo.lookup
740 741
    else:
        raise util.Abort(_('either two or three arguments required'))
742
    a = r.ancestor(lookup(rev1), lookup(rev2))
mpm@selenic.com's avatar
mpm@selenic.com committed
743 744
    ui.write("%d:%s\n" % (r.rev(a), hex(a)))

745
def debugcommands(ui, cmd='', *args):
746
    for cmd, vals in sorted(table.iteritems()):
747 748 749 750
        cmd = cmd.split('|')[0].strip('^')
        opts = ', '.join([i[1] for i in vals[1]])
        ui.write('%s: %s\n' % <