I'm trying to create a tree of files and directories using the net-sftp library.
I can get a recursive listing of files by using the .glob method and can determine if one of the results is a directory by using the .opendir method.
I've been able to create a hash that has files and another hash that has directories, but I'd like to be able to create a tree.
files = []
directories = []
sftp.dir.glob("/home/**/**") do |entry|
fullpath = "/home/" + entry.name
file = Hash.new
file[:path] = fullpath
sftp.opendir(fullpath) do |response|
unless response.ok?
files.push(file)
else
directories.push(file)
end
end
else
end
end
Is creating such a tree possible from the results that net-sftp returns?
I was able to generate a tree with the following code:
def self.get_tree(host, username, password, path, name=nil)
data = {:text =>(name || path)}
data[:children] = children = []
Net::SFTP.start(host, username, :password => password) do |sftp|
sftp.dir.foreach(path) do |entry|
next if (entry.name == '..' || entry.name == '.')
if entry.longname.start_with?('d')
children << self.get_tree(host,username,password, path + entry.name + '/')
end
if !entry.longname.start_with?('d')
children << entry.name
end
end
end
end
It's a recursive function that will create a full tree when given a directory path using Net::SFTP.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With