|
| 1 | +# Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +# or more contributor license agreements. See the NOTICE file |
| 3 | +# distributed with this work for additional information |
| 4 | +# regarding copyright ownership. The ASF licenses this file |
| 5 | +# to you under the Apache License, Version 2.0 (the |
| 6 | +# "License"); you may not use this file except in compliance |
| 7 | +# with the License. You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, |
| 12 | +# software distributed under the License is distributed on an |
| 13 | +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +# KIND, either express or implied. See the License for the |
| 15 | +# specific language governing permissions and limitations |
| 16 | +# under the License. |
| 17 | + |
| 18 | +"""Griffe extensions for datafusion-python docs. |
| 19 | +
|
| 20 | +`SphinxRefsToAutorefs` rewrites sphinx-style cross-reference roles |
| 21 | +(``:func:`~path`, :class:`~path``, etc.) inside docstrings into |
| 22 | +mkdocstrings autoref syntax (``[`tail`][path]``) so that the same |
| 23 | +docstring renders as a clickable cross-reference both in JetBrains-style |
| 24 | +IDEs (which understand sphinx roles) and on the published docs site |
| 25 | +(which understands mkdocstrings autorefs). |
| 26 | +""" |
| 27 | + |
| 28 | +from __future__ import annotations |
| 29 | + |
| 30 | +import re |
| 31 | +from typing import Any |
| 32 | + |
| 33 | +from griffe import Extension, Object |
| 34 | + |
| 35 | +_ROLE_RE = re.compile( |
| 36 | + r":(?:py:)?(?P<role>func|class|meth|attr|mod|obj|exc|const|data)" |
| 37 | + r":`(?P<tilde>~?)(?P<target>[\w.]+)`" |
| 38 | +) |
| 39 | + |
| 40 | + |
| 41 | +def _rewrite(text: str) -> str: |
| 42 | + def repl(match: re.Match[str]) -> str: |
| 43 | + target = match.group("target") |
| 44 | + tail = target.rsplit(".", 1)[-1] |
| 45 | + return f"[`{tail}`][{target}]" |
| 46 | + |
| 47 | + return _ROLE_RE.sub(repl, text) |
| 48 | + |
| 49 | + |
| 50 | +class SphinxRefsToAutorefs(Extension): |
| 51 | + """Convert sphinx-style cross-references into mkdocstrings autorefs.""" |
| 52 | + |
| 53 | + def on_object(self, *, obj: Object, **_: Any) -> None: |
| 54 | + docstring = obj.docstring |
| 55 | + if docstring is None: |
| 56 | + return |
| 57 | + new = _rewrite(docstring.value) |
| 58 | + if new != docstring.value: |
| 59 | + docstring.value = new |
0 commit comments