Skip to content

Instantly share code, notes, and snippets.

@rklemme
Created Mar 4, 2010
Embed
What would you like to do?
Resumable directory search like "find -depth"
#! 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