require 'shellwords'
require 'fileutils'
include FileUtils
class RejectionError < RuntimeError ; end
class NoFileError < RuntimeError ; end
class FormatError < RuntimeError ; end
OLD = 0
NEW = 1
begin
names = Array.new
while line = STDIN.gets
name = Shellwords.shellwords(line.strip)
next if name.length == 0
raise(FormatError, "入力が不正です") unless name.length == 2
STDERR.puts "#{name[OLD]} -> #{name[NEW]}"
unless File.exist?(name[OLD])
raise(NoFileError, "#{name[OLD]}: そのようなファイルやフォルダは存在しません")
end
if File.exist?(name[NEW])
buf = String.new
STDERR.print "#{name[NEW]} は既に存在します。上書きしますか? (Y/N) ->"
STDERR.print "->" until /^[yn]$/i =~ ( buf = STDIN.gets.chomp )
raise(RejectionError, "#{name[NEW]} の上書きを拒否しました") if /^n$/i =~ buf
end
names << name
end
rescue RejectionError => exception
STDERR.puts exception.message
retry
rescue NoFileError => exception
STDERR.puts exception.message
retry
rescue FormatError => exception
STDERR.puts "#{exception.class}: #{exception.message}"
retry
rescue => exception
STDERR.puts "#{exception.class}: #{exception.message}"
exit(1)
end
names.each do |name|
FileUtils.mv(name[OLD], name[NEW])
end
STDERR.puts "#{names.length} 個のファイルをリネームしました"