-
Notifications
You must be signed in to change notification settings - Fork 320
/
secretsgen.go
48 lines (40 loc) · 1.37 KB
/
secretsgen.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
package secretsgen
import (
"bytes"
"fmt"
"strconv"
"encr.dev/pkg/option"
"encr.dev/v2/app"
"encr.dev/v2/codegen"
"encr.dev/v2/internals/pkginfo"
"encr.dev/v2/parser/infra/secrets"
)
func Gen(gen *codegen.Generator, svc option.Option[*app.Service], pkg *pkginfo.Package, secrets []*secrets.Secrets) {
addedImport := make(map[*pkginfo.File]bool)
for _, secret := range secrets {
file := secret.File
rw := gen.Rewrite(file)
if !addedImport[file] {
// Add an import of the runtime package to be able to load secrets.
insertPos := file.AST().Name.End()
ln := gen.FS.Position(insertPos)
rw.Insert(insertPos, []byte(fmt.Sprintf("\nimport __encore_secrets %s;/*line :%d:%d*/",
strconv.Quote("encore.dev/appruntime/infrasdk/secrets"),
ln.Line, ln.Column)))
addedImport[secret.File] = true
}
getName := func(svc *app.Service) string { return svc.Name }
svcName := strconv.Quote(option.Map(svc, getName).GetOrElse(""))
// Rewrite the value spec to load the secrets.
spec := secret.Spec
var buf bytes.Buffer
buf.WriteString("{\n")
for _, key := range secret.Keys {
fmt.Fprintf(&buf, "\t%s: __encore_secrets.Load(%s, %s),\n", key, strconv.Quote(key), svcName)
}
ep := gen.FS.Position(spec.End())
fmt.Fprintf(&buf, "}/*line :%d:%d*/", ep.Line, ep.Column)
rw.Insert(spec.Type.Pos(), []byte("= "))
rw.Insert(spec.End(), buf.Bytes())
}
}