gpt4 book ai didi

build - 在 "cargo build"期间获取事件依赖项及其版本的列表

转载 作者:行者123 更新时间:2023-11-29 07:51:41 25 4
gpt4 key购买 nike

一些 crate 提供酒吧 const &str -version 字符串,有些没有。为了有一个通用的解决方案,我需要一个所有依赖项及其版本的列表,这些依赖项是cargo build 已知和使用的。在编译期间,所以我可以构建自己的 const &str的这是我自己的版本和我编译的所有版本-调试输出。

是否可以在 build.rs 中获取所有依赖项及其版本的列表? ?
Cargo.lock似乎是一个很好的来源。解析 Cargo.lock 真的好吗?在 build.rs ?是否保证已更新为 Cargo 实际使用并写入磁盘的内容?

最佳答案

我自己的答案,通过解析 Cargo.lock 解决了.以下为我们提供了依赖项和依赖项的依赖项列表 - 每个最终以某种方式链接的 crate(除此之外)。

Cargo.toml :

[package]
name = "mycrate"
version = "0.1.0"
authors = ["John Doe"]
build = "build.rs"

[build-dependencies]
toml = "0.2"

build.rs :
extern crate toml;

use std::env;
use std::fs;
use std::path;
use std::io::{Read, Write};

fn main() {
// Read Cargo.lock and de-toml it
let mut lock_buf = String::new();
fs::File::open("Cargo.lock").unwrap().read_to_string(&mut lock_buf).unwrap();
let lock_toml = toml::Parser::new(&lock_buf).parse().unwrap();

// Get the table of [[package]]s. This is the deep list of dependencies and dependencies of
// dependencies.
let mut packages = Vec::new();
for package in lock_toml.get("package").unwrap().as_slice().unwrap() {
let package = package.as_table().unwrap();
packages.push((package.get("name").unwrap().as_str().unwrap(),
package.get("version").unwrap().as_str().unwrap()));
}
packages.sort();

// Write out the file to be included in the module stub
let out_dir = env::var("OUT_DIR").unwrap();
let mut versions_file = fs::File::create(&path::Path::new(&out_dir).join("versions.include")).unwrap();
versions_file.write(format!("pub const BUILD_DEPS: [(&'static str, &'static str); {}] = [", packages.len()).as_ref()).unwrap();
for package in packages {
versions_file.write(format!("(\"{}\", \"{}\"),\n", package.0, package.1).as_ref()).unwrap();
}
versions_file.write("];".as_ref()).unwrap();
}

src/versions.rs :
//! Information about the build-environment

// More info from env!() and friends go here

include!(concat!(env!("OUT_DIR"), "/versions.include"));

src/main.rs或任何需要的地方:
mod versions;

fn main() {
println!("I was built using {}", versions::BUILD_DEPS.iter().map(|&(ref pkg, ref ver)| format!("{} {}", pkg, ver)).collect::<Vec<_>>().join(", "));
}

然后输出就像

I was built using android_glue 0.2.1, bitflags 0.3.3, bitflags 0.4.0, bitflags 0.6.0, bitflags 0.7.0, block 0.1.6, byteorder 0.5.3, bytes 0.3.0, cfg-if 0.1.0, cgl 0.1.5, cgmath 0.7.0, clippy 0.0.104 ...



当然,我们可以在编译时构建一个类似字符串的表示,但将它整齐地分开可以在运行时解析这些信息。
据我所知,如果 Cargo.lock 有效不存在:Cargo 总是在 build.rs 之前生成它正在运行。

关于build - 在 "cargo build"期间获取事件依赖项及其版本的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41618456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com