/
resources.go
105 lines (87 loc) · 2.63 KB
/
resources.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
104
105
package hook
import (
"bytes"
"context"
"fmt"
"regexp"
"github.com/authgear/authgear-server/pkg/util/resource"
)
var DenoFileFilenameRegexp = regexp.MustCompile(`^deno/[.0-9a-zA-Z]+\.ts$`)
//go:generate mockgen -source=resources.go -destination=resources_mock_test.go -package hook
type denoClientContextKeyType struct{}
var ContextKeyDenoClient = denoClientContextKeyType{}
type ResourceManager interface {
Read(desc resource.Descriptor, view resource.View) (interface{}, error)
}
type DenoFileDescriptor struct{}
func (DenoFileDescriptor) MatchResource(path string) (*resource.Match, bool) {
if DenoFileFilenameRegexp.MatchString(path) {
return &resource.Match{}, true
}
return nil, false
}
func (d DenoFileDescriptor) FindResources(fs resource.Fs) ([]resource.Location, error) {
allLocations, err := resource.EnumerateAllLocations(fs)
if err != nil {
return nil, err
}
var locations []resource.Location
for _, location := range allLocations {
_, ok := d.MatchResource(location.Path)
if ok {
l := location
locations = append(locations, l)
}
}
return locations, nil
}
func (DenoFileDescriptor) ViewResources(resources []resource.ResourceFile, rawView resource.View) (interface{}, error) {
output := bytes.Buffer{}
app := func(p string) error {
var target *resource.ResourceFile
for _, resrc := range resources {
if resrc.Location.Fs.GetFsLevel() == resource.FsLevelApp && resrc.Location.Path == p {
s := resrc
target = &s
}
}
if target == nil {
return resource.ErrResourceNotFound
}
output.Write(target.Data)
return nil
}
// We have to support AppFileView and EffectiveFileView
// because the portal assumes every editable resources support these two views.
switch view := rawView.(type) {
case resource.AppFileView:
err := app(view.AppFilePath())
if err != nil {
return nil, err
}
return output.Bytes(), nil
case resource.EffectiveFileView:
err := app(view.EffectiveFilePath())
if err != nil {
return nil, err
}
return output.Bytes(), nil
case resource.ValidateResourceView:
// Actual validation happens in UpdateResource.
return nil, nil
default:
return nil, fmt.Errorf("unsupported view: %T", rawView)
}
}
func (DenoFileDescriptor) UpdateResource(ctx context.Context, _ []resource.ResourceFile, resrc *resource.ResourceFile, data []byte) (*resource.ResourceFile, error) {
denoClient := ctx.Value(ContextKeyDenoClient).(*DenoClientImpl)
err := denoClient.Check(ctx, string(data))
if err != nil {
return nil, err
}
return &resource.ResourceFile{
Location: resrc.Location,
Data: data,
}, nil
}
var DenoFile = resource.RegisterResource(DenoFileDescriptor{})