Skip to content

Commit 1ee7a03

Browse files
authored
Add github_link (#11)
1 parent eb051bb commit 1ee7a03

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed

sphinx_runpython/github_link.py

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
# Taken from https://github.com/scikit-learn/scikit-learn/blob/main/doc/sphinxext/github_link.py
2+
import inspect
3+
import os
4+
import subprocess
5+
import sys
6+
from functools import partial
7+
from operator import attrgetter
8+
9+
REVISION_CMD = "git rev-parse --short HEAD"
10+
11+
12+
def _get_git_revision():
13+
try:
14+
revision = subprocess.check_output(REVISION_CMD.split()).strip()
15+
except (subprocess.CalledProcessError, OSError):
16+
print("Failed to execute git to get revision")
17+
return None
18+
return revision.decode("utf-8")
19+
20+
21+
def _linkcode_resolve(domain, info, package, url_fmt, revision):
22+
"""
23+
Determine a link to online source for a class/method/function
24+
25+
This is called by sphinx.ext.linkcode
26+
27+
An example with a long-untouched module that everyone has:
28+
29+
>>> _linkcode_resolve('py', {'module': 'tty',
30+
... 'fullname': 'setraw'},
31+
... package='tty',
32+
... url_fmt='http://hg.python.org/cpython/file/'
33+
... '{revision}/Lib/{package}/{path}#L{lineno}',
34+
... revision='xxxx')
35+
'http://hg.python.org/cpython/file/xxxx/Lib/tty/tty.py#L18'
36+
"""
37+
38+
if revision is None:
39+
return
40+
if domain not in ("py", "pyx"):
41+
return
42+
if not info.get("module") or not info.get("fullname"):
43+
return
44+
45+
class_name = info["fullname"].split(".")[0]
46+
module = __import__(info["module"], fromlist=[class_name])
47+
obj = attrgetter(info["fullname"])(module)
48+
49+
# Unwrap the object to get the correct source
50+
# file in case that is wrapped by a decorator
51+
obj = inspect.unwrap(obj)
52+
53+
try:
54+
fn = inspect.getsourcefile(obj)
55+
except Exception:
56+
fn = None
57+
if not fn:
58+
try:
59+
fn = inspect.getsourcefile(sys.modules[obj.__module__])
60+
except Exception:
61+
fn = None
62+
if not fn:
63+
return
64+
65+
fn = os.path.relpath(fn, start=os.path.dirname(__import__(package).__file__))
66+
try:
67+
lineno = inspect.getsourcelines(obj)[1]
68+
except Exception:
69+
lineno = ""
70+
return url_fmt.format(revision=revision, package=package, path=fn, lineno=lineno)
71+
72+
73+
def make_linkcode_resolve(package, url_fmt):
74+
"""
75+
Returns a linkcode_resolve function for the given URL format
76+
77+
revision is a git commit reference (hash or name)
78+
79+
package is the name of the root module of the package
80+
81+
url_fmt is along the lines of::
82+
83+
'https://github.com/USER/PROJECT/blob/{revision}/{package}/{path}#L{lineno}'
84+
"""
85+
revision = _get_git_revision()
86+
return partial(
87+
_linkcode_resolve, revision=revision, package=package, url_fmt=url_fmt
88+
)

0 commit comments

Comments
 (0)