-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathloader.go
103 lines (87 loc) · 2.1 KB
/
loader.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package luaprovider
import (
"bytes"
"context"
"fmt"
"github.com/mangalorg/libmangal"
"github.com/philippgille/gokv"
"github.com/philippgille/gokv/syncmap"
lua "github.com/yuin/gopher-lua"
"net/http"
)
var _ libmangal.ProviderLoader = (*loader)(nil)
type Options struct {
HTTPClient *http.Client
HTTPStoreProvider func() (gokv.Store, error)
PackagePaths []string
}
func DefaultOptions() Options {
return Options{
HTTPClient: &http.Client{},
HTTPStoreProvider: func() (gokv.Store, error) {
return syncmap.NewStore(syncmap.DefaultOptions), nil
},
}
}
// NewLoader creates new lua provider loader for the given script.
//
// It won't run the script itself.
func NewLoader(script []byte, info libmangal.ProviderInfo, options Options) (libmangal.ProviderLoader, error) {
if err := info.Validate(); err != nil {
return nil, err
}
return loader{
options: options,
info: info,
script: script,
}, nil
}
type loader struct {
options Options
info libmangal.ProviderInfo
script []byte
}
func (l loader) Info() libmangal.ProviderInfo {
return l.info
}
func (l loader) String() string {
return l.info.Name
}
func (l loader) Load(ctx context.Context) (libmangal.Provider, error) {
provider := &provider{
info: l.info,
options: l.options,
}
state, store, err := newState(l.options)
if err != nil {
return nil, err
}
provider.store = store
provider.state = state
provider.state.SetContext(ctx)
lfunc, err := provider.state.Load(bytes.NewReader(l.script), l.info.Name)
if err != nil {
return nil, err
}
err = provider.state.CallByParam(lua.P{
Fn: lfunc,
NRet: 0,
Protect: true,
})
if err != nil {
return nil, err
}
for name, fn := range map[string]**lua.LFunction{
methodSearchMangas: &provider.fnSearchMangas,
methodMangaVolumes: &provider.fnMangaVolumes,
methodVolumeChapters: &provider.fnVolumeChapters,
methodChapterPages: &provider.fnChapterPages,
} {
var found bool
*fn, found = provider.state.GetGlobal(name).(*lua.LFunction)
if !found {
return nil, fmt.Errorf("missing function: %s", name)
}
}
return provider, nil
}