Skip to content

Commit 587b307

Browse files
authored
orb-mcu-util: hw rev: overwrite file if content is different (#252)
to prevent useless writes to flash. Plus, use tokio::fs instead of std::fs in async context
1 parent 9d05f7b commit 587b307

File tree

1 file changed

+32
-10
lines changed

1 file changed

+32
-10
lines changed

mcu-util/src/main.rs

+32-10
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
#![forbid(unsafe_code)]
22

3-
use std::io::Write;
43
use std::path::PathBuf;
54
use std::time::Duration;
65

@@ -10,6 +9,9 @@ use clap::{
109
};
1110
use color_eyre::eyre::{Context, Result};
1211
use orb_build_info::{make_build_info, BuildInfo};
12+
use tokio::fs;
13+
use tokio::fs::OpenOptions;
14+
use tokio::io::AsyncWriteExt;
1315
use tracing::{debug, error};
1416

1517
use crate::orb::Orb;
@@ -162,19 +164,39 @@ async fn execute(args: Args) -> Result<()> {
162164
.await?
163165
}
164166
SubCommand::HardwareRevision { filename } => {
165-
let hw_str = orb.get_revision().await?;
167+
let hw_rev = orb.get_revision().await?;
166168
match filename {
167169
None => {
168-
println!("{}", hw_str);
170+
println!("{}", hw_rev);
169171
}
170172
Some(ref filename) => {
171-
let mut file =
172-
std::fs::File::create(filename).with_context(|| {
173-
format!("Failed to create file {filename:?}")
174-
})?;
175-
write!(file, "{}", hw_str).with_context(|| {
176-
format!("Failed to write to file {filename:?}")
177-
})?;
173+
let hw_str = format!("{}", hw_rev);
174+
// check that the file exists and compare content with what's going to be
175+
// written to avoid writing the same content.
176+
if let Ok(existing_content) = fs::read_to_string(filename)
177+
.await
178+
.with_context(|| format!("Failed to read file {filename:?}"))
179+
{
180+
if existing_content == hw_str {
181+
debug!("Content is the same, skipping write");
182+
return Ok(());
183+
}
184+
}
185+
186+
// overwrite the file with the new content
187+
let mut file = OpenOptions::new()
188+
.read(true)
189+
.write(true)
190+
.truncate(true)
191+
.create(true)
192+
.open(filename)
193+
.await
194+
.with_context(|| format!("Failed to open file {filename:?}"))?;
195+
file.set_len(0).await?;
196+
if file.write(hw_str.as_bytes()).await? != hw_str.len() {
197+
return Err(color_eyre::eyre::eyre!("Failed to write to file"));
198+
}
199+
file.flush().await?;
178200
}
179201
}
180202
}

0 commit comments

Comments
 (0)