Return `src_text` with every in-body comment removed. A line-leading comment takes its whole line (including indentation and the trailing newline) with it; a trailing comment after code leaves the code and is trimmed of the resulting trailing whitespace. Runs of blank lines created
(src_text: str)
| 143 | |
| 144 | |
| 145 | def _strip_text(src_text: str) -> str: |
| 146 | """Return `src_text` with every in-body comment removed. |
| 147 | |
| 148 | A line-leading comment takes its whole line (including indentation and the |
| 149 | trailing newline) with it; a trailing comment after code leaves the code |
| 150 | and is trimmed of the resulting trailing whitespace. Runs of blank lines |
| 151 | created by removal collapse to a single blank, and the original trailing |
| 152 | newline is preserved.""" |
| 153 | src = src_text.encode("utf-8") |
| 154 | spans = _inbody_comment_spans(src) |
| 155 | if not spans: |
| 156 | return src_text |
| 157 | |
| 158 | # Delete right-to-left so earlier byte offsets stay valid. For each comment |
| 159 | # span, swallow the leading indentation when the comment starts the line, |
| 160 | # and the trailing newline when nothing but whitespace follows it -- that |
| 161 | # turns a whole-line comment into a clean line deletion instead of an empty |
| 162 | # indented line. |
| 163 | out = bytearray(src) |
| 164 | for start, end in reversed(spans): |
| 165 | line_start = out.rfind(b"\n", 0, start) + 1 |
| 166 | before = out[line_start:start] |
| 167 | line_end = out.find(b"\n", end) |
| 168 | if line_end == -1: |
| 169 | line_end = len(out) |
| 170 | after = out[end:line_end] |
| 171 | leading_only = before.strip() == b"" |
| 172 | trailing_only = after.strip() == b"" |
| 173 | if leading_only and trailing_only: |
| 174 | cut_end = line_end + 1 if line_end < len(out) else line_end |
| 175 | del out[line_start:cut_end] |
| 176 | else: |
| 177 | del out[start:end] |
| 178 | |
| 179 | result = out.decode("utf-8", errors="replace") |
| 180 | lines = [ln.rstrip() for ln in result.split("\n")] |
| 181 | |
| 182 | collapsed: list[str] = [] |
| 183 | for ln in lines: |
| 184 | if ln == "" and collapsed and collapsed[-1] == "": |
| 185 | continue |
| 186 | collapsed.append(ln) |
| 187 | |
| 188 | new_text = "\n".join(collapsed) |
| 189 | if src_text.endswith("\n") and not new_text.endswith("\n"): |
| 190 | new_text += "\n" |
| 191 | return new_text |
| 192 | |
| 193 | |
| 194 | def _iter_files(targets: list[Path]) -> Iterable[Path]: |
no test coverage detected