如何防止`rust doc`将依赖项添加到文档中?

31
我刚开始接触 Rust,尝试为我编写的代码生成文档。当我输入“cargo doc”时,看到了一些奇怪的东西。
21:53 $ cargo doc
   Compiling regex-syntax v0.2.2
   Compiling libc v0.2.2
   Compiling memchr v0.1.7
   Compiling aho-corasick v0.3.4
   Compiling regex v0.1.41
   Compiling my_project v0.0.1 (path/to/my_project)

当我打开my_project/target/doc/my_project/index.html时,我注意到我的文档中包含了所有的依赖项。

Those damn crates

我希望用户看到的只有如何使用 我的 代码,而不是这些依赖项的文档。如何实现这一点?

Cargo.lock

[root]
name = "my_project"
version = "0.0.1"
dependencies = [
 "regex 0.1.41 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "aho-corasick"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "memchr 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "libc"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"

[[package]]
name = "memchr"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "libc 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "regex"
version = "0.1.41"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "aho-corasick 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)",
 "memchr 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)",
 "regex-syntax 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "regex-syntax"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
2个回答

51
我找到了答案:cargo doc --no-deps

3
非常感谢!我之前没有看到过这个。不幸的是,该命令有些反直觉。我本来期望cargo do是不包括依赖的,而cargo doc --with-deps则包括依赖。 - yerlilbilgin
11
如果您在添加 --no-deps 标志之前已生成了文档,则需要删除 /target/doc 目录并重新生成文档,以便清除出现在页面上的依赖项。在我尝试这样做之前,我很困惑为什么这不起作用。 - Keavon
1
这条最后的评论对我很有帮助,奇怪的是更改文档生成设置并不会重建整个文档。 - SeedyROM
我想展示我的依赖关系,即来自同一工作区的crate,但不包括第三方依赖。这是否可能? - Anatoly Bugakov

4

默认情况下,cargo doc 会为本地包和所有依赖项构建文档。输出以 rustdoc 的常规格式放置在 target/doc 目录中。

要避免构建依赖项的文档,请传递 --no-deps 参数。

通常情况下,我也倾向于传递 --open 参数。这将在构建文档后在浏览器中打开它们。

cargo doc --no-deps --open

这里可以找到更多有关如何构建软件包文档的详细信息。


简单的例子。考虑以下lib.rs文件。

//! This is my module documentation. My library is so nice!

/// four() is a function that returns `4`
///
/// ````
/// use mylib::four;
/// let x = four();
/// assert_eq!(four(), 4);
/// ````
pub fn four() -> i32 { 4 }

#[cfg(test)]
mod tests {
    use super::four;
    #[test]
    fn it_works() {
        assert_eq!(four(), 4);
    }
}

当执行以下命令时

cargo doc --no-deps --open

浏览器打开的内容如下:

文档示例


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接