shell.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. """pm.shell(): the one place Hermes resolves the shell it runs commands with.
  2. Owned by pm because the shell is a bundled tool on Windows (Git for Windows
  3. carries bash.exe), and the store is the authority on whether it exists.
  4. Callers that need bash (the terminal backend, `_find_bash`) call this instead
  5. of hunting fixed locations.
  6. Resolution order:
  7. 1. Windows: the git Package's staged bash (via facts.json) — the store
  8. structurally guarantees it in a bundle; no hunt.
  9. 2. Windows: explicit override, Program Files, per-user and PortableGit,
  10. then PATH —
  11. minus C:\\Windows\\System32\bash.exe (the WSL launcher stub, first on PATH
  12. on most machines; #116818) and WindowsApps\bash.exe (an MSIX alias that
  13. only spawns inside its package). See windows_bash_candidates().
  14. 3. Provisioned PATH: shutil.which("bash") — the store dirs are on the
  15. process PATH after pm.activate() ran.
  16. 4. POSIX fallback table for non-bundle / daemon-launch PATH edge cases
  17. (/usr/bin/bash, /bin/bash, $SHELL, /bin/sh). A systemd/cron-launched
  18. gateway may have a minimal PATH and macOS /bin/bash is not on PATH by
  19. default, so `which` alone is not enough there.
  20. """
  21. from __future__ import annotations
  22. import ntpath
  23. import os
  24. import shutil
  25. import subprocess
  26. from collections.abc import Mapping
  27. from pm import paths
  28. from pm.lock import Facts
  29. def _staged_bash() -> str | None:
  30. """The git Package's bash.exe under the store (Windows bundles only)."""
  31. import platform
  32. if platform.system() != "Windows":
  33. return None
  34. facts_path = paths.facts_path()
  35. if not facts_path.is_file():
  36. return None
  37. try:
  38. facts = Facts(facts_path)
  39. fact = facts.get("git")
  40. if fact is None or "entry" not in fact:
  41. return None
  42. entry = paths.store_root() / fact["entry"]
  43. for candidate in (
  44. entry / "usr" / "bin" / "bash.exe",
  45. entry / "bin" / "bash.exe",
  46. ):
  47. if candidate.is_file():
  48. return str(candidate)
  49. except Exception:
  50. return None
  51. return None
  52. # PATH dirs whose bash.exe is not a shell: System32 holds the WSL launcher
  53. # stub (prints "no installed distributions", exits 1) and WindowsApps holds
  54. # MSIX execution aliases that fail with WinError 5 from an arbitrary process.
  55. _WINDOWS_BASH_STUB_DIRS = ("system32", "windowsapps")
  56. def windows_bash_candidates(on_path: str | None, env: Mapping[str, str]) -> list[str]:
  57. """Ordered bash.exe candidates for a Windows host, as pure data: the
  58. explicit override and Git for Windows roots first, then ``on_path``
  59. (the ``shutil.which("bash")`` result) unless it is a stub. System32
  60. precedes Git on most PATHs (#116818)."""
  61. programfiles = env.get("ProgramFiles", r"C:\Program Files")
  62. candidates = []
  63. if env.get("HERMES_GIT_BASH_PATH"):
  64. candidates.append(env["HERMES_GIT_BASH_PATH"])
  65. roots = [ntpath.join(programfiles, "Git")]
  66. if env.get("ProgramFiles(x86)"):
  67. roots.append(ntpath.join(env["ProgramFiles(x86)"], "Git"))
  68. if env.get("LOCALAPPDATA"):
  69. roots.extend((ntpath.join(env["LOCALAPPDATA"], "hermes", "git"),
  70. ntpath.join(env["LOCALAPPDATA"], "Programs", "Git")))
  71. for root in roots:
  72. candidates.extend((ntpath.join(root, "bin", "bash.exe"),
  73. ntpath.join(root, "usr", "bin", "bash.exe")))
  74. if on_path:
  75. norm = ntpath.normpath(on_path).lower()
  76. if not any(stub in norm for stub in _WINDOWS_BASH_STUB_DIRS):
  77. candidates.append(on_path)
  78. return list(dict.fromkeys(candidates))
  79. def _bash_starts(candidate: str) -> bool:
  80. """An existing bash.exe can still be broken or be a launcher stub."""
  81. try:
  82. return subprocess.run(
  83. [candidate, "-c", "exit 0"], stdin=subprocess.DEVNULL,
  84. stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
  85. timeout=5, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
  86. check=False,
  87. ).returncode == 0
  88. except (OSError, subprocess.TimeoutExpired):
  89. return False
  90. def bash() -> str | None:
  91. """Resolve the bash binary to use, or None if none is available."""
  92. staged = _staged_bash()
  93. if staged and _bash_starts(staged):
  94. return staged
  95. on_path = shutil.which("bash")
  96. if os.name == "nt":
  97. return next((c for c in windows_bash_candidates(on_path, os.environ)
  98. if os.path.isfile(c) and _bash_starts(c)), None)
  99. if on_path:
  100. return on_path
  101. # POSIX fallbacks for minimal-PATH daemon launches / macOS /bin/bash.
  102. for candidate in (
  103. "/usr/bin/bash",
  104. "/bin/bash",
  105. os.environ.get("SHELL"),
  106. "/bin/sh",
  107. ):
  108. if candidate and os.path.isfile(candidate) and os.access(candidate, os.X_OK):
  109. return candidate
  110. return None