Module: Dapp::Helper::Cli

Included in:
CLI
Defined in:
lib/dapp/helper/cli.rb

Instance Method Summary collapse

Instance Method Details

#cli_wrapper(cli) ⇒ Object



10
11
12
13
14
15
16
# File 'lib/dapp/helper/cli.rb', line 10

def cli_wrapper(cli)
  yield
rescue OptionParser::MissingArgument, OptionParser::InvalidOption, OptionParser::InvalidArgument => e
  STDERR.puts "Error: #{e.message}"
  puts cli.opt_parser
  exit 1
end

#composite_options(opt) ⇒ Object



65
66
67
68
# File 'lib/dapp/helper/cli.rb', line 65

def composite_options(opt)
  @composite_options ||= {}
  @composite_options[opt] ||= []
end

#parse_options(cli, argv) ⇒ Object



4
5
6
7
8
# File 'lib/dapp/helper/cli.rb', line 4

def parse_options(cli, argv)
  cli_wrapper(cli) do
    cli.parse_options(argv)
  end
end

#parse_subcommand(cli, args) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/dapp/helper/cli.rb', line 26

def parse_subcommand(cli, args)
  argv = args
  divided_subcommand = []
  subcommand_argv = []

  cmd_arr = args.dup
  loop do
    if cli.class::SUBCOMMANDS.include? cmd_arr.join(' ')
      argv = args[0...args.index(cmd_arr.first)]
      divided_subcommand = cmd_arr
      index = cmd_arr.one? ? args.index(cmd_arr.first).next : args.index(cmd_arr.last).next
      subcommand_argv = args[index..-1]
    elsif !cmd_arr.empty?
      cmd_arr.pop
      next
    end
    break
  end

  [argv, divided_subcommand, subcommand_argv]
end

#prepare_subcommand(divided_subcommand) ⇒ Object



57
58
59
60
61
62
63
# File 'lib/dapp/helper/cli.rb', line 57

def prepare_subcommand(divided_subcommand)
  Array(divided_subcommand)
    .map { |c| c.split(/[-_]/) }
    .flatten
    .map(&:capitalize)
    .join
end

#required_argument(cli) ⇒ Object



18
19
20
21
22
23
24
# File 'lib/dapp/helper/cli.rb', line 18

def required_argument(cli)
  unless (arg = cli.cli_arguments.pop)
    puts cli.opt_parser
    exit 1
  end
  arg
end

#run_subcommand(cli, divided_subcommand, subcommand_argv) ⇒ Object



48
49
50
51
52
53
54
55
# File 'lib/dapp/helper/cli.rb', line 48

def run_subcommand(cli, divided_subcommand, subcommand_argv)
  if !divided_subcommand.empty?
    cli.class.const_get(prepare_subcommand(divided_subcommand)).new.run(subcommand_argv)
  else
    puts cli.opt_parser
    exit 1
  end
end