Created
March 4, 2010 15:27
-
-
Save rklemme/321803 to your computer and use it in GitHub Desktop.
Resumable directory search like "find -depth"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! ruby19 | |
DirDfs = Struct.new :root, :state_file do | |
def self.resume(state_file) | |
File.open(state_file, "rb") do |io| | |
Marshal.load(io) | |
end | |
end | |
def initialize(root, state_file) | |
@stack = [[root]] | |
self.state_file = state_file | |
end | |
def dfs | |
until @stack.empty? | |
while @stack.last.first | |
f = File.join(*@stack.map(&:first)) | |
if test ?d, f | |
@stack.push(Dir.entries(f).select {|s| /\A\.{1,2}\z/ !~ s}) | |
else | |
yield f | |
@stack.last.shift | |
end | |
save | |
end | |
@stack.pop | |
d = File.join(*@stack.map(&:first)) | |
yield d | |
@stack.last and @stack.last.shift | |
save | |
end | |
File.delete(state_file) rescue nil | |
self | |
end | |
def save | |
File.open(state_file, "wb") do |io| | |
Marshal.dump(self, io) | |
end | |
end | |
end | |
dd = if test ?f, 'c:/xxx.bin' | |
DirDfs.resume 'c:/xxx.bin' | |
else | |
DirDfs.new 'c:/Temp', 'c:/xxx.bin' | |
end | |
dd.dfs do |f| | |
print(test(?d, f) ? "DIR " : " ", f, "\n") | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment