Class: Net::FTP

Inherits:
Object
  • Object
show all
Defined in:
lib/ftp-ext.rb

Instance Method Summary collapse

Instance Method Details

#put_dir(opts = {}) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/ftp-ext.rb', line 7

def put_dir(opts = {})
  # Set default options
  options = {
    :local     => ".",
    :remote    => ".",
    :verbose   => false,
    :erase     => false,
    :exclude   => []
  }.merge!(opts)
  
  # Format options[:exclude]
  unless options[:preformatted]
    options[:exclude].map! { |f| File.join(options[:local], f) }
    options[:preformatted] = true        
  end
  
  # Check for existence of directory on remote server
  # and create it if it isn't there. If it does exist,
  # call sync_dir instead.
  if !remote_file_exists?(options[:remote])
    file_segments = options[:remote].split(File::SEPARATOR)
    
    # Make directory and all missing parent directories
    file_segments.length.times do |n|
      fpath = File.join(file_segments[0..n])
      
      unless remote_file_exists?(fpath) || fpath == ""
        puts "mkdir #{fpath}" if options[:verbose] == true
        mkdir(fpath)
      end
    end
  else
    options[:erase] ? (rmrf_dir(options[:remote], options[:verbose]); put_dir(options)) : sync_dir(options)
    return
  end
  
  # Upload files recursively
  Dir.foreach(options[:local]) do |f|
    local  = File.join(options[:local], f)
    remote = File.join(options[:remote], f)
    
    (puts "excluding #{local}"; next) if options[:exclude].include?(local)
    
    if File.file?(local)
      puts "cp #{remote}" if options[:verbose] == true
      File.binary?(local) ? putbinaryfile(local, remote) : puttextfile(local, remote)
      
    # ignore . and .., but upload other directories
    elsif !f.match(/^\.+$/)
      put_dir(options.merge({ :local => local, :remote => remote }))
    end
    
  end
  
end

#rmrf_dir(dir, verbose = false) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/ftp-ext.rb', line 63

def rmrf_dir(dir, verbose = false)
  return if !remote_file_exists?(dir)
  
  # Get file list from the server and begin deleting files
  begin
    flist = nlst(dir)
    
    flist.each do |f|
      # Ignore . and ..
      next if f.match(/^\.+$/)
      
      # Try to delete the file. If we fail then it's a directory
      begin
        delete(f)
        puts "rm #{f}" if verbose
      rescue Exception => e
        rmrf_dir(f, verbose)
      end
      
    end
  rescue Exception => e
    # If the directory is empty, error silently and continue execution
  end
  
  rmdir(dir)
  puts "rm -rf #{dir}" if verbose
  
end