base_output_printer.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. # Copyright Materialize, Inc. and contributors. All rights reserved.
  2. #
  3. # Use of this software is governed by the Business Source License
  4. # included in the LICENSE file at the root of this repository.
  5. #
  6. # As of the Change Date specified in that file, in accordance with
  7. # the Business Source License, use of this software will be governed
  8. # by the Apache License, Version 2.0.
  9. import re
  10. from enum import Enum
  11. from materialize.output_consistency.output.format_constants import (
  12. COMMENT_PREFIX,
  13. OUTPUT_LINE_SEPARATOR,
  14. SECTION_COLLAPSED_PREFIX,
  15. SECTION_EXPANDED_PREFIX,
  16. )
  17. class OutputPrinterMode(Enum):
  18. PRINT = 1
  19. COLLECT = 2
  20. class BaseOutputPrinter:
  21. def __init__(self, print_mode: OutputPrinterMode = OutputPrinterMode.PRINT):
  22. self.print_mode = print_mode
  23. self.collected_output = []
  24. def print_empty_line(self) -> None:
  25. self._print_raw("")
  26. def start_section(self, header: str, collapsed: bool = True) -> None:
  27. prefix = SECTION_COLLAPSED_PREFIX if collapsed else SECTION_EXPANDED_PREFIX
  28. self._print_raw(f"{prefix}{header}")
  29. def print_separator_line(self) -> None:
  30. self._print_text(OUTPUT_LINE_SEPARATOR)
  31. def _print_executable(self, sql: str) -> None:
  32. self._print_raw(sql)
  33. def _print_text(self, text: str) -> None:
  34. adjusted_text = re.sub("\n", f"\n{COMMENT_PREFIX}", text)
  35. adjusted_text = f"{COMMENT_PREFIX}{adjusted_text}"
  36. self._print_raw(adjusted_text)
  37. def _print_raw(self, sql: str) -> None:
  38. if self.print_mode == OutputPrinterMode.PRINT:
  39. print(sql)
  40. elif self.print_mode == OutputPrinterMode.COLLECT:
  41. self.collected_output.append(sql)
  42. else:
  43. raise RuntimeError(f"Unsupported mode: {self.print_mode}")