Exemplo n.º 1
0
def test_parse_specs():
    assert list(parse_specs(["dataclasses"])) == ["dataclasses"]
    with pytest.raises(ValueError, match="Module not found"):
        with pytest.warns(RuntimeWarning, match="Cannot find spec for unknown"):
            assert parse_specs(["unknown"])
    with pytest.warns(RuntimeWarning, match="Cannot find spec for unknown"):
        assert list(parse_specs(["dataclasses", "unknown"])) == ["dataclasses"]

    with pytest.warns(RuntimeWarning, match="Error loading test.import_err.err"):
        assert list(parse_specs([here / "import_err"])) == [
            "test.import_err",
            "test.import_err.err",
        ]
    with pytest.raises(ValueError, match="Module not found"):
        assert parse_specs([])
Exemplo n.º 2
0
def test_parse_specs():
    assert list(parse_specs(["dataclasses"])) == ["dataclasses"]
    with pytest.raises(ValueError,
                       match="No valid module specifications found."):
        with pytest.warns(RuntimeWarning,
                          match="Cannot find spec for unknown"):
            assert parse_specs(["unknown"])
    with pytest.warns(RuntimeWarning, match="Cannot find spec for unknown"):
        assert list(parse_specs(["dataclasses", "unknown"])) == ["dataclasses"]

    with pytest.warns(RuntimeWarning, match="Error importing subpackage"):
        assert list(parse_specs([here / "import_err"])) == [
            "import_err",
            "import_err.err",
        ]
    with pytest.raises(ValueError,
                       match="No valid module specifications found."):
        assert parse_specs([])
Exemplo n.º 3
0
def cli(args: list[str] = None) -> None:
    """ Command-line entry point """
    opts = parser.parse_args(args)
    if opts.version:
        print(
            f"pdoc: {get_dev_version()}\n"
            f"Python: {platform.python_version()}\n"
            f"Platform: {platform.platform()}"
        )
        return

    render.configure(
        edit_url_map=dict(x.split("=", 1) for x in opts.edit_url),
        template_directory=opts.template_directory,
        docformat=opts.docformat,
    )

    if opts.output_directory:
        pdoc.pdoc(
            *opts.modules,
            output_directory=opts.output_directory,
            format="html",  # opts.format or
        )
        return
    else:
        all_modules: Collection[str]
        if opts.modules:
            all_modules = extract.parse_specs(opts.modules)
        else:
            all_modules = pdoc.web.AllModules()

        with pdoc.web.DocServer(
            (opts.host, opts.port),
            all_modules,
        ) as httpd:
            url = f"http://{opts.host}:{opts.port}"
            print(f"pdoc server ready at {url}")
            if not opts.no_browser:
                if len(opts.modules) == 1:
                    mod = next(iter(all_modules))
                    url += f"/{mod.replace('.', '/')}.html"
                pdoc.web.open_browser(url)
            try:
                httpd.serve_forever()
            except KeyboardInterrupt:
                httpd.server_close()
                return
Exemplo n.º 4
0
def pdoc(
    *modules: Union[Path, str],
    output_directory: Optional[Path] = None,
    format: Literal["html"] = "html",
) -> str:
    """
    Render the documentation for a list of modules.

     - If `output_directory` is `None`, returns the rendered documentation
       for the first module in the list.
     - If `output_directory` is set, recursively writes the rendered output
       for all specified modules and their submodules to the target destination.

    Rendering options can be configured by calling `pdoc.render.configure` in advance.
    """
    retval = io.StringIO()
    if output_directory:

        def write(mod: doc.Module):
            assert output_directory
            outfile = output_directory / f"{mod.fullname.replace('.', '/')}.html"
            outfile.parent.mkdir(parents=True, exist_ok=True)
            outfile.write_bytes(r(mod).encode())

    else:

        def write(mod: doc.Module):
            retval.write(r(mod))

    all_modules = extract.parse_specs(modules)

    if format == "html":

        def r(mod: doc.Module) -> str:
            return render.html_module(module=mod, all_modules=all_modules)

    elif format == "markdown":  # pragma: no cover
        raise NotImplementedError(
            "Markdown support is currently unimplemented, but PRs are welcome!"
        )
    elif format == "repr":
        r = render.repr_module
    else:
        raise ValueError(f"Invalid rendering format {format!r}.")

    for mod in all_modules:
        try:
            m = extract.load_module(mod)
        except RuntimeError:
            warnings.warn(f"Error importing {mod}:\n{traceback.format_exc()}",
                          RuntimeWarning)
        else:
            write(doc.Module(m))

        if not output_directory:
            return retval.getvalue()

    assert output_directory

    if format == "html":
        index = render.html_index(all_modules)
        if index:
            (output_directory / "index.html").write_bytes(index.encode())

    return retval.getvalue()