|
| 1 | +import io |
| 2 | +import json |
| 3 | +import logging |
| 4 | +import os |
| 5 | +import select |
| 6 | +import subprocess |
| 7 | +import time |
| 8 | + |
| 9 | +from unidiff import PatchedFile, PatchSet |
| 10 | + |
| 11 | +from codegen.utils.performance.stopwatch_utils import stopwatch |
| 12 | + |
| 13 | +logger = logging.getLogger(__name__) |
| 14 | + |
| 15 | +HIGHLIGHTED_DIFF_FILENAME = "highlighted_diff.json" |
| 16 | + |
| 17 | + |
| 18 | +@stopwatch |
| 19 | +def syntax_highlight_modified_files(codebase, raw_diff: str, flags: list[dict]) -> str: |
| 20 | + modified_files = PatchSet(io.StringIO(raw_diff)) |
| 21 | + highlighted_files = {} |
| 22 | + highlighted_diff_files = {} |
| 23 | + |
| 24 | + # TODO: refactor this |
| 25 | + with subprocess.Popen( |
| 26 | + ". ~/.bashrc > /dev/null && nvm use > /dev/null && yarn run --silent highlight", |
| 27 | + shell=True, |
| 28 | + cwd="/codegen/codegen-frontend/app/modules/syntaxHighlight", |
| 29 | + stdin=subprocess.PIPE, |
| 30 | + stdout=subprocess.PIPE, |
| 31 | + stderr=subprocess.PIPE, |
| 32 | + text=True, |
| 33 | + bufsize=1, |
| 34 | + universal_newlines=True, |
| 35 | + ) as highlighter: |
| 36 | + poll = select.poll() |
| 37 | + poll.register(highlighter.stdout, select.POLLIN) |
| 38 | + |
| 39 | + for file in modified_files: |
| 40 | + filename = file.path |
| 41 | + modified_filename = file.target_file |
| 42 | + highlighted_files[filename] = ( |
| 43 | + "" if file.is_removed_file else _highlight_file(highlighter, poll, modified_filename if not modified_filename.startswith("b/") else modified_filename[2:], flags) |
| 44 | + ) |
| 45 | + |
| 46 | + codebase.stash_changes() |
| 47 | + |
| 48 | + for file in modified_files: |
| 49 | + filename = file.path |
| 50 | + original_filename = file.source_file |
| 51 | + original = "" if file.is_added_file else _highlight_file(highlighter, poll, original_filename if not original_filename.startswith("a/") else original_filename[2:], flags) |
| 52 | + modified = highlighted_files[filename] |
| 53 | + highlighted_hunks = _construct_diff_highlight(codebase, original.splitlines(), modified.splitlines(), file) |
| 54 | + highlighted_diff_files[filename] = highlighted_hunks |
| 55 | + |
| 56 | + try: |
| 57 | + codebase.restore_stashed_changes() |
| 58 | + except Exception as e: |
| 59 | + # This can happen if there are no changes stashed in the first place |
| 60 | + logger.warning(f"Error restoring stashed changes: {e}") |
| 61 | + |
| 62 | + _, err = highlighter.communicate() |
| 63 | + returncode = highlighter.returncode |
| 64 | + |
| 65 | + if err: |
| 66 | + logger.error(f"Highlighter exited with error: {err}") |
| 67 | + |
| 68 | + if returncode != 0: |
| 69 | + raise Exception(f"Highlighter exited with code {returncode}") |
| 70 | + |
| 71 | + highlighted_diff = json.dumps(highlighted_diff_files) |
| 72 | + logger.info(f"Generated highlighted diff (size={len(highlighted_diff)})") |
| 73 | + return highlighted_diff |
| 74 | + |
| 75 | + |
| 76 | +@stopwatch |
| 77 | +def _highlight_file(highlighter: subprocess.Popen[str], poll: select.poll, filename: str, flags: list[dict]): |
| 78 | + stdin_input = { |
| 79 | + "file": f"{os.getcwd()}/{filename}", |
| 80 | + "flags": list(filter(lambda flag: flag["filepath"] == filename, flags)), |
| 81 | + } |
| 82 | + stdin_input = json.dumps(stdin_input) |
| 83 | + |
| 84 | + logger.info(f"> Highlighting {filename}...") |
| 85 | + highlighter.stdin.write(f"{stdin_input}\n") |
| 86 | + highlighter.stdin.flush() |
| 87 | + highlighted = "" |
| 88 | + |
| 89 | + while True: |
| 90 | + # if monotonic.monotonic() > timeout_at: |
| 91 | + # raise Exception("Syntax highlighter timed out") |
| 92 | + # |
| 93 | + # poll_result = poll.poll(0.01) |
| 94 | + # |
| 95 | + # if not poll_result: |
| 96 | + # continue |
| 97 | + |
| 98 | + # TODO: this can deadlock in case the subprocess does not write a newline |
| 99 | + line = highlighter.stdout.readline() |
| 100 | + |
| 101 | + if not line: |
| 102 | + time.sleep(0.01) |
| 103 | + |
| 104 | + if line == "\x03\n": |
| 105 | + break |
| 106 | + |
| 107 | + highlighted += line |
| 108 | + |
| 109 | + return highlighted |
| 110 | + |
| 111 | + |
| 112 | +def _construct_diff_highlight(codebase, source: list[str], target: list[str], patched_file: PatchedFile) -> list: |
| 113 | + original_lines = 0 |
| 114 | + modified_lines = 0 |
| 115 | + full_file = "" |
| 116 | + full_file_lines = 0 |
| 117 | + highlighted_hunks = [] |
| 118 | + |
| 119 | + for hunk in patched_file: |
| 120 | + hunk_lines = "" |
| 121 | + |
| 122 | + while original_lines < (hunk.source_start - 1): |
| 123 | + full_file += f" {source[original_lines]}\n" |
| 124 | + full_file_lines += 1 |
| 125 | + original_lines += 1 |
| 126 | + modified_lines += 1 |
| 127 | + |
| 128 | + for line in hunk: |
| 129 | + if line.is_removed: |
| 130 | + full_file += f"-{source[original_lines]}\n" |
| 131 | + hunk_lines += f"-{source[original_lines]}\n" |
| 132 | + original_lines += 1 |
| 133 | + full_file_lines += 1 |
| 134 | + elif line.is_added: |
| 135 | + full_file += f"+{target[modified_lines]}\n" |
| 136 | + hunk_lines += f"+{target[modified_lines]}\n" |
| 137 | + modified_lines += 1 |
| 138 | + full_file_lines += 1 |
| 139 | + else: |
| 140 | + if len(source) > original_lines: |
| 141 | + full_file += f" {source[original_lines]}\n" |
| 142 | + hunk_lines += f" {source[original_lines]}\n" |
| 143 | + elif len(target) > modified_lines: |
| 144 | + full_file += f" {target[modified_lines]}\n" |
| 145 | + hunk_lines += f" {target[modified_lines]}\n" |
| 146 | + else: |
| 147 | + logger.warning(f"Lines {original_lines}/{modified_lines} not found in {patched_file.path} in {codebase.current_commit.hexsha}: {line}") |
| 148 | + original_lines += 1 |
| 149 | + modified_lines += 1 |
| 150 | + full_file_lines += 1 |
| 151 | + |
| 152 | + if hunk_lines.endswith("\n"): |
| 153 | + hunk_lines = hunk_lines[:-1] |
| 154 | + |
| 155 | + highlighted_hunks.append({"lines": hunk_lines, "starts_at": full_file_lines - len(hunk), "ends_at": full_file_lines - 1}) |
| 156 | + |
| 157 | + if original_lines < len(source): |
| 158 | + full_file += "\n ".join(source[original_lines:]) |
| 159 | + |
| 160 | + # TODO: we know the file length so we can add a property to diff and determine if we can expand down even if we haven't loaded the entire file on FE yet |
| 161 | + |
| 162 | + return highlighted_hunks |
0 commit comments