commands.py 114 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 6 7
#
# This software may be used and distributed according to the terms
# of the GNU General Public License, incorporated herein by reference.

8
from node import *
Matt Mackall's avatar
Matt Mackall committed
9
from i18n import _
10
import os, re, sys, urllib
11
import hg, util, revlog, bundlerepo, extensions
12
import difflib, patch, time, help, mdiff, tempfile
13
import errno, version, socket
14
import archival, changegroup, cmdutil, hgweb.server, sshserver, hbisect
15

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

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

    Schedule files to be version controlled and added to the repository.

23 24
    The files will be added to the repository at the next commit. To
    undo an add before that, see hg revert.
25

26
    If no names are given, add all files in the repository.
27 28
    """

29 30
    rejected = None
    exacts = {}
31
    names = []
32 33
    for src, abs, rel, exact in cmdutil.walk(repo, pats, opts,
                                             badmatch=util.always):
34
        if exact:
35 36
            if ui.verbose:
                ui.status(_('adding %s\n') % rel)
37
            names.append(abs)
38
            exacts[abs] = 1
39
        elif abs not in repo.dirstate:
40
            ui.status(_('adding %s\n') % rel)
41
            names.append(abs)
42
    if not opts.get('dry_run'):
43 44 45
        rejected = repo.add(names)
        rejected = [p for p in rejected if p in exacts]
    return rejected and 1 or 0
46

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

    Add all new files and remove all missing files from the repository.

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

    Use the -s option to detect renamed files.  With a parameter > 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.
60
    """
61 62 63 64
    try:
        sim = float(opts.get('similarity') or 0)
    except ValueError:
        raise util.Abort(_('similarity must be a number'))
65 66 67
    if sim < 0 or sim > 100:
        raise util.Abort(_('similarity must be between 0 and 100'))
    return cmdutil.addremove(repo, pats, opts, similarity=sim/100.)
68

69
def annotate(ui, repo, *pats, **opts):
70 71 72 73 74 75 76 77 78 79 80
    """show changeset information per file line

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

    This command is useful to discover who did a change or when a change took
    place.

    Without the -a option, annotate will avoid processing files it
    detects as binary. With -a, annotate will generate an annotation
    anyway, probably with undesirable results.
    """
81 82
    datefunc = ui.quiet and util.shortdate or util.datestr
    getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
83

84
    if not pats:
85
        raise util.Abort(_('at least one file name or pattern required'))
86

87 88 89 90 91 92 93
    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),
             ('follow', lambda x: x[0].path()),
            ]

94 95
    if (not opts['user'] and not opts['changeset'] and not opts['date']
        and not opts['follow']):
96
        opts['number'] = 1
97

98 99 100 101 102 103 104 105 106
    linenumber = opts.get('line_number') is not None
    if (linenumber and (not opts['changeset']) and (not opts['number'])):
        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])

Brendan Cully's avatar
Brendan Cully committed
107
    ctx = repo.changectx(opts['rev'])
108

109 110
    for src, abs, rel, exact in cmdutil.walk(repo, pats, opts,
                                             node=ctx.node()):
111 112
        fctx = ctx.filectx(abs)
        if not opts['text'] and util.binary(fctx.data()):
113
            ui.write(_("%s: binary file\n") % ((pats and rel) or abs))
114 115
            continue

116 117
        lines = fctx.annotate(follow=opts.get('follow'),
                              linenumber=linenumber)
118 119
        pieces = []

120 121 122 123 124
        for f in funcmap:
            l = [f(n) for n, dummy in lines]
            if l:
                m = max(map(len, l))
                pieces.append(["%*s" % (m, x) for x in l])
125

mpm@selenic.com's avatar
mpm@selenic.com committed
126 127 128
        if pieces:
            for p, l in zip(zip(*pieces), lines):
                ui.write("%s: %s" % (" ".join(p), l[1]))
129

