|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import re |
| 4 | +from pathlib import Path |
| 5 | + |
| 6 | +# Matches the opening fence of an executable code block: |
| 7 | +# ```{python} or ```{python} (with trailing whitespace) |
| 8 | +_EXEC_FENCE_RE = re.compile(r"^```\{python\}\s*$") |
| 9 | + |
| 10 | +# Matches the closing fence: |
| 11 | +# ``` |
| 12 | +_CLOSE_FENCE_RE = re.compile(r"^```\s*$") |
| 13 | + |
| 14 | +# Matches a hash-pipe option line: |
| 15 | +# #| key: value |
| 16 | +_HASHPIPE_RE = re.compile(r"^#\|\s*(\S+?):\s*(.*)$") |
| 17 | + |
| 18 | +# The delimiter that separates display code from eval code: |
| 19 | +_DELIMITER = "# ---" |
| 20 | + |
| 21 | + |
| 22 | +def expand_mock_cells(text: str) -> str: |
| 23 | + """Rewrite `source-code: mock` cells in *text* into two-cell pairs. |
| 24 | +
|
| 25 | + Parameters |
| 26 | + ---------- |
| 27 | + text |
| 28 | + The full content of a `.qmd` file. |
| 29 | +
|
| 30 | + Returns |
| 31 | + ------- |
| 32 | + str |
| 33 | + The rewritten content. Unchanged if no mock cells are found. |
| 34 | + """ |
| 35 | + lines = text.split("\n") |
| 36 | + out: list[str] = [] |
| 37 | + i = 0 |
| 38 | + |
| 39 | + while i < len(lines): |
| 40 | + line = lines[i] |
| 41 | + |
| 42 | + # Look for an opening executable fence |
| 43 | + if not _EXEC_FENCE_RE.match(line): |
| 44 | + out.append(line) |
| 45 | + i += 1 |
| 46 | + continue |
| 47 | + |
| 48 | + # Collect the entire cell (fence-to-fence) |
| 49 | + cell_start = i |
| 50 | + i += 1 |
| 51 | + cell_body: list[str] = [] |
| 52 | + found_close = False |
| 53 | + while i < len(lines): |
| 54 | + if _CLOSE_FENCE_RE.match(lines[i]): |
| 55 | + found_close = True |
| 56 | + i += 1 |
| 57 | + break |
| 58 | + cell_body.append(lines[i]) |
| 59 | + i += 1 |
| 60 | + |
| 61 | + if not found_close: |
| 62 | + # Malformed cell — emit as-is |
| 63 | + out.append(lines[cell_start]) |
| 64 | + out.extend(cell_body) |
| 65 | + continue |
| 66 | + |
| 67 | + # Parse hash-pipe options from the top of the cell body |
| 68 | + options: dict[str, str] = {} |
| 69 | + option_lines: list[str] = [] |
| 70 | + body_start = 0 |
| 71 | + for j, bline in enumerate(cell_body): |
| 72 | + m = _HASHPIPE_RE.match(bline) |
| 73 | + if m: |
| 74 | + options[m.group(1)] = m.group(2).strip() |
| 75 | + option_lines.append(bline) |
| 76 | + body_start = j + 1 |
| 77 | + else: |
| 78 | + break |
| 79 | + |
| 80 | + # Not a mock cell — emit unchanged |
| 81 | + if options.get("source-code") != "mock": |
| 82 | + out.append(lines[cell_start]) |
| 83 | + out.extend(cell_body) |
| 84 | + out.append("```") |
| 85 | + continue |
| 86 | + |
| 87 | + # Split the remaining body at the delimiter |
| 88 | + raw_body = cell_body[body_start:] |
| 89 | + display_lines: list[str] = [] |
| 90 | + eval_lines: list[str] = [] |
| 91 | + found_delim = False |
| 92 | + for bline in raw_body: |
| 93 | + if not found_delim and bline.strip() == _DELIMITER: |
| 94 | + found_delim = True |
| 95 | + continue |
| 96 | + if found_delim: |
| 97 | + eval_lines.append(bline) |
| 98 | + else: |
| 99 | + display_lines.append(bline) |
| 100 | + |
| 101 | + # Collect options to forward (everything except source-code) |
| 102 | + # output-title and output-frame are forwarded to the eval cell only |
| 103 | + output_title = options.pop("output-title", None) |
| 104 | + output_frame = options.pop("output-frame", None) |
| 105 | + # Remove source-code from forwarded options |
| 106 | + options.pop("source-code", None) |
| 107 | + |
| 108 | + # Build forwarded option lines for both cells |
| 109 | + forwarded = [] |
| 110 | + for key, val in options.items(): |
| 111 | + forwarded.append(f"#| {key}: {val}") |
| 112 | + |
| 113 | + # --- Emit the display cell (eval: false) --- |
| 114 | + out.append("```{python}") |
| 115 | + out.append("#| eval: false") |
| 116 | + for fwd in forwarded: |
| 117 | + # Don't forward echo/output overrides to display cell |
| 118 | + if not fwd.startswith("#| echo:") and not fwd.startswith("#| output:"): |
| 119 | + out.append(fwd) |
| 120 | + out.extend(display_lines) |
| 121 | + out.append("```") |
| 122 | + |
| 123 | + # --- Emit the eval cell (echo: false) --- |
| 124 | + if found_delim and eval_lines: |
| 125 | + out.append("") |
| 126 | + out.append("```{python}") |
| 127 | + out.append("#| echo: false") |
| 128 | + if output_title: |
| 129 | + out.append(f"#| output-title: {output_title}") |
| 130 | + if output_frame: |
| 131 | + out.append(f"#| output-frame: {output_frame}") |
| 132 | + for fwd in forwarded: |
| 133 | + # Don't forward eval overrides to eval cell |
| 134 | + if not fwd.startswith("#| eval:"): |
| 135 | + out.append(fwd) |
| 136 | + out.extend(eval_lines) |
| 137 | + out.append("```") |
| 138 | + elif not found_delim: |
| 139 | + # No delimiter found — the entire body is display-only (eval: false). |
| 140 | + # This is a valid use case (equivalent to just eval: false). |
| 141 | + pass |
| 142 | + |
| 143 | + return "\n".join(out) |
| 144 | + |
| 145 | + |
| 146 | +def process_qmd_file(path: Path) -> bool: |
| 147 | + """Process a single `.qmd` file, rewriting mock cells in place. |
| 148 | +
|
| 149 | + Parameters |
| 150 | + ---------- |
| 151 | + path |
| 152 | + Path to the `.qmd` file. |
| 153 | +
|
| 154 | + Returns |
| 155 | + ------- |
| 156 | + bool |
| 157 | + `True` if the file was modified, `False` otherwise. |
| 158 | + """ |
| 159 | + content = path.read_text(encoding="utf-8") |
| 160 | + if "#| source-code: mock" not in content: |
| 161 | + return False |
| 162 | + |
| 163 | + rewritten = expand_mock_cells(content) |
| 164 | + if rewritten == content: |
| 165 | + return False |
| 166 | + |
| 167 | + path.write_text(rewritten, encoding="utf-8") |
| 168 | + return True |
| 169 | + |
| 170 | + |
| 171 | +def process_directory(directory: Path) -> list[str]: |
| 172 | + """Process all `.qmd` files under *directory*. |
| 173 | +
|
| 174 | + Parameters |
| 175 | + ---------- |
| 176 | + directory |
| 177 | + Root directory to scan recursively. |
| 178 | +
|
| 179 | + Returns |
| 180 | + ------- |
| 181 | + list[str] |
| 182 | + Relative paths of files that were modified. |
| 183 | + """ |
| 184 | + modified: list[str] = [] |
| 185 | + for qmd in sorted(directory.rglob("*.qmd")): |
| 186 | + if process_qmd_file(qmd): |
| 187 | + try: |
| 188 | + rel = str(qmd.relative_to(directory)) |
| 189 | + except ValueError: |
| 190 | + rel = str(qmd) |
| 191 | + modified.append(rel) |
| 192 | + return modified |
0 commit comments