@@ -421,25 +421,29 @@ pub fn get_backup_path(
421421}
422422
423423fn simple_backup_path ( path : & Path , suffix : & str ) -> PathBuf {
424- let mut p = path. to_string_lossy ( ) . into_owned ( ) ;
425- p . push_str ( suffix) ;
426- PathBuf :: from ( p )
424+ let mut file_name = path. file_name ( ) . unwrap_or_default ( ) . to_os_string ( ) ;
425+ file_name . push ( suffix) ;
426+ path . with_file_name ( file_name )
427427}
428428
429429fn numbered_backup_path ( path : & Path ) -> PathBuf {
430+ let file_name = path. file_name ( ) . unwrap_or_default ( ) ;
430431 for i in 1_u64 .. {
431- let path_str = & format ! ( "{}.~{}~" , path. to_string_lossy( ) , i) ;
432- let path = Path :: new ( path_str) ;
432+ let mut numbered_file_name = file_name. to_os_string ( ) ;
433+ numbered_file_name. push ( format ! ( ".~{}~" , i) ) ;
434+ let path = path. with_file_name ( numbered_file_name) ;
433435 if !path. exists ( ) {
434- return path. to_path_buf ( ) ;
436+ return path;
435437 }
436438 }
437439 panic ! ( "cannot create backup" )
438440}
439441
440442fn existing_backup_path ( path : & Path , suffix : & str ) -> PathBuf {
441- let test_path_str = & format ! ( "{}.~1~" , path. to_string_lossy( ) ) ;
442- let test_path = Path :: new ( test_path_str) ;
443+ let file_name = path. file_name ( ) . unwrap_or_default ( ) ;
444+ let mut numbered_file_name = file_name. to_os_string ( ) ;
445+ numbered_file_name. push ( ".~1~" ) ;
446+ let test_path = path. with_file_name ( numbered_file_name) ;
443447 if test_path. exists ( ) {
444448 numbered_backup_path ( path)
445449 } else {
@@ -660,6 +664,44 @@ mod tests {
660664 let result = determine_backup_suffix ( & matches) ;
661665 assert_eq ! ( result, "-v" ) ;
662666 }
667+
668+ #[ test]
669+ fn test_numbered_backup_path ( ) {
670+ assert_eq ! ( numbered_backup_path( & Path :: new( "" ) ) , PathBuf :: from( ".~1~" ) ) ;
671+ assert_eq ! (
672+ numbered_backup_path( & Path :: new( "/" ) ) ,
673+ PathBuf :: from( "/.~1~" )
674+ ) ;
675+ assert_eq ! (
676+ numbered_backup_path( & Path :: new( "/hello/world" ) ) ,
677+ PathBuf :: from( "/hello/world.~1~" )
678+ ) ;
679+ assert_eq ! (
680+ numbered_backup_path( & Path :: new( "/hello/world/" ) ) ,
681+ PathBuf :: from( "/hello/world.~1~" )
682+ ) ;
683+ }
684+
685+ #[ test]
686+ fn test_simple_backup_path ( ) {
687+ assert_eq ! (
688+ simple_backup_path( & Path :: new( "" ) , ".bak" ) ,
689+ PathBuf :: from( ".bak" )
690+ ) ;
691+ assert_eq ! (
692+ simple_backup_path( & Path :: new( "/" ) , ".bak" ) ,
693+ PathBuf :: from( "/.bak" )
694+ ) ;
695+ assert_eq ! (
696+ simple_backup_path( & Path :: new( "/hello/world" ) , ".bak" ) ,
697+ PathBuf :: from( "/hello/world.bak" )
698+ ) ;
699+ assert_eq ! (
700+ simple_backup_path( & Path :: new( "/hello/world/" ) , ".bak" ) ,
701+ PathBuf :: from( "/hello/world.bak" )
702+ ) ;
703+ }
704+
663705 #[ test]
664706 fn test_source_is_target_backup ( ) {
665707 let source = Path :: new ( "data.txt.bak" ) ;
0 commit comments