plugin_inputs.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. """What a venv sync or currency probe should take as its plugin members.
  2. Each request names exactly one source, so conflicting member inputs cannot be
  3. expressed. Stdlib only: the client, the worker and the engine all import it.
  4. """
  5. from __future__ import annotations
  6. from collections.abc import Mapping, Sequence
  7. from dataclasses import dataclass
  8. from pathlib import Path
  9. @dataclass(frozen=True)
  10. class Members:
  11. """Build exactly these members and skip config discovery.
  12. A mapping keys each member's installed identity to the tree that supplies it."""
  13. dirs: Sequence[Path] | Mapping[Path, Path]
  14. @dataclass(frozen=True)
  15. class Candidates:
  16. """Discover the enabled members and add these candidate directories."""
  17. dirs: Sequence[Path]
  18. @dataclass(frozen=True)
  19. class Selection:
  20. """Publish a proposed plugin enablement with the members it implies."""
  21. data: Mapping
  22. @dataclass(frozen=True)
  23. class StagedUpdate:
  24. """Publish a staged plugin tree over its install."""
  25. data: Mapping
  26. PluginInput = Members | Candidates | Selection | StagedUpdate
  27. def encode(plugins: PluginInput | None) -> dict | None:
  28. """JSON form for the worker request; paths become absolute strings."""
  29. if plugins is None:
  30. return None
  31. if isinstance(plugins, Members):
  32. if isinstance(plugins.dirs, Mapping):
  33. return {"kind": "members", "sources": [[str(Path(key).absolute()), str(Path(source).absolute())]
  34. for key, source in plugins.dirs.items()]}
  35. return {"kind": "members", "paths": [str(Path(path).absolute()) for path in plugins.dirs]}
  36. if isinstance(plugins, Candidates):
  37. return {"kind": "candidates", "paths": [str(Path(path).absolute()) for path in plugins.dirs]}
  38. kind = "selection" if isinstance(plugins, Selection) else "staged"
  39. return {"kind": kind, "data": dict(plugins.data)}
  40. def decode(value: dict | None) -> PluginInput | None:
  41. if value is None:
  42. return None
  43. kind = value["kind"]
  44. if kind == "members":
  45. if "sources" in value:
  46. return Members({Path(identity): Path(source) for identity, source in value["sources"]})
  47. return Members([Path(path) for path in value["paths"]])
  48. if kind == "candidates":
  49. return Candidates([Path(path) for path in value["paths"]])
  50. if kind == "selection":
  51. return Selection(value["data"])
  52. if kind == "staged":
  53. return StagedUpdate(value["data"])
  54. raise ValueError(f"unknown plugin input kind: {kind!r}")