pyo3_stub_gen/generate/
docstring.rs

1use std::fmt;
2
3pub fn write_docstring(f: &mut fmt::Formatter, doc: &str, indent: &str) -> fmt::Result {
4    let doc = doc.trim();
5    if !doc.is_empty() {
6        writeln!(f, r#"{indent}r""""#)?;
7
8        // Dedent the docstring (similar to Python's textwrap.dedent)
9        let lines: Vec<&str> = doc.lines().collect();
10
11        // Find the minimum indentation of non-empty lines (excluding the first line)
12        let min_indent = lines
13            .iter()
14            .skip(1) // Skip first line as it's usually right after the opening """
15            .filter(|line| !line.trim().is_empty())
16            .map(|line| line.chars().take_while(|c| c.is_whitespace()).count())
17            .min()
18            .unwrap_or(0);
19
20        // Write each line with common indentation removed
21        for (i, line) in lines.iter().enumerate() {
22            if i == 0 {
23                // First line: write as-is (it's usually not indented in the original)
24                writeln!(f, "{indent}{line}")?;
25            } else if line.trim().is_empty() {
26                // Empty line: write just the base indent
27                writeln!(f, "{indent}")?;
28            } else {
29                // Other lines: remove common indentation
30                let dedented = if line.len() >= min_indent {
31                    &line[min_indent..]
32                } else {
33                    line.trim_start()
34                };
35                writeln!(f, "{indent}{dedented}")?;
36            }
37        }
38
39        writeln!(f, r#"{indent}""""#)?;
40    }
41    Ok(())
42}