Skip to content

Commit

Permalink
fix: Only touch include file if contents is changed (#1058)
Browse files Browse the repository at this point in the history
Most generated files are untouched when the contents doesn't change. Use the same mechanism for include file as well.
  • Loading branch information
caspermeijn committed Jun 10, 2024
1 parent e7049d3 commit ba77654
Showing 1 changed file with 28 additions and 16 deletions.
44 changes: 28 additions & 16 deletions prost-build/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -806,30 +806,22 @@ impl Config {
.expect("every module should have a filename");
let output_path = target.join(file_name);

let previous_content = fs::read(&output_path);

if previous_content
.map(|previous_content| previous_content == content.as_bytes())
.unwrap_or(false)
{
trace!("unchanged: {:?}", file_name);
} else {
trace!("writing: {:?}", file_name);
fs::write(output_path, content)?;
}
write_file_if_changed(&output_path, content.as_bytes())?;
}

if let Some(ref include_file) = self.include_file {
trace!("Writing include file: {:?}", target.join(include_file));
let mut file = fs::File::create(target.join(include_file))?;
self.write_line(&mut file, 0, "// This file is @generated by prost-build.")?;
let path = target.join(include_file);
trace!("Writing include file: {:?}", path);
let mut buffer = Vec::new();
self.write_line(&mut buffer, 0, "// This file is @generated by prost-build.")?;
self.write_includes(
modules.keys().collect(),
&mut file,
&mut buffer,
if target_is_env { None } else { Some(&target) },
&file_names,
)?;
file.flush()?;

write_file_if_changed(&path, &buffer)?;
}

Ok(())
Expand Down Expand Up @@ -1072,6 +1064,26 @@ impl Config {
}
}

/// Write a slice as the entire contents of a file.
///
/// This function will create a file if it does not exist,
/// and will entirely replace its contents if it does. When
/// the contents is already correct, it doesn't touch to the file.
fn write_file_if_changed(path: &Path, content: &[u8]) -> std::io::Result<()> {
let previous_content = fs::read(path);

if previous_content
.map(|previous_content| previous_content == content)
.unwrap_or(false)
{
trace!("unchanged: {:?}", path);
Ok(())
} else {
trace!("writing: {:?}", path);
fs::write(path, content)
}
}

impl default::Default for Config {
fn default() -> Config {
Config {
Expand Down

0 comments on commit ba77654

Please sign in to comment.