Пример #1
0
def _dispatch(req):
    args = req.args
    ui = req.ui

    # check for cwd
    cwd = _earlygetopt(['--cwd'], args)
    if cwd:
        os.chdir(cwd[-1])

    rpath = _earlygetopt(["-R", "--repository", "--repo"], args)
    path, lui = _getlocal(ui, rpath)

    # Now that we're operating in the right directory/repository with
    # the right config settings, check for shell aliases
    shellaliasfn = _checkshellalias(lui, ui, args)
    if shellaliasfn:
        return shellaliasfn()

    # Configure extensions in phases: uisetup, extsetup, cmdtable, and
    # reposetup. Programs like TortoiseHg will call _dispatch several
    # times so we keep track of configured extensions in _loaded.
    extensions.loadall(lui)
    exts = [ext for ext in extensions.extensions() if ext[0] not in _loaded]
    # Propagate any changes to lui.__class__ by extensions
    ui.__class__ = lui.__class__

    # (uisetup and extsetup are handled in extensions.loadall)

    for name, module in exts:
        cmdtable = getattr(module, 'cmdtable', {})
        overrides = [cmd for cmd in cmdtable if cmd in commands.table]
        if overrides:
            ui.warn(
                _("extension '%s' overrides commands: %s\n") %
                (name, " ".join(overrides)))
        commands.table.update(cmdtable)
        _loaded.add(name)

    # (reposetup is handled in hg.repository)

    addaliases(lui, commands.table)

    if not lui.configbool("ui", "strict"):
        # All aliases and commands are completely defined, now.
        # Check abbreviation/ambiguity of shell alias again, because shell
        # alias may cause failure of "_parse" (see issue4355)
        shellaliasfn = _checkshellalias(lui, ui, args, precheck=False)
        if shellaliasfn:
            return shellaliasfn()

    # check for fallback encoding
    fallback = lui.config('ui', 'fallbackencoding')
    if fallback:
        encoding.fallbackencoding = fallback

    fullargs = args
    cmd, func, args, options, cmdoptions = _parse(lui, args)

    if options["config"]:
        raise util.Abort(_("option --config may not be abbreviated!"))
    if options["cwd"]:
        raise util.Abort(_("option --cwd may not be abbreviated!"))
    if options["repository"]:
        raise util.Abort(
            _("option -R has to be separated from other options (e.g. not -qR) "
              "and --repository may only be abbreviated as --repo!"))

    if options["encoding"]:
        encoding.encoding = options["encoding"]
    if options["encodingmode"]:
        encoding.encodingmode = options["encodingmode"]
    if options["time"]:

        def get_times():
            t = os.times()
            if t[4] == 0.0:  # Windows leaves this as zero, so use time.clock()
                t = (t[0], t[1], t[2], t[3], time.clock())
            return t

        s = get_times()

        def print_time():
            t = get_times()
            ui.warn(
                _("time: real %.3f secs (user %.3f+%.3f sys %.3f+%.3f)\n") %
                (t[4] - s[4], t[0] - s[0], t[2] - s[2], t[1] - s[1],
                 t[3] - s[3]))

        atexit.register(print_time)

    uis = set([ui, lui])

    if req.repo:
        uis.add(req.repo.ui)

    if options['verbose'] or options['debug'] or options['quiet']:
        for opt in ('verbose', 'debug', 'quiet'):
            val = str(bool(options[opt]))
            for ui_ in uis:
                ui_.setconfig('ui', opt, val, '--' + opt)

    if options['traceback']:
        for ui_ in uis:
            ui_.setconfig('ui', 'traceback', 'on', '--traceback')

    if options['noninteractive']:
        for ui_ in uis:
            ui_.setconfig('ui', 'interactive', 'off', '-y')

    if cmdoptions.get('insecure', False):
        for ui_ in uis:
            ui_.setconfig('web', 'cacerts', '', '--insecure')

    if options['version']:
        return commands.version_(ui)
    if options['help']:
        return commands.help_(ui, cmd, command=True)
    elif not cmd:
        return commands.help_(ui, 'shortlist')

    repo = None
    cmdpats = args[:]
    if cmd not in commands.norepo.split():
        # use the repo from the request only if we don't have -R
        if not rpath and not cwd:
            repo = req.repo

        if repo:
            # set the descriptors of the repo ui to those of ui
            repo.ui.fin = ui.fin
            repo.ui.fout = ui.fout
            repo.ui.ferr = ui.ferr
        else:
            try:
                repo = hg.repository(ui, path=path)
                if not repo.local():
                    raise util.Abort(_("repository '%s' is not local") % path)
                repo.ui.setconfig("bundle", "mainreporoot", repo.root, 'repo')
            except error.RequirementError:
                raise
            except error.RepoError:
                if cmd not in commands.optionalrepo.split():
                    if (cmd in commands.inferrepo.split() and args
                            and not path):  # try to infer -R from command args
                        repos = map(cmdutil.findrepo, args)
                        guess = repos[0]
                        if guess and repos.count(guess) == len(repos):
                            req.args = ['--repository', guess] + fullargs
                            return _dispatch(req)
                    if not path:
                        raise error.RepoError(
                            _("no repository found in '%s'"
                              " (.hg not found)") % os.getcwd())
                    raise
        if repo:
            ui = repo.ui
            if options['hidden']:
                repo = repo.unfiltered()
        args.insert(0, repo)
    elif rpath:
        ui.warn(_("warning: --repository ignored\n"))

    msg = ' '.join(' ' in a and repr(a) or a for a in fullargs)
    ui.log("command", '%s\n', msg)
    d = lambda: util.checksignature(func)(ui, *args, **cmdoptions)
    try:
        return runcommand(lui, repo, cmd, fullargs, ui, options, d, cmdpats,
                          cmdoptions)
    finally:
        if repo and repo != req.repo:
            repo.close()
