rustrust-cargorustdoccargo-doc

How to use a local file as crate logo when generating rustdoc?


It is possible to set both the favicon and the logo of the rustdoc for a crate by using:

as documented here.

However I do not want to upload my logo publicly and would therefore like to automatically include these files in /target/doc and reference them from there.

Currently I have put the respective data urls (base64 encoded) into these fields and it works fine, but it enormously bloats the source file where these attributes are set.

I know I could just copy the images into target/doc after generating the documentation using a script and then reference them using the relative url, but I would like to avoid this, so that I can still generate the documentation using cargo doc.

Edit

The suggestion from the comment to set the --output flag of rustdoc using rustdocflags in .cargo/config.toml also did not work, because it leads to error: Option 'output' given more than once. Apart from that, it is not suited for me, because (at least as far as I understand) I can only give absolute paths there, whereas I would need a solution using relative paths for the images, because I have those images stored in a subdirectory of the cargo root directory, to allow for easy transfer to another system using git, etc.


Solution

  • Thanks to the latest comment from eggyal I finally figured out how to do this:

    In my build.rs I copy the files to target/doc/:

    fn main() {
        // Copy the images to the output when generating documentation
        println!("cargo:rerun-if-changed=assets/doc");
        std::fs::copy("assets/doc/logo.ico", "target/doc/logo.ico").expect("Failed to copy crate favicon when building documentation.");
        std::fs::copy("assets/doc/logo.png", "target/doc/logo.png").expect("Failed to copy crate logo when building documentation.");
    }
    

    and then I just had to make sure, to use an absolute path when referencing them, like so:

    #![doc(html_favicon_url = "/logo.ico")]
    #![doc(html_logo_url = "/logo.png")]
    

    In general it would be better to read the CARGO_TARGET_DIR environment variable instead of hardcoding target/doc, but this is not yet available in build scripts.