1999-08-13 01:37:52 -04:00
|
|
|
$expect_verbose = false
|
|
|
|
|
|
|
|
class IO
|
2011-08-26 18:22:37 -04:00
|
|
|
# Reads from the IO until pattern +pat+ matches or the +timeout+ is over.
|
|
|
|
# It returns an array with the read buffer, followed by the matches.
|
|
|
|
# If a block is given, the result is yielded to the block and returns nil.
|
|
|
|
#
|
|
|
|
# The optional timeout parameter defines, in seconds, the total time to wait
|
|
|
|
# for the pattern. If the timeout expires or eof is found, nil is returned
|
|
|
|
# or yielded. However, the buffer in a timeout session is kept for the next
|
|
|
|
# expect call. The default timeout is 9999999 seconds.
|
1999-08-13 01:37:52 -04:00
|
|
|
def expect(pat,timeout=9999999)
|
|
|
|
buf = ''
|
|
|
|
case pat
|
|
|
|
when String
|
|
|
|
e_pat = Regexp.new(Regexp.quote(pat))
|
|
|
|
when Regexp
|
|
|
|
e_pat = pat
|
2010-04-09 11:04:54 -04:00
|
|
|
else
|
|
|
|
raise TypeError, "unsupported pattern class: #{pattern.class}"
|
1999-08-13 01:37:52 -04:00
|
|
|
end
|
2010-04-09 11:07:34 -04:00
|
|
|
@unusedBuf ||= ''
|
1999-08-13 01:37:52 -04:00
|
|
|
while true
|
2010-04-09 11:07:34 -04:00
|
|
|
if not @unusedBuf.empty?
|
|
|
|
c = @unusedBuf.slice!(0).chr
|
|
|
|
elsif !IO.select([self],nil,nil,timeout) or eof? then
|
1999-08-13 01:37:52 -04:00
|
|
|
result = nil
|
2010-04-09 11:07:34 -04:00
|
|
|
@unusedBuf = buf
|
1999-08-13 01:37:52 -04:00
|
|
|
break
|
2010-04-09 11:07:34 -04:00
|
|
|
else
|
|
|
|
c = getc.chr
|
1999-08-13 01:37:52 -04:00
|
|
|
end
|
|
|
|
buf << c
|
|
|
|
if $expect_verbose
|
|
|
|
STDOUT.print c
|
|
|
|
STDOUT.flush
|
|
|
|
end
|
2002-08-13 05:21:18 -04:00
|
|
|
if mat=e_pat.match(buf) then
|
|
|
|
result = [buf,*mat.to_a[1..-1]]
|
1999-08-13 01:37:52 -04:00
|
|
|
break
|
|
|
|
end
|
|
|
|
end
|
2001-07-02 04:46:28 -04:00
|
|
|
if block_given? then
|
1999-08-13 01:37:52 -04:00
|
|
|
yield result
|
|
|
|
else
|
|
|
|
return result
|
|
|
|
end
|
|
|
|
nil
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|