Module: MultiTimeout::CLI

Defined in:
lib/multi_timeout.rb

Class Method Summary collapse

Class Method Details

.consume_command(argv) ⇒ Object



82
83
84
85
86
87
88
89
# File 'lib/multi_timeout.rb', line 82

def consume_command(argv)
  argv = argv.dup
  options = []
  while argv.first =~ /^-/
    options << argv.shift
  end
  return argv, options
end

.consume_signals(argv) ⇒ Object



91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/multi_timeout.rb', line 91

def consume_signals(argv)
  timeouts = {}
  signal = nil
  argv = argv.map do |item|
    if !signal && item =~ VALID_SIGNAL
      signal = $1
      next
    elsif signal
      signal = signal.sub("-", "")
      signal = signal.to_i if signal =~ /^\d+$/
      timeouts[signal] = human_value_to_seconds(item)
      signal = nil
      next
    else
      item
    end
  end.compact

  return timeouts, argv
end

.human_value_to_seconds(t) ⇒ Object



112
113
114
115
116
117
118
119
120
121
122
# File 'lib/multi_timeout.rb', line 112

def human_value_to_seconds(t)
  unit =
    case t
    when /^\d+s$/ then 1
    when /^\d+m$/ then 60
    when /^\d+h$/ then 60 * 60
    when /^\d+$/  then 1
    else raise "Unknown format for time #{t}"
    end
  t.to_i * unit
end

.parse_options(argv) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/multi_timeout.rb', line 58

def parse_options(argv)
  options = {:timeouts => []}
  options[:timeouts], argv = consume_signals(argv)
  command, argv = consume_command(argv)

  OptionParser.new do |opts|
    opts.banner = <<-BANNER.gsub(/^ {10}/, "")
      Use multiple timeouts to soft and then hard kill a command

      Usage:
          multi-timeout -9 5s -2 4s sleep 20

      Options:
    BANNER
    opts.on("-SIGNAL TIME", Integer, "Kill with this SIGNAL after TIME") { raise } # this is never used, just placeholder for docs
    opts.on("-h", "--help", "Show this.") { puts opts; exit }
    opts.on("-v", "--version", "Show Version"){ puts MultiTimeout::VERSION; exit}
  end.parse!(argv)

  raise "No timeouts given" if options[:timeouts].empty?

  [command, options]
end

.run(argv) ⇒ Object



54
55
56
# File 'lib/multi_timeout.rb', line 54

def run(argv)
  MultiTimeout.run(*parse_options(argv))
end