@@ -5,7 +5,6 @@ use mdbook::errors::Result;
55use mdbook:: utils;
66use mdbook:: MDBook ;
77use pathdiff:: diff_paths;
8- use std:: env;
98use std:: path:: { Path , PathBuf } ;
109use std:: sync:: mpsc:: channel;
1110use std:: thread:: sleep;
@@ -89,13 +88,16 @@ fn find_gitignore(book_root: &Path) -> Option<PathBuf> {
8988}
9089
9190fn filter_ignored_files ( ignore : Gitignore , paths : & [ PathBuf ] ) -> Vec < PathBuf > {
92- let current_dir = env:: current_dir ( ) . expect ( "Unable to determine the current directory" ) ;
91+ let ignore_root = ignore
92+ . path ( )
93+ . canonicalize ( )
94+ . expect ( "ignore root canonicalize error" ) ;
9395
9496 paths
9597 . iter ( )
9698 . filter ( |path| {
9799 let relative_path =
98- diff_paths ( & current_dir , & path ) . expect ( "One of the paths should be an absolute" ) ;
100+ diff_paths ( & path , & ignore_root ) . expect ( "One of the paths should be an absolute" ) ;
99101 !ignore
100102 . matched_path_or_any_parents ( & relative_path, relative_path. is_dir ( ) )
101103 . is_ignore ( )
@@ -185,3 +187,50 @@ where
185187 }
186188 }
187189}
190+
191+ #[ cfg( test) ]
192+ mod tests {
193+ use super :: * ;
194+ use ignore:: gitignore:: GitignoreBuilder ;
195+ use std:: env;
196+
197+ fn path_to_buf ( root : & str , file_name : & str ) -> PathBuf {
198+ let mut path = PathBuf :: from ( root) ;
199+ path. push ( file_name) ;
200+ path
201+ }
202+
203+ #[ test]
204+ fn test_filter_ignored_files ( ) {
205+ let current_dir = env:: current_dir ( ) . unwrap ( ) ;
206+
207+ let ignore = GitignoreBuilder :: new ( & current_dir)
208+ . add_line ( None , "*.html" )
209+ . unwrap ( )
210+ . build ( )
211+ . unwrap ( ) ;
212+ let should_remain = path_to_buf ( current_dir. to_str ( ) . unwrap ( ) , "record.text" ) ;
213+ let should_filter = path_to_buf ( current_dir. to_str ( ) . unwrap ( ) , "index.html" ) ;
214+
215+ let remain = filter_ignored_files ( ignore, & [ should_remain. clone ( ) , should_filter] ) ;
216+ assert_eq ! ( remain, vec![ should_remain] )
217+ }
218+
219+ #[ test]
220+ fn filter_ignored_files_should_handle_parent_dir ( ) {
221+ let current_dir = env:: current_dir ( ) . unwrap ( ) ;
222+
223+ let ignore = GitignoreBuilder :: new ( & current_dir)
224+ . add_line ( None , "*.html" )
225+ . unwrap ( )
226+ . build ( )
227+ . unwrap ( ) ;
228+
229+ let parent_dir = format ! ( "{}/../" , current_dir. to_str( ) . unwrap( ) ) ;
230+ let should_remain = path_to_buf ( & parent_dir, "record.text" ) ;
231+ let should_filter = path_to_buf ( & parent_dir, "index.html" ) ;
232+
233+ let remain = filter_ignored_files ( ignore, & [ should_remain. clone ( ) , should_filter] ) ;
234+ assert_eq ! ( remain, vec![ should_remain] )
235+ }
236+ }
0 commit comments