On Fri, Dec 11, 2020 at 05:03:50PM -0700, Jonathan Corbet wrote:
> The right solution is probably something like this:
> 
>       try:
>           import rst2pdf
>           extensions.append('rst2pdf.pdfbuilder')
>       except ModuleNotFoundError:
>           pass # no rst2pdf for you

I tested it, but it still fails, and the error message is even more cryptic:

        Sphinx error:
        Builder name pdf not registered or available through entry point
        make[1]: *** [Documentation/Makefile:120: rst2pdf] Error 2
        make: *** [Makefile:1663: rst2pdf] Error 2

It seems to me that the missing dependency should be treated in the Makefile
target rather than in Sphinx. Looking through the Makefile, I took inspiration
from the latex version and did the following:

        HAVE_RST2PDF := $(shell if python -c "import rst2pdf" >/dev/null 2>&1; 
then echo 1; else echo 0; fi)

         
        ifeq ($(HAVE_RST2PDF),0)

        rst2pdf:
               $(warning The 'rst2pdf' python module was not found. Make sure 
you have it installed to produce PDF output.)
               @echo "  SKIP    Sphinx $@ target."

        else # HAVE_RST2PDF

        rst2pdf:
               @$(srctree)/scripts/sphinx-pre-install --version-check
               @+$(foreach var,$(SPHINXDIRS),$(call 
loop_cmd,sphinx,pdf,$(var),pdf,$(var)))

        endif # HAVE_RST2PDF

With this, the following message is shown in case it isn't installed:

        Documentation/Makefile:122: The 'rst2pdf' python module was not found. 
Make sure you have it installed to produce PDF output.
          SKIP    Sphinx rst2pdf target.

But with that check on the Makefile in place, on the Sphinx side, we can indeed
just do Jon's snippet to only add the extension if it is installed. Another
option would be to split the 'try' into 'try' and 'else', where the 'else' only
executes if the 'try' is succesful. The benefit is that this makes it clearer
that only the import is being "tried":

        # Enable experimental rst2pdf, if available
        try:
            import rst2pdf
        except ModuleNotFoundError:
            pass
        else:
            extensions.append("rst2pdf.pdfbuilder")

Something interesting I noticed is that when building with Sphinx 3, and if
rst2pdf is installed, even when building other targets, like htmldocs, (since
the rst2pdf extension is added based on rst2pdf being installed and not if it is
being used) the following is printed:

        WARNING: the rst2pdf.pdfbuilder extension is not safe for parallel 
writing
        WARNING: doing serial write

Looking into rst2pdf's pdfbuilder.py, indeed 'parallel_write_safe' is False, so
we should probably make sure rst2pdf isn't negatively impacting build time for
other formats before merging this patch.

Thanks,
Nícolas

Reply via email to