Factor out engine loop code

This commit is contained in:
lash 2023-04-09 15:58:35 +01:00
parent 95bee7f8e0
commit 8ddfd68f33
Signed by untrusted user who does not match committer: lash
GPG Key ID: 21D2E7BB88C2A746
2 changed files with 41 additions and 28 deletions

View File

@ -1,12 +1,9 @@
package main
import (
"bufio"
"bytes"
"context"
"flag"
"fmt"
"strings"
"os"
"git.defalsify.org/festive/engine"
@ -22,32 +19,9 @@ func main() {
ctx := context.Background()
en := engine.NewDefaultEngine(dir)
err := en.Init(root, ctx)
err := engine.Loop(root, &en, ctx)
if err != nil {
fmt.Fprintf(os.Stderr, "cannot init: %v\n", err)
fmt.Fprintf(os.Stderr, "loop exited with error: %v", err)
os.Exit(1)
}
b := bytes.NewBuffer(nil)
en.WriteResult(b)
fmt.Println(b.String())
running := true
for running {
reader := bufio.NewReader(os.Stdin)
in, err := reader.ReadString('\n')
if err != nil {
fmt.Fprintf(os.Stderr, "cannot read input: %v\n", err)
os.Exit(1)
}
in = strings.TrimSpace(in)
running, err = en.Exec([]byte(in), ctx)
if err != nil {
fmt.Fprintf(os.Stderr, "unexpected termination: %v\n", err)
os.Exit(1)
}
b := bytes.NewBuffer(nil)
en.WriteResult(b)
fmt.Println(b.String())
}
}

39
go/engine/loop.go Normal file
View File

@ -0,0 +1,39 @@
package engine
import (
"bufio"
"bytes"
"context"
"fmt"
"os"
"strings"
)
func Loop(startSym string, en *Engine, ctx context.Context) error {
err := en.Init(startSym, ctx)
if err != nil {
return fmt.Errorf("cannot init: %v\n", err)
}
b := bytes.NewBuffer(nil)
en.WriteResult(b)
fmt.Println(b.String())
running := true
for running {
reader := bufio.NewReader(os.Stdin)
in, err := reader.ReadString('\n')
if err != nil {
return fmt.Errorf("cannot read input: %v\n", err)
}
in = strings.TrimSpace(in)
running, err = en.Exec([]byte(in), ctx)
if err != nil {
return fmt.Errorf("unexpected termination: %v\n", err)
}
b := bytes.NewBuffer(nil)
en.WriteResult(b)
fmt.Println(b.String())
}
return nil
}