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
+4 -1
View File
@@ -4,6 +4,7 @@ import (
"fmt"
"io"
"os"
"time"
"golang.org/x/term"
@@ -20,8 +21,10 @@ func loop(ptmx pty.Pty) error {
return err
}
_ = watcher.Expect("100")
i := watcher.ExpectWithTimeout(time.Duration(10*time.Second), "100")
// i := watcher.Expect("100")
io.WriteString(ptmx, "exit\r")
println(i)
return sh.Wait()
}
+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
}
}
}