Skip to content

Commit

Permalink
remove module index if only one module is documented, refs mitmproxy#318
Browse files Browse the repository at this point in the history
  • Loading branch information
mhils committed Jan 21, 2022
1 parent dda98ce commit ad32abc
Show file tree
Hide file tree
Showing 11 changed files with 445 additions and 76 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

# Unreleased: pdoc next

- **Breaking:** For projects that only document a single module (and its submodules),
the module index has been removed. `index.html` now redirects to the top-level module instead.
Direct submodules continue to be accessible in the menu.
See [#318](https://github.com/mitmproxy/pdoc/issues/318) for details.
- pdoc web server now picks a random port if 8080 is unavailable and no explicit port has been passed.
- Improve search tokenization to better match
on function arguments.
Expand Down
3 changes: 0 additions & 3 deletions pdoc/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,9 +202,6 @@ def cli(args: list[str] = None) -> None:
url = f"http://{opts.host}:{httpd.server_port}"
print(f"pdoc server ready at {url}")
if not opts.no_browser:
if len(opts.modules) == 1 or len(httpd.all_modules) == 1:
mod = next(iter(httpd.all_modules))
url += f"/{mod.replace('.', '/')}.html"
pdoc.web.open_browser(url)
try:
httpd.serve_forever()
Expand Down
2 changes: 2 additions & 0 deletions pdoc/render.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
link,
linkify,
minify_css,
root_module_name,
to_html,
to_markdown_with_context,
)
Expand Down Expand Up @@ -173,4 +174,5 @@ def repr_module(module: pdoc.doc.Module) -> str:
env.filters["minify_css"] = minify_css
env.globals["__version__"] = pdoc.__version__
env.globals["env"] = os.environ
env.globals["root_module_name"] = root_module_name
configure() # add default globals
23 changes: 23 additions & 0 deletions pdoc/render_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,29 @@ def edit_url(
return None


@pass_context
@cache
def root_module_name(context: Context) -> Optional[str]:
"""
Return the name of the (unique) top-level module, or `None`
if no such module exists.
For example, assuming `foo`, `foo.bar`, and `foo.baz` are documented,
this function will return `foo`. If `foo` and `bar` are documented,
this function will return `None` as there is no unique top-level module.
"""
all_modules: dict[str, pdoc.doc.Module] = context["all_modules"]
shortest_name = min(all_modules, key=len, default=None)
prefix = f"{shortest_name}."
all_others_are_submodules = all(
x.startswith(prefix) or x == shortest_name for x in all_modules
)
if all_others_are_submodules:
return shortest_name
else:
return None


def minify_css(css: str) -> str:
"""Do some very basic CSS minification."""
css = re.sub(r"[ ]{4}|\n|(?<=[:{}]) | (?=[{}])", "", css)
Expand Down
12 changes: 11 additions & 1 deletion pdoc/templates/default/index.html.jinja2
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
{% if root_module_name() %}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="refresh" content="0; url=./{{ root_module_name().replace(".","/") }}.html" />
</head>
</html>
{% else %}
{% extends "default/module.html.jinja2" %}
{% block title %}Module List &ndash; pdoc {{ __version__ }}{% endblock %}
{% block style %}
Expand Down Expand Up @@ -33,7 +42,7 @@
<div>
<h2>Available Modules</h2>
<ul>
{% for submodule in all_modules if "._" not in submodule %}
{% for submodule in all_modules if "._" not in submodule and not submodule.startswith("_") %}
<li><a href="{{ submodule.replace(".","/") }}.html">{{ submodule }}</a></li>
{% endfor %}
</ul>
Expand All @@ -58,3 +67,4 @@
{% include "search.html.jinja2" %}
{% endif %}
{% endblock %}
{% endif %}
2 changes: 1 addition & 1 deletion pdoc/templates/default/module.html.jinja2
Original file line number Diff line number Diff line change
Expand Up @@ -712,7 +712,7 @@
&nbsp;
{{- parentmodule -}}
</a>
{% elif all_modules|length > 1 %}
{% elif not root_module_name() %}
<a class="pdoc-button module-list-button" href="{{ "../" * module.modulename.count(".") }}index.html">
{% include "box-arrow-in-left.svg" %}
&nbsp;
Expand Down
23 changes: 13 additions & 10 deletions test/test_snapshot.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,24 @@

class Snapshot:
id: str
path: Path
specs: list[Path]
render_options: dict
with_output_directory: bool
min_version: tuple[int, int]

def __init__(
self,
id: str,
filename: Optional[str] = None,
filenames: Optional[list[str]] = None,
render_options: Optional[dict] = None,
with_output_directory: bool = False,
min_version: tuple[int, int] = (3, 7),
):
self.id = id
self.path = snapshot_dir / (filename or f"{id}.py")
self.specs = [
snapshot_dir / f
for f in (filenames or [f"{id}.py"])
]
self.render_options = render_options or {}
self.with_output_directory = with_output_directory
self.min_version = min_version
Expand All @@ -46,7 +49,7 @@ def make(self, format: str) -> str:
with tempfile.TemporaryDirectory() as tmpdirname:
tmpdir = Path(tmpdirname)
# noinspection PyTypeChecker
pdoc.pdoc(self.path, format=format, output_directory=Path(tmpdir)) # type: ignore
pdoc.pdoc(*self.specs, format=format, output_directory=Path(tmpdir)) # type: ignore

if format == "html":
rendered = "<style>iframe {width: 100%; min-height: 50vh}</style>\n"
Expand All @@ -72,7 +75,7 @@ def make(self, format: str) -> str:

else:
# noinspection PyTypeChecker
rendered = pdoc.pdoc(self.path, format=format) # type: ignore
rendered = pdoc.pdoc(*self.specs, format=format) # type: ignore
pdoc.render.configure()
pdoc.render.env.globals["__version__"] = pdoc.__version__
return rendered
Expand All @@ -93,28 +96,28 @@ def outfile(self, format: str) -> Path:
Snapshot("flavors_rst"),
Snapshot(
"example_customtemplate",
"demo.py",
["demo.py"],
{"template_directory": here / ".." / "examples" / "custom-template"},
min_version=(3, 9),
),
Snapshot(
"example_darkmode",
"demo.py",
["demo.py"],
{"template_directory": here / ".." / "examples" / "dark-mode"},
min_version=(3, 9),
),
Snapshot(
"example_mkdocs",
"demo.py",
["demo.py"],
{"template_directory": here / ".." / "examples" / "mkdocs" / "pdoc-template"},
min_version=(3, 9),
),
Snapshot("demo_long", min_version=(3, 9)),
Snapshot("demo_eager", min_version=(3, 9)),
Snapshot("demopackage", "demopackage"),
Snapshot("demopackage", ["demopackage"]),
Snapshot(
"demopackage_dir",
"demopackage",
["demopackage", "demo.py"],
render_options={
"edit_url_map": {
"demopackage.child_b": "https://gitlab.example.com/foo/bar/-/blob/main/demopackage/child_b",
Expand Down
7 changes: 0 additions & 7 deletions test/testdata/demopackage.html
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,6 @@
<label id="navtoggle" for="togglestate" class="pdoc-button"><svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 30 30'><path stroke-linecap='round' stroke="currentColor" stroke-miterlimit='10' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/></svg></label>
<input id="togglestate" type="checkbox">
<div>
<a class="pdoc-button module-list-button" href="index.html">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-box-arrow-in-left" viewBox="0 0 16 16">
<path fill-rule="evenodd" d="M10 3.5a.5.5 0 0 0-.5-.5h-8a.5.5 0 0 0-.5.5v9a.5.5 0 0 0 .5.5h8a.5.5 0 0 0 .5-.5v-2a.5.5 0 0 1 1 0v2A1.5 1.5 0 0 1 9.5 14h-8A1.5 1.5 0 0 1 0 12.5v-9A1.5 1.5 0 0 1 1.5 2h8A1.5 1.5 0 0 1 11 3.5v2a.5.5 0 0 1-1 0v-2z"/>
<path fill-rule="evenodd" d="M4.146 8.354a.5.5 0 0 1 0-.708l3-3a.5.5 0 1 1 .708.708L5.707 7.5H14.5a.5.5 0 0 1 0 1H5.707l2.147 2.146a.5.5 0 0 1-.708.708l-3-3z"/>
</svg> &nbsp;
Module Index
</a>


<input type="search" placeholder="Search..." role="searchbox" aria-label="search"
Expand Down
382 changes: 381 additions & 1 deletion test/testdata/demopackage_dir.html

Large diffs are not rendered by default.

7 changes: 7 additions & 0 deletions test/testdata/demopackage_dir.txt
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,10 @@
<method def b(self): ...>>>
# demopackage/_child_e.html
<module demopackage._child_e # _child_e docstr>
# demo.html
<module demo # A small `pdoc` examp…
<class demo.Dog # 🐕
<method def __init__(self, name: str): ... # Make a Dog without a…>
<var name: str # The name of our dog.…>
<var friends: list[demo.Dog] # The friends of our d…>
<method def bark(self, loud: bool = True): ... # *woof*>>>
56 changes: 3 additions & 53 deletions test/testdata/render_options.html

Large diffs are not rendered by default.

0 comments on commit ad32abc

Please sign in to comment.