如何从Net-SFTP结果创建文件/目录树?

6

我正在尝试使用net-sftp库创建文件和目录树。

通过使用.glob方法,我可以获取递归列表中的文件,并使用.opendir方法确定结果是否为目录。

我已经能够创建一个包含文件的哈希表和另一个包含目录的哈希表,但我希望能够创建一棵树。

 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

从net-sftp的结果中创建这样的树结构是否可能?
1个回答

3
我可以用以下代码生成一棵树:
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

这是一个递归函数,使用Net::SFTP可以在给定目录路径的情况下创建完整的树形结构。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接