commands.py 144 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
import archival, changegroup, cmdutil, sshserver, hbisect, hgweb, hgweb.server
15
import merge as mergemod
16
import minirst
17

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

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

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

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

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

    .. container:: verbose

       An example showing how new (unknown) files are added
Martin Geisler's avatar
Martin Geisler committed
34
       automatically by :hg:`add`::
35 36 37 38 39 40 41 42

         $ ls
         foo.c
         $ hg status
         ? foo.c
         $ hg add
         adding foo.c
         $ hg status
43
         A foo.c
44 45
    """

46
    bad = []
47
    names = []
48
    m = cmdutil.match(repo, pats, opts)
49
    oldbad = m.bad
50
    m.bad = lambda x, y: bad.append(x) or oldbad(x, y)
51 52 53 54 55 56 57

    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))
58
    if not opts.get('dry_run'):
59 60
        bad += [f for f in repo.add(names) if f in m.files()]
    return bad and 1 or 0
61

62
def addremove(ui, repo, *pats, **opts):
63
    """add all new files, delete all missing files
64

65 66
    Add all new files and remove all missing files from the
    repository.
67

68 69 70
    New files are ignored if they match any of the patterns in
    .hgignore. As with add, these changes take effect at the next
    commit.
71

72 73 74 75 76 77
    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.
78
    """
79 80 81 82
    try:
        sim = float(opts.get('similarity') or 0)
    except ValueError:
        raise util.Abort(_('similarity must be a number'))
83 84
    if sim < 0 or sim > 100:
        raise util.Abort(_('similarity must be between 0 and 100'))
85
    return cmdutil.addremove(repo, pats, opts, similarity=sim / 100.0)
86

87
def annotate(ui, repo, *pats, **opts):
88
    """show changeset information by line for each file
89

90 91
    List changes in files, showing the revision id responsible for
    each line
92

93 94
    This command is useful for discovering when a change was made and
    by whom.
95

96 97 98 99
    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.
