Class: Flydata::Cli

Inherits:
Object
  • Object
show all
Includes:
CommandLoggable, Helpers
Defined in:
lib/flydata/cli.rb

Constant Summary

Constants included from Helpers

Helpers::UNIT_PREFIX

Instance Method Summary collapse

Methods included from CommandLoggable

#before_logging, #log_error_stderr, #log_info_stdout, #log_warn_stderr

Methods included from Helpers

as_size, development?, env_mode, env_suffix, flydata_api_host_file, flydata_conf_file, flydata_version, format_menu_list, retry_on, to_command_class, usage_text

Constructor Details

#initialize(args) ⇒ Cli

Returns a new instance of Cli.



10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/flydata/cli.rb', line 10

def initialize(args)
  @args = args
  unless $log
    $log = Logger.new(FLYDATA_LOG)
    # 2014-10-24 14:05:21 -0700 command.info: message
    $log.datetime_format = "%Y-%m-%d %H:%M:%S %z "
    $log.formatter = proc do |severity, datetime, progname, msg|
      "#{datetime} command.#{severity.to_s.downcase}: #{msg}\n"
    end
  end
  log_info("Start command.", {cmd: @args.join(' '), ver:flydata_version})
end

Instance Method Details

#runObject



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/flydata/cli.rb', line 23

def run
  unless check_environment
    log_error_stderr("Sorry, you have to run the installation command to use flydata. Please go to https://console.flydata.com/ and sign up.")
    return
  end
  begin
    if @args.size > 0
      first_arg = @args.shift
      cmd, sub_cmd = parse_command(first_arg)
      begin
        require_command_source(cmd)
        cmd_cls = "Flydata::Command::#{cmd.capitalize}".constantize
      rescue NameError 
        # NameError is raised when the constant is not defined in its target
        # file, that is, command not found.
        # Other exceptions mean that some other error happended.
        raise "Command not found: #{cmd}"
      end
      # Command class can define options for each subcommand by defining method "slop_subcommandname"
      slop_method = sub_cmd ? "slop_#{sub_cmd}".to_sym : :slop
      options = cmd_cls.respond_to?(slop_method) ? cmd_cls.send(slop_method) : Slop.new(strict: true)
      options.parse!(@args)
      cmd_obj = cmd_cls.new(options)
      sub_cmd ? cmd_obj.send(sub_cmd,*@args) : cmd_obj.run(*@args)
    else
      $stderr.puts usage_text
      return
    end
  rescue => e
    #raise e
    $stderr.puts
    $stderr.puts
    $stderr.puts "!! #{e.to_s}"
    $stderr.puts
    $stderr.puts e.respond_to?(:description) ? e.description : AgentError.description
    log_error_with_backtrace('Error occured during command.', {error: e, args: @args})
    raise e if FLYDATA_DEBUG
    exit 1
  end
end