hatch_build.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. """Custom build hook for Hatch."""
  2. import importlib.util
  3. import pathlib
  4. import subprocess
  5. import sys
  6. from typing import Any
  7. from hatchling.builders.hooks.plugin.interface import BuildHookInterface
  8. class CustomBuilder(BuildHookInterface):
  9. """Custom build hook for Hatch."""
  10. PLUGIN_NAME = "custom"
  11. def marker(self) -> pathlib.Path:
  12. """Get the marker file path.
  13. Returns:
  14. The marker file path.
  15. """
  16. return (
  17. pathlib.Path(self.directory)
  18. / f".reflex-{self.metadata.version}.pyi_generated"
  19. )
  20. def finalize(
  21. self, version: str, build_data: dict[str, Any], artifact_path: str
  22. ) -> None:
  23. """Finalize the build process.
  24. Args:
  25. version: The version of the package.
  26. build_data: The build data.
  27. artifact_path: The path to the artifact.
  28. """
  29. if self.marker().exists():
  30. return
  31. if importlib.util.find_spec("pre_commit"):
  32. import pre_commit.yaml
  33. from diff_match_patch import diff_match_patch
  34. patch = """@@ -82,16 +82,28 @@
  35. ort yaml
  36. +%0Aimport toml
  37. %0A%0ALoader
  38. @@ -209,24 +209,28 @@
  39. der=Loader)%0A
  40. +def
  41. yaml_load =
  42. @@ -226,37 +226,145 @@
  43. aml_load
  44. - = functools.partial(
  45. +(stream):%0A try:%0A return toml.loads(stream).get(%22tool%22, %7B%7D).get(%22pre-commit%22, %7B%7D)%0A except ValueError:%0A return
  46. yaml.loa
  47. @@ -364,16 +364,23 @@
  48. aml.load
  49. +(stream
  50. , Loader
  51. """ # noqa: W291
  52. dmp = diff_match_patch()
  53. patches = dmp.patch_fromText(patch)
  54. new_text, _ = dmp.patch_apply(
  55. patches, pathlib.Path(pre_commit.yaml.__file__).read_text()
  56. )
  57. pathlib.Path(pre_commit.yaml.__file__).write_text(new_text)
  58. if not (pathlib.Path(self.root) / "scripts").exists():
  59. return
  60. for file in (pathlib.Path(self.root) / "reflex").rglob("**/*.pyi"):
  61. file.unlink(missing_ok=True)
  62. subprocess.run(
  63. [sys.executable, "-m", "reflex.utils.pyi_generator"],
  64. check=True,
  65. )
  66. self.marker().touch()