Skip to content

feat: add linkcode_resolve function for enhanced documentation linking #1185

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 9, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 45 additions & 2 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
#
import os
import sys
from pathlib import Path

sys.path.insert(0, os.path.abspath('../'))


Expand Down Expand Up @@ -41,7 +43,7 @@
'matplotlib.sphinxext.plot_directive',
'sphinx.ext.autodoc',
'sphinx.ext.mathjax',
'sphinx.ext.viewcode',
'sphinx.ext.linkcode',
'sphinx.ext.napoleon',
'sphinx.ext.imgconverter',
'IPython.sphinxext.ipython_console_highlighting',
Expand Down Expand Up @@ -184,4 +186,45 @@
]


# -- Extension configuration -------------------------------------------------
# -- linkcode setting -------------------------------------------------

import inspect
import os
import sys
import functools

GITHUB_REPO = "https://github.com/AtsushiSakai/PythonRobotics"
GITHUB_BRANCH = "master"


def linkcode_resolve(domain, info):
if domain != "py":
return None

modname = info["module"]
fullname = info["fullname"]

try:
module = __import__(modname, fromlist=[fullname])
obj = functools.reduce(getattr, fullname.split("."), module)
except (ImportError, AttributeError):
return None

try:
srcfile = inspect.getsourcefile(obj)
srcfile = get_relative_path_from_parent(srcfile, "PythonRobotics")
lineno = inspect.getsourcelines(obj)[1]
except Exception:
return None

return f"{GITHUB_REPO}/blob/{GITHUB_BRANCH}/{srcfile}#L{lineno}"


def get_relative_path_from_parent(file_path: str, parent_dir: str):
path = Path(file_path).resolve()

try:
parent_path = next(p for p in path.parents if p.name == parent_dir)
return str(path.relative_to(parent_path))
except StopIteration:
raise ValueError(f"Parent directory '{parent_dir}' not found in {file_path}")