生成 rustdoc 时如何使用本地文件作为 crate 徽标? 编辑

问题描述

可以使用以下方法为 crate 设置 faviconlogofavicon

  • #![doc(html_favicon_url = "<url_to>/favicon.ico")]
  • #![doc(html_logo_url = "<url_to>/logo.png")]

如记录here

但是,我不想公开上传我的徽标,因此希望自动将这些文件包含在 /target/doc 中并从那里引用它们。

目前,我已将相应的数据 url(base64 编码)放入这些字段中,并且它工作正常,但它极大地膨胀了设置这些属性的源文件

我知道我可以在使用脚本生成文档后将图像复制到 target/doc 中,然后使用相对 url 引用它们,但我想避免这种情况,以便我仍然可以使用生成文档cargo doc

编辑

评论中使用 --output 中的 rustdocflags 设置 rustdoc.cargo/config.toml 标志的建议也不起作用,因为它导致 error: Option 'output' given more than once。除此之外,它不适合我,因为(至少据我所知)我只能在那里给出绝对路径,而我需要使用图像的相对路径的解决方案,因为我将这些图像存储在货物根目录的子目录,方便使用git等转移到另一个系统。

解决方法

感谢 eggyal 的最新评论,我终于想出了如何做到这一点:

在我的 build.rs 中,我将文件复制到 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.");
}

然后我只需要确保在引用它们时使用绝对路径,如下所示:

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

一般来说,最好读取 CARGO_TARGET_DIR 环境变量而不是硬编码 target/doc,但这在构建脚本中是 not yet available