Пример #2
0
def _dispatch(req):
    args = req.args
    ui = req.ui

    shellaliasfn = _checkshellalias(ui, args)
    if shellaliasfn:
        return shellaliasfn()

    # read --config before doing anything else
    # (e.g. to change trust settings for reading .hg/hgrc)
    cfgs = _parseconfig(ui, _earlygetopt(['--config'], args))

    # check for cwd
    cwd = _earlygetopt(['--cwd'], args)
    if cwd:
        os.chdir(cwd[-1])

    rpath = _earlygetopt(["-R", "--repository", "--repo"], args)
    path, lui = _getlocal(ui, rpath)

    # Configure extensions in phases: uisetup, extsetup, cmdtable, and
    # reposetup. Programs like TortoiseHg will call _dispatch several
    # times so we keep track of configured extensions in _loaded.
    extensions.loadall(lui)
    exts = [ext for ext in extensions.extensions() if ext[0] not in _loaded]
    # Propagate any changes to lui.__class__ by extensions
    ui.__class__ = lui.__class__

    # (uisetup and extsetup are handled in extensions.loadall)

    for name, module in exts:
        cmdtable = getattr(module, 'cmdtable', {})
        overrides = [cmd for cmd in cmdtable if cmd in commands.table]
        if overrides:
            ui.warn(_("extension '%s' overrides commands: %s\n")
                    % (name, " ".join(overrides)))
        commands.table.update(cmdtable)
        _loaded.add(name)

    # (reposetup is handled in hg.repository)

    addaliases(lui, commands.table)

    # check for fallback encoding
    fallback = lui.config('ui', 'fallbackencoding')
    if fallback:
        encoding.fallbackencoding = fallback

    fullargs = args
    cmd, func, args, options, cmdoptions = _parse(lui, args)

    if options["config"]:
        raise util.Abort(_("option --config may not be abbreviated!"))
    if options["cwd"]:
        raise util.Abort(_("option --cwd may not be abbreviated!"))
    if options["repository"]:
        raise util.Abort(_(
            "Option -R has to be separated from other options (e.g. not -qR) "
            "and --repository may only be abbreviated as --repo!"))

    if options["encoding"]:
        encoding.encoding = options["encoding"]
    if options["encodingmode"]:
        encoding.encodingmode = options["encodingmode"]
    if options["time"]:
        def get_times():
            t = os.times()
            if t[4] == 0.0: # Windows leaves this as zero, so use time.clock()
                t = (t[0], t[1], t[2], t[3], time.clock())
            return t
        s = get_times()
        def print_time():
            t = get_times()
            ui.warn(_("Time: real %.3f secs (user %.3f+%.3f sys %.3f+%.3f)\n") %
                (t[4]-s[4], t[0]-s[0], t[2]-s[2], t[1]-s[1], t[3]-s[3]))
        atexit.register(print_time)

    uis = set([ui, lui])

    if req.repo:
        uis.add(req.repo.ui)

        # copy configs that were passed on the cmdline (--config) to the repo ui
        for cfg in cfgs:
            req.repo.ui.setconfig(*cfg)

    for opt in ('verbose', 'debug', 'quiet', 'traceback'):
        val = bool(options[opt])
        if val:
            for ui_ in uis:
                ui_.setconfig('ui', opt, str(val))

    if options['noninteractive']:
        for ui_ in uis:
            ui_.setconfig('ui', 'interactive', 'off')

    if cmdoptions.get('insecure', False):
        for ui_ in uis:
            ui_.setconfig('web', 'cacerts', '')

    if options['help']:
        return commands.help_(ui, cmd, options['version'])
    elif options['version']:
        return commands.version_(ui)
    elif not cmd:
        return commands.help_(ui, 'shortlist')

    repo = None
    cmdpats = args[:]
    if cmd not in commands.norepo.split():
        # use the repo from the request only if we don't have -R
        if not rpath:
            repo = req.repo

        if repo:
            # set the descriptors of the repo ui to those of ui
            repo.ui.fin = ui.fin
            repo.ui.fout = ui.fout
            repo.ui.ferr = ui.ferr
        else:
            try:
                repo = hg.repository(ui, path=path)
                if not repo.local():
                    raise util.Abort(_("repository '%s' is not local") % path)
                repo.ui.setconfig("bundle", "mainreporoot", repo.root)
            except error.RequirementError:
                raise
            except error.RepoError:
                if cmd not in commands.optionalrepo.split():
                    if args and not path: # try to infer -R from command args
                        repos = map(cmdutil.findrepo, args)
                        guess = repos[0]
                        if guess and repos.count(guess) == len(repos):
                            req.args = ['--repository', guess] + fullargs
                            return _dispatch(req)
                    if not path:
                        raise error.RepoError(_("no repository found in %r"
                                                " (.hg not found)") % os.getcwd())
                    raise
        if repo:
            ui = repo.ui
        args.insert(0, repo)
    elif rpath:
        ui.warn(_("warning: --repository ignored\n"))

    msg = ' '.join(' ' in a and repr(a) or a for a in fullargs)
    ui.log("command", msg + "\n")
    d = lambda: util.checksignature(func)(ui, *args, **cmdoptions)
    try:
        return runcommand(lui, repo, cmd, fullargs, ui, options, d,
                          cmdpats, cmdoptions)
    finally:
        if repo and repo != req.repo:
            repo.close()
Пример #3
0
def _dispatch(ui, args):
    # read --config before doing anything else
    # (e.g. to change trust settings for reading .hg/hgrc)
    _parseconfig(ui, _earlygetopt(['--config'], args))

    # check for cwd
    cwd = _earlygetopt(['--cwd'], args)
    if cwd:
        os.chdir(cwd[-1])

    # read the local repository .hgrc into a local ui object
    path = cmdutil.findrepo(os.getcwd()) or ""
    if not path:
        lui = ui
    else:
        try:
            lui = ui.copy()
            lui.readconfig(os.path.join(path, ".hg", "hgrc"))
        except IOError:
            pass

    # now we can expand paths, even ones in .hg/hgrc
    rpath = _earlygetopt(["-R", "--repository", "--repo"], args)
    if rpath:
        path = lui.expandpath(rpath[-1])
        lui = ui.copy()
        lui.readconfig(os.path.join(path, ".hg", "hgrc"))

    # Configure extensions in phases: uisetup, extsetup, cmdtable, and
    # reposetup. Programs like TortoiseHg will call _dispatch several
    # times so we keep track of configured extensions in _loaded.
    extensions.loadall(lui)
    exts = [ext for ext in extensions.extensions() if ext[0] not in _loaded]

    # (uisetup and extsetup are handled in extensions.loadall)

    for name, module in exts:
        cmdtable = getattr(module, 'cmdtable', {})
        overrides = [cmd for cmd in cmdtable if cmd in commands.table]
        if overrides:
            ui.warn(_("extension '%s' overrides commands: %s\n")
                    % (name, " ".join(overrides)))
        commands.table.update(cmdtable)
        _loaded.add(name)

    # (reposetup is handled in hg.repository)

    addaliases(lui, commands.table)

    # check for fallback encoding
    fallback = lui.config('ui', 'fallbackencoding')
    if fallback:
        encoding.fallbackencoding = fallback

    fullargs = args
    cmd, func, args, options, cmdoptions = _parse(lui, args)

    if options["config"]:
        raise util.Abort(_("Option --config may not be abbreviated!"))
    if options["cwd"]:
        raise util.Abort(_("Option --cwd may not be abbreviated!"))
    if options["repository"]:
        raise util.Abort(_(
            "Option -R has to be separated from other options (e.g. not -qR) "
            "and --repository may only be abbreviated as --repo!"))

    if options["encoding"]:
        encoding.encoding = options["encoding"]
    if options["encodingmode"]:
        encoding.encodingmode = options["encodingmode"]
    if options["time"]:
        def get_times():
            t = os.times()
            if t[4] == 0.0: # Windows leaves this as zero, so use time.clock()
                t = (t[0], t[1], t[2], t[3], time.clock())
            return t
        s = get_times()
        def print_time():
            t = get_times()
            ui.warn(_("Time: real %.3f secs (user %.3f+%.3f sys %.3f+%.3f)\n") %
                (t[4]-s[4], t[0]-s[0], t[2]-s[2], t[1]-s[1], t[3]-s[3]))
        atexit.register(print_time)

    if options['verbose'] or options['debug'] or options['quiet']:
        ui.setconfig('ui', 'verbose', str(bool(options['verbose'])))
        ui.setconfig('ui', 'debug', str(bool(options['debug'])))
        ui.setconfig('ui', 'quiet', str(bool(options['quiet'])))
    if options['traceback']:
        ui.setconfig('ui', 'traceback', 'on')
    if options['noninteractive']:
        ui.setconfig('ui', 'interactive', 'off')

    if options['help']:
        return commands.help_(ui, cmd, options['version'])
    elif options['version']:
        return commands.version_(ui)
    elif not cmd:
        return commands.help_(ui, 'shortlist')

    repo = None
    if cmd not in commands.norepo.split():
        try:
            repo = hg.repository(ui, path=path)
            ui = repo.ui
            if not repo.local():
                raise util.Abort(_("repository '%s' is not local") % path)
            ui.setconfig("bundle", "mainreporoot", repo.root)
        except error.RepoError:
            if cmd not in commands.optionalrepo.split():
                if args and not path: # try to infer -R from command args
                    repos = map(cmdutil.findrepo, args)
                    guess = repos[0]
                    if guess and repos.count(guess) == len(repos):
                        return _dispatch(ui, ['--repository', guess] + fullargs)
                if not path:
                    raise error.RepoError(_("There is no Mercurial repository"
                                      " here (.hg not found)"))
                raise
        args.insert(0, repo)
    elif rpath:
        ui.warn("warning: --repository ignored\n")

    d = lambda: util.checksignature(func)(ui, *args, **cmdoptions)
    return runcommand(lui, repo, cmd, fullargs, ui, options, d)
Пример #4
0
def _dispatch(ui, args):
    # read --config before doing anything else
    # (e.g. to change trust settings for reading .hg/hgrc)
    _parseconfig(ui, _earlygetopt(['--config'], args))

    # check for cwd
    cwd = _earlygetopt(['--cwd'], args)
    if cwd:
        os.chdir(cwd[-1])

    # read the local repository .hgrc into a local ui object
    path = cmdutil.findrepo(os.getcwd()) or ""
    if not path:
        lui = ui
    else:
        try:
            lui = ui.copy()
            lui.readconfig(os.path.join(path, ".hg", "hgrc"))
        except IOError:
            pass

    # now we can expand paths, even ones in .hg/hgrc
    rpath = _earlygetopt(["-R", "--repository", "--repo"], args)
    if rpath:
        path = lui.expandpath(rpath[-1])
        lui = ui.copy()
        lui.readconfig(os.path.join(path, ".hg", "hgrc"))

    # Configure extensions in phases: uisetup, extsetup, cmdtable, and
    # reposetup. Programs like TortoiseHg will call _dispatch several
    # times so we keep track of configured extensions in _loaded.
    extensions.loadall(lui)
    exts = [ext for ext in extensions.extensions() if ext[0] not in _loaded]

    # (uisetup and extsetup are handled in extensions.loadall)

    for name, module in exts:
        cmdtable = getattr(module, 'cmdtable', {})
        overrides = [cmd for cmd in cmdtable if cmd in commands.table]
        if overrides:
            ui.warn(
                _("extension '%s' overrides commands: %s\n") %
                (name, " ".join(overrides)))
        commands.table.update(cmdtable)
        _loaded.add(name)

    # (reposetup is handled in hg.repository)

    addaliases(lui, commands.table)

    # check for fallback encoding
    fallback = lui.config('ui', 'fallbackencoding')
    if fallback:
        encoding.fallbackencoding = fallback

    fullargs = args
    cmd, func, args, options, cmdoptions = _parse(lui, args)

    if options["config"]:
        raise util.Abort(_("Option --config may not be abbreviated!"))
    if options["cwd"]:
        raise util.Abort(_("Option --cwd may not be abbreviated!"))
    if options["repository"]:
        raise util.Abort(
            _("Option -R has to be separated from other options (e.g. not -qR) "
              "and --repository may only be abbreviated as --repo!"))

    if options["encoding"]:
        encoding.encoding = options["encoding"]
    if options["encodingmode"]:
        encoding.encodingmode = options["encodingmode"]
    if options["time"]:

        def get_times():
            t = os.times()
            if t[4] == 0.0:  # Windows leaves this as zero, so use time.clock()
                t = (t[0], t[1], t[2], t[3], time.clock())
            return t

        s = get_times()

        def print_time():
            t = get_times()
            ui.warn(
                _("Time: real %.3f secs (user %.3f+%.3f sys %.3f+%.3f)\n") %
                (t[4] - s[4], t[0] - s[0], t[2] - s[2], t[1] - s[1],
                 t[3] - s[3]))

        atexit.register(print_time)

    if options['verbose'] or options['debug'] or options['quiet']:
        ui.setconfig('ui', 'verbose', str(bool(options['verbose'])))
        ui.setconfig('ui', 'debug', str(bool(options['debug'])))
        ui.setconfig('ui', 'quiet', str(bool(options['quiet'])))
    if options['traceback']:
        ui.setconfig('ui', 'traceback', 'on')
    if options['noninteractive']:
        ui.setconfig('ui', 'interactive', 'off')

    if options['help']:
        return commands.help_(ui, cmd, options['version'])
    elif options['version']:
        return commands.version_(ui)
    elif not cmd:
        return commands.help_(ui, 'shortlist')

    repo = None
    if cmd not in commands.norepo.split():
        try:
            repo = hg.repository(ui, path=path)
            ui = repo.ui
            if not repo.local():
                raise util.Abort(_("repository '%s' is not local") % path)
            ui.setconfig("bundle", "mainreporoot", repo.root)
        except error.RepoError:
            if cmd not in commands.optionalrepo.split():
                if args and not path:  # try to infer -R from command args
                    repos = map(cmdutil.findrepo, args)
                    guess = repos[0]
                    if guess and repos.count(guess) == len(repos):
                        return _dispatch(ui,
                                         ['--repository', guess] + fullargs)
                if not path:
                    raise error.RepoError(
                        _("There is no Mercurial repository"
                          " here (.hg not found)"))
                raise
        args.insert(0, repo)
    elif rpath:
        ui.warn("warning: --repository ignored\n")

    d = lambda: util.checksignature(func)(ui, *args, **cmdoptions)
    return runcommand(lui, repo, cmd, fullargs, ui, options, d)
