1
1
#![ forbid( unsafe_code) ]
2
2
3
- use std:: io:: Write ;
4
3
use std:: path:: PathBuf ;
5
4
use std:: time:: Duration ;
6
5
@@ -10,6 +9,9 @@ use clap::{
10
9
} ;
11
10
use color_eyre:: eyre:: { Context , Result } ;
12
11
use orb_build_info:: { make_build_info, BuildInfo } ;
12
+ use tokio:: fs;
13
+ use tokio:: fs:: OpenOptions ;
14
+ use tokio:: io:: AsyncWriteExt ;
13
15
use tracing:: { debug, error} ;
14
16
15
17
use crate :: orb:: Orb ;
@@ -162,19 +164,39 @@ async fn execute(args: Args) -> Result<()> {
162
164
. await ?
163
165
}
164
166
SubCommand :: HardwareRevision { filename } => {
165
- let hw_str = orb. get_revision ( ) . await ?;
167
+ let hw_rev = orb. get_revision ( ) . await ?;
166
168
match filename {
167
169
None => {
168
- println ! ( "{}" , hw_str ) ;
170
+ println ! ( "{}" , hw_rev ) ;
169
171
}
170
172
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 ?;
178
200
}
179
201
}
180
202
}
0 commit comments