1- use std:: path:: Path ;
1+ use std:: path:: { MAIN_SEPARATOR , MAIN_SEPARATOR_STR , Path } ;
22
33pub struct FileUtil {
44}
55
66impl FileUtil {
7+ pub fn normalize_path ( s : & str ) -> String {
8+ let src_char = if MAIN_SEPARATOR == '/' {
9+ "\\ "
10+ } else {
11+ "/"
12+ } ;
13+
14+ s. replace ( src_char, MAIN_SEPARATOR_STR )
15+ }
16+
717 pub fn get_sub_path ( path : & Path , base_dir : & str ) -> String {
18+ let nbase_dir = FileUtil :: normalize_path ( base_dir) ;
19+
820 let base;
9- if base_dir . ends_with ( "/" ) {
10- base = base_dir . to_owned ( ) ;
21+ if nbase_dir . ends_with ( MAIN_SEPARATOR_STR ) {
22+ base = nbase_dir ;
1123 } else {
12- base = base_dir . to_owned ( ) + "/" ;
24+ base = nbase_dir + MAIN_SEPARATOR_STR ;
1325 }
1426
1527 let sub_path;
1628
1729 let full_path = path. to_string_lossy ( ) ;
18- if full_path. starts_with ( & base) {
19- sub_path = & full_path[ base. len ( ) ..] ;
30+ let nfull_path = FileUtil :: normalize_path ( & full_path) ;
31+ if nfull_path. starts_with ( & base) {
32+ sub_path = & nfull_path[ base. len ( ) ..] ;
2033 } else {
21- sub_path = & full_path ;
34+ sub_path = & nfull_path ;
2235 }
2336
2437 sub_path. to_owned ( )
@@ -34,20 +47,20 @@ mod tests {
3447 fn test_get_sub_path ( ) {
3548 let p = Path :: new ( "/some/where/on/the/rainbow.docx" ) ;
3649 let b = "/some/where/on/" ;
37- assert_eq ! ( "the/rainbow.docx" , FileUtil :: get_sub_path( p, b) ) ;
50+ assert_eq ! ( FileUtil :: normalize_path ( "the/rainbow.docx" ) , FileUtil :: get_sub_path( p, b) ) ;
3851 }
3952
4053 #[ test]
4154 fn test_get_sub_path1 ( ) {
4255 let p = Path :: new ( "/some/where/on/the/rainbow.docx" ) ;
4356 let b = "/some/where/on" ;
44- assert_eq ! ( "the/rainbow.docx" , FileUtil :: get_sub_path( p, b) ) ;
57+ assert_eq ! ( FileUtil :: normalize_path ( "the/rainbow.docx" ) , FileUtil :: get_sub_path( p, b) ) ;
4558 }
4659
4760 #[ test]
4861 fn test_get_sub_path2 ( ) {
4962 let b = "/some/where/on/" ;
5063 let p = Path :: new ( "/elsewhere/cloud.docx" ) ;
51- assert_eq ! ( "/elsewhere/cloud.docx" , FileUtil :: get_sub_path( p, b) ) ;
64+ assert_eq ! ( FileUtil :: normalize_path ( "/elsewhere/cloud.docx" ) , FileUtil :: get_sub_path( p, b) ) ;
5265 }
5366}
0 commit comments