Пример #5
0
def _dispatch(ui, args):
    # read --config before doing anything else
    # (e.g. to change trust settings for reading .hg/hgrc)
    config = _earlygetopt(['--config'], args)
    if config:
        ui.updateopts(config=_parseconfig(config))

    # check for cwd
    cwd = _earlygetopt(['--cwd'], args)
    if cwd:
        os.chdir(cwd[-1])

    # read the local repository .hgrc into a local ui object
    path = _findrepo(os.getcwd()) or ""
    if not path:
        lui = ui
    if path:
        try:
            lui = _ui.ui(parentui=ui)
            lui.readconfig(os.path.join(path, ".hg", "hgrc"))
        except IOError:
            pass

    # now we can expand paths, even ones in .hg/hgrc
    rpath = _earlygetopt(["-R", "--repository", "--repo"], args)
    if rpath:
        path = lui.expandpath(rpath[-1])
        lui = _ui.ui(parentui=ui)
        lui.readconfig(os.path.join(path, ".hg", "hgrc"))

    extensions.loadall(lui)
    for name, module in extensions.extensions():
        if name in _loaded:
            continue

        # setup extensions
        # TODO this should be generalized to scheme, where extensions can
        #      redepend on other extensions.  then we should toposort them, and
        #      do initialization in correct order
        extsetup = getattr(module, 'extsetup', None)
        if extsetup:
            extsetup()

        cmdtable = getattr(module, 'cmdtable', {})
        overrides = [cmd for cmd in cmdtable if cmd in commands.table]
        if overrides:
            ui.warn(_("extension '%s' overrides commands: %s\n")
                    % (name, " ".join(overrides)))
        commands.table.update(cmdtable)
        _loaded[name] = 1
    # check for fallback encoding
    fallback = lui.config('ui', 'fallbackencoding')
    if fallback:
        util._fallbackencoding = fallback

    fullargs = args
    cmd, func, args, options, cmdoptions = _parse(lui, args)

    if options["config"]:
        raise util.Abort(_("Option --config may not be abbreviated!"))
    if options["cwd"]:
        raise util.Abort(_("Option --cwd may not be abbreviated!"))
    if options["repository"]:
        raise util.Abort(_(
            "Option -R has to be separated from other options (i.e. not -qR) "
            "and --repository may only be abbreviated as --repo!"))

    if options["encoding"]:
        util._encoding = options["encoding"]
    if options["encodingmode"]:
        util._encodingmode = options["encodingmode"]
    if options["time"]:
        def get_times():
            t = os.times()
            if t[4] == 0.0: # Windows leaves this as zero, so use time.clock()
                t = (t[0], t[1], t[2], t[3], time.clock())
            return t
        s = get_times()
        def print_time():
            t = get_times()
            ui.warn(_("Time: real %.3f secs (user %.3f+%.3f sys %.3f+%.3f)\n") %
                (t[4]-s[4], t[0]-s[0], t[2]-s[2], t[1]-s[1], t[3]-s[3]))
        atexit.register(print_time)

    ui.updateopts(options["verbose"], options["debug"], options["quiet"],
                 not options["noninteractive"], options["traceback"])

    if options['help']:
        return commands.help_(ui, cmd, options['version'])
    elif options['version']:
        return commands.version_(ui)
    elif not cmd:
        return commands.help_(ui, 'shortlist')

    repo = None
    if cmd not in commands.norepo.split():
        try:
            repo = hg.repository(ui, path=path)
            ui = repo.ui
            if not repo.local():
                raise util.Abort(_("repository '%s' is not local") % path)
            ui.setconfig("bundle", "mainreporoot", repo.root)
        except error.RepoError:
            if cmd not in commands.optionalrepo.split():
                if args and not path: # try to infer -R from command args
                    repos = map(_findrepo, args)
                    guess = repos[0]
                    if guess and repos.count(guess) == len(repos):
                        return _dispatch(ui, ['--repository', guess] + fullargs)
                if not path:
                    raise error.RepoError(_("There is no Mercurial repository"
                                      " here (.hg not found)"))
                raise
        args.insert(0, repo)
    elif rpath:
        ui.warn("warning: --repository ignored\n")

    d = lambda: util.checksignature(func)(ui, *args, **cmdoptions)
    return runcommand(lui, repo, cmd, fullargs, ui, options, d)