100
    """
101 102 103 104 105
    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
        opts['file'] = 1

106 107
    datefunc = ui.quiet and util.shortdate or util.datestr
    getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
108

109
    if not pats:
110
        raise util.Abort(_('at least one filename or pattern is required'))
111

112 113 114 115
    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),
116
             ('file', lambda x: x[0].path()),
117 118
            ]

119
    if (not opts.get('user') and not opts.get('changeset')
120
        and not opts.get('date') and not opts.get('file')):
121
        opts['number'] = 1
122

123
    linenumber = opts.get('line_number') is not None
124
    if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
125 126 127 128 129 130 131
        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])

132
    ctx = repo[opts.get('rev')]
133
    m = cmdutil.match(repo, pats, opts)
134
    follow = not opts.get('no_follow')
Matt Mackall's avatar
Matt Mackall committed
135 136
    for abs in ctx.walk(m):
        fctx = ctx[abs]
137
        if not opts.get('text') and util.binary(fctx.data()):
138
            ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
139 140
            continue

141
        lines = fctx.annotate(follow=follow, linenumber=linenumber)
142 143
        pieces = []

144 145 146
        for f in funcmap:
            l = [f(n) for n, dummy in lines]
            if l:
147 148
                ml = max(map(len, l))
                pieces.append(["%*s" % (ml, x) for x in l])
149

mpm@selenic.com's avatar
mpm@selenic.com committed
150 151 152
        if pieces:
            for p, l in zip(zip(*pieces), lines):
                ui.write("%s: %s" % (" ".join(p), l[1]))
153

154
def archive(ui, repo, dest, **opts):
155
    '''create an unversioned archive of a repository revision
156

157 158
    By default, the revision used is the parent of the working
    directory; use -r/--rev to specify a different revision.
159

160 161 162 163
    The archive type is automatically detected based on file
    extension (or override using -t/--type).

    Valid types are:
164

165 166 167 168 169 170
    :``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
171

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

175 176 177 178
    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.
179 180
    '''

181
    ctx = repo[opts.get('rev')]
182
    if not ctx:
183
        raise util.Abort(_('no working directory: please specify a revision'))
184
    node = ctx.node()
Vadim Gelfer's avatar
Vadim Gelfer committed
185
    dest = cmdutil.make_filename(repo, dest, node)
186 187
    if os.path.realpath(dest) == repo.root:
        raise util.Abort(_('repository root cannot be destination'))
188 189 190 191 192 193 194 195 196 197

    def guess_type():
        exttypes = {
            'tar': ['.tar'],
            'tbz2': ['.tbz2', '.tar.bz2'],
            'tgz': ['.tgz', '.tar.gz'],
            'zip': ['.zip'],
        }

        for type, extensions in exttypes.items():
198
            if util.any(dest.endswith(ext) for ext in extensions):
199 200 201 202
                return type
        return None

    kind = opts.get('type') or guess_type() or 'files'
203
    prefix = opts.get('prefix')
204

205 206 207 208
    if dest == '-':
        if kind == 'files':
            raise util.Abort(_('cannot archive plain files to stdout'))
        dest = sys.stdout
209 210
        if not prefix:
            prefix = os.path.basename(repo.root) + '-%h'
211

Vadim Gelfer's avatar
Vadim Gelfer committed
212
    prefix = cmdutil.make_filename(repo, prefix, node)
213
    matchfn = cmdutil.match(repo, [], opts)
214
    archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
215
                     matchfn, prefix)
216

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

220 221
    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
222

223 224 225
    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
226

227 228 229 230
    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.
231

Martin Geisler's avatar
Martin Geisler committed
232
    See :hg:`help dates` for a list of formats valid for -d/--date.
233
    '''
Daniel Holth's avatar
Daniel Holth committed
234 235 236 237 238
    if rev and node:
        raise util.Abort(_("please specify just one revision"))

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

240 241 242
    if not rev:
        raise util.Abort(_("please specify a revision to backout"))

243 244 245 246
    date = opts.get('date')
    if date:
        opts['date'] = util.parsedate(date)

247
    cmdutil.bail_if_changed(repo)
Vadim Gelfer's avatar
Vadim Gelfer committed
248
    node = repo.lookup(rev)
249

250
    op1, op2 = repo.dirstate.parents()
251 252
    a = repo.changelog.ancestor(op1, node)
    if a != node:
253
        raise util.Abort(_('cannot backout change on a different branch'))
254

255 256
    p1, p2 = repo.changelog.parents(node)
    if p1 == nullid:
257
        raise util.Abort(_('cannot backout a change with no parents'))
Vadim Gelfer's avatar
Vadim Gelfer committed
258
    if p2 != nullid:
259
        if not opts.get('parent'):
260
            raise util.Abort(_('cannot backout a merge changeset without '
261 262 263
                               '--parent'))
        p = repo.lookup(opts['parent'])
        if p not in (p1, p2):
264
            raise util.Abort(_('%s is not a parent of %s') %
265
                             (short(p), short(node)))
266 267
        parent = p
    else:
268
        if opts.get('parent'):
269 270
            raise util.Abort(_('cannot use --parent on non-merge changeset'))
        parent = p1
271

272 273
    # the backout should appear on the same branch
    branch = repo.dirstate.branch()
274
    hg.clean(repo, node, show_stats=False)
275
    repo.dirstate.setbranch(branch)
Vadim Gelfer's avatar
Vadim Gelfer committed
276
    revert_opts = opts.copy()
277
    revert_opts['date'] = None
278
    revert_opts['all'] = True
Vadim Gelfer's avatar
Vadim Gelfer committed
279
    revert_opts['rev'] = hex(parent)
280
    revert_opts['no_backup'] = None
Vadim Gelfer's avatar
Vadim Gelfer committed
281 282 283
    revert(ui, repo, **revert_opts)
    commit_opts = opts.copy()
    commit_opts['addremove'] = False
284
    if not commit_opts['message'] and not commit_opts['logfile']:
285
        # we don't translate commit messages
286
        commit_opts['message'] = "Backed out changeset %s" % short(node)
287
        commit_opts['force_editor'] = True
Vadim Gelfer's avatar
Vadim Gelfer committed
288 289 290 291 292
    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)))
293
    if op1 != node:
294
        hg.clean(repo, op1, show_stats=False)
295
        if opts.get('merge'):
296 297
            ui.status(_('merging with changeset %s\n')
                      % nice(repo.changelog.tip()))
298
            hg.merge(repo, hex(repo.changelog.tip()))
299 300 301
        else:
            ui.status(_('the backout changeset is a new head - '
                        'do not forget to merge\n'))
302 303
            ui.status(_('(use "backout --merge" '
                        'if you want to auto-merge)\n'))
Vadim Gelfer's avatar
Vadim Gelfer committed
304

305
def bisect(ui, repo, rev=None, extra=None, command=None,
306 307 308
               reset=None, good=None, bad=None, skip=None, noupdate=None):
    """subdivision search of changesets

