class Faceapp::CLI

Constants

OPTION_REGEXP
PARAMS

Attributes

debug[R]
options[R]
params[R]
silent[R]

Public Class Methods

new(args) click to toggle source
# File lib/faceapp/cli.rb, line 12
def initialize(args)
  @params, @options = parse_arguments(args)
end

Public Instance Methods

print_usage() click to toggle source
run!() click to toggle source
# File lib/faceapp/cli.rb, line 16
def run!
  print_usage if params.empty? || options[:help]

  options[:logger] = Logger.new(STDERR) if debug?

  filter = params[:filter]
  input = parse_input(params[:input])
  output = parse_output(params[:output])

  client = Faceapp::Client.new(options)

  code = client.upload_photo(input)

  info "Successfuly uploaded input photo. Result code = #{code}"
  info "Applying filter '#{filter}'"

  client.apply_filter(code, filter, output)

  info 'Done.'
rescue => e
  info "Error: #{e.message}"

  debug { e.backtrace.join("\n") }

  exit(-1)
ensure
  input.close if input.is_a?(File)
  output.close if output.is_a?(File)
end

Private Instance Methods

debug?() click to toggle source
# File lib/faceapp/cli.rb, line 144
def debug?
  options[:debug] && !silent?
end
info(text = nil) { || ... } click to toggle source
# File lib/faceapp/cli.rb, line 137
def info(text = nil)
  return if silent?

  STDERR.puts(text) if text
  STDERR.puts(yield) if block_given?
end
parse_arguments(args) click to toggle source
# File lib/faceapp/cli.rb, line 100
def parse_arguments(args)
  params = []
  options = {}

  args.each do |arg|
    match = OPTION_REGEXP.match(arg)

    if match
      options[match[:name].to_sym] = parse_option(match[:value])
    else
      params << arg
    end
  end

  params = PARAMS.zip(params).to_h

  [params, options]
end
parse_input(input) click to toggle source
# File lib/faceapp/cli.rb, line 74
def parse_input(input)
  case input
  when '-'
    StringIO.new(STDIN.read)
  when nil
    print_usage
  else
    File.open(input, 'rb')
  end
rescue => e
  info "Unable to open input: #{e.message}"
  exit(-1)
end
parse_option(value) click to toggle source
# File lib/faceapp/cli.rb, line 119
def parse_option(value)
  case value
  when String
    value
  when 'false', '0'
    false
  else
    true
  end
end
parse_output(output) click to toggle source
# File lib/faceapp/cli.rb, line 88
def parse_output(output)
  case output
  when String
    File.open(output, 'wb')
  else
    STDOUT
  end
rescue => e
  info "Unable to open output: #{e.message}"
  exit(-1)
end
silent?() click to toggle source
# File lib/faceapp/cli.rb, line 148
def silent?
  options[:silent]
end