Пример #6
0
def _dispatch(ui, args):
    # read --config before doing anything else
    # (e.g. to change trust settings for reading .hg/hgrc)
    config = _earlygetopt(['--config'], args)
    if config:
        ui.updateopts(config=_parseconfig(config))

    # check for cwd
    cwd = _earlygetopt(['--cwd'], args)
    if cwd:
        os.chdir(cwd[-1])

    # read the local repository .hgrc into a local ui object
    path = _findrepo(os.getcwd()) or ""
    if not path:
        lui = ui
    if path:
        try:
            lui = _ui.ui(parentui=ui)
            lui.readconfig(os.path.join(path, ".hg", "hgrc"))
        except IOError:
            pass

    # now we can expand paths, even ones in .hg/hgrc
    rpath = _earlygetopt(["-R", "--repository", "--repo"], args)
    if rpath:
        path = lui.expandpath(rpath[-1])
        lui = _ui.ui(parentui=ui)
        lui.readconfig(os.path.join(path, ".hg", "hgrc"))

    extensions.loadall(lui)
    for name, module in extensions.extensions():
        if name in _loaded:
            continue

        # setup extensions
        # TODO this should be generalized to scheme, where extensions can
        #      redepend on other extensions.  then we should toposort them, and
        #      do initialization in correct order
        extsetup = getattr(module, 'extsetup', None)
        if extsetup:
            extsetup()

        cmdtable = getattr(module, 'cmdtable', {})
        overrides = [cmd for cmd in cmdtable if cmd in commands.table]
        if overrides:
            ui.warn(_("extension '%s' overrides commands: %s\n")
                    % (name, " ".join(overrides)))
        commands.table.update(cmdtable)
        _loaded[name] = 1
    # check for fallback encoding
    fallback = lui.config('ui', 'fallbackencoding')
    if fallback:
        util._fallbackencoding = fallback

    fullargs = args
    cmd, func, args, options, cmdoptions = _parse(lui, args)

    if options["config"]:
        raise util.Abort(_("Option --config may not be abbreviated!"))
    if options["cwd"]:
        raise util.Abort(_("Option --cwd may not be abbreviated!"))
    if options["repository"]:
        raise util.Abort(_(
            "Option -R has to be separated from other options (i.e. not -qR) "
            "and --repository may only be abbreviated as --repo!"))

    if options["encoding"]:
        util._encoding = options["encoding"]
    if options["encodingmode"]:
        util._encodingmode = options["encodingmode"]
    if options["time"]:
        def get_times():
            t = os.times()
            if t[4] == 0.0: # Windows leaves this as zero, so use time.clock()
                t = (t[0], t[1], t[2], t[3], time.clock())
            return t
        s = get_times()
        def print_time():
            t = get_times()
            ui.warn(_("Time: real %.3f secs (user %.3f+%.3f sys %.3f+%.3f)\n") %
                (t[4]-s[4], t[0]-s[0], t[2]-s[2], t[1]-s[1], t[3]-s[3]))
        atexit.register(print_time)

    ui.updateopts(options["verbose"], options["debug"], options["quiet"],
                 not options["noninteractive"], options["traceback"])

    if options['help']:
        return commands.help_(ui, cmd, options['version'])
    elif options['version']:
        return commands.version_(ui)
    elif not cmd:
        return commands.help_(ui, 'shortlist')

    repo = None
    if cmd not in commands.norepo.split():
        try:
            repo = hg.repository(ui, path=path)
            ui = repo.ui
            if not repo.local():
                raise util.Abort(_("repository '%s' is not local") % path)
            ui.setconfig("bundle", "mainreporoot", repo.root)
        except RepoError:
            if cmd not in commands.optionalrepo.split():
                if args and not path: # try to infer -R from command args
                    repos = map(_findrepo, args)
                    guess = repos[0]
                    if guess and repos.count(guess) == len(repos):
                        return _dispatch(ui, ['--repository', guess] + fullargs)
                if not path:
                    raise RepoError(_("There is no Mercurial repository here"
                                      " (.hg not found)"))
                raise
        d = lambda: func(ui, repo, *args, **cmdoptions)
    else:
        d = lambda: func(ui, *args, **cmdoptions)

    # run pre-hook, and abort if it fails
    ret = hook.hook(lui, repo, "pre-%s" % cmd, False, args=" ".join(fullargs))
    if ret:
        return ret
    ret = _runcommand(ui, options, cmd, d)
    # run post-hook, passing command result
    hook.hook(lui, repo, "post-%s" % cmd, False, args=" ".join(fullargs),
              result = ret)
    return ret