oprypin / mkdocs-gen-files

MkDocs plugin to programmatically generate documentation pages during the build
https://oprypin.github.io/mkdocs-gen-files
MIT License
98 stars 8 forks source link

Proposed feature: Skip N levels when building literate nav #29

Closed CBroz1 closed 8 months ago

CBroz1 commented 8 months ago

I've worked on projects where the core codebase was in a subdirectory (e.g., src/project/), which resulted in additional clicks to go from top -> api reference -> src -> project -> relevant files

I propose an optional build_literate_nav parameter that would skip the first N levels as follows:

class Nav:
    ...
    def build_literate_nav(self, indentation: int | str = "", skip_levels : int = 0) -> Iterable[str]:
        """Builds a file suitable for https://github.com/oprypin/mkdocs-literate-nav, as a sequence of lines to be written into a file.

        For an example, see https://mkdocstrings.github.io/recipes/#generate-a-literate-navigation-file
        """
        if isinstance(indentation, int):
            indentation = " " * indentation
        for item in self.items():
            if item.level < skip_levels: 
                continue
            adjusted_level = item.level - skip_levels
            line = item.title
            if line.startswith(self._markdown_escape_chars):
                line = "\\" + line
            if item.filename is not None:
                line = f"[{line}]({item.filename})"
            yield indentation + "    " * adjusted_level + "* " + line + "\n"

In my case, this would permit me to include nav.build_literate_nav(skip_levels=2) in my page-generator script to remove the additional clicks mentioned above

If this is of interest, I'd be happy to open a PR

Thanks for all your work on this project!

oprypin commented 8 months ago

I think you could just skip the 2 levels when putting them into the Nav object, rather than when rendering it

CBroz1 commented 8 months ago

That's true. I suppose the generator script would look something like this:

nav = mkdocs_gen_files.Nav()
for path in sorted(Path("src/project/").glob("**/*.py")):
    rel_path = path.relative_to("src/project")
    with mkdocs_gen_files.open(f"api/{rel_path.with_suffix('')}.md", "w") as f:
        module_path = ".".join([p for p in path.with_suffix("").parts])
        print(f"::: {module_path}", file=f)
    nav[rel_path.parts] = f"{rel_path.with_suffix('')}.md"