130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
def archive(ui, repo, dest, **opts):
    '''create unversioned archive of a repository revision

    By default, the revision used is the parent of the working
    directory; use "-r" to specify a different revision.

    To specify the type of archive to create, use "-t".  Valid
    types are:

    "files" (default): a directory full of files
    "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

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

    Each member added to an archive file has a directory prefix
    prepended.  Use "-p" to specify a format string for the prefix.
    The default is the basename of the archive, with suffixes removed.
    '''

154 155 156 157
    ctx = repo.changectx(opts['rev'])
    if not ctx:
        raise util.Abort(_('repository has no revisions'))
    node = ctx.node()
Vadim Gelfer's avatar
Vadim Gelfer committed
158
    dest = cmdutil.make_filename(repo, dest, node)
159 160
    if os.path.realpath(dest) == repo.root:
        raise util.Abort(_('repository root cannot be destination'))
161
    dummy, matchfn, dummy = cmdutil.matchpats(repo, [], opts)
162 163 164 165 166 167 168
    kind = opts.get('type') or 'files'
    prefix = opts['prefix']
    if dest == '-':
        if kind == 'files':
            raise util.Abort(_('cannot archive plain files to stdout'))
        dest = sys.stdout
        if not prefix: prefix = os.path.basename(repo.root) + '-%h'
Vadim Gelfer's avatar
Vadim Gelfer committed
169
    prefix = cmdutil.make_filename(repo, prefix, node)
170 171
    archival.archive(repo, dest, node, kind, not opts['no_decode'],
                     matchfn, prefix)
172

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

Vadim Gelfer's avatar
Vadim Gelfer committed
176 177
    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
178 179

    If you back out a changeset other than the tip, a new head is
180 181
    created.  This head will be the new tip and you should merge this
    backout changeset with another head (current one by default).
