@@ -366,12 +366,7 @@ pub fn container_init_process(
366366 }
367367
368368 // add HOME into envs if not exists
369- if !ctx. envs . contains_key ( "HOME" ) {
370- if let Some ( dir_home) = utils:: get_user_home ( ctx. process . user ( ) . uid ( ) ) {
371- ctx. envs
372- . insert ( "HOME" . to_owned ( ) , dir_home. to_string_lossy ( ) . to_string ( ) ) ;
373- }
374- }
369+ set_home_env_if_not_exists ( & mut ctx. envs , ctx. process . user ( ) . uid ( ) . into ( ) ) ;
375370
376371 args. executor . validate ( ctx. spec ) ?;
377372 args. executor . setup_envs ( ctx. envs ) ?;
@@ -901,6 +896,14 @@ fn verify_cwd() -> Result<()> {
901896 Ok ( ( ) )
902897}
903898
899+ fn set_home_env_if_not_exists ( envs : & mut HashMap < String , String > , uid : Uid ) {
900+ if envs. get ( "HOME" ) . is_none_or ( |v| v. is_empty ( ) ) {
901+ if let Some ( dir_home) = utils:: get_user_home ( uid. into ( ) ) {
902+ envs. insert ( "HOME" . to_owned ( ) , dir_home. to_string_lossy ( ) . to_string ( ) ) ;
903+ }
904+ }
905+ }
906+
904907#[ cfg( test) ]
905908mod tests {
906909 use std:: fs;
@@ -1192,4 +1195,30 @@ mod tests {
11921195 let set_io_prioritys = test_command. get_io_priority_args ( ) ;
11931196 assert_eq ! ( set_io_prioritys[ 0 ] , want_io_priority) ;
11941197 }
1198+
1199+ #[ test]
1200+ fn test_set_home_env_if_not_exists_already_exists ( ) {
1201+ let mut envs = HashMap :: new ( ) ;
1202+ envs. insert ( "HOME" . to_owned ( ) , "/existing/home" . to_owned ( ) ) ;
1203+
1204+ set_home_env_if_not_exists ( & mut envs, Uid :: from_raw ( 0 ) ) ;
1205+ assert_eq ! ( envs. get( "HOME" ) , Some ( & "/existing/home" . to_string( ) ) ) ;
1206+ }
1207+
1208+ #[ test]
1209+ fn test_set_home_env_if_not_exists_already_exists_but_empty_value ( ) {
1210+ let mut envs = HashMap :: new ( ) ;
1211+ envs. insert ( "HOME" . to_owned ( ) , "" . to_owned ( ) ) ;
1212+
1213+ set_home_env_if_not_exists ( & mut envs, Uid :: from_raw ( 0 ) ) ;
1214+ assert_eq ! ( envs. get( "HOME" ) , Some ( & "/root" . to_string( ) ) ) ;
1215+ }
1216+
1217+ #[ test]
1218+ fn test_set_home_env_if_not_exists_not_set ( ) {
1219+ let mut envs = HashMap :: new ( ) ;
1220+
1221+ set_home_env_if_not_exists ( & mut envs, Uid :: from_raw ( 0 ) ) ;
1222+ assert_eq ! ( envs. get( "HOME" ) , Some ( & "/root" . to_string( ) ) ) ;
1223+ }
11951224}
0 commit comments