@@ -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,15 @@ fn verify_cwd() -> Result<()> {
901896 Ok ( ( ) )
902897}
903898
899+ // Set the HOME environment variable if it is not already set or is empty.
900+ fn set_home_env_if_not_exists ( envs : & mut HashMap < String , String > , uid : Uid ) {
901+ if envs. get ( "HOME" ) . is_none_or ( |v| v. is_empty ( ) ) {
902+ if let Some ( dir_home) = utils:: get_user_home ( uid. into ( ) ) {
903+ envs. insert ( "HOME" . to_owned ( ) , dir_home. to_string_lossy ( ) . to_string ( ) ) ;
904+ }
905+ }
906+ }
907+
904908#[ cfg( test) ]
905909mod tests {
906910 use std:: fs;
@@ -1192,4 +1196,30 @@ mod tests {
11921196 let set_io_prioritys = test_command. get_io_priority_args ( ) ;
11931197 assert_eq ! ( set_io_prioritys[ 0 ] , want_io_priority) ;
11941198 }
1199+
1200+ #[ test]
1201+ fn test_set_home_env_if_not_exists_already_exists ( ) {
1202+ let mut envs = HashMap :: new ( ) ;
1203+ envs. insert ( "HOME" . to_owned ( ) , "/existing/home" . to_owned ( ) ) ;
1204+
1205+ set_home_env_if_not_exists ( & mut envs, Uid :: from_raw ( 0 ) ) ;
1206+ assert_eq ! ( envs. get( "HOME" ) , Some ( & "/existing/home" . to_string( ) ) ) ;
1207+ }
1208+
1209+ #[ test]
1210+ fn test_set_home_env_if_not_exists_already_exists_but_empty_value ( ) {
1211+ let mut envs = HashMap :: new ( ) ;
1212+ envs. insert ( "HOME" . to_owned ( ) , "" . to_owned ( ) ) ;
1213+
1214+ set_home_env_if_not_exists ( & mut envs, Uid :: from_raw ( 0 ) ) ;
1215+ assert_eq ! ( envs. get( "HOME" ) , Some ( & "/root" . to_string( ) ) ) ;
1216+ }
1217+
1218+ #[ test]
1219+ fn test_set_home_env_if_not_exists_not_set ( ) {
1220+ let mut envs = HashMap :: new ( ) ;
1221+
1222+ set_home_env_if_not_exists ( & mut envs, Uid :: from_raw ( 0 ) ) ;
1223+ assert_eq ! ( envs. get( "HOME" ) , Some ( & "/root" . to_string( ) ) ) ;
1224+ }
11951225}
0 commit comments