helpers.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import contextlib
  2. import pathlib
  3. from pathlib import Path
  4. import re
  5. import time
  6. from typing import Union
  7. from unittest import mock
  8. def flatten_result(result):
  9. return re.sub(r"[\s\r\n]+", " ", result).strip()
  10. def result_lines(result):
  11. return [
  12. x.strip()
  13. for x in re.split(r"\r?\n", re.sub(r" +", " ", result))
  14. if x.strip() != ""
  15. ]
  16. def result_raw_lines(result):
  17. return [x for x in re.split(r"\r?\n", result) if x.strip() != ""]
  18. def make_path(
  19. filespec: Union[Path, str],
  20. make_absolute: bool = True,
  21. check_exists: bool = False,
  22. ) -> Path:
  23. path = Path(filespec)
  24. if make_absolute:
  25. path = path.resolve(strict=check_exists)
  26. if check_exists and (not path.exists()):
  27. raise FileNotFoundError(f"No file or directory at {filespec}")
  28. return path
  29. def _unlink_path(path, missing_ok=False):
  30. # Replicate 3.8+ functionality in 3.7
  31. cm = contextlib.nullcontext()
  32. if missing_ok:
  33. cm = contextlib.suppress(FileNotFoundError)
  34. with cm:
  35. path.unlink()
  36. def replace_file_with_dir(pathspec):
  37. path = pathlib.Path(pathspec)
  38. _unlink_path(path, missing_ok=True)
  39. path.mkdir(exist_ok=True)
  40. return path
  41. def file_with_template_code(filespec):
  42. with open(filespec, "w") as f:
  43. f.write(
  44. """
  45. i am an artificial template just for you
  46. """
  47. )
  48. return filespec
  49. @contextlib.contextmanager
  50. def rewind_compile_time(hours=1):
  51. rewound = time.time() - (hours * 3_600)
  52. with mock.patch("mako.codegen.time") as codegen_time:
  53. codegen_time.time.return_value = rewound
  54. yield