main.go (2127B)
1 // Example: Manual data storage using session id provided to engine. 2 package main 3 4 import ( 5 "context" 6 "flag" 7 "fmt" 8 "io/ioutil" 9 "os" 10 "path" 11 12 testdataloader "github.com/peteole/testdata-loader" 13 14 "git.defalsify.org/vise.git/engine" 15 "git.defalsify.org/vise.git/resource" 16 "git.defalsify.org/vise.git/logging" 17 fsdb "git.defalsify.org/vise.git/db/fs" 18 ) 19 20 var ( 21 logg = logging.NewVanilla() 22 baseDir = testdataloader.GetBasePath() 23 scriptDir = path.Join(baseDir, "examples", "session") 24 emptyResult = resource.Result{} 25 ) 26 27 func save(ctx context.Context, sym string, input []byte) (resource.Result, error) { 28 sessionId := ctx.Value("SessionId").(string) 29 sessionDir := path.Join(scriptDir, sessionId) 30 err := os.MkdirAll(sessionDir, 0700) 31 if err != nil { 32 return emptyResult, err 33 } 34 fp := path.Join(sessionDir, "data.txt") 35 if len(input) > 0 { 36 logg.Debugf("write data %s session %s", input, sessionId) 37 err = ioutil.WriteFile(fp, input, 0600) 38 if err != nil { 39 return emptyResult, err 40 } 41 } 42 r, err := ioutil.ReadFile(fp) 43 if err != nil { 44 err = ioutil.WriteFile(fp, []byte("(not set)"), 0600) 45 if err != nil { 46 return emptyResult, err 47 } 48 } 49 return resource.Result{ 50 Content: string(r), 51 }, nil 52 } 53 54 func main() { 55 var root string 56 var size uint 57 var sessionId string 58 flag.UintVar(&size, "s", 0, "max size of output") 59 flag.StringVar(&root, "root", "root", "entry point symbol") 60 flag.StringVar(&sessionId, "session-id", "default", "session id") 61 flag.Parse() 62 fmt.Fprintf(os.Stderr, "starting session at symbol '%s' using resource dir: %s\n", root, scriptDir) 63 64 ctx := context.Background() 65 store := fsdb.NewFsDb() 66 err := store.Connect(ctx, scriptDir) 67 if err != nil { 68 panic(err) 69 } 70 rs := resource.NewDbResource(store) 71 rs.AddLocalFunc("do_save", save) 72 cfg := engine.Config{ 73 Root: "root", 74 SessionId: sessionId, 75 OutputSize: uint32(size), 76 StateDebug: true, 77 } 78 ctx = context.WithValue(ctx, "SessionId", sessionId) 79 en := engine.NewEngine(cfg, rs) 80 err = engine.Loop(ctx, en, os.Stdin, os.Stdout, nil) 81 if err != nil { 82 fmt.Fprintf(os.Stderr, "loop exited with error: %v\n", err) 83 os.Exit(1) 84 } 85 }