309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
    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.
326
    """
327 328 329 330
    def print_result(nodes, good):
        displayer = cmdutil.show_changeset(ui, repo, {})
        if len(nodes) == 1:
            # narrowed it down to a single revision
331 332 333 334
            if good:
                ui.write(_("The first good revision is:\n"))
            else:
                ui.write(_("The first bad revision is:\n"))
335
            displayer.show(repo[nodes[0]])
336 337
        else:
            # multiple possible revisions
338 339 340 341 342 343
            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"))
344
            for n in nodes:
345
                displayer.show(repo[n])
346
        displayer.close()
347 348 349 350 351 352 353 354 355 356 357

    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

358 359 360 361 362 363 364 365 366 367
    # 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
368
    elif extra or good + bad + skip + reset + bool(command) > 1:
369
        raise util.Abort(_('incompatible arguments'))
370 371 372 373 374 375 376

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

377 378 379 380
    state = hbisect.load_state(repo)

    if command:
        changesets = 1
381 382 383
        try:
            while changesets:
                # update state
384
                status = util.system(command)
385 386 387 388 389 390 391 392 393 394 395
                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"
396 397 398
                ctx = repo[rev or '.']
                state[transition].append(ctx.node())
                ui.status(_('Changeset %d:%s: %s\n') % (ctx, ctx, transition))
399 400 401 402 403 404 405 406
                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)
407
        return print_result(nodes, good)
408 409 410

    # update state
    node = repo.lookup(rev or '.')
411 412 413 414 415 416 417 418
    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)
419

420 421
    if not check_state(state):
        return
422 423

    # actually bisect
424
    nodes, changesets, good = hbisect.bisect(repo.changelog, state)
425
    if changesets == 0:
426
        print_result(nodes, good)
427 428 429
    else:
        assert len(nodes) == 1 # only a single node can be tested next
        node = nodes[0]
430 431 432 433 434
        # 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)
435 436
        ui.write(_("Testing changeset %d:%s "
                   "(%d changesets remaining, ~%d tests)\n")
437
                 % (rev, short(node), changesets, tests))
438 439 440 441
        if not noupdate:
            cmdutil.bail_if_changed(repo)
            return hg.clean(repo, node)

442
def branch(ui, repo, label=None, **opts):
443 444
    """set or show the current branch name

445 446 447 448 449
    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.
450

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

454 455 456
    Use -C/--clean to reset the working directory branch to that of
    the parent of the working directory, negating a previous branch
    change.
457

Martin Geisler's avatar
Martin Geisler committed
458 459
    Use the command :hg:`update` to switch to an existing branch. Use
    :hg:`commit --close-branch` to mark this branch as closed.
460 461
    """

462 463 464 465 466
    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:
467 468
        utflabel = encoding.fromlocal(label)
        if not opts.get('force') and utflabel in repo.branchtags():
469
            if label not in [p.branch() for p in repo.parents()]:
470
                raise util.Abort(_('a branch of the same name already exists'
471
                                   " (use 'hg update' to switch to it)"))
472
        repo.dirstate.setbranch(utflabel)
473
        ui.status(_('marked working directory as branch %s\n') % label)
474
    else:
475
        ui.write("%s\n" % encoding.tolocal(repo.dirstate.branch()))
476

477
def branches(ui, repo, active=False, closed=False):
478 479
    """list repository named branches

480 481 482
    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).
483

484 485
    If -a/--active is specified, only show active branches. A branch
    is considered active if it contains repository heads.
486

Martin Geisler's avatar
Martin Geisler committed
487
    Use the command :hg:`update` to switch to an existing branch.
488
    """
489

490
    hexfunc = ui.debugflag and hex or short
491
    activebranches = [repo[n].branch() for n in repo.heads()]
492 493 494 495 496
    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)
497 498
                          for tag, node in repo.branchtags().items()],
                      reverse=True)
499 500 501

    for isactive, node, tag in branches:
        if (not active) or isactive:
502
            encodedtag = encoding.tolocal(tag)
503
            if ui.quiet:
504
                ui.write("%s\n" % encodedtag)
505
            else:
506 507 508 509
                hn = repo.lookup(node)
                if isactive:
                    notice = ''
                elif hn not in repo.branchheads(tag, closed=False):
510 511
                    if not closed:
                        continue
512
                    notice = _(' (closed)')
513
                else:
514
                    notice = _(' (inactive)')
515 516
                rev = str(node).rjust(31 - encoding.colwidth(encodedtag))
                data = encodedtag, rev, hexfunc(hn), notice
517
                ui.write("%s %s:%s%s\n" % data)
518

519
def bundle(ui, repo, fname, dest=None, **opts):
520 521
    """create a changegroup file

