Skip to content

Commit 76f168b

Browse files
authored
Fix path (#76)
1 parent 5d8a8b2 commit 76f168b

File tree

4 files changed

+33
-31
lines changed

4 files changed

+33
-31
lines changed

.vscode/settings.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
"python.testing.pytestArgs": ["-v"],
33
"python.testing.unittestEnabled": false,
44
"python.testing.pytestEnabled": true,
5+
"python.terminal.activateEnvironment": false,
56
"[python]": {
67
"editor.defaultFormatter": "ms-python.black-formatter",
78
"editor.formatOnSave": true,

docs/conf.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,8 +59,7 @@
5959
use_repository_button=True,
6060
)
6161

62-
# proj/doc/.. → proj
63-
project_dir = HERE.parent
62+
rtd_links_prefix = "src"
6463

6564

6665
def setup(app: Sphinx):

src/scanpydoc/rtd_github_links/__init__.py

Lines changed: 18 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
2828
Uses the following config values in ``conf.py``::
2929
30-
project_dir: Path = ... # default: Path.cwd()
30+
rtd_links_prefix: os.PathLike | str = ... # default: '.'
3131
3232
# sphinx book theme style
3333
html_context = dict(
@@ -41,8 +41,8 @@
4141
github_version=...,
4242
)
4343
44-
The ``project_dir`` is used to figure out the .py file path relative to the git root,
45-
that is to construct the path in the github URL.
44+
The ``rtd_links_prefix`` is for figuring out the .py file path relative to the git root,
45+
that is to construct the path in the GitHub URL.
4646
4747
Which ``html_context`` style you want to use depends on your theme, e.g.
4848
:doc:`Sphinx Book Theme <sphinx_book_theme:index>`.
@@ -78,13 +78,13 @@
7878
from .. import _setup_sig, metadata
7979

8080

81-
project_dir = None # type: Path
82-
github_base_url = None # type: str
81+
rtd_links_prefix: Path = None
82+
github_base_url: str = None
8383

8484

8585
def _init_vars(app: Sphinx, config: Config):
8686
"""Called when ``conf.py`` has been loaded."""
87-
global github_base_url, project_dir
87+
global github_base_url, rtd_links_prefix
8888
_check_html_context(config)
8989
try:
9090
github_base_url = "https://github.com/{github_user}/{github_repo}/tree/{github_version}".format_map(
@@ -94,7 +94,7 @@ def _init_vars(app: Sphinx, config: Config):
9494
github_base_url = "{repository_url}/tree/{repository_branch}".format_map(
9595
config.html_context
9696
)
97-
project_dir = Path(config.project_dir)
97+
rtd_links_prefix = PurePosixPath(config.rtd_links_prefix)
9898

9999

100100
def _get_obj_module(qualname: str) -> tuple[Any, ModuleType]:
@@ -137,6 +137,14 @@ def _get_linenos(obj):
137137
return start, start + len(lines) - 1
138138

139139

140+
def _module_path(module: ModuleType) -> PurePosixPath:
141+
stem = PurePosixPath(*module.__name__.split("."))
142+
if Path(module.__file__).name == "__init__.py":
143+
return stem / "__init__.py"
144+
else:
145+
return stem.with_suffix(".py")
146+
147+
140148
def github_url(qualname: str) -> str:
141149
"""Get the full GitHub URL for some object’s qualname.
142150
@@ -151,13 +159,7 @@ def github_url(qualname: str) -> str:
151159
except Exception:
152160
print(f"Error in github_url({qualname!r}):", file=sys.stderr)
153161
raise
154-
try: # only works when installed in dev mode
155-
path = PurePosixPath(Path(module.__file__).resolve().relative_to(project_dir))
156-
except ValueError:
157-
# no dev mode or something from another package
158-
path = PurePosixPath(*module.__file__.split("/")[-2:])
159-
if (project_dir / "src").is_dir():
160-
path = "src" / path
162+
path = rtd_links_prefix / _module_path(module)
161163
start, end = _get_linenos(obj)
162164
fragment = f"#L{start}-L{end}" if start and end else ""
163165
return f"{github_base_url}/{path}{fragment}"
@@ -188,14 +190,8 @@ def _check_html_context(config: Config):
188190
@_setup_sig
189191
def setup(app: Sphinx) -> dict[str, Any]:
190192
"""Register the :func:`github_url` :ref:`Jinja filter <jinja:filters>`."""
191-
# Guess default project dir
192-
proj_dir = Path.cwd()
193-
if proj_dir.name == "docs":
194-
proj_dir = proj_dir.parent
195-
elif not (proj_dir / "docs").is_dir():
196-
proj_dir = proj_dir.parent
197-
198-
app.add_config_value("project_dir", proj_dir, "")
193+
194+
app.add_config_value("rtd_links_prefix", PurePosixPath("."), "")
199195
app.connect("config-inited", _init_vars)
200196

201197
# if linkcode config not set

tests/test_rtd_github_links.py

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from dataclasses import Field
2-
from pathlib import Path
2+
from pathlib import Path, PurePosixPath
33

44
import pytest
55
from _pytest.monkeypatch import MonkeyPatch
@@ -11,14 +11,20 @@
1111

1212

1313
@pytest.fixture
14-
def env(monkeypatch: MonkeyPatch):
15-
monkeypatch.setattr("scanpydoc.rtd_github_links.github_base_url", ".")
16-
monkeypatch.setattr("scanpydoc.rtd_github_links.project_dir", HERE.parent)
14+
def _env(monkeypatch: MonkeyPatch) -> None:
15+
monkeypatch.setattr("scanpydoc.rtd_github_links.github_base_url", "x")
1716

1817

19-
def test_as_function(env):
20-
pth = "./src/scanpydoc/rtd_github_links/__init__.py"
21-
assert github_url("scanpydoc.rtd_github_links") == pth
18+
@pytest.fixture(params=[".", "src"])
19+
def pfx(monkeypatch: MonkeyPatch, _env, request):
20+
pfx = PurePosixPath(request.param)
21+
monkeypatch.setattr("scanpydoc.rtd_github_links.rtd_links_prefix", pfx)
22+
return pfx
23+
24+
25+
def test_as_function(pfx):
26+
pth = "x" / pfx / "scanpydoc/rtd_github_links/__init__.py"
27+
assert github_url("scanpydoc.rtd_github_links") == str(pth)
2228
s, e = _get_linenos(github_url)
2329
assert github_url("scanpydoc.rtd_github_links.github_url") == f"{pth}#L{s}-L{e}"
2430

0 commit comments

Comments
 (0)