Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

4.4 KB
Raw Blame
"""Compatibility alias: this package is now ``dodaios``."""
# rename-stub: generated by scripts/rename/rewrite_package.py
# Do not add modules here. Old start commands (``python -m jarvis``,
# ``-m jarvis.ui.web.launcher``, ...) and old imports keep working: every
# ``jarvis.*`` name resolves to the SAME module object as its ``dodaios.*``
# twin, so no module is imported twice and no state exists twice.
#
# The file lives inside the ``dodaios`` directory so the repository has no
# ``jarvis`` folder, but it is never imported as ``dodaios._legacy_alias``:
# setup.py publishes this directory as the top-level ``jarvis`` package of every
# wheel, sdist and editable install.

from __future__ import annotations

import importlib
import importlib.abc
import importlib.machinery
import importlib.util
import os
import sys

_OLD = "jarvis"
_NEW = "dodaios"


def _real_name(name: str) -> str:
    return _NEW + name[len(_OLD) :]


class _AliasFinder(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader):
    """Answer ``jarvis.x`` with the module object of ``dodaios.x``."""

    def find_spec(self, fullname, path=None, target=None):  # noqa: ANN001, ANN201
        if not fullname.startswith(_OLD + "."):
            return None
        try:
            real = importlib.util.find_spec(_real_name(fullname))
        except (ImportError, ValueError):  # no parent package under the new name either
            return None
        if real is None:
            return None
        spec = importlib.machinery.ModuleSpec(
            fullname,
            self,
            origin=real.origin,
            is_package=real.submodule_search_locations is not None,
        )
        if real.submodule_search_locations is not None:
            spec.submodule_search_locations = list(real.submodule_search_locations)
        spec.has_location = real.has_location
        spec.cached = real.cached
        return spec

    def create_module(self, spec):  # noqa: ANN001, ANN201
        module = importlib.import_module(_real_name(spec.name))
        # The import system stamps the alias spec on whatever this returns;
        # ``exec_module`` puts the module's own spec back.
        spec.loader_state = getattr(module, "__spec__", None)
        return module

    def exec_module(self, module) -> None:  # noqa: ANN001
        # Already executed under its real name. It keeps its real spec, so a
        # reload, its resources and its relative imports behave as if the old
        # name had never been used.
        alias = getattr(module, "__spec__", None)
        real = getattr(alias, "loader_state", None)
        if real is not None and getattr(alias, "loader", None) is self:
            module.__spec__ = real

    # ``python -m jarvis.x`` asks the loader for code, not for a module.
    def _real_loader(self, fullname: str):  # noqa: ANN202
        spec = importlib.util.find_spec(_real_name(fullname))
        if spec is None or spec.loader is None:
            raise ImportError(f"no module named {fullname}", name=fullname)
        return spec.loader

    def get_code(self, fullname):  # noqa: ANN001, ANN201
        return self._real_loader(fullname).get_code(_real_name(fullname))

    def get_source(self, fullname):  # noqa: ANN001, ANN201
        return self._real_loader(fullname).get_source(_real_name(fullname))

    def is_package(self, fullname):  # noqa: ANN001, ANN201
        return self._real_loader(fullname).is_package(_real_name(fullname))


def _install() -> None:
    if not any(isinstance(finder, _AliasFinder) for finder in sys.meta_path):
        # First, so the path finder never builds a second copy from the real
        # package's directory under the old name.
        sys.meta_path.insert(0, _AliasFinder())
    try:
        real = importlib.import_module(_NEW)
    except ModuleNotFoundError as exc:
        if exc.name != _NEW:
            raise
        # An install that maps only the old name finds this file inside the
        # ``dodaios`` directory; the folder that holds that directory goes on
        # the path so the real package imports too.
        here = os.path.dirname(os.path.abspath(__file__))
        sys.path.append(os.path.dirname(os.path.dirname(here)))
        importlib.invalidate_caches()
        real = importlib.import_module(_NEW)
    prefix = _NEW + "."
    for name, module in list(sys.modules.items()):
        if name.startswith(prefix):
            sys.modules.setdefault(_OLD + name[len(_NEW) :], module)
    sys.modules[_OLD] = real


_install()