ReadUntil emulates a terminal and reads one byte at a time until the matcher returns true or the context expires. If the matcher is nil, read until EOF. The PTY must be sized to 80x80 or there could be unexpected results.
(ctx context.Context, matcher func(line string) bool)
| 40 | // returns true or the context expires. If the matcher is nil, read until EOF. |
| 41 | // The PTY must be sized to 80x80 or there could be unexpected results. |
| 42 | func (tr *TerminalReader) ReadUntil(ctx context.Context, matcher func(line string) bool) (retErr error) { |
| 43 | readBytes := make([]byte, 0) |
| 44 | readErrs := make(chan error, 1) |
| 45 | defer func() { |
| 46 | // Dump the terminal contents since they can be helpful for debugging, but |
| 47 | // trim empty lines since much of the terminal will usually be blank. |
| 48 | got := tr.term.String() |
| 49 | lines := strings.Split(got, "\n") |
| 50 | for i := range lines { |
| 51 | if strings.TrimSpace(lines[i]) != "" { |
| 52 | lines = lines[i:] |
| 53 | break |
| 54 | } |
| 55 | } |
| 56 | for i := len(lines) - 1; i >= 0; i-- { |
| 57 | if strings.TrimSpace(lines[i]) != "" { |
| 58 | lines = lines[:i+1] |
| 59 | break |
| 60 | } |
| 61 | } |
| 62 | gotTrimmed := strings.Join(lines, "\n") |
| 63 | tr.t.Logf("Terminal contents:\n%s", gotTrimmed) |
| 64 | // EOF is expected when matcher == nil |
| 65 | if retErr != nil && !(xerrors.Is(retErr, io.EOF) && matcher == nil) { |
| 66 | tr.t.Logf("Bytes Read: %q", string(readBytes)) |
| 67 | } |
| 68 | }() |
| 69 | for { |
| 70 | b := make([]byte, 1) |
| 71 | go func() { |
| 72 | _, err := tr.r.Read(b) |
| 73 | readErrs <- err |
| 74 | }() |
| 75 | select { |
| 76 | case err := <-readErrs: |
| 77 | if err != nil { |
| 78 | return err |
| 79 | } |
| 80 | readBytes = append(readBytes, b...) |
| 81 | _, err = tr.term.Write(b) |
| 82 | if err != nil { |
| 83 | return err |
| 84 | } |
| 85 | case <-ctx.Done(): |
| 86 | return ctx.Err() |
| 87 | } |
| 88 | if matcher == nil { |
| 89 | // A nil matcher means to read until EOF. |
| 90 | continue |
| 91 | } |
| 92 | got := tr.term.String() |
| 93 | lines := strings.Split(got, "\n") |
| 94 | for _, line := range lines { |
| 95 | if matcher(line) { |
| 96 | return nil |
| 97 | } |
| 98 | } |
| 99 | } |