Class: RunKit::Options::Help

Inherits:
Object
  • Object
show all
Defined in:
lib/run_kit/options/help.rb

Constant Summary collapse

INDENT =
2

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config, width = nil) ⇒ Help

Returns a new instance of Help.



13
14
15
16
# File 'lib/run_kit/options/help.rb', line 13

def initialize(config, width = nil)
  @config = config
  @width = (width || Term.winsize[1]).clamp(60, 100)
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



11
12
13
# File 'lib/run_kit/options/help.rb', line 11

def config
  @config
end

#widthObject (readonly)

Returns the value of attribute width.



11
12
13
# File 'lib/run_kit/options/help.rb', line 11

def width
  @width
end

Instance Method Details

Build the usage line from the configured app name and positionals.



52
53
54
55
56
57
58
# File 'lib/run_kit/options/help.rb', line 52

def banner
  text = config.banner
  text ||= [color.blue("Usage:"), color.green(config.app_name), "[options]"].tap do
    _1.push(*config.positionals.map(&:meta))
  end.join(" ")
  Term.wrap(text, width)
end

#colorObject

one-liners



73
# File 'lib/run_kit/options/help.rb', line 73

def color = @color ||= Color.new(config.color)

#separator_text(position) ⇒ Object

Render separator text at its recorded position between flags.



61
62
63
64
65
66
67
68
69
70
# File 'lib/run_kit/options/help.rb', line 61

def separator_text(position)
  StringIO.new.tap do |buf|
    config.separators.each do |(pos, str)|
      if pos == position
        buf << color.blue(str)
        buf << "\n"
      end
    end
  end.string
end

#to_sObject

Render generated help, unless the caller supplied complete help text.



19
20
21
22
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
# File 'lib/run_kit/options/help.rb', line 19

def to_s
  return config.help if config.help

  # usage: xyz (banner)
  buf = StringIO.new
  buf << banner
  buf << "\n"
  buf << "\n" if config.separators.any? { _1.first.zero? }

  # Render each flag with aligned switch labels and wrapped help text.
  label_width = widest_label
  config.flags.each.with_index do |flag, idx|
    buf << separator_text(idx) # sep

    # left
    label = flag_label(flag)
    buf << " " * INDENT
    buf << label

    # right
    if flag.help
      buf << " " * (label_width - Term.width(label) + 2)
      indent = INDENT + label_width + 2
      buf << Term.wrap(flag.help, width - indent).gsub("\n", "\n#{" " * indent}")
    end
    buf << "\n"
  end
  buf << separator_text(config.flags.length)

  buf.string
end

#widest_labelObject



74
# File 'lib/run_kit/options/help.rb', line 74

def widest_label = config.flags.map { Term.width(flag_label(_1)) }.max