Strips leading whitespace from a docstring. `inspect.cleandoc` is a good reference, but has a few incompatibilities. = _PyCompile_CleanDoc
(doc: &str)
| 10426 | /// `inspect.cleandoc` is a good reference, but has a few incompatibilities. |
| 10427 | // = _PyCompile_CleanDoc |
| 10428 | fn clean_doc(doc: &str) -> String { |
| 10429 | let doc = expandtabs(doc, 8); |
| 10430 | // First pass: find minimum indentation of non-blank lines AFTER the first line. |
| 10431 | // A "blank line" is one containing only spaces (or empty). |
| 10432 | let margin = doc |
| 10433 | .split('\n') |
| 10434 | .skip(1) // skip first line |
| 10435 | .filter(|line| line.chars().any(|c| c != ' ')) // non-blank lines only |
| 10436 | .map(|line| line.chars().take_while(|c| *c == ' ').count()) |
| 10437 | .min() |
| 10438 | .unwrap_or(0); |
| 10439 | |
| 10440 | let mut cleaned = String::with_capacity(doc.len()); |
| 10441 | // Strip all leading spaces from the first line |
| 10442 | if let Some(first_line) = doc.split('\n').next() { |
| 10443 | let trimmed = first_line.trim_start(); |
| 10444 | // Early exit: no leading spaces on first line AND margin == 0 |
| 10445 | if trimmed.len() == first_line.len() && margin == 0 { |
| 10446 | return doc.to_owned(); |
| 10447 | } |
| 10448 | cleaned.push_str(trimmed); |
| 10449 | } |
| 10450 | // Subsequent lines: skip up to `margin` leading spaces |
| 10451 | for line in doc.split('\n').skip(1) { |
| 10452 | cleaned.push('\n'); |
| 10453 | let skip = line.chars().take(margin).take_while(|c| *c == ' ').count(); |
| 10454 | cleaned.push_str(&line[skip..]); |
| 10455 | } |
| 10456 | |
| 10457 | cleaned |
| 10458 | } |
| 10459 | |
| 10460 | // copied from rustpython_common::str, so we don't have to depend on it just for this function |
| 10461 | fn expandtabs(input: &str, tab_size: usize) -> String { |
no test coverage detected