Class: NanDoc::Cli::ExclusiveOptions

Inherits:
Object
  • Object
show all
Includes:
OptionMethods
Defined in:
lib/nandoc/cli/option-methods/exclusive-options.rb

Instance Method Summary collapse

Methods included from OptionMethods

#exclusive_opt_flags, #normalize_opt_key, #normalize_opts, #option_enum, #unnormalize_opt_key, #unnormalize_opt_keys

Constructor Details

#initialize(&block) ⇒ ExclusiveOptions

Returns a new instance of ExclusiveOptions.



5
6
7
8
9
10
11
12
13
# File 'lib/nandoc/cli/option-methods/exclusive-options.rb', line 5

def initialize &block
  @exclusive_flag_keys = nil
  @default_short = nil
  @default_key = nil
  @notice_stream = $stderr
  instance_eval(&block)
  fail('definition block needs at least flags()') unless
    @exclusive_flag_keys
end

Instance Method Details

#default(*a) ⇒ Object

params: [short_name_string] name_key



18
19
20
21
22
23
24
25
26
27
28
# File 'lib/nandoc/cli/option-methods/exclusive-options.rb', line 18

def default *a
  if a.first.kind_of?(String)
    @default_short = a.shift
  end
  if a.first.kind_of?(Symbol)
    @default_key = a.shift
  else
    fail("bad args: #{a.first.inspect}")
  end
  fail("extra args: #{a.inspect}") if a.any?
end

#flags(*exclusive_flag_keys) ⇒ Object



14
15
16
# File 'lib/nandoc/cli/option-methods/exclusive-options.rb', line 14

def flags * exclusive_flag_keys
  @exclusive_flag_keys = exclusive_flag_keys
end

#notice_stream(mixed) ⇒ Object



29
30
31
# File 'lib/nandoc/cli/option-methods/exclusive-options.rb', line 29

def notice_stream mixed
  @notice_stream = mixed
end

#parse(cmd, opts) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/nandoc/cli/option-methods/exclusive-options.rb', line 32

def parse cmd, opts
  these = @exclusive_flag_keys & opts.keys
  if these.empty? && @default_key
    if @notice_stream
      msg =
      ["using default: "+unnormalize_opt_key(@default_key),
        @default_short ? "(#{@default_short})" : nil
      ].compact.join(' ')
      @notice_stream.puts msg
    end
    these.push(@default_key)
  end
  if these.size > 1
    flags = unnormalize_opt_keys(@exclusive_flag_keys)
    cmd.command_abort <<-ABORT.gsub(/^  */,'')
      #{flags.join(' and ')} are mutually exclusive.
      usage: #{cmd.usage}
      #{cmd.invite_to_more_command_help}
    ABORT
  end
  these.first
end