在“cargo build”期间获取活动依赖项及其版本的列表

9
一些板条箱提供了pub const &str-版本的字符串,而有些则没有。为了拥有一个通用解决方案,我需要一份所有依赖项及其版本的清单,这些版本已知并由cargo build在编译期间使用,因此我可以构建自己的const &str,其中包含“这是我的自己的版本和我编译所使用的所有版本”-调试输出。
是否有可能在build.rs中获取所有依赖项及其版本的列表? Cargo.lock似乎是一个很好的来源。实际上,在build.rs中解析Cargo.lock是否可靠?它是否保证已更新为Cargo实际使用的版本并写入磁盘?

也许 cargo outdated 会有用? - undefined
货物锁定文件包含所有这些信息,但我不确定在构建过程的哪个阶段生成它。 - undefined
Cargo.lock可能是一个不错的源文件,但在build.rs中解析Cargo.lock是否真的靠谱呢?它能保证在运行build.rs之前已经更新并写入磁盘了吗? - undefined
这是我不确定的事情,也不想依赖它 :) - undefined
1个回答

0
这里有一个适用的箱子:build-infolib.rsdocs.rs)。
它似乎无法自动生成包含依赖信息的 'static str,但它会自动解析 Cargo.lock 并将相关信息包含到最终的二进制文件中,产生类似的效果。
示例代码(build-info 0.0.32)
如果您不想包含递归依赖关系,这段代码可能会比您需要的要复杂一些。

build.rs

fn main() {
    build_info_build::build_script().collect_dependencies(true);
}

main.rs

use std::collections::BTreeSet;

build_info::build_info!(fn build_info);

/// Collect all of the dependencies of this workspace into a single set.
fn get_dependencies() -> BTreeSet<(&'static str, &'static build_info::semver::Version)> {
    // called recursively on each of the dependencies in the tree
    fn visit(
        info: &'static build_info::CrateInfo,
        set: &mut BTreeSet<(&'static str, &'static build_info::semver::Version)>,
    ) {
        set.insert((&info.name, &info.version));
        for dep in &info.dependencies {
            visit(dep, set);
        }
    }
    let mut set = BTreeSet::new();
    let root_info = &build_info().crate_info;
    visit(root_info, &mut set);
    set
}

fn main() {
    for (name, version) in get_dependencies() {
        println!("{} {}", name, version);
    }
}

替代方案

请查看cargo-auditcargo-auditable,这是一个针对相同问题的安全导向解决方案,前者甚至可以在不原生包含此功能的程序上部分工作。不幸的是,虽然cargo audit bin可以用于检查已编译的Rust程序中已知的安全漏洞,但我没有看到任何打印其恢复的库列表的标志。


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