【问题标题】:How can I create a file/directory tree from Net-SFTP results?如何从 Net-SFTP 结果创建文件/目录树?
【发布时间】:2015-02-04 16:10:40
【问题描述】:

我正在尝试使用 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 返回的结果创建这样的树?

【问题讨论】:

    标签: ruby recursion tree net-sftp


    【解决方案1】:

    我能够使用以下代码生成一棵树:

    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 给定目录路径时,它将创建一棵完整的树。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-17
      • 2011-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-18
      相关资源
      最近更新 更多