default.go (2425B)
1 package engine 2 3 import ( 4 "context" 5 "fmt" 6 "os" 7 "path" 8 9 "git.defalsify.org/vise.git/cache" 10 "git.defalsify.org/vise.git/persist" 11 "git.defalsify.org/vise.git/resource" 12 "git.defalsify.org/vise.git/state" 13 ) 14 15 // NewDefaultEngine is a convenience function to instantiate a filesystem-backed engine with no output constraints. 16 func NewDefaultEngine(dir string, persisted bool, session *string) (EngineIsh, error) { 17 var err error 18 st := state.NewState(0) 19 rs := resource.NewFsResource(dir) 20 ca := cache.NewCache() 21 cfg := Config{ 22 Root: "root", 23 } 24 if session != nil { 25 cfg.SessionId = *session 26 } else if !persisted { 27 return nil, fmt.Errorf("session must be set if persist is used") 28 } 29 ctx := context.TODO() 30 var en EngineIsh 31 if persisted { 32 dp := path.Join(dir, ".state") 33 err = os.MkdirAll(dp, 0700) 34 if err != nil { 35 return nil, err 36 } 37 pr := persist.NewFsPersister(dp) 38 en, err = NewPersistedEngine(ctx, cfg, pr, rs) 39 if err != nil { 40 Logg.Infof("persisted engine create error. trying again with persisting empty state first...") 41 pr = pr.WithContent(&st, ca) 42 err = pr.Save(cfg.SessionId) 43 if err != nil { 44 return nil, err 45 } 46 en, err = NewPersistedEngine(ctx, cfg, pr, rs) 47 } 48 } else { 49 enb := NewEngine(ctx, cfg, &st, rs, ca) 50 en = &enb 51 } 52 return en, err 53 } 54 55 // NewSizedEngine is a convenience function to instantiate a filesystem-backed engine with a specified output constraint. 56 func NewSizedEngine(dir string, size uint32, persisted bool, session *string) (EngineIsh, error) { 57 var err error 58 st := state.NewState(0) 59 rs := resource.NewFsResource(dir) 60 ca := cache.NewCache() 61 cfg := Config{ 62 OutputSize: size, 63 Root: "root", 64 } 65 if session != nil { 66 cfg.SessionId = *session 67 } else if !persisted { 68 return nil, fmt.Errorf("session must be set if persist is used") 69 } 70 ctx := context.TODO() 71 var en EngineIsh 72 if persisted { 73 dp := path.Join(dir, ".state") 74 err = os.MkdirAll(dp, 0700) 75 if err != nil { 76 return nil, err 77 } 78 pr := persist.NewFsPersister(dp) 79 en, err = NewPersistedEngine(ctx, cfg, pr, rs) 80 if err != nil { 81 Logg.Infof("persisted engine create error. trying again with persisting empty state first...") 82 pr = pr.WithContent(&st, ca) 83 err = pr.Save(cfg.SessionId) 84 if err != nil { 85 return nil, err 86 } 87 en, err = NewPersistedEngine(ctx, cfg, pr, rs) 88 } 89 } else { 90 enb := NewEngine(ctx, cfg, &st, rs, ca) 91 en = &enb 92 } 93 return en, err 94 }