Skip to content

Commit

Permalink
Don't dirty shadow.rs unless contents have changed
Browse files Browse the repository at this point in the history
Stop spurious rebuilds for any project that uses shadow-rs - even if no
source has changed, because the shadow.rs file is blindly clobbered on
every build, cargo thinks something has changed due to the directive to
rebuild if shadow.rs changes. Instead, check if any of the new contents
are actually different, ignoring the "Generation time" header.
  • Loading branch information
vlovich committed Jan 31, 2025
1 parent e33e8c9 commit 3ae4ac0
Showing 1 changed file with 17 additions and 1 deletion.
18 changes: 17 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,17 @@ pub(crate) fn get_std_env() -> BTreeMap<String, String> {
env_map
}

fn is_same_contents<P1: AsRef<Path>, P2: AsRef<Path>>(p1: P1, p2: P2) -> SdResult<bool> {
let c1 = std::fs::read_to_string(p1.as_ref())?;
let c2 = std::fs::read_to_string(p2.as_ref())?;

// Skip the auto-generated header comment which always changes
let c1 = c1.split('\n').skip_while(|line| line.starts_with("//")).collect::<Vec<_>>();
let c2 = c2.split('\n').skip_while(|line| line.starts_with("//")).collect::<Vec<_>>();

Ok(c1 == c2)
}

/// `shadow-rs` configuration.
///
/// This struct encapsulates the configuration for the `shadow-rs` build process. It allows for fine-grained control over
Expand Down Expand Up @@ -474,9 +485,10 @@ impl Shadow {
path.join(DEFINE_SHADOW_RS)
}
};
let tmp_out = out.with_file_name(format!(".{DEFINE_SHADOW_RS}.tmp"));

let mut shadow = Shadow {
f: File::create(out)?,
f: File::create(&tmp_out)?,
map: Default::default(),
std_env: Default::default(),
deny_const,
Expand All @@ -502,6 +514,10 @@ impl Shadow {

shadow.write_all()?;

if !is_same_contents(&tmp_out, &out).unwrap_or(false) {
std::fs::rename(tmp_out, out)?;
}

// handle hook
if let Some(h) = builder.get_hook() {
shadow.hook(h.hook_inner())?
Expand Down

0 comments on commit 3ae4ac0

Please sign in to comment.