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

1

6

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?

Applaud answered 4/2, 2015 at 16:10 Comment(0)
A
3

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.

Applaud answered 27/8, 2016 at 16:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.