lib/archiver/cli.rb in archiver-0.1.0 vs lib/archiver/cli.rb in archiver-1.0.0

- old
+ new

@@ -1,42 +1,113 @@ # -*- encoding : utf-8 -*- # Created by Thomas Boerger on 2012-03-16. # Copyright (c) 2012. All rights reserved. -require 'thor' +require 'optparse' require 'progressbar' module Archiver - class Cli < Thor - include Thor::Actions + class Cli + attr_accessor :stdout + attr_accessor :stderr + attr_accessor :config + attr_accessor :parser + + def initialize(argv, stdout, stderr) + @stdout = stdout + @stderr = stderr + + @config = { + :verbose => false + } + + @parser = OptionParser.new do |opt| + opt.banner = "Usage: archiver [options] <fromdir> <intodir>" - method_option :verbose, :type => :boolean, :aliases => '-V', :default => false - method_option :source, :type => :string, :aliases => '-s', :default => '.' + opt.on("-V", "--verbose", "Verbose output format") do + @config[:verbose] = true + end - desc 'renaming [DESTINATION]', 'Rename all files in the defined directory' - def renaming(destination) - source = options['source'] - verbose = options['verbose'] + opt.on("-h", "--help", "Show this help message") do + puts @parser + exit 0 + end + + opt.on("-v", "--version", "Show current version") do + puts "archiver v#{Version::STRING}" + exit 0 + end + end + + unless argv.size == 2 + puts @parser + exit 1 + end - output = Archiver::Output::Cli.new(verbose) + @config[:fromdir] = argv.shift + @config[:intodir] = argv.shift - begin - action = Archiver::Action::Renaming.new( - source, - destination, - output - ) + @parser.parse! + + checks + process + end + + def checks + unless File.directory? config[:fromdir] + error "Fromdir does not exist" + end - action.process - rescue Archiver::Error::InvalidDirectory => e - raise Thor::Error.new 'Directories does not exist!' - rescue => e - if verbose - raise Thor::Error.new "Some action failed: #{e.message}" + unless File.directory? config[:intodir] + error "Intodir does not exist" + end + + config[:fromdir_real] = File.realpath config[:fromdir] + config[:intodir_real] = File.realpath config[:intodir] + end + + def process + unless config[:verbose] + progress = ProgressBar.new('Archiver', records.count) + end + + records.each do |record| + next unless record.process? + record.move config[:intodir_real] + + if config[:verbose] + puts "#{record.path} -> #{record.filename}" else - raise Thor::Error.new 'Some action failed!' + progress.inc end end + + if config[:verbose] + puts "Processed #{records.count} records!" + else + progress.finish + end + rescue SystemExit, Interrupt + progress.finish if progress + exit 1 + end + + def records + @records ||= begin + rows = [] + Dir.glob(File.join(config[:fromdir_real], '**', '*')).each do |row| + next if File.directory? row + rows << Record.new(row) + end + + rows + end + end + + def error(message) + puts "Error: #{message}" + puts @parser + exit 1 end end end