Skip to content

Instantly share code, notes, and snippets.

@hyuki

hyuki/upftp.rb

Created Mar 15, 2020
Embed
What would you like to do?
upftp.rb
#!/usr/bin/env ruby
require 'net/ftp'
require 'fileutils'
require 'time'
require 'pp'
HOSTNAME = ENV['UPFTP_HOSTNAME']
USERNAME = ENV['UPFTP_USERNAME']
PASSWORD = ENV['UPFTP_PASSWORD']
LOCAL_ROOTDIR = ENV['UPFTP_LOCAL_ROOTDIR']
REMOTE_ROOTDIR = ENV['UPFTP_REMOTE_ROOTDIR']
DEBUG_MODE = true
LAST_LINE = '# upftp 2020'
def cputs(s)
puts "\x1b[31m#{s}\x1b[0m"
end
def error(message)
cputs "ERROR: upftp: #{message}"
abort
end
def main(filelist)
ftp = Net::FTP.new(HOSTNAME, {
# ssl: true,
debug_mode: DEBUG_MODE,
username: USERNAME,
password: PASSWORD,
});
error "#{filelist} は存在しません。" if not File.exist?(filelist)
lines = IO.readlines(filelist).map {|line| line.chomp}
error "#{filelist} は空っぽです。" if lines.size == 0
error "#{filelist} の最後の行は次のようになっている必要があります(バージョンチェックのため)。\n#{LAST_LINE}" if lines[-1] != LAST_LINE
updated_lines = []
updated = false
lines.each_with_index do |line, index|
linenumber = index + 1
updated_lines << line
next if line.match(/^#/)
error "#{linenumber}: #{line}\nの行は形式エラーです。" if not line.match(/^([^,\s]+)(,(\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d \+0900)|,?)$/)
filename = $1.to_s
updatetime = $3.to_s
local_filename = "#{LOCAL_ROOTDIR}/#{filename}"
remote_filename = "#{REMOTE_ROOTDIR}/#{filename}"
error "#{linenumber}: #{local_filename} は存在しません。" if not File.exist?(local_filename)
if updatetime == ''
updatetime = '1999-01-01 00:00 +0900'
end
ut = Time.parse(updatetime) # filelist.txtに書かれている転送時刻
mt = Time.parse(File::Stat.new(local_filename).mtime.to_s) # ファイルの更新タイムスタンプ
puts "COMPARE: #{ut} < #{mt}" if DEBUG_MODE
if ut < mt
puts "Update: #{filename}"
puts "PUT: #{local_filename} -> #{remote_filename}" if DEBUG_MODE
ftp.putbinaryfile(local_filename, remote_filename)
updatetime = mt.to_s
else
puts "IGNORE: #{local_filename}" if DEBUG_MODE
end
updated_lines[-1] = "#{filename},#{updatetime}"
updated = true
end
if updated
system("mv #{filelist} .#{filelist}")
open(filelist, "w") do |f|
updated_lines.each do |line|
f.puts line
end
end
end
ftp.quit
end
if ARGV.length == 0
puts "This is upftp, Ruby version."
puts "Usage: upftp filelist.txt"
abort
end
main(ARGV[0])
# vim: set filetype=ruby:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.