Add (*Watcher) ExpectWithTimeout

This commit is contained in:
HAYAMA_Kaoru
2024-11-29 12:49:11 +09:00
parent 0961e035fc
commit 9bca54b14e
2 changed files with 37 additions and 9 deletions
+33 -8
View File
@@ -4,6 +4,7 @@ import (
"io"
"os"
"strings"
"time"
"github.com/aymanbagabas/go-pty"
)
@@ -44,16 +45,40 @@ func (W *Watcher) updateLastLine() {
}
}
func (W *Watcher) checkWords(token string, words []string) int {
W.lastline += token
for i, word := range words {
if strings.Contains(W.lastline, word) {
W.updateLastLine()
return i
}
}
W.updateLastLine()
return -1
}
func (W *Watcher) Expect(words ...string) int {
for frag := range W.ch {
W.lastline += frag
for i, word := range words {
if strings.Contains(W.lastline, word) {
W.updateLastLine()
return i
}
for token := range W.ch {
if found := W.checkWords(token, words); found >= 0 {
return found
}
W.updateLastLine()
}
return -1
}
func (W *Watcher) ExpectWithTimeout(d time.Duration, words ...string) int {
timer := time.NewTimer(d)
defer timer.Stop()
for {
select {
case token := <-W.ch:
if found := W.checkWords(token, words); found >= 0 {
return found
}
case <-timer.C:
return -1
}
}
}