Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a file/directory tree from Net-SFTP results?

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?

like image 730
Jamie Little Avatar asked Feb 04 '15 16:02

Jamie Little


1 Answers

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.

like image 77
Jamie Little Avatar answered Nov 12 '22 03:11

Jamie Little