我正在努力定义local_file,直到第36行。我不确定除了local_file中的#{file}之外还应该做些什么来使这个工作。我试图通过比较它们的时间戳或它们是否存在来找到需要上传的文件或目录。我知道dir没有定义,但我对它应该是什么感到困惑,或者这是正确的方法还是可扩展的。我可以使用的是关于功能的建议,或修复我所拥有的简单方法。谢谢你的帮助!
当我跑步时,我得到:
box.ru:36:in block (3 levels) in <main>': undefined local variable or method
dir'for main:Object(NameError)
#!/usr/bin/env ruby
require 'rubygems'
require 'net/ssh'
require 'net/sftp'
require 'highline/import'
require 'find'
host = 'server'
local_path = '/Users/awesome1/Development/box'
remote_path = '/home/awesome2/box'
def sanitize_string(string_name)
string_name.gsub(/[^\w\.\-]/,"_")
end
puts "box username:"
user0 = gets.chomp
user = sanitize_string(user0)
pass0 = ask("Enter password for #{user}: ") { |q| q.echo = false }
pass = sanitize_string(pass0)
puts 'connecting to box...'
Net::SSH.start( host, user, :password => pass ) do|ssh|
result = ssh.exec!("cd #{remote_path} && ls")
puts result
ssh.sftp.connect do |sftp|
puts 'Checking for files which need updating'
Find.find(local_path) do |file|
next if File.stat(file).directory?
local_file = "#{dir}/#{file}"
remote_file = remote_path + local_file.sub(local_path, '')
begin
remote_dir = File.dirname(remote_file)
sftp.stat(remote_dir)
rescue Net::SFTP::Operations::StatusException => e
raise unless e.code == 2
sftp.mkdir(remote_dir, :mode => dir_perm)
end
begin
rstat = sftp.stat(remote_file)
rescue Net::SFTP::Operations::StatusException => e
raise unless e.code == 2
sftp.put_file(local_file, remote_file)
sftp.setstat(remote_file, :permissions => file_perm)
next
end
if File.stat(local_file).mtime > Time.at(rstat.mtime)
puts "Copying #{local_file} to #{remote_file}"
ssh.sftp.upload(local_file, remote_file)
end
end
end
end
答案 0 :(得分:0)
错误消息是明确的:您在第36行引用了undefined variable or method dir
。
ssh.sftp.connect do |sftp|
puts 'Checking for files which need updating'
Find.find(local_path) do |file|
next if File.stat(file).directory?
local_file = "#{dir}/#{file}" # where does dir come from?
将错误行更新为(或仅重用file
)
local_file = file
因为Find
会产生前缀为local_path
的文件名。