Class: Tiun::CLI

Inherits:
Object show all
Defined in:
lib/tiun/cli.rb

Constant Summary collapse

DEFAULT_OPTIONS =
{
   config: nil,
}.to_os

Instance Method Summary collapse

Constructor Details

#initialize(argv = nil) ⇒ CLI

Returns a new instance of CLI.



83
84
85
# File 'lib/tiun/cli.rb', line 83

def initialize argv = nil
   @argv = argv&.split(/\s+/)
end

Instance Method Details

#actionsObject



45
46
47
# File 'lib/tiun/cli.rb', line 45

def actions
   @actions ||= parse.actions.select { |a| Tiun::Actor.kinds.include?(a) }
end

#default_parseObject



55
56
57
# File 'lib/tiun/cli.rb', line 55

def default_parse
   @parse = OpenStruct.new(options: options, actions: option_parser.default_argv)
end

#option_parserObject



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/tiun/cli.rb', line 12

def option_parser
   @option_parser ||=
      OptionParser.new do |opts|
         opts.banner = "Usage: setup.rb [options & actions]"

         opts.on("-c", "--use-config=CONFIG", String, "use specific tiun config file to apply") do |config|
            options[:config] = config
         end

         opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
            options[:verbose] = v
         end

         opts.on("-h", "--help", "This help") do |v|
            puts opts
            puts "\nActions: \n#{actions.join("\n")}"
            exit
         end
      end

   if @argv
      @option_parser.default_argv.replace(@argv)
   elsif @option_parser.default_argv.empty?
      @option_parser.default_argv << "-h"
   end

   @option_parser
end

#optionsObject



41
42
43
# File 'lib/tiun/cli.rb', line 41

def options
   @options ||= DEFAULT_OPTIONS.dup
end

#parseObject



67
68
69
70
71
# File 'lib/tiun/cli.rb', line 67

def parse
   parse!
rescue OptionParser::InvalidOption
   default_parse
end

#parse!Object



59
60
61
62
63
64
65
# File 'lib/tiun/cli.rb', line 59

def parse!
   return @parse if @parse

   option_parser.parse!

   default_parse
end

#runObject



73
74
75
76
77
78
79
80
81
# File 'lib/tiun/cli.rb', line 73

def run
   actions.reduce({}.to_os) do |res, action_name|
      res[action_name] = Tiun::Actor.for!(action_name, tiun)

      res
   end.map do |action_name, actor|
      actor.apply_to(Tiun)
   end
end

#tiunObject



49
50
51
52
53
# File 'lib/tiun/cli.rb', line 49

def tiun
   @tiun ||= options.config &&
      Tiun.setup_with(options.config) ||
      Tiun.setup
end