module Lhj class Command class RenameImage < Command self.summary = '重命名图片' self.arguments = [ CLAide::Argument.new('--pre=xx', false), CLAide::Argument.new('--name=xx', false), CLAide::Argument.new('--other=xx', false) ] def self.options [ %w[--pre 图片前缀], %w[--name 图片名称], %w[--other 图片变化后的名称] ] end def validate! super help! '输入图片信息' unless @image_pre || @image_name || @image_other_name end def initialize(argv) @current_path = argv.shift_argument || Dir.pwd @image_pre = argv.option('pre') @image_name = argv.option('name') @image_other_name = argv.option('other') super end def handle rename_image end def rename_image Dir.glob("#{@current_path}/**/*.{png}").sort.each do |f| filename = File.basename(f, File.extname(f)) m_filename = modify_name(filename, File.extname(f)) target = File.join(@current_path, m_filename) File.rename(f, target) end end def modify_name(file_name, extname) name = file_name.downcase + extname if @image_pre name = @image_pre + file_name.downcase + extname elsif @image_name && @image_other_name if file_name =~ /#{@image_name}/ other_name = file_name.gsub(/#{@image_name}/, @image_other_name) name = other_name + extname end end name end end end end