From 1c6825fb9b4d5c8c73fee01a8fbd328cea2b78fa Mon Sep 17 00:00:00 2001 From: Sam Goldstein Date: Thu, 29 Oct 2009 00:10:30 -0700 Subject: [PATCH] added support for recursive globbing FakeDir.glob now handles recursive globs (i.e. '**') like the standard lib Dir. Previously they were treated identically to single wild cards (i.e. '*') Resolves issue #16 http://github.com/defunkt/fakefs/issues#issue/16 --- lib/fakefs/file_system.rb | 20 +++++++++++++++++++- test/fakefs_test.rb | 15 +++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/lib/fakefs/file_system.rb b/lib/fakefs/file_system.rb index 09af802..9eb02e9 100644 --- a/lib/fakefs/file_system.rb +++ b/lib/fakefs/file_system.rb @@ -106,7 +106,20 @@ module FakeFS return [] unless dir.respond_to? :[] pattern , *parts = parts - matches = dir.reject {|k,v| /\A#{pattern.gsub('?','.').gsub('*', '.*')}\Z/ !~ k }.values + matches = case pattern + when '**' + case parts + when ['*'], [] + parts = [] # end recursion + directories_under(dir).map do |d| + d.values.select{|f| f.is_a? FakeFile } + end.flatten.uniq + else + directories_under(dir) + end + else + dir.reject {|k,v| /\A#{pattern.gsub('?','.').gsub('*', '.*')}\Z/ !~ k }.values + end if parts.empty? # we're done recursing matches @@ -114,5 +127,10 @@ module FakeFS matches.map{|entry| find_recurser(entry, parts) } end end + + def directories_under(dir) + children = dir.values.select{|f| f.is_a? FakeDir} + ([dir] + children + children.map{|c| directories_under(c)}).flatten.uniq + end end end diff --git a/test/fakefs_test.rb b/test/fakefs_test.rb index c35daaa..85d6d34 100644 --- a/test/fakefs_test.rb +++ b/test/fakefs_test.rb @@ -397,6 +397,21 @@ class FakeFSTest < Test::Unit::TestCase #assert_equal ['/'], Dir['/'] end + def test_dir_glob_handles_recursive_globs + File.open('/one/two/three/four.rb', 'w') + File.open('/one/five.rb', 'w') + assert_equal ['/one/five.rb', '/one/two/three/four.rb'], Dir['/one/**/*.rb'] + assert_equal ['/one/two'], Dir['/one/**/two'] + assert_equal ['/one/two/three'], Dir['/one/**/three'] + end + + def test_dir_recursive_glob_ending_in_wildcards_only_returns_files + File.open('/one/two/three/four.rb', 'w') + File.open('/one/five.rb', 'w') + assert_equal ['/one/five.rb', '/one/two/three/four.rb'], Dir['/one/**/*'] + assert_equal ['/one/five.rb', '/one/two/three/four.rb'], Dir['/one/**'] + end + def test_chdir_changes_directories_like_a_boss # I know memes! FileUtils.mkdir_p '/path'