@@ -52,10 +52,12 @@ pub fn load_config() -> Result<CloudConfig> {
5252}
5353
5454pub fn save_config ( config : & CloudConfig ) -> Result < ( ) > {
55- let dir = config_dir ( ) ;
56- std:: fs:: create_dir_all ( & dir) . with_context ( || format ! ( "Failed to create {}" , dir. display( ) ) ) ?;
57-
5855 let path = config_path ( ) ;
56+ if let Some ( parent) = path. parent ( ) {
57+ std:: fs:: create_dir_all ( parent)
58+ . with_context ( || format ! ( "Failed to create {}" , parent. display( ) ) ) ?;
59+ }
60+
5961 let json = serde_json:: to_string_pretty ( config) . context ( "Failed to serialize config" ) ?;
6062 std:: fs:: write ( & path, json)
6163 . with_context ( || format ! ( "Failed to write config to {}" , path. display( ) ) ) ?;
@@ -71,3 +73,40 @@ pub fn clear_config() -> Result<()> {
7173 }
7274 Ok ( ( ) )
7375}
76+
77+ #[ cfg( test) ]
78+ mod tests {
79+ use super :: * ;
80+ use std:: sync:: { Mutex , OnceLock } ;
81+
82+ static ENV_LOCK : OnceLock < Mutex < ( ) > > = OnceLock :: new ( ) ;
83+
84+ fn env_lock ( ) -> std:: sync:: MutexGuard < ' static , ( ) > {
85+ ENV_LOCK . get_or_init ( || Mutex :: new ( ( ) ) ) . lock ( ) . unwrap ( )
86+ }
87+
88+ #[ test]
89+ fn save_config_creates_parent_dir_for_rustapi_config_path_override ( ) {
90+ let _guard = env_lock ( ) ;
91+ let dir = tempfile:: tempdir ( ) . expect ( "tempdir" ) ;
92+ let config_file = dir. path ( ) . join ( "nested" ) . join ( "cloud-config.json" ) ;
93+ std:: env:: set_var ( "RUSTAPI_CONFIG_PATH" , config_file. to_str ( ) . unwrap ( ) ) ;
94+
95+ let cfg = CloudConfig {
96+ token : Some ( "test-token" . into ( ) ) ,
97+ refresh_token : None ,
98+ user : Some ( UserInfo {
99+ login : "test" . into ( ) ,
100+ tier : "hobby" . into ( ) ,
101+ avatar_url : None ,
102+ } ) ,
103+ last_login : None ,
104+ cloud_url : Some ( "http://127.0.0.1:8080" . into ( ) ) ,
105+ } ;
106+
107+ save_config ( & cfg) . expect ( "save under override path" ) ;
108+ assert ! ( config_file. exists( ) ) ;
109+
110+ std:: env:: remove_var ( "RUSTAPI_CONFIG_PATH" ) ;
111+ }
112+ }
0 commit comments