user_facing.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. """The terminal's PATH: the user's own tools first, Hermes's after them.
  2. Hermes's process puts its store's tool dirs first (``pm.install.activate``), so Hermes's own
  3. code resolves the pinned binaries. Terminal commands belong to the user and the agent, so they
  4. run the tools the user installed, and Hermes's tools are the fallback for a machine without
  5. them. Hermes's own operations must not depend on this PATH: they resolve pinned tools
  6. through PM (``pm.env_for``, ``pm.installed_package``).
  7. A sealed Windows payload's store sits under ``WindowsApps``. In the process tree that the
  8. app's execution alias starts, a program whose own executable is outside the package cannot
  9. start one inside it: cmd.exe running npm's ``npx.cmd`` gets "Access is denied" from the
  10. packaged ``node.exe``, and a venv's ``Scripts\\python.exe`` redirector exits 101 when it
  11. starts the packaged Python. A copy of the same files outside the package starts without
  12. error, so there :func:`copies` swaps those dirs for PM's verified copies.
  13. """
  14. from __future__ import annotations
  15. import logging
  16. import os
  17. from pathlib import Path
  18. LOG = logging.getLogger(__name__)
  19. # Packages whose packaged dirs a sealed Windows payload swaps for writable copies.
  20. COPIED = ("npm", "node", "python")
  21. def applies() -> bool:
  22. """True for a sealed payload on Windows, the only layout with the restriction above."""
  23. from pm.install import sealed
  24. from pm.store import current_target
  25. return current_target().startswith("win32") and sealed()
  26. def writable_copy(name: str, *, realize: bool = True, explicit: bool = False,
  27. why: str = "a copy outside the package is required"):
  28. """``(facts, store)`` of PM's verified copy of the installed *name* in the writable store.
  29. The first call copies the installed entry and checks its digest. It downloads nothing.
  30. If the install already lives in the writable store, that install is the answer. Returns
  31. ``None`` when *name* is not installed, or when no copy exists and *realize* is false.
  32. Raises the lazy-install refusal, naming *why*, when a copy is needed and lazy installs
  33. are off.
  34. """
  35. from pm import paths
  36. from pm.filesystem import long_root
  37. from pm.install import _install, _installed_location, _lockfile, _refuse_lazy, lazy_installs_allowed
  38. from pm.lock import Facts
  39. from pm.registry import get_package
  40. from pm.store import Store, current_target
  41. package, lockfile, target = get_package(name), _lockfile(), current_target()
  42. location = _installed_location(package, lockfile, target)
  43. if location is None:
  44. return None
  45. # Spelled like Store spells its root, so the comparison and the copy's file calls agree.
  46. writable = long_root(paths.writable_store_root())
  47. if location[1].root == writable:
  48. return location
  49. copied = _installed_location(package, lockfile, target, verify=explicit, roots=(writable,))
  50. if copied is not None or not realize:
  51. return copied
  52. if not explicit and not lazy_installs_allowed():
  53. raise _refuse_lazy(name, why)
  54. copy_store, copy_facts = Store(writable), Facts(writable / "facts.json")
  55. _install(package, lockfile, copy_facts, copy_store, target, copy_from=location)
  56. return copy_facts, copy_store
  57. def _dirs(facts, store, name: str) -> list[str]:
  58. """The PATH dirs that *store*'s install of *name* contributes, natively spelled."""
  59. from pm.filesystem import native
  60. dirs = facts.env_for(name, store.root).get("PATH") or []
  61. return [native(d) for d in ([dirs] if isinstance(dirs, str) else dirs) if d]
  62. def _sealed_dirs(name: str) -> list[str]:
  63. from pm.install import _facts, _store
  64. facts, store = _facts(), _store()
  65. return _dirs(facts, store, name) if facts.installed(name, None, store.root) else []
  66. def _copy_dirs(name: str) -> list[str]:
  67. """The PATH dirs of *name*'s writable copy, made on first use, or ``[]`` when PM may not make one."""
  68. from pm.package import InstallError
  69. try:
  70. location = writable_copy(name)
  71. except (InstallError, OSError) as exc:
  72. LOG.debug("user-facing %s stays the packaged copy: %s", name, exc)
  73. return []
  74. return _dirs(*location, name) if location is not None else []
  75. def copies(dirs: list[str]) -> list[str]:
  76. """*dirs* with each packaged npm, node and python dir swapped for its writable copy on a
  77. sealed Windows payload. A packaged dir stays when PM may not copy it (lazy installs off)."""
  78. if not applies():
  79. return list(dirs)
  80. swap: dict[str, list[str]] = {}
  81. for name in COPIED:
  82. sealed = _sealed_dirs(name)
  83. copied = _copy_dirs(name) if sealed else []
  84. if copied:
  85. swap.update((os.path.normcase(d), copied) for d in sealed)
  86. return list(dict.fromkeys(c for d in dirs for c in swap.get(os.path.normcase(d), [d])))
  87. def _python_stub_dir(directory: str) -> bool:
  88. """True for the Windows app-alias dir when its ``python.exe`` is only the Store stub.
  89. The stub opens the Microsoft Store instead of running Python. A real Store Python puts its
  90. aliases in the same dir, and it also ships a ``python3.N.exe``, which the stub does not.
  91. """
  92. parts = [os.path.normcase(part) for part in Path(directory).parts[-2:]]
  93. if parts != [os.path.normcase("Microsoft"), os.path.normcase("WindowsApps")]:
  94. return False
  95. try:
  96. return not any(Path(directory).glob("python3.*.exe"))
  97. except OSError:
  98. return True
  99. def _python_dirs() -> list[str]:
  100. from pm.install import env_for
  101. return [d for d in env_for("python", base_env={"PATH": ""}).get("PATH", "").split(os.pathsep) if d]
  102. def user_facing_path(path: str) -> str:
  103. """*path* with Hermes's store tool dirs (their writable copies, see :func:`copies`) moved
  104. behind the user's own entries.
  105. Hermes's Python stops just before the app-alias dir that holds the Store stub, so a
  106. machine without Python still runs a real one.
  107. """
  108. from pm.install import _store_path_dirs
  109. store = _store_path_dirs()
  110. if not store:
  111. return path
  112. ours = copies(store)
  113. keys = {os.path.normcase(d) for d in (*store, *ours)}
  114. kept = [p for p in path.split(os.pathsep) if p and os.path.normcase(p) not in keys]
  115. python = {os.path.normcase(d) for d in copies(_python_dirs())}
  116. cut = next((i for i, p in enumerate(kept) if _python_stub_dir(p)), len(kept))
  117. early = [d for d in ours if os.path.normcase(d) in python]
  118. late = [d for d in ours if os.path.normcase(d) not in python]
  119. return os.pathsep.join(dict.fromkeys([*kept[:cut], *early, *kept[cut:], *late]))