Debian Codegraph @

ext/pty/lib/expect.rb

raw
1 # frozen_string_literal: true
2 $expect_verbose = false
3
4 class IO
5 # call-seq:
6 # IO#expect(pattern,timeout=9999999) -> Array
7 # IO#expect(pattern,timeout=9999999) { |result| ... } -> nil
8 #
9 # The +expect+ library adds instance method IO#expect,
10 # which is similar to the
11 # {TCL expect extension}[https://www.tcl.tk/man/expect5.31/expect.1.html].
12 #
13 # To use this method, you must require +expect+:
14 #
15 # require 'expect'
16 #
17 # Reads from the IO until the given +pattern+ matches or the +timeout+ is over.
18 #
19 # It returns an array with the read buffer, followed by the matches.
20 # If a block is given, the result is yielded to the block and returns nil.
21 #
22 # When called without a block, it waits until the input that matches the
23 # given +pattern+ is obtained from the IO or the time specified as the
24 # timeout passes. An array is returned when the pattern is obtained from the
25 # IO. The first element of the array is the entire string obtained from the
26 # IO until the pattern matches, followed by elements indicating which the
27 # pattern which matched to the anchor in the regular expression.
28 #
29 # The optional timeout parameter defines, in seconds, the total time to wait
30 # for the pattern. If the timeout expires or eof is found, nil is returned
31 # or yielded. However, the buffer in a timeout session is kept for the next
32 # expect call. The default timeout is 9999999 seconds.
33 def expect(pat,timeout=9999999)
34 buf = ''.dup
35 case pat
36 when String
37 e_pat = Regexp.new(Regexp.quote(pat))
38 when Regexp
39 e_pat = pat
40 else
41 raise TypeError, "unsupported pattern class: #{pat.class}"
42 end
43 @unusedBuf ||= ''
44 while true
45 if not @unusedBuf.empty?
46 c = @unusedBuf.slice!(0)
47 elsif !IO.select([self],nil,nil,timeout) or eof? then
48 result = nil
49 @unusedBuf = buf
50 break
51 else
52 c = getc
53 end
54 buf << c
55 if $expect_verbose
56 STDOUT.print c
57 STDOUT.flush
58 end
59 if mat=e_pat.match(buf) then
60 result = [buf,*mat.captures]
61 break
62 end
63 end
64 if block_given? then
65 yield result
66 else
67 return result
68 end
69 nil
70 end
71 end