File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -274,11 +274,25 @@ where
274274 T : Serialize ,
275275{
276276 async fn write_to_file ( & self , path : impl AsRef < Path > + Debug ) -> eyre:: Result < ( ) > {
277+ let path = path. as_ref ( ) ;
278+
279+ let temp_path = path. with_extension ( "tmp" ) ;
277280 let contents = serde_json:: to_vec_pretty ( self ) . wrap_err ( "failed to serialize to JSON" ) ?;
278- let mut file = File :: create ( path) . await . wrap_err ( "failed to create file" ) ?;
281+
282+ let mut file = File :: create ( & temp_path)
283+ . await
284+ . wrap_err ( "failed to create temp file" ) ?;
285+
279286 file. write_all ( & contents)
280287 . await
281- . wrap_err ( "failed to write to file" ) ?;
288+ . wrap_err ( "failed to write to temp file" ) ?;
289+
290+ file. sync_all ( ) . await . wrap_err ( "failed to sync to disk" ) ?;
291+
292+ tokio:: fs:: rename ( & temp_path, path)
293+ . await
294+ . wrap_err ( "failed to rename temp file to target" ) ?;
295+
282296 Ok ( ( ) )
283297 }
284298}
You can’t perform that action at this time.
0 commit comments