Rustdoc 嵌套 include! 更改

摘要

当使用 include_str! 包含 doctest 时,如果该 doctest 本身也使用 include!include_str!include_bytes!,则路径是相对于 Markdown 文件解析的,而不是相对于 Rust 源文件。

详情

在 2024 版本之前,使用 #[doc=include_str!("path/file.md")] 添加文档不会将 span 信息传递到该文件中的任何 doctest 中。因此,如果 Markdown 文件与源文件位于不同的目录中,则任何包含的路径都必须相对于源文件指定。

例如,考虑一个包含以下文件的库 crate

  • Cargo.toml
  • README.md
  • src/
    • lib.rs
  • examples/
    • data.bin

假设 lib.rs 包含以下内容

#![doc=include_str!("../README.md")]

并假设此 README.md 文件

``` let _ = include_bytes!("../examples/data.bin"); // ^^^ notice this ```

在 2024 版本之前,README.md 中的路径需要相对于 lib.rs 文件。在 2024 及更高版本中,它现在相对于 README.md 本身,因此我们将 README.md 更新为

``` let _ = include_bytes!("examples/data.bin"); ```

迁移

没有自动迁移来转换受影响的 doctest 中的路径。如果您的 doctest 之一受到影响,那么在迁移到新版本并构建测试时,您会看到类似这样的错误

error: couldn't read `../examples/data.bin`: No such file or directory (os error 2) --> src/../README.md:2:24 | 2 | let _ = include_bytes!("../examples/data.bin"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = note: this error originates in the macro `include_bytes` (in Nightly builds, run with -Z macro-backtrace for more info) help: there is a file with the same name in a different directory | 2 | let _ = include_bytes!("examples/data.bin"); | ~~~~~~~~~~~~~~~~~~~

要将您的 doctest 迁移到 Rust 2024,请更新任何受影响的路径,使其相对于包含 doctest 的文件。