core.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. """Result and context types shared by every resolver, plus passive command location.
  2. `locate_command` reads only file metadata. It never opens a file, spawns, or connects.
  3. """
  4. from __future__ import annotations
  5. import os
  6. import shutil
  7. from dataclasses import dataclass, field
  8. from enum import Enum
  9. from typing import Generic, Literal, TypeVar
  10. Kind = Literal["explicit_path", "path_executable", "known_path", "package_runner", "missing"]
  11. T = TypeVar("T")
  12. class _Absent:
  13. __slots__ = ()
  14. def __repr__(self) -> str:
  15. return "ABSENT"
  16. ABSENT = _Absent()
  17. class CheckState(Enum):
  18. NOT_CHECKED = "not_checked"
  19. PRESENT = "present"
  20. ABSENT = "absent"
  21. UNAVAILABLE = "unavailable"
  22. ERROR = "error"
  23. @dataclass(frozen=True)
  24. class Observation(Generic[T]):
  25. """One checked fact. Consumers branch on `state`; `detail` is never parsed."""
  26. state: CheckState
  27. value: T | None = None
  28. detail: str = ""
  29. @classmethod
  30. def not_checked(cls) -> Observation[T]:
  31. return cls(CheckState.NOT_CHECKED)
  32. @dataclass(frozen=True)
  33. class Candidate:
  34. value: str
  35. source: str
  36. present: bool
  37. @dataclass(frozen=True)
  38. class LookupContext:
  39. """`path`: ABSENT = caller did not say (ambient), None = ambient, "" = search nothing."""
  40. path: str | None | _Absent = ABSENT
  41. pathext: str | None = None
  42. def effective_path(self) -> str | None:
  43. if isinstance(self.path, str):
  44. return self.path
  45. return None
  46. @dataclass(frozen=True)
  47. class Resolution:
  48. kind: Kind
  49. candidates: tuple[Candidate, ...] = field(default_factory=tuple)
  50. @property
  51. def command(self) -> tuple[str, ...]:
  52. first = next((c for c in self.candidates if c.present), None)
  53. return (first.value,) if first else ()
  54. @property
  55. def source(self) -> str:
  56. first = next((c for c in self.candidates if c.present), None)
  57. return first.source if first else "none"
  58. @property
  59. def present(self) -> tuple[Candidate, ...]:
  60. return tuple(c for c in self.candidates if c.present)
  61. @property
  62. def found(self) -> bool:
  63. return self.kind != "missing"
  64. def _which(name: str, ctx: LookupContext) -> str | None:
  65. if ctx.path == "":
  66. return None
  67. if ctx.pathext is not None and os.name == "nt":
  68. # shutil.which reads PATHEXT from os.environ; an explicit pathext is honored without mutating it.
  69. exts = [e for e in ctx.pathext.split(os.pathsep) if e]
  70. for ext in ["", *exts]:
  71. hit = shutil.which(name + ext, path=ctx.effective_path())
  72. if hit:
  73. return hit
  74. return None
  75. return shutil.which(name, path=ctx.effective_path())
  76. def _is_executable_file(path: str) -> bool:
  77. return os.path.isfile(path) and os.access(path, os.X_OK)
  78. def _expand(path: str) -> str:
  79. return os.path.expandvars(os.path.expanduser(path))
  80. def locate_command(name: str, ctx: LookupContext | None = None, *, known_dirs: tuple[str, ...] = ()) -> Resolution:
  81. """Find `name` on PATH, then in `known_dirs`, recording every candidate in probe order."""
  82. ctx = ctx or LookupContext()
  83. name = name.strip()
  84. if os.sep in name or (os.altsep and os.altsep in name):
  85. expanded = _expand(name)
  86. # A relative explicit path would resolve against the ambient cwd; only absolute paths are trusted.
  87. present = os.path.isabs(expanded) and _is_executable_file(expanded)
  88. cand = Candidate(expanded, "explicit", present)
  89. return Resolution("explicit_path" if present else "missing", (cand,))
  90. candidates: list[Candidate] = []
  91. hit = _which(name, ctx)
  92. candidates.append(Candidate(hit or name, "PATH", hit is not None))
  93. for d in known_dirs:
  94. base = os.path.join(_expand(d), name)
  95. found = next((v for v in _known_dir_variants(base) if _is_executable_file(v)), None)
  96. candidates.append(Candidate(found or base, f"known_dir:{d}", found is not None))
  97. kind: Kind = "missing"
  98. for c in candidates:
  99. if c.present:
  100. kind = "path_executable" if c.source == "PATH" else "known_path"
  101. break
  102. return Resolution(kind, tuple(candidates))
  103. def _known_dir_variants(base: str) -> tuple[str, ...]:
  104. """On Windows a bare name in a known dir may carry any PATHEXT suffix; one candidate is recorded per dir."""
  105. if os.name != "nt":
  106. return (base,)
  107. exts = [e for e in os.environ.get("PATHEXT", ".EXE;.CMD;.BAT").split(os.pathsep) if e]
  108. return (base, *[base + e for e in exts])