22
33use anyhow:: { Context , Result } ;
44use serde:: { Deserialize , Serialize } ;
5- use std:: io:: Write ;
5+ use std:: io:: { Read , Write } ;
66use std:: path:: { Path , PathBuf } ;
7- use std:: {
8- borrow:: Cow ,
9- fs:: { self , File } ,
10- } ;
7+ use std:: { borrow:: Cow , fs} ;
118use tmc_langs_framework:: file_util;
129use toml:: { value:: Table , Value } ;
1310
@@ -66,28 +63,30 @@ impl TmcConfig {
6663
6764 pub fn save ( self , client_name : & str ) -> Result < ( ) > {
6865 let path = Self :: get_location ( client_name) ?;
69- file_util:: lock!( & path) ;
66+ let mut lock = file_util:: create_file_lock ( & path) ?;
67+ let mut guard = lock. lock ( ) ?;
7068
7169 let toml = toml:: to_string_pretty ( & self ) . context ( "Failed to serialize HashMap" ) ?;
72- fs:: write ( & path, toml. as_bytes ( ) )
70+ guard
71+ . write_all ( toml. as_bytes ( ) )
7372 . with_context ( || format ! ( "Failed to write TOML to {}" , path. display( ) ) ) ?;
7473 Ok ( ( ) )
7574 }
7675
7776 pub fn reset ( client_name : & str ) -> Result < ( ) > {
7877 let path = Self :: get_location ( client_name) ?;
79- file_util:: lock!( & path) ;
80-
81- Self :: init_at ( client_name, & path) ?;
78+ Self :: init_at ( client_name, & path) ?; // init locks the file
8279 Ok ( ( ) )
8380 }
8481
8582 pub fn load ( client_name : & str ) -> Result < TmcConfig > {
8683 let path = Self :: get_location ( client_name) ?;
87- file_util:: lock!( & path) ;
84+ let mut lock = file_util:: open_file_lock ( & path) ?;
85+ let mut guard = lock. lock ( ) ?;
8886
89- let config = match fs:: read ( & path) {
90- Ok ( bytes) => match toml:: from_slice ( & bytes) {
87+ let mut buf = vec ! [ ] ;
88+ let config = match guard. read_to_end ( & mut buf) {
89+ Ok ( _) => match toml:: from_slice ( & buf) {
9190 Ok ( config) => Ok ( config) ,
9291 Err ( _) => {
9392 log:: error!(
@@ -112,10 +111,9 @@ impl TmcConfig {
112111
113112 // initializes the default configuration file at the given path
114113 fn init_at ( client_name : & str , path : & Path ) -> Result < TmcConfig > {
115- file_util:: lock!( path) ;
116-
117- let mut file = File :: create ( & path)
114+ let mut lock = file_util:: create_file_lock ( path)
118115 . with_context ( || format ! ( "Failed to create new config file at {}" , path. display( ) ) ) ?;
116+ let mut guard = lock. lock ( ) ?;
119117
120118 let default_project_dir = dirs:: data_local_dir ( )
121119 . context ( "Failed to find local data directory" ) ?
@@ -134,7 +132,8 @@ impl TmcConfig {
134132 } ;
135133
136134 let toml = toml:: to_string_pretty ( & config) . context ( "Failed to serialize config" ) ?;
137- file. write_all ( toml. as_bytes ( ) )
135+ guard
136+ . write_all ( toml. as_bytes ( ) )
138137 . with_context ( || format ! ( "Failed to write default config to {}" , path. display( ) ) ) ?;
139138 Ok ( config)
140139 }
0 commit comments