Vadim Gelfer's avatar
Vadim Gelfer committed
182 183 184 185 186 187

    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 for a normal
    merge.'''
Daniel Holth's avatar
Daniel Holth committed
188 189 190 191 192
    if rev and node:
        raise util.Abort(_("please specify just one revision"))

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

194 195 196
    if not rev:
        raise util.Abort(_("please specify a revision to backout"))

197 198 199 200
    date = opts.get('date')
    if date:
        opts['date'] = util.parsedate(date)

201
    cmdutil.bail_if_changed(repo)
Vadim Gelfer's avatar
Vadim Gelfer committed
202
    node = repo.lookup(rev)
203

204
    op1, op2 = repo.dirstate.parents()
205 206 207 208
    a = repo.changelog.ancestor(op1, node)
    if a != node:
        raise util.Abort(_('cannot back out change on a different branch'))

209 210
    p1, p2 = repo.changelog.parents(node)
    if p1 == nullid:
Vadim Gelfer's avatar
Vadim Gelfer committed
211 212
        raise util.Abort(_('cannot back out a change with no parents'))
    if p2 != nullid:
213 214 215 216 217
        if not opts['parent']:
            raise util.Abort(_('cannot back out a merge changeset without '
                               '--parent'))
        p = repo.lookup(opts['parent'])
        if p not in (p1, p2):
218
            raise util.Abort(_('%s is not a parent of %s') %
219
                             (short(p), short(node)))
220 221 222 223 224
        parent = p
    else:
        if opts['parent']:
            raise util.Abort(_('cannot use --parent on non-merge changeset'))
        parent = p1
225

226
    hg.clean(repo, node, show_stats=False)
Vadim Gelfer's avatar
Vadim Gelfer committed
227
    revert_opts = opts.copy()
228
    revert_opts['date'] = None
229
    revert_opts['all'] = True
Vadim Gelfer's avatar
Vadim Gelfer committed
230
    revert_opts['rev'] = hex(parent)
231
    revert_opts['no_backup'] = None
Vadim Gelfer's avatar
Vadim Gelfer committed
232 233 234
    revert(ui, repo, **revert_opts)
    commit_opts = opts.copy()
    commit_opts['addremove'] = False
235
    if not commit_opts['message'] and not commit_opts['logfile']:
236
        commit_opts['message'] = _("Backed out changeset %s") % (short(node))
237
        commit_opts['force_editor'] = True
Vadim Gelfer's avatar
Vadim Gelfer committed
238 239 240 241 242
    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)))
243
    if op1 != node:
244
        hg.clean(repo, op1, show_stats=False)
245
        if opts['merge']:
246 247
            ui.status(_('merging with changeset %s\n') % nice(repo.changelog.tip()))
            hg.merge(repo, hex(repo.changelog.tip()))
248 249 250
        else:
            ui.status(_('the backout changeset is a new head - '
                        'do not forget to merge\n'))
251 252
            ui.status(_('(use "backout --merge" '
                        'if you want to auto-merge)\n'))
Vadim Gelfer's avatar
Vadim Gelfer committed
253

254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
def bisect(ui, repo, rev=None, extra=None,
               reset=None, good=None, bad=None, skip=None, noupdate=None):
    """subdivision search of changesets

    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. Once you have performed tests, mark the
    working directory as bad or good and bisect will either update to
    another candidate changeset or announce that it has found the bad
    revision.
    """
    # 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
    elif extra or good + bad + skip + reset > 1:
        raise util.Abort("Incompatible arguments")

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

    # load state
    state = {'good': [], 'bad': [], 'skip': []}
    if os.path.exists(repo.join("bisect.state")):
        for l in repo.opener("bisect.state"):
            kind, node = l[:-1].split()
            node = repo.lookup(node)
            if kind not in state:
                raise util.Abort(_("unknown bisect kind %s") % kind)
            state[kind].append(node)

    # update state
    node = repo.lookup(rev or '.')
    if good:
        state['good'].append(node)
    elif bad:
        state['bad'].append(node)
    elif skip:
        state['skip'].append(node)

    # save state
    f = repo.opener("bisect.state", "w", atomictemp=True)
    wlock = repo.wlock()
    try:
        for kind in state:
            for node in state[kind]:
                f.write("%s %s\n" % (kind, hg.hex(node)))
        f.rename()
    finally:
        del wlock

    if not state['good'] or not state['bad']:
        return

    # actually bisect
320
    node, changesets, good = hbisect.bisect(repo.changelog, state)
321
    if changesets == 0:
322
        ui.write(_("The first %s revision is:\n") % (good and "good" or "bad"))
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
        displayer = cmdutil.show_changeset(ui, repo, {})
        displayer.show(changenode=node)
    elif node is not None:
        # 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)
        ui.write(_("Testing changeset %s:%s "
                   "(%s changesets remaining, ~%s tests)\n")
                 % (rev, hg.short(node), changesets, tests))
        if not noupdate:
            cmdutil.bail_if_changed(repo)
            return hg.clean(repo, node)

338
def branch(ui, repo, label=None, **opts):
339 340
    """set or show the current branch name

341 342 343
    With no argument, show the current branch name. With one argument,
    set the working directory branch name (the branch does not exist in
    the repository until the next commit).
344 345 346

    Unless --force is specified, branch will not let you set a
    branch name that shadows an existing branch.
347 348

    Use the command 'hg update' to switch to an existing branch.
349 350
    """

351
    if label:
352 353 354 355
        if not opts.get('force') and label in repo.branchtags():
            if label not in [p.branch() for p in repo.workingctx().parents()]:
                raise util.Abort(_('a branch of the same name already exists'
                                   ' (use --force to override)'))
356
        repo.dirstate.setbranch(util.fromlocal(label))
357
        ui.status(_('marked working directory as branch %s\n') % label)
358
    else:
359
        ui.write("%s\n" % util.tolocal(repo.dirstate.branch()))
360

361
def branches(ui, repo, active=False):
362 363
    """list repository named branches

364 365 366 367
    List the repository's named branches, indicating which ones are
    inactive.  If active is specified, only show active branches.

    A branch is considered active if it contains unmerged heads.
368 369

    Use the command 'hg update' to switch to an existing branch.
370 371
    """
    b = repo.branchtags()
372 373
    heads = dict.fromkeys(repo.heads(), 1)
    l = [((n in heads), repo.changelog.rev(n), n, t) for t, n in b.items()]
374
    l.sort()
375 376 377 378 379 380
    l.reverse()
    for ishead, r, n, t in l:
        if active and not ishead:
            # If we're only displaying active branches, abort the loop on
            # encountering the first inactive head
            break
381
        else:
382 383 384 385 386 387 388 389 390
            hexfunc = ui.debugflag and hex or short
            if ui.quiet:
                ui.write("%s\n" % t)
            else:
                spaces = " " * (30 - util.locallen(t))
                # The code only gets here if inactive branches are being
                # displayed or the branch is active.
                isinactive = ((not ishead) and " (inactive)") or ''
                ui.write("%s%s %s:%s%s\n" % (t, spaces, r, hexfunc(n), isinactive))
391

392
def bundle(ui, repo, fname, dest=None, **opts):
393 394
    """create a changegroup file

395 396
    Generate a compressed changegroup file collecting changesets not
    found in the other repository.
397

398 399
    If no destination repository is specified the destination is assumed
    to have all the nodes specified by one or more --base parameters.
400
    To create a bundle containing all changesets, use --base null.
401

402 403 404 405
    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.
406

407 408
    Applying bundles preserves all changeset contents including
    permissions, copy/rename information, and revision history.
409
    """
410 411 412 413 414 415 416 417
    revs = opts.get('rev') or None
    if revs:
        revs = [repo.lookup(rev) for rev in revs]
    base = opts.get('base')
    if base:
        if dest:
            raise util.Abort(_("--base is incompatible with specifiying "
                               "a destination"))
418 419 420
        base = [repo.lookup(rev) for rev in base]
        # create the right base
        # XXX: nodesbetween / changegroup* should be "fixed" instead
421
        o = []
Matt Mackall's avatar
Matt Mackall committed
422
        has = {nullid: None}
423
        for n in base:
Matt Mackall's avatar
Matt Mackall committed
424
            has.update(repo.changelog.reachable(n))
425
        if revs:
426
            visit = list(revs)
427
        else:
428
            visit = repo.changelog.heads()
Matt Mackall's avatar
Matt Mackall committed
429
        seen = {}
430 431
        while visit:
            n = visit.pop(0)
Matt Mackall's avatar
Matt Mackall committed
432
            parents = [p for p in repo.changelog.parents(n) if p not in has]
433 434 435
            if len(parents) == 0:
                o.insert(0, n)
            else:
436 437
                for p in parents:
                    if p not in seen:
Matt Mackall's avatar
Matt Mackall committed
438
                        seen[p] = 1
439
                        visit.append(p)
440
    else:
441
        cmdutil.setremoteconfig(ui, opts)
Alexis S. L. Carvalho's avatar
Alexis S. L. Carvalho committed
442
        dest, revs, checkout = hg.parseurl(
Matt Mackall's avatar
Matt Mackall committed
443
            ui.expandpath(dest or 'default-push', dest or 'default'), revs)
444 445 446 447 448 449 450
        other = hg.repository(ui, dest)
        o = repo.findoutgoing(other, force=opts['force'])

    if revs:
        cg = repo.changegroupsubset(o, revs, 'bundle')
    else:
        cg = repo.changegroup(o, 'bundle')
451
    changegroup.writebundle(cg, fname, "HG10BZ")
452

453
def cat(ui, repo, file1, *pats, **opts):
454
    """output the current or given revision of files
455 456

    Print the specified files as they were at the given revision.
457 458
    If no revision is given, the parent of the working directory is used,
    or tip if no revision is checked out.
459 460 461 462 463 464 465 466 467

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

    %s   basename of file being printed
    %d   dirname of file being printed, or '.' if in repo root
    %p   root-relative path name of file being printed
    """
Brendan Cully's avatar
Brendan Cully committed
468
    ctx = repo.changectx(opts['rev'])
Matt Mackall's avatar
Matt Mackall committed
469
    err = 1
470 471
    for src, abs, rel, exact in cmdutil.walk(repo, (file1,) + pats, opts,
                                             ctx.node()):
Vadim Gelfer's avatar
Vadim Gelfer committed
472
        fp = cmdutil.make_file(repo, opts['output'], ctx.node(), pathname=abs)
473
        data = ctx.filectx(abs).data()
474
        if opts.get('decode'):
475 476
            data = repo.wwritedata(abs, data)
        fp.write(data)
Matt Mackall's avatar
Matt Mackall committed
477 478
        err = 0
    return err
mpm@selenic.com's avatar
mpm@selenic.com committed
479

480
def clone(ui, source, dest=None, **opts):
481 482 483 484 485 486 487 488 489 490 491
    """make a copy of an existing repository

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

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

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

    For efficiency, hardlinks are used for cloning whenever the source
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
    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.

    You can safely clone repositories and checked out files using full
    hardlinks with

      $ cp -al REPO REPOCLONE

    which is the fastest way to clone. However, 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).
507

508 509 510
    If you use the -r option to clone up to a specific revision, no
    subsequent revisions will be present in the cloned repository.
    This option implies --pull, even on local repositories.
511 512

    See pull for valid source format details.
513 514

    It is possible to specify an ssh:// URL as the destination, but no
515 516 517
    .hg/hgrc and working directory will be created on the remote side.
    Look at the help text for the pull command for important details
    about ssh:// URLs.
518
    """
519
    cmdutil.setremoteconfig(ui, opts)
Matt Mackall's avatar
Matt Mackall committed
520
    hg.clone(ui, source, dest,
521
             pull=opts['pull'],
522
             stream=opts['uncompressed'],
523 524
             rev=opts['rev'],
             update=not opts['noupdate'])
mpm@selenic.com's avatar
mpm@selenic.com committed
525

526
def commit(ui, repo, *pats, **opts):
527 528 529 530 531
    """commit the specified files or all outstanding changes

    Commit changes to the given files into the repository.

    If a list of files is omitted, all changes reported by "hg status"
532
    will be committed.
533

534 535
    If no commit message is specified, the configured editor is started to
    enter a message.
536
    """
537 538 539 540
    def commitfunc(ui, repo, files, message, match, opts):
        return repo.commit(files, message, opts['user'], opts['date'], match,
                           force_editor=opts.get('force_editor'))
    cmdutil.commit(ui, repo, commitfunc, pats, opts)
Bryan O'Sullivan's avatar
Bryan O'Sullivan committed
541 542

def copy(ui, repo, *pats, **opts):
543 544 545 546 547 548 549 550 551 552
    """mark files as copied for the next commit

    Mark dest as having copies of source files.  If dest is a
    directory, copies are put in that directory.  If dest is a file,
    there can only be one source.

    By default, this command copies the contents of files as they
    stand in the working directory.  If invoked with --after, the
    operation is recorded, but no copying is performed.

553 554
    This command takes effect in the next commit. To undo a copy
    before that, see hg revert.
555
    """
Matt Mackall's avatar
Matt Mackall committed
556
    wlock = repo.wlock(False)
557
    try:
Matt Mackall's avatar
Matt Mackall committed
558
        return cmdutil.copy(ui, repo, pats, opts)
559 560
    finally:
        del wlock
mpm@selenic.com's avatar
mpm@selenic.com committed
561

mpm@selenic.com's avatar
mpm@selenic.com committed
562 563
def debugancestor(ui, index, rev1, rev2):
    """find the ancestor revision of two revisions in a given index"""
564
    r = revlog.revlog(util.opener(os.getcwd(), audit=False), index)
mpm@selenic.com's avatar
mpm@selenic.com committed
565 566 567
    a = r.ancestor(r.lookup(rev1), r.lookup(rev2))
    ui.write("%d:%s\n" % (r.rev(a), hex(a)))

568
def debugcomplete(ui, cmd='', **opts):
Benoit Boissinot's avatar
Benoit Boissinot committed
569
    """returns the completion list associated with the given command"""
570 571 572 573 574

    if opts['options']:
        options = []
        otables = [globalopts]
        if cmd:
575
            aliases, entry = cmdutil.findcmd(ui, cmd, table)
576 577 578 579 580 581 582 583 584
            otables.append(entry[1])
        for t in otables:
            for o in t:
                if o[0]:
                    options.append('-%s' % o[0])
                options.append('--%s' % o[1])
        ui.write("%s\n" % "\n".join(options))
        return

585
    clist = cmdutil.findpossible(ui, cmd, table).keys()
Benoit Boissinot's avatar
Benoit Boissinot committed
586
    clist.sort()
587
    ui.write("%s\n" % "\n".join(clist))
Benoit Boissinot's avatar
Benoit Boissinot committed
588

589 590 591 592 593 594 595 596
def debugfsinfo(ui, path = "."):
    file('.debugfsinfo', 'w').write('')
    ui.write('exec: %s\n' % (util.checkexec(path) and 'yes' or 'no'))
    ui.write('symlink: %s\n' % (util.checklink(path) and 'yes' or 'no'))
    ui.write('case-sensitive: %s\n' % (util.checkfolding('.debugfsinfo')
                                and 'yes' or 'no'))
    os.unlink('.debugfsinfo')

597
def debugrebuildstate(ui, repo, rev=""):
598
    """rebuild the dirstate as it would look like for the given revision"""
599
    if rev == "":
600
        rev = repo.changelog.tip()
601 602
    ctx = repo.changectx(rev)
    files = ctx.manifest()
603
    wlock = repo.wlock()
604 605 606 607
    try:
        repo.dirstate.rebuild(rev, files)
    finally:
        del wlock
608

609 610
def debugcheckstate(ui, repo):
    """validate the correctness of the current dirstate"""
611
    parent1, parent2 = repo.dirstate.parents()
612 613
    m1 = repo.changectx(parent1).manifest()
    m2 = repo.changectx(parent2).manifest()
614
    errors = 0
615 616
    for f in repo.dirstate:
        state = repo.dirstate[f]
617
        if state in "nr" and f not in m1:
618
            ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
619 620
            errors += 1
        if state in "a" and f in m1:
621
            ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
622 623
            errors += 1
        if state in "m" and f not in m1 and f not in m2:
624
            ui.warn(_("%s in state %s, but not in either manifest\n") %
625
                    (f, state))
626 627
            errors += 1
    for f in m1:
628
        state = repo.dirstate[f]
629
        if state not in "nrm":
630
            ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
631 632
            errors += 1
    if errors:
633 634
        error = _(".hg/dirstate inconsistent with current parent's manifest")
        raise util.Abort(error)
635

636
def showconfig(ui, repo, *values, **opts):
637 638 639 640 641 642 643 644 645 646
    """show combined config settings from all hgrc files

    With no args, print names and values of all config items.

    With one arg of the form section.name, print just the value of
    that config item.

    With multiple args, print names and values of all config items
    with matching section names."""

647
    untrusted = bool(opts.get('untrusted'))
648 649 650
    if values:
        if len([v for v in values if '.' in v]) > 1:
            raise util.Abort(_('only one config item permitted'))
651
    for section, name, value in ui.walkconfig(untrusted=untrusted):
652 653 654 655 656 657 658 659 660
        sectname = section + '.' + name
        if values:
            for v in values:
                if v == section:
                    ui.write('%s=%s\n' % (sectname, value))
                elif v == sectname:
                    ui.write(value, '\n')
        else:
            ui.write('%s=%s\n' % (sectname, value))
Bryan O'Sullivan's avatar
Bryan O'Sullivan committed
661

Matt Mackall's avatar
Matt Mackall committed
662
def debugsetparents(ui, repo, rev1, rev2=None):
TK Soh's avatar
TK Soh committed
663
    """manually set the parents of the current working directory
Matt Mackall's avatar
Matt Mackall committed
664 665 666 667 668 669 670 671

    This is useful for writing repository conversion tools, but should
    be used with care.
    """

    if not rev2:
        rev2 = hex(nullid)

672 673 674 675
    wlock = repo.wlock()
    try:
        repo.dirstate.setparents(repo.lookup(rev1), repo.lookup(rev2))
    finally:
676
        del wlock
Matt Mackall's avatar
Matt Mackall committed
677

678 679
def debugstate(ui, repo):
    """show the contents of the current dirstate"""
680
    k = repo.dirstate._map.items()
681
    k.sort()
682 683
    for file_, ent in k:
        if ent[3] == -1:
684
            # Pad or slice to locale representation
685
            locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(0)))
686 687 688
            timestr = 'unset'
            timestr = timestr[:locale_len] + ' '*(locale_len - len(timestr))
        else:
689
            timestr = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ent[3]))
690 691 692 693 694
        if ent[1] & 020000:
            mode = 'lnk'
        else:
            mode = '%3o' % (ent[1] & 0777)
        ui.write("%c %s %10d %s %s\n" % (ent[0], mode, ent[2], timestr, file_))
695 696
    for f in repo.dirstate.copies():
        ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
697

698
def debugdata(ui, file_, rev):
699 700
    """dump the contents of a data file revision"""
    r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_[:-2] + ".i")
701 702 703
    try:
        ui.write(r.revision(r.lookup(rev)))
    except KeyError:
704
        raise util.Abort(_('invalid revision identifier %s') % rev)
705

Matt Mackall's avatar
Matt Mackall committed
706
def debugdate(ui, date, range=None, **opts):
Matt Mackall's avatar
Matt Mackall committed
707
    """parse and display a date"""
Matt Mackall's avatar
Matt Mackall committed
708 709 710 711
    if opts["extended"]:
        d = util.parsedate(date, util.extendeddateformats)
    else:
        d = util.parsedate(date)
Matt Mackall's avatar
Matt Mackall committed
712 713
    ui.write("internal: %s %s\n" % d)
    ui.write("standard: %s\n" % util.datestr(d))
Matt Mackall's avatar
Matt Mackall committed
714 715 716
    if range:
        m = util.matchdate(range)
        ui.write("match: %s\n" % m(d[0]))
Matt Mackall's avatar
Matt Mackall committed
717

718
def debugindex(ui, file_):
719
    """dump the contents of an index file"""
720
    r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_)
721
    ui.write("   rev    offset  length   base linkrev" +
mpm@selenic.com's avatar
mpm@selenic.com committed
722
             " nodeid       p1           p2\n")
Benoit Boissinot's avatar
Benoit Boissinot committed
723
    for i in xrange(r.count()):
mason@suse.com's avatar
mason@suse.com committed
724
        node = r.node(i)
725 726 727 728
        try:
            pp = r.parents(node)
        except:
            pp = [nullid, nullid]
mpm@selenic.com's avatar
mpm@selenic.com committed
729
        ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
mason@suse.com's avatar
mason@suse.com committed
730 731
                i, r.start(i), r.length(i), r.base(i), r.linkrev(node),
            short(node), short(pp[0]), short(pp[1])))
mpm@selenic.com's avatar
mpm@selenic.com committed
732

733
def debugindexdot(ui, file_):
734
    """dump an index DAG as a .dot file"""
735
    r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_)
736
    ui.write("digraph G {\n")
Benoit Boissinot's avatar
Benoit Boissinot committed
737
    for i in xrange(r.count()):
738 739 740 741 742
        node = r.node(i)
        pp = r.parents(node)
        ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
        if pp[1] != nullid:
            ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
743
    ui.write("}\n")
mpm@selenic.com's avatar
mpm@selenic.com committed
744

745 746 747
def debuginstall(ui):
    '''test Mercurial installation'''

748
    def writetemp(contents):
749
        (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
750 751 752 753 754
        f = os.fdopen(fd, "wb")
        f.write(contents)
        f.close()
        return name

755 756 757 758 759 760 761 762
    problems = 0

    # encoding
    ui.status(_("Checking encoding (%s)...\n") % util._encoding)
    try:
        util.fromlocal("test")
    except util.Abort, inst:
        ui.write(" %s\n" % inst)
763
        ui.write(_(" (check that your locale is properly set)\n"))
764 765 766 767 768 769 770 771
        problems += 1

    # compiled modules
    ui.status(_("Checking extensions...\n"))
    try:
        import bdiff, mpatch, base85
    except Exception, inst:
        ui.write(" %s\n" % inst)
772 773
        ui.write(_(" One or more extensions could not be found"))
        ui.write(_(" (check that you compiled the extensions)\n"))
774 775 776 777 778 779 780 781 782
        problems += 1

    # templates
    ui.status(_("Checking templates...\n"))
    try:
        import templater
        t = templater.templater(templater.templatepath("map-cmdline.default"))
    except Exception, inst:
        ui.write(" %s\n" % inst)
783
        ui.write(_(" (templates seem to have been installed incorrectly)\n"))
784 785 786 787
        problems += 1

    # patch
    ui.status(_("Checking patch...\n"))
788 789 790 791
    patchproblems = 0
    a = "1\n2\n3\n4\n"
    b = "1\n2\n3\ninsert\n4\n"
    fa = writetemp(a)
792 793
    d = mdiff.unidiff(a, None, b, None, os.path.basename(fa),
        os.path.basename(fa))
794 795 796 797 798 799 800 801 802
    fd = writetemp(d)

    files = {}
    try:
        patch.patch(fd, ui, cwd=os.path.dirname(fa), files=files)
    except util.Abort, e:
        ui.write(_(" patch call failed:\n"))
        ui.write(" " + str(e) + "\n")
        patchproblems += 1
803
    else:
804 805 806 807 808 809 810 811 812 813 814 815
        if list(files) != [os.path.basename(fa)]:
            ui.write(_(" unexpected patch output!\n"))
            patchproblems += 1
        a = file(fa).read()
        if a != b:
            ui.write(_(" patch test failed!\n"))
            patchproblems += 1

    if patchproblems:
        if ui.config('ui', 'patch'):
            ui.write(_(" (Current patch tool may be incompatible with patch,"
                       " or misconfigured. Please check your .hgrc file)\n"))
816
        else:
817
            ui.write(_(" Internal patcher failure, please report this error"
818 819 820 821 822
                       " to http://www.selenic.com/mercurial/bts\n"))
    problems += patchproblems

    os.unlink(fa)
    os.unlink(fd)
823 824 825

    # editor
    ui.status(_("Checking commit editor...\n"))
826
    editor = ui.geteditor()
827
    cmdpath = util.find_exe(editor) or util.find_exe(editor.split()[0])
828
    if not cmdpath:
829
        if editor == 'vi':
830
            ui.write(_(" No commit editor set and can't find vi in PATH\n"))
831
            ui.write(_(" (specify a commit editor in your .hgrc file)\n"))
832 833
        else:
            ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
834
            ui.write(_(" (specify a commit editor in your .hgrc file)\n"))
835 836
            problems += 1

837 838 839 840 841 842 843 844 845 846 847 848
    # check username
    ui.status(_("Checking username...\n"))
    user = os.environ.get("HGUSER")
    if user is None:
        user = ui.config("ui", "username")
    if user is None:
        user = os.environ.get("EMAIL")
    if not user:
        ui.warn(" ")
        ui.username()
        ui.write(_(" (specify a username in your .hgrc file)\n"))

849 850 851 852 853 854 855 856
    if not problems:
        ui.status(_("No problems detected\n"))
    else:
        ui.write(_("%s problems detected,"
                   " please check your install!\n") % problems)

    return problems

Matt Mackall's avatar
Matt Mackall committed
857
def debugrename(ui, repo, file1, *pats, **opts):
858
    """dump rename information"""
Matt Mackall's avatar
Matt Mackall committed
859 860 861 862

    ctx = repo.changectx(opts.get('rev', 'tip'))
    for src, abs, rel, exact in cmdutil.walk(repo, (file1,) + pats, opts,
                                             ctx.node()):
863 864
        fctx = ctx.filectx(abs)
        m = fctx.filelog().renamed(fctx.filenode())
Matt Mackall's avatar
Matt Mackall committed
865 866 867 868
        if m:
            ui.write(_("%s renamed from %s:%s\n") % (rel, m[0], hex(m[1])))
        else:
            ui.write(_("%s not renamed\n") % rel)
869

870
def debugwalk(ui, repo, *pats, **opts):
871
    """show how files match on given patterns"""