Skip to content
Open
Show file tree
Hide file tree
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
18 changes: 12 additions & 6 deletions pdoc/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,7 @@ def _warn_deprecated(option, alternative='', use_config_mako=False):

def _generate_lunr_search(modules: List[pdoc.Module],
index_docstrings: bool,
template_config: dict):
template_config: dict, *, show_inherited_members: bool):
"""Generate index.js for search"""

def trim_docstring(docstring):
Expand All @@ -390,19 +390,24 @@ def trim_docstring(docstring):
\s*</?\w*[^>]*>\s* # simple HTML tags
''', ' ', docstring, flags=re.VERBOSE | re.MULTILINE)

def recursive_add_to_index(dobj):
def recursive_add_to_index(dobj, module):
if isinstance(dobj, pdoc.Module):
module = dobj
target = dobj if show_inherited_members else dobj._inherits_top()
info = {
'ref': dobj.refname,
'url': to_url_id(dobj.module),
'url': to_url_id(module if target is dobj else target.module),
}
if target is not dobj:
info['anchor'] = target.refname
if index_docstrings:
info['doc'] = trim_docstring(dobj.docstring)
if isinstance(dobj, pdoc.Function):
info['func'] = 1
nonlocal index
index.append(info)
for member_dobj in getattr(dobj, 'doc', {}).values():
recursive_add_to_index(member_dobj)
recursive_add_to_index(member_dobj, module)

@lru_cache()
def to_url_id(module):
Expand All @@ -414,7 +419,7 @@ def to_url_id(module):
index: List[Dict] = []
url_cache: Dict[str, int] = {}
for top_module in modules:
recursive_add_to_index(top_module)
recursive_add_to_index(top_module, top_module)
urls = sorted(url_cache.keys(), key=url_cache.__getitem__)

cmd = ['node', str(Path(__file__).with_name('build-index.js'))]
Expand Down Expand Up @@ -619,7 +624,8 @@ def docfilter(obj, _filters=args.filter.strip().split(',')):
lunr_config = config.get('lunr_search')
if lunr_config is not None:
_generate_lunr_search(
modules, lunr_config.get("index_docstrings", True), template_config)
modules, lunr_config.get("index_docstrings", True), template_config,
show_inherited_members=config['show_inherited_members'])


_PANDOC_COMMAND = '''\
Expand Down
2 changes: 1 addition & 1 deletion pdoc/templates/search.mako
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@
results.forEach(function (result) {
const dobj = DOCS[parseInt(result.ref)];
const docstring = dobj.doc;
const url = URLS[dobj.url] + '#' + dobj.ref;
const url = URLS[dobj.url] + '#' + (dobj.anchor || dobj.ref);
const pretty_name = dobj.ref + (dobj.func ? '()' : '');
let text = '';
if (docstring) {
Expand Down
55 changes: 55 additions & 0 deletions pdoc/test/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import doctest
import enum
import inspect
import json
import os
import shutil
import signal
Expand Down Expand Up @@ -292,6 +293,60 @@ def test_lunr_search(self):
run(EXAMPLE_MODULE, config='lunr_search={"fuzziness": 1}')
self.assertFalse(stderr.read())

def test_lunr_search_inherited_links(self):
with temp_dir() as path:
package = Path(path, 'search_inheritance')
package.mkdir()
(package / '__init__.py').write_text('')
(package / 'base.py').write_text('''
class Base:
def method(self):
"""Base method documentation."""

@property
def value(self):
"""Base property documentation."""
''')
(package / 'child.py').write_text('''
from .base import Base

class Child(Base):
"""Child documentation."""

class GrandChild(Child):
"""Grandchild documentation."""

class Override(Child):
def method(self):
"""Overridden method documentation."""
''')
for show_inherited in (False, True):
pdoc.reset()
# Exercise the browser-built index without requiring Node or a CDN.
with patch.object(sys, 'path', [path, *sys.path]), \
patch('pdoc.cli.subprocess.Popen', side_effect=FileNotFoundError), \
self.assertWarns(RuntimeWarning), \
run_html('search_inheritance', '-c', 'lunr_search={}', '-c',
f'show_inherited_members={show_inherited}'):
urls, index = Path('index.js').read_text().split(';\nINDEX=')
urls = json.loads(urls.removeprefix('URLS='))
index = {doc['ref']: doc for doc in json.loads(index)}

for cls in ('Child', 'GrandChild', 'Override'):
for member in ('method', 'value'):
ref = f'search_inheritance.child.{cls}.{member}'
with self.subTest(ref=ref, show_inherited_members=show_inherited):
doc = index[ref]
local = show_inherited or (cls == 'Override' and member == 'method')
expected = (ref if local else
f'search_inheritance.base.Base.{member}')
anchor = doc.get('anchor', doc['ref'])
target = urls[doc['url']]
self.assertEqual(anchor, expected)
self.assertEqual(target, 'search_inheritance/' +
('child.html' if local else 'base.html'))
self.assertIn(f'id="{anchor}"', Path(target).read_text())

def test_force(self):
with run_html(EXAMPLE_MODULE):
with redirect_streams() as (stdout, stderr):
Expand Down
Loading