#!/usr/bin/env ruby # encoding: UTF-8 require 'image_optim/runner' require 'image_optim/true_false_nil' require 'image_optim/non_negative_integer_range' options = {} option_parser = OptionParser.new do |op| ImageOptim::TrueFalseNil.add_to_option_parser(op) ImageOptim::NonNegativeIntegerRange.add_to_option_parser(op) op.banner = <<-TEXT.gsub(/^\s*\|/, '') |#{ImageOptim.full_version} | |Usege: | #{op.program_name} [options] image_path … | |Configuration will be read and prepanded to options from two paths: | #{ImageOptim::Config::GLOBAL_CONFIG_PATH} | #{ImageOptim::Config::LOCAL_CONFIG_PATH} | TEXT op.on('-r', '-R', '--recursive', 'Recurively scan directories '\ 'for images') do |recursive| options[:recursive] = recursive end op.separator nil op.on('--[no-]threads N', Integer, 'Number of threads or disable '\ '(defaults to number of processors)') do |threads| options[:threads] = threads end op.on('--[no-]nice N', Integer, 'Nice level (defaults to 10)') do |nice| options[:nice] = nice end op.separator nil op.separator ' Disabling workers:' ImageOptim::Worker.klasses.each do |klass| bin = klass.bin_sym op.on("--no-#{bin}", "disable #{bin} worker") do |enable| options[bin] = enable end end op.separator nil op.separator ' Worker options:' ImageOptim::Worker.klasses.each_with_index do |klass, i| op.separator nil unless i.zero? bin = klass.bin_sym klass.option_definitions.each do |option_definition| name = option_definition.name.to_s.gsub('_', '-') default = option_definition.default type = option_definition.type type, marking = case when [TrueClass, FalseClass, ImageOptim::TrueFalseNil].include?(type) [type, 'B'] when Integer >= type [Integer, 'N'] when Array >= type [Array, 'a,b,c'] when ImageOptim::NonNegativeIntegerRange == type [type, 'M-N'] else fail "Unknown type #{type}" end description_lines = %W[ #{option_definition.description.gsub(' - ', ' - ')} (defaults to #{default}) ].join(' '). scan(/.*?.{1,60}(?:\s|\z)/). join("\n "). split("\n") op.on("--#{bin}-#{name} #{marking}", type, *description_lines) do |value| options[bin] = {} unless options[bin].is_a?(Hash) options[bin][option_definition.name.to_sym] = value end end end op.separator nil op.separator ' Common options:' op.on('-v', '--verbose', 'Verbose output') do |verbose| options[:verbose] = verbose end op.on_tail('-h', '--help', 'Show full help') do puts op.help exit end op.on_tail('--version', 'Show version') do puts ImageOptim.version exit end end begin args = ARGV.dup # assume -v to be request to print version if it is the only argument args = %w[--version] if args == %w[-v] option_parser.parse!(args) if options[:verbose] $stderr.puts ImageOptim.full_version end unless ImageOptim::Runner.run!(args, options) abort end rescue OptionParser::ParseError => e abort "#{e}\n\n#{option_parser.help}" rescue => e if options[:verbose] abort "#{e}\n#{e.backtrace.join("\n")}" else abort e.to_s end end