Class | Net::SFTP::Operations::Dir |
In: |
lib/net/sftp/operations/dir.rb
|
Parent: | Object |
A convenience class for working with remote directories. It provides methods for searching and enumerating directory entries, similarly to the standard ::Dir class.
sftp.dir.foreach("/remote/path") do |entry| puts entry.name end p sftp.dir.entries("/remote/path").map { |e| e.name } sftp.dir.glob("/remote/path", "**/*.rb") do |entry| puts entry.name end
sftp | [R] | The SFTP session object that drives this directory factory. |
Returns an array of Name objects representing the items in the given remote directory, path.
# File lib/net/sftp/operations/dir.rb, line 42 42: def entries(path) 43: results = [] 44: foreach(path) { |entry| results << entry } 45: return results 46: end
Calls the block once for each entry in the named directory on the remote server. Yields a Name object to the block, rather than merely the name of the entry.
# File lib/net/sftp/operations/dir.rb, line 30 30: def foreach(path) 31: handle = sftp.opendir!(path) 32: while entries = sftp.readdir!(handle) 33: entries.each { |entry| yield entry } 34: end 35: return nil 36: ensure 37: sftp.close!(handle) if handle 38: end
Works as ::Dir.glob, matching (possibly recursively) all directory entries under path against pattern. If a block is given, matches will be yielded to the block as they are found; otherwise, they will be returned in an array when the method finishes.
Because working over an SFTP connection is always going to be slower than working purely locally, don‘t expect this method to perform with the same level of alacrity that ::Dir.glob does; it will work best for shallow directory hierarchies with relatively few directories, though it should be able to handle modest numbers of files in each directory.
# File lib/net/sftp/operations/dir.rb, line 58 58: def glob(path, pattern, flags=0) 59: flags |= ::File::FNM_PATHNAME 60: path = path.chop if path[-1,1] == "/" 61: 62: results = [] unless block_given? 63: queue = entries(path).reject { |e| e.name == "." || e.name == ".." } 64: while queue.any? 65: entry = queue.shift 66: 67: if entry.directory? && !%w(. ..).include?(::File.basename(entry.name)) 68: queue += entries("#{path}/#{entry.name}").map do |e| 69: e.name.replace("#{entry.name}/#{e.name}") 70: e 71: end 72: end 73: 74: if ::File.fnmatch(pattern, entry.name, flags) 75: if block_given? 76: yield entry 77: else 78: results << entry 79: end 80: end 81: end 82: 83: return results unless block_given? 84: end