|
| 1 | +"""Utility functions and variables which are useful for all scripts.""" |
| 2 | +import difflib |
| 3 | +import importlib.util |
| 4 | +import os |
| 5 | +import pathlib |
| 6 | +import typing |
| 7 | + |
| 8 | + |
| 9 | +MODMAIL_DIR = pathlib.Path(importlib.util.find_spec("modmail").origin).parent |
| 10 | +PROJECT_DIR = MODMAIL_DIR.parent |
| 11 | +try: |
| 12 | + import pygments |
| 13 | +except ModuleNotFoundError: |
| 14 | + pygments = None |
| 15 | +else: |
| 16 | + from pygments.formatters import Terminal256Formatter |
| 17 | + from pygments.lexers.diff import DiffLexer |
| 18 | + |
| 19 | + |
| 20 | +class CheckFileEdit: |
| 21 | + """Check if a file is edited within the body of this class.""" |
| 22 | + |
| 23 | + def __init__(self, *files: os.PathLike): |
| 24 | + self.files: typing.List[pathlib.Path] = [] |
| 25 | + for f in files: |
| 26 | + self.files.append(pathlib.Path(f)) |
| 27 | + self.return_value: typing.Optional[int] = None |
| 28 | + self.edited_files: typing.Dict[pathlib.Path] = dict() |
| 29 | + |
| 30 | + def __enter__(self): |
| 31 | + self.file_contents = {} |
| 32 | + for file in self.files: |
| 33 | + try: |
| 34 | + with open(file, "r") as f: |
| 35 | + self.file_contents[file] = f.readlines() |
| 36 | + except FileNotFoundError: |
| 37 | + self.file_contents[file] = None |
| 38 | + return self |
| 39 | + |
| 40 | + def __exit__(self, exc_type, exc_value, exc_traceback): # noqa: ANN001 |
| 41 | + for file in self.files: |
| 42 | + with open(file, "r") as f: |
| 43 | + original_contents = self.file_contents[file] |
| 44 | + new_contents = f.readlines() |
| 45 | + if original_contents != new_contents: |
| 46 | + # construct a diff |
| 47 | + diff = difflib.unified_diff( |
| 48 | + original_contents, new_contents, fromfile="before", tofile="after" |
| 49 | + ) |
| 50 | + try: |
| 51 | + diff = "".join(diff) |
| 52 | + except TypeError: |
| 53 | + diff = None |
| 54 | + else: |
| 55 | + if pygments is not None: |
| 56 | + diff = pygments.highlight(diff, DiffLexer(), Terminal256Formatter()) |
| 57 | + self.edited_files[file] = diff |
| 58 | + |
| 59 | + def write(self, path: str, contents: typing.Union[str, bytes], *, force: bool = False, **kwargs) -> bool: |
| 60 | + """ |
| 61 | + Write to the provided path with contents. Must be within the context manager. |
| 62 | +
|
| 63 | + Returns False if contents are not edited, True if they are. |
| 64 | + If force is True, will modify the files even if the contents match. |
| 65 | +
|
| 66 | + Any extras kwargs are passed to open() |
| 67 | + """ |
| 68 | + path = pathlib.Path(path) |
| 69 | + if path not in self.files: |
| 70 | + raise AssertionError(f"{path} must have been passed to __init__") |
| 71 | + |
| 72 | + if not force: |
| 73 | + try: |
| 74 | + with open(path, "r") as f: |
| 75 | + if contents == f.read(): |
| 76 | + return False |
| 77 | + except FileNotFoundError: |
| 78 | + pass |
| 79 | + if isinstance(contents, str): |
| 80 | + contents = contents.encode() |
| 81 | + |
| 82 | + with open(path, "wb") as f: |
| 83 | + f.write(contents) |
| 84 | + |
| 85 | + return True |
0 commit comments