522 523
    Generate a compressed changegroup file collecting changesets not
    known to be in another repository.
524

timeless's avatar
timeless committed
525 526
    If you omit the destination repository, then hg assumes the
    destination will have all the nodes you specify with --base
527 528
    parameters. To create a bundle containing all changesets, use
    -a/--all (or --base null).
529

530 531 532
    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).
533

534 535 536 537
    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.
538

539 540
    Applying bundles preserves all changeset contents including
    permissions, copy/rename information, and revision history.
541
    """
542 543 544
    revs = opts.get('rev') or None
    if revs:
        revs = [repo.lookup(rev) for rev in revs]
545 546 547 548
    if opts.get('all'):
        base = ['null']
    else:
        base = opts.get('base')
549 550
    if base:
        if dest:
551
            raise util.Abort(_("--base is incompatible with specifying "
552
                               "a destination"))
553 554 555
        base = [repo.lookup(rev) for rev in base]
        # create the right base
        # XXX: nodesbetween / changegroup* should be "fixed" instead
556
        o = []
557
        has = set((nullid,))
558
        for n in base:
Matt Mackall's avatar
Matt Mackall committed
559
            has.update(repo.changelog.reachable(n))
560
        if revs:
561
            visit = list(revs)
562
            has.difference_update(revs)
563
        else:
564
            visit = repo.changelog.heads()
Matt Mackall's avatar
Matt Mackall committed
565
        seen = {}
566 567
        while visit:
            n = visit.pop(0)
Matt Mackall's avatar
Matt Mackall committed
568
            parents = [p for p in repo.changelog.parents(n) if p not in has]
569
            if len(parents) == 0:
570 571
                if n not in has:
                    o.append(n)
572
            else:
573 574
                for p in parents:
                    if p not in seen:
Matt Mackall's avatar
Matt Mackall committed
575
                        seen[p] = 1
576
                        visit.append(p)
577
    else:
578
        dest = ui.expandpath(dest or 'default-push', dest or 'default')
579
        dest, branches = hg.parseurl(dest, opts.get('branch'))
Matt Mackall's avatar
Matt Mackall committed
580
        other = hg.repository(cmdutil.remoteui(repo, opts), dest)
581
        revs, checkout = hg.addbranchrevs(repo, other, branches, revs)
582
        o = repo.findoutgoing(other, force=opts.get('force'))
583

584 585 586 587
    if not o:
        ui.status(_("no changes found\n"))
        return

588 589 590 591
    if revs:
        cg = repo.changegroupsubset(o, revs, 'bundle')
    else:
        cg = repo.changegroup(o, 'bundle')
592 593 594 595 596 597 598 599

    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)
600

601
def cat(ui, repo, file1, *pats, **opts):
602
    """output the current or given revision of files
603

604 605 606
    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.
607

608 609
    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
610
    for the export command, with the following additions:
611

612 613 614
    :``%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
615
    """
616
    ctx = repo[opts.get('rev')]
Matt Mackall's avatar
Matt Mackall committed
617
    err = 1
618
    m = cmdutil.match(repo, (file1,) + pats, opts)
Matt Mackall's avatar
Matt Mackall committed
619
    for abs in ctx.walk(m):
620
        fp = cmdutil.make_file(repo, opts.get('output'), ctx.node(), pathname=abs)
Matt Mackall's avatar
Matt Mackall committed
621
        data = ctx[abs].data()
622
        if opts.get('decode'):
623 624
            data = repo.wwritedata(abs, data)
        fp.write(data)
Matt Mackall's avatar
Matt Mackall committed
625 626
        err = 0
    return err
mpm@selenic.com's avatar
mpm@selenic.com committed
627

628
def clone(ui, source, dest=None, **opts):
629 630 631 632
    """make a copy of an existing repository

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

633 634
    If no destination directory name is specified, it defaults to the
    basename of the source.
