|
17 | 17 |
|
18 | 18 | import pypandoc # type: ignore |
19 | 19 |
|
20 | | -import functools |
21 | | - |
22 | 20 | from gapic.utils.lines import wrap |
23 | 21 |
|
24 | | -@functools.lru_cache(maxsize=None) |
25 | | -def _convert_pandoc(text: str, columns: int, source_format: str) -> str: |
26 | | - """Cached helper to run pypandoc with specific column width. |
27 | | - |
28 | | - Args: |
29 | | - columns: Must be positive. Enforced by caller. |
30 | | - """ |
31 | | - return pypandoc.convert_text(text, 'rst', |
32 | | - format=source_format, |
33 | | - extra_args=['--columns=%d' % columns], |
34 | | - verify_format=False, |
35 | | - ).strip() |
36 | 22 |
|
| 23 | +import functools |
| 24 | + |
| 25 | +@functools.lru_cache(maxsize=None) |
| 26 | +def _p(t, c, f): |
| 27 | + return pypandoc.convert_text(t, "rst", format=f, verify_format=False, extra_args=["--columns=%d" % c]).strip() |
37 | 28 |
|
38 | 29 |
|
39 | 30 | def rst( |
@@ -71,29 +62,12 @@ def rst( |
71 | 62 | width=width - indent, |
72 | 63 | ) |
73 | 64 | else: |
74 | | - # Check if snake_case-only AND NOT a list. |
75 | | - # This regex excludes underscores surrounded by word characters, meaning it finds "real" formatting. |
76 | | - has_real_formatting = re.search(r"(?<!\w)_|_(?!\w)|[|*`\[\]]", text) |
77 | | - is_list = re.search(r"^\s*([-+*]|\d+\.)\s+", text, re.MULTILINE) |
78 | | - |
79 | | - if not has_real_formatting and not is_list: |
80 | | - # Mimic Pandoc behavior for plain text with snake_case: |
81 | | - # 1. Collapse multiple spaces (Markdown behavior) |
82 | | - text_normalized = re.sub(r'[ \t]+', ' ', text) |
83 | | - # 2. Wrap without the specific 'docstring first line' offset |
84 | | - answer = wrap( |
85 | | - text_normalized, |
86 | | - indent=indent, |
87 | | - offset=0, |
88 | | - width=width - indent, |
89 | | - ) |
| 65 | + # Fast path for snake_case and other simple symbols |
| 66 | + if not re.search(r"[*`]|(?<!\w)_|_(?!\w)|\[.*\]\s*[(\[]|^\||^\s*([-+*]|\d+\.)\s+", text, re.M): |
| 67 | + answer = wrap(re.sub(r"[ \t]+", " ", text).replace("|", "\\|"), indent=indent, width=width - indent) |
90 | 68 | else: |
91 | | - # Convert from CommonMark to ReStructured Text. |
92 | | - answer = _convert_pandoc( |
93 | | - str(text), |
94 | | - width - indent, |
95 | | - str(source_format) |
96 | | - ).replace('\n', f"\n{' ' * indent}") |
| 69 | + # Convert from CommonMark to ReStructured Text (cached). |
| 70 | + answer = _p(str(text), width - indent, str(source_format)).replace("\n", f"\n{' ' * indent}") |
97 | 71 |
|
98 | 72 | # Add a newline to the end of the document if any line breaks are |
99 | 73 | # already present. |
|
0 commit comments