main.go (2414B)
1 // Example: Toggling states with external functions, with engine debugger. 2 package main 3 4 import ( 5 "context" 6 "fmt" 7 "os" 8 "path" 9 10 testdataloader "github.com/peteole/testdata-loader" 11 12 "git.defalsify.org/vise.git/engine" 13 "git.defalsify.org/vise.git/resource" 14 "git.defalsify.org/vise.git/state" 15 "git.defalsify.org/vise.git/logging" 16 fsdb "git.defalsify.org/vise.git/db/fs" 17 ) 18 19 const ( 20 USER_FOO = iota + state.FLAG_USERSTART 21 USER_BAR 22 USER_BAZ 23 ) 24 25 var ( 26 logg = logging.NewVanilla() 27 baseDir = testdataloader.GetBasePath() 28 scriptDir = path.Join(baseDir, "examples", "state") 29 ) 30 31 type flagResource struct { 32 st *state.State 33 } 34 35 func(f *flagResource) get(ctx context.Context, sym string, input []byte) (resource.Result, error) { 36 return resource.Result{ 37 Content: state.FlagDebugger.AsString(f.st.Flags, 3), 38 }, nil 39 } 40 41 42 func(f *flagResource) do(ctx context.Context, sym string, input []byte) (resource.Result, error) { 43 var r resource.Result 44 45 logg.DebugCtxf(ctx, "in do", "sym", sym) 46 47 switch(sym) { 48 case "do_foo": 49 if f.st.MatchFlag(USER_FOO, false) { 50 r.FlagSet = append(r.FlagSet, USER_FOO) 51 } else { 52 r.FlagReset = append(r.FlagReset, USER_FOO) 53 } 54 case "do_bar": 55 if f.st.MatchFlag(USER_BAR, false) { 56 r.FlagSet = append(r.FlagSet, USER_BAR) 57 } else { 58 r.FlagReset = append(r.FlagReset, USER_BAR) 59 } 60 case "do_baz": 61 if f.st.MatchFlag(USER_BAZ, false) { 62 r.FlagSet = append(r.FlagSet, USER_BAZ) 63 } else { 64 r.FlagReset = append(r.FlagReset, USER_BAZ) 65 } 66 } 67 return r, nil 68 } 69 70 func main() { 71 root := "root" 72 fmt.Fprintf(os.Stderr, "starting session at symbol '%s' using resource dir: %s\n", root, scriptDir) 73 74 ctx := context.Background() 75 st := state.NewState(3) 76 store := fsdb.NewFsDb() 77 err := store.Connect(ctx, scriptDir) 78 if err != nil { 79 panic(err) 80 } 81 rs := resource.NewDbResource(store) 82 cfg := engine.Config{ 83 Root: "root", 84 } 85 86 aux := &flagResource{st: st} 87 rs.AddLocalFunc("do_foo", aux.do) 88 rs.AddLocalFunc("do_bar", aux.do) 89 rs.AddLocalFunc("do_baz", aux.do) 90 rs.AddLocalFunc("states", aux.get) 91 92 state.FlagDebugger.Register(USER_FOO, "FOO") 93 state.FlagDebugger.Register(USER_BAR, "BAR") 94 state.FlagDebugger.Register(USER_BAZ, "BAZ") 95 96 en := engine.NewEngine(cfg, rs) 97 en = en.WithState(st) 98 en = en.WithDebug(nil) 99 err = engine.Loop(ctx, en, os.Stdin, os.Stdout, nil) 100 if err != nil { 101 fmt.Fprintf(os.Stderr, "loop exited with error: %v\n", err) 102 os.Exit(1) 103 } 104 }