635

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

Martin Geisler's avatar
Martin Geisler committed
639
    See :hg:`help urls` for valid source format details.
640

641
    It is possible to specify an ``ssh://`` URL as the destination, but no
642
    .hg/hgrc and working directory will be created on the remote side.
Martin Geisler's avatar
Martin Geisler committed
643
    Please see :hg:`help urls` for important details about ``ssh://`` URLs.
644

645 646 647 648
    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
649 650
    defined by all -r/--rev options (including all their ancestors)
    will be pulled into the destination repository.
651 652 653 654 655 656
    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.

657 658
    For efficiency, hardlinks are used for cloning whenever the source
    and destination are on the same filesystem (note this applies only
659
    to the repository data, not to the working directory). Some
660 661 662
    filesystems, such as AFS, implement hardlinking incorrectly, but
    do not report errors. In these cases, use the --pull option to
    avoid hardlinking.
663

664
    In some cases, you can clone repositories and the working directory
665
    using full hardlinks with ::
666 667 668

      $ cp -al REPO REPOCLONE

669 670 671 672 673 674
    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.
675 676 677 678

    Mercurial will update the working directory to the first applicable
    revision from this list:

679 680 681 682 683 684 685 686 687 688
    a) null if -U or the source repository has no changesets
    b) if -u . and the source repository is local, the first parent of
       the source repository's working directory
    c) the changeset specified with -u (if a branch name, this means the
       latest head of that branch)
    d) the changeset specified with -r
    e) the tipmost head specified with -b
    f) the tipmost head specified with the url#branch source syntax
    g) the tipmost head of the default branch
    h) tip
689
    """
690 691 692
    if opts.get('noupdate') and opts.get('updaterev'):
        raise util.Abort(_("cannot specify both --noupdate and --updaterev"))

Matt Mackall's avatar
Matt Mackall committed
693
    hg.clone(cmdutil.remoteui(ui, opts), source, dest,
694 695 696
             pull=opts.get('pull'),
             stream=opts.get('uncompressed'),
             rev=opts.get('rev'),
697 698
             update=opts.get('updaterev') or not opts.get('noupdate'),
             branch=opts.get('branch'))
mpm@selenic.com's avatar
mpm@selenic.com committed
699

700
def commit(ui, repo, *pats, **opts):
701 702
    """commit the specified files or all outstanding changes

703
    Commit changes to the given files into the repository. Unlike a
704 705
    centralized RCS, this operation is a local operation. See hg push
    for a way to actively distribute your changes.
706

Martin Geisler's avatar
Martin Geisler committed
707
    If a list of files is omitted, all changes reported by :hg:`status`
708
    will be committed.
709

710 711
    If you are committing the result of a merge, do not provide any
    filenames or -I/-X filters.
712

713 714
    If no commit message is specified, the configured editor is
    started to prompt you for a message.
715

Martin Geisler's avatar
Martin Geisler committed
716
    See :hg:`help dates` for a list of formats valid for -d/--date.
717
    """
718 719
    extra = {}
    if opts.get('close_branch'):
720 721 722 723
        if repo['.'].node() not in repo.branchheads():
            # The topo heads set is included in the branch heads set of the
            # current branch, so it's sufficient to test branchheads
            raise util.Abort(_('can only close branch heads'))
724
        extra['close'] = 1
725 726 727 728
    e = cmdutil.commiteditor
    if opts.get('force_editor'):
        e = cmdutil.commitforceeditor

729
    def commitfunc(ui, repo, message, match, opts):
730 731
        return repo.commit(message, opts.get('user'), opts.get('date'), match,
                           editor=e, extra=extra)
732

733 734 735
    branch = repo[None].branch()
    bheads = repo.branchheads(branch)

736 737
    node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
    if not node:
738
        ui.status(_("nothing changed\n"))
739
        return
740 741 742 743 744

    ctx = repo[node]
    parents = ctx.parents()

    if bheads and [x for x in parents if x.node() not in bheads]:
745
        ui.status(_('created new head\n'))
Bryan O'Sullivan's avatar
Bryan O'Sullivan committed
746

747 748
    if not opts.get('close_branch'):
        for r in parents:
749
            if r.extra().get('close'):
750 751
                ui.status(_('reopening closed branch head %d\n') % r)

752
    if ui.debugflag:
753
        ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
754
    elif ui.verbose:
755
        ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
756

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

760 761 762
    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.