Skip to content

Commit

Permalink
BUG: Fix git_link_template not showing for property, cached_property (#…
Browse files Browse the repository at this point in the history
…451)

* fix properties and cached_properties failing when adding git links

see #450

* fix whitespace for flake8

* special case for namedtuple fields

* add special case for member_descriptor

* Extend existing _unwrap_descriptor() function

---------

Co-authored-by: Kernc <[email protected]>
  • Loading branch information
mivanit and kernc authored Dec 13, 2024
1 parent 6330d7e commit f33f891
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 8 deletions.
21 changes: 16 additions & 5 deletions pdoc/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@
import typing
from contextlib import contextmanager
from copy import copy
from functools import lru_cache, reduce, partial, wraps
from functools import cached_property, lru_cache, reduce, partial, wraps
from itertools import tee, groupby
from types import ModuleType
from types import FunctionType, ModuleType
from typing import ( # noqa: F401
cast, Any, Callable, Dict, Generator, Iterable, List, Literal, Mapping, NewType,
Optional, Set, Tuple, Type, TypeVar, Union,
Expand Down Expand Up @@ -429,11 +429,22 @@ def _is_descriptor(obj):
inspect.ismemberdescriptor(obj))


def _unwrap_descriptor(obj):
def _unwrap_descriptor(dobj):
obj = dobj.obj
if isinstance(obj, property):
return (getattr(obj, 'fget', False) or
getattr(obj, 'fset', False) or
getattr(obj, 'fdel', obj))
if isinstance(obj, cached_property):
return obj.func
if isinstance(obj, FunctionType):
return obj
if (inspect.ismemberdescriptor(obj) or
getattr(getattr(obj, '__class__', 0), '__name__', 0) == '_tuplegetter'):
class_name = dobj.qualname.rsplit('.', 1)[0]
obj = getattr(dobj.module.obj, class_name)
return obj
# XXX: Follow descriptor protocol? Already proved buggy in conditions above
return getattr(obj, '__get__', obj)


Expand Down Expand Up @@ -558,7 +569,7 @@ def source(self) -> str:
available, an empty string.
"""
try:
lines, _ = inspect.getsourcelines(_unwrap_descriptor(self.obj))
lines, _ = inspect.getsourcelines(_unwrap_descriptor(self))
except (ValueError, TypeError, OSError):
return ''
return inspect.cleandoc(''.join(['\n'] + lines))
Expand Down Expand Up @@ -1432,7 +1443,7 @@ def return_annotation(self, *, link=None) -> str:
# global variables
lambda: _get_type_hints(not self.cls and self.module.obj)[self.name],
# properties
lambda: inspect.signature(_unwrap_descriptor(self.obj)).return_annotation,
lambda: inspect.signature(_unwrap_descriptor(self)).return_annotation,
# Use raw annotation strings in unmatched forward declarations
lambda: cast(Class, self.cls).obj.__annotations__[self.name],
# Extract annotation from the docstring for C builtin function
Expand Down
7 changes: 4 additions & 3 deletions pdoc/html_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -564,20 +564,21 @@ def format_git_link(template: str, dobj: pdoc.Doc):
try:
if 'commit' in _str_template_fields(template):
commit = _git_head_commit()
abs_path = inspect.getfile(inspect.unwrap(dobj.obj))
obj = pdoc._unwrap_descriptor(dobj)
abs_path = inspect.getfile(inspect.unwrap(obj))
path = _project_relative_path(abs_path)

# Urls should always use / instead of \\
if os.name == 'nt':
path = path.replace('\\', '/')

lines, start_line = inspect.getsourcelines(dobj.obj)
lines, start_line = inspect.getsourcelines(obj)
start_line = start_line or 1 # GH-296
end_line = start_line + len(lines) - 1
url = template.format(**locals())
return url
except Exception:
warn(f'format_git_link for {dobj.obj} failed:\n{traceback.format_exc()}')
warn(f'format_git_link for {obj} failed:\n{traceback.format_exc()}')
return None


Expand Down

0 comments on commit f33f891

Please sign in to comment.