--- a/src/ki18n/ki18n.py +++ b/src/ki18n/ki18n.py @@ -33,6 +33,8 @@ from pathlib import Path from typing import Any +from .paths import bundle_root, is_frozen + DEFAULT_LANGUAGE = "en" log = logging.getLogger(__name__) @@ -71,7 +73,9 @@ """A process-wide internationalization manager. ``project_root`` is the application directory containing its installation - ``i18n`` directory. If omitted, it is derived from ``sys.argv[0]``. + ``i18n`` directory. If omitted, the application root returned by + :func:`ki18n.paths.bundle_root` is used, which does not depend on where + ``ki18n`` itself is located. Resources under the user's application data directory take precedence over resources installed with the application: ``strings.json`` files are merged key by key (a subset is enough), other files such as ``help.md`` are @@ -100,8 +104,8 @@ """Create the manager (only the first construction has an effect). ``project_root`` is the directory containing the installed ``i18n`` - folder. ``local_root`` is the application's per-user directory (for - example ``~/.local/share/my-app``); user resources are read from its + folder; if omitted it is :func:`ki18n.paths.bundle_root`. + ``local_root`` is the application's per-user directory (for example ``~/.local/share/my-app``); user resources are read from its ``i18n`` subfolder. If omitted, the directory is derived from the user data directory and the name of ``project_root``. ``key_aliases`` maps former keys to current keys for the user's strings files. @@ -115,17 +119,14 @@ raise ValueError(f"Invalid default language: {default_language!r}") from exc if project_root is None: - executable = Path(sys.argv[0]) - if not executable.is_absolute(): - executable = Path.cwd() / executable - root = executable.resolve().parent + root = bundle_root().resolve() else: root = Path(project_root).expanduser().resolve() self.default_language = default_language self.project_root = root self.i18n_root = root / "i18n" - self._app_name = root.name or "app" + self._app_name = self._default_app_name(root) if local_root is None: self.local_root = self._user_data_root() / self._app_name else: @@ -149,6 +150,20 @@ self._initialized = True @staticmethod + def _default_app_name(root: Path) -> str: + """Name used for the default per-user data directory. + + Normally the name of ``root``. In a frozen one-file build ``root`` is a + temporary extraction directory whose name changes on every start, so the + name of the executable is used instead. + """ + if is_frozen(): + meipass = getattr(sys, "_MEIPASS", None) + if meipass and root == Path(meipass).resolve(): + return Path(sys.executable).stem or "app" + return root.name or "app" + + @staticmethod def _user_data_root() -> Path: """Return the conventional per-user application data directory.""" if os.name == "nt":