def _dispatch()

in eden/scm/edenscm/mercurial/dispatch.py [0:0]


def _dispatch(req):
    args = req.args
    ui = req.ui

    # check for cwd
    cwd = req.earlyoptions["cwd"]
    if cwd:
        os.chdir(cwd)

    rpath = req.earlyoptions["repository"]
    path, lui = _getlocal(ui, rpath)

    uis = {ui, lui}

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

    if req.earlyoptions["profile"]:
        for ui_ in uis:
            ui_.setconfig("profiling", "enabled", "true", "--profile")

    with profiling.profile(lui) as profiler:
        # Configure extensions in phases: uisetup, extsetup, cmdtable, and
        # reposetup
        extensions.loadall(lui)
        # Propagate any changes to lui.__class__ by extensions
        ui.__class__ = lui.__class__

        # setup color handling before pager, because setting up pager
        # might cause incorrect console information
        coloropt = req.earlyoptions.get("color", False)
        for ui_ in uis:
            if coloropt:
                ui_.setconfig("ui", "color", coloropt, "--color")
            color.setup(ui_)

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

        # (reposetup is handled in hg.repository)

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

        fullargs = args

        cmd, func, args, options, cmdoptions, foundaliases = _parse(lui, args)
        lui.cmdname = ui.cmdname = cmd

        # Do not profile the 'debugshell' command.
        if cmd == "debugshell":
            profiler.stop()

        if cmd == "help" and len(foundaliases) > 0:
            cmd = foundaliases[0]
            options["help"] = True

        if options["encoding"]:
            encoding.encoding = options["encoding"]
        if options["encodingmode"]:
            encoding.encodingmode = options["encodingmode"]
        if (
            options["outputencoding"]
            and options["outputencoding"] != "same as encoding"
        ):
            encoding.outputencoding = options["outputencoding"]
        i18n.init()

        if options["config"] != req.earlyoptions["config"]:
            raise error.Abort(_("option --config may not be abbreviated!"))
        if options["configfile"] != req.earlyoptions["configfile"]:
            raise error.Abort(_("option --configfile may not be abbreviated!"))
        if options["cwd"] != req.earlyoptions["cwd"]:
            raise error.Abort(_("option --cwd may not be abbreviated!"))
        if options["repository"] != req.earlyoptions["repository"]:
            raise error.Abort(
                _(
                    "option -R has to be separated from other options (e.g. not "
                    "-qR) and --repository may only be abbreviated as --repo!"
                )
            )
        if options["debugger"] != req.earlyoptions["debugger"]:
            raise error.Abort(_("option --debugger may not be abbreviated!"))
        # don't validate --profile/--traceback, which can be enabled from now

        if options["time"]:

            def get_times():
                t = os.times()
                if t[4] == 0.0:
                    # Windows leaves this as zero, so use time.clock()
                    if sys.version_info[0] >= 3:
                        x = time.perf_counter()
                    else:
                        x = time.clock()
                    t = (t[0], t[1], t[2], t[3], x)
                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])
                )

            ui.atexit(print_time)
        if options["profile"]:
            profiler.start()

        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 options["insecure"]:
            for ui_ in uis:
                ui_.insecureconnections = True

        if util.parsebool(options["pager"]):
            # ui.pager() expects 'internal-always-' prefix in this case
            ui.pager("internal-always-" + cmd)
        elif options["pager"] != "auto":
            for ui_ in uis:
                ui_.disablepager()

        if options["version"]:
            return commands.version_(ui)
        if options["help"]:
            if len(foundaliases) > 0:
                aliascmd = foundaliases[0]
                return commands.help_(ui, aliascmd, command=cmd is not None)

            return commands.help_(ui, cmd, command=cmd is not None)
        elif not cmd:
            return commands.help_(ui)

        msg = _formatargs(fullargs)
        with perftrace.trace("Main Python Command"):
            repo = None
            if func.cmdtemplate:
                templ = cmdtemplatestate(ui, cmdoptions)
                args.insert(0, templ)
                ui.atexit(templ.end)
            cmdpats = args[:]
            if not func.norepo:
                # 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, presetupfuncs=req.prereposetups
                        )
                        if not repo.local():
                            raise error.Abort(_("repository '%s' is not local") % path)
                        _initblackbox(req, repo, func.cmdtype)
                        scmutil.setup(repo.ui)
                        repo.ui.setconfig("bundle", "mainreporoot", repo.root, "repo")
                    except error.RequirementError:
                        raise
                    except error.RepoError:
                        if rpath:  # invalid -R path
                            raise
                        if not func.optionalrepo:
                            if func.inferrepo and args and not path:
                                # try to infer -R from command args
                                repos = pycompat.maplist(cmdutil.findrepo, args)
                                guess = repos[0]
                                if guess and repos.count(guess) == len(repos):
                                    req.args = ["--repository", guess] + fullargs
                                    req.earlyoptions["repository"] = guess
                                    return _dispatch(req)
                            if not path:
                                raise error.RepoError(
                                    _(
                                        "'%s' is not inside a repository, but this command requires a repository"
                                    )
                                    % pycompat.getcwd(),
                                    hint=_(
                                        "use 'cd' to go to a directory inside a repository and try again"
                                    ),
                                )
                            raise
                if repo:
                    ui = repo.ui
                    if options["hidden"]:
                        repo.ui.setconfig("visibility", "all-heads", "true", "--hidden")
                    if repo != req.repo:
                        ui.atexit(repo.close)

                    # Stuff this in to the request so exception handling code has access to repo/repo.ui.
                    req.cmdrepo = repo
                args.insert(0, repo)
            elif rpath:
                ui.warn(_("warning: --repository ignored\n"))

            from . import mdiff, match as matchmod

            mdiff.init(ui)
            matchmod.init(ui)

            ui.log("command", "%s\n", msg)
            if repo:
                repo.dirstate.loginfo(ui, "pre")
            strcmdopt = cmdoptions
            d = lambda: util.checksignature(func)(ui, *args, **strcmdopt)
            ret = runcommand(
                lui, repo, cmd, fullargs, ui, options, d, cmdpats, cmdoptions
            )
            hintutil.show(lui)
            if repo:
                repo.dirstate.loginfo(ui, "post")
            return ret