Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The update of cargo metadata is controlled through deny const #185

Merged
merged 3 commits into from
Oct 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "shadow-rs"
version = "0.35.0"
version = "0.35.1"
authors = ["baoyachi <[email protected]>"]
edition = "2021"
description = "A build-time information stored in your rust project"
Expand Down
5 changes: 3 additions & 2 deletions example_shadow_hook/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,16 @@ fn hook(file: &File) -> SdResult<()> {
}

fn append_write_const(mut file: &File) -> SdResult<()> {
let hook_const: &str = r#"pub const HOOK_CONST: &str = "hello hook const";"#;
let hook_const: &str = r#"#[allow(clippy::all, clippy::pedantic, clippy::restriction, clippy::nursery)]
pub const HOOK_CONST: &str = "hello hook const";"#;
writeln!(file, "{hook_const}")?;
Ok(())
}

fn append_write_fn(mut file: &File) -> SdResult<()> {
let hook_fn: &str = r#"
pub fn hook_fn() -> &'static str{
"hello hook bar fn"
HOOK_CONST
}"#;
writeln!(file, "{hook_fn}")?;
Ok(())
Expand Down
1 change: 1 addition & 0 deletions example_shadow_hook/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ fn main() {
// how to use new_hook function: https://github.com/baoyachi/shadow-rs/blob/master/example_shadow_hook/build.rs
println!("const:{}", build::HOOK_CONST); //expect:'hello hook const'
println!("fn:{}", build::hook_fn()); //expect:'hello hook bar fn'
assert_eq!(build::hook_fn(), build::HOOK_CONST);
}
63 changes: 38 additions & 25 deletions src/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::build::*;
use crate::date_time::now_date_time;
use crate::env::dep_source_replace::filter_cargo_tree;
use crate::err::SdResult;
use crate::Format;
use crate::{Format, Shadow};
use is_debug::build_channel;
use std::collections::BTreeMap;
use std::env;
Expand Down Expand Up @@ -85,7 +85,8 @@ The project's semver pre-release version, as determined by the Cargo.toml manife
pub const PKG_VERSION_PRE: ShadowConst = "PKG_VERSION_PRE";

impl SystemEnv {
fn init(&mut self, std_env: &BTreeMap<String, String>) -> SdResult<()> {
fn init(&mut self, shadow: &Shadow) -> SdResult<()> {
let std_env = &shadow.std_env;
let mut update_val = |c: ShadowConst, v: String| {
if let Some(val) = self.map.get_mut(c) {
val.v = v;
Expand All @@ -110,23 +111,42 @@ impl SystemEnv {
);
}

if let Ok(out) = Command::new("cargo").arg("tree").output() {
let input = String::from_utf8(out.stdout)?;
if let Some(index) = input.find('\n') {
let lines =
filter_cargo_tree(input.get(index..).unwrap_or_default().split('\n').collect());
update_val(CARGO_TREE, lines);
// If the build constant `CARGO_TREE` is not in the deny list,
// See discussions and issues related to this functionality:
// - https://github.com/baoyachi/shadow-rs/issues/184
// - https://github.com/baoyachi/shadow-rs/issues/135
// - https://github.com/rust-lang/cargo/issues/12195
// - https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#lockfile-path
if !shadow.deny_contains(CARGO_TREE) {
if let Ok(out) = Command::new("cargo").arg("tree").output() {
let input = String::from_utf8(out.stdout)?;
if let Some(index) = input.find('\n') {
let lines = filter_cargo_tree(
input.get(index..).unwrap_or_default().split('\n').collect(),
);
update_val(CARGO_TREE, lines);
}
}
}

if let Ok(out) = Command::new("cargo")
.args(["metadata", "--format-version", "1"])
.output()
{
update_val(
CARGO_METADATA,
String::from_utf8(out.stdout)?.trim().to_string(),
);
// If the build constant `CARGO_METADATA` is not in the deny list,
// See discussions and issues related to this functionality:
// - https://github.com/baoyachi/shadow-rs/issues/184
// - https://github.com/baoyachi/shadow-rs/issues/135
// - https://github.com/rust-lang/cargo/issues/12195
// - https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#lockfile-path
if !shadow.deny_contains(CARGO_METADATA) {
// Attempt to run the `cargo metadata --format-version 1` command.
if let Ok(output) = Command::new("cargo")
.args(["metadata", "--format-version", "1"])
.output()
{
// If successful, parse the output and update the value associated with `CARGO_METADATA`.
update_val(
CARGO_METADATA,
String::from_utf8(output.stdout)?.trim().to_string(),
);
}
}

if let Some(v) = std_env.get("TARGET") {
Expand Down Expand Up @@ -247,9 +267,7 @@ mod dep_source_replace {

/// Create all `shadow-rs` constants which are determined by the build environment.
/// The data for these constants is provided by the `std_env` argument.
pub(crate) fn new_system_env(
std_env: &BTreeMap<String, String>,
) -> BTreeMap<ShadowConst, ConstVal> {
pub(crate) fn new_system_env(shadow: &Shadow) -> BTreeMap<ShadowConst, ConstVal> {
let mut env = SystemEnv::default();
env.map.insert(
BUILD_OS,
Expand All @@ -271,11 +289,6 @@ pub(crate) fn new_system_env(

env.map.insert(CARGO_TREE, ConstVal::new(CARGO_TREE_DOC));

// env.map.insert(
// CARGO_METADATA,
// ConstVal::new("display build cargo dependencies by metadata.It's use by exec command `cargo metadata`"),
// );

env.map
.insert(BUILD_TARGET, ConstVal::new(BUILD_TARGET_DOC));

Expand All @@ -298,7 +311,7 @@ pub(crate) fn new_system_env(
env.map
.insert(CARGO_MANIFEST_DIR, ConstVal::new(CARGO_MANIFEST_DIR_DOC));

if let Err(e) = env.init(std_env) {
if let Err(e) = env.init(shadow) {
println!("{e}");
}
env.map
Expand Down
15 changes: 13 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,7 @@ pub struct Shadow {
pub map: BTreeMap<ShadowConst, ConstVal>,
/// Build environment variables, obtained through [`std::env::vars`].
pub std_env: BTreeMap<String, String>,
/// Constants in the denylist, passed through [`new_deny`] or [`Shadow::build`].
/// Constants in the deny list, passed through [`new_deny`] or [`Shadow::build`].
pub deny_const: BTreeSet<ShadowConst>,
}

Expand Down Expand Up @@ -355,6 +355,17 @@ impl Shadow {
CiType::None
}

/// Checks if the specified build constant is in the deny list.
///
/// # Arguments
/// * `deny_const` - A value of type `ShadowConst` representing the build constant to check.
///
/// # Returns
/// * `true` if the build constant is present in the deny list; otherwise, `false`.
pub fn deny_contains(&self, deny_const: ShadowConst) -> bool {
self.deny_const.contains(&deny_const)
}

/// Create a new [`Shadow`] configuration with a provided denylist.
/// The project source path and output file are automatically derived from Cargo build environment variables.
pub fn build(deny_const: BTreeSet<ShadowConst>) -> SdResult<Shadow> {
Expand Down Expand Up @@ -392,7 +403,7 @@ impl Shadow {
for (k, v) in new_project(&shadow.std_env) {
map.insert(k, v);
}
for (k, v) in new_system_env(&shadow.std_env) {
for (k, v) in new_system_env(&shadow) {
map.insert(k, v);
}
shadow.map = map;
Expand Down
Loading