Skip to content

Commit 79e27a7

Browse files
it works :)
1 parent 8e9e931 commit 79e27a7

File tree

4 files changed

+39
-17
lines changed

4 files changed

+39
-17
lines changed

cmd/lekko/gen.go

Lines changed: 37 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ import (
3232
"github.com/lekkodev/cli/pkg/secrets"
3333
"github.com/pkg/errors"
3434
"github.com/spf13/cobra"
35+
strcase "github.com/stoewer/go-strcase"
3536
"golang.org/x/mod/modfile"
3637
"google.golang.org/protobuf/encoding/protojson"
3738
"google.golang.org/protobuf/proto"
@@ -60,9 +61,9 @@ func genGoCmd() *cobra.Command {
6061
if err != nil {
6162
return errors.Wrap(err, "new repo")
6263
}
63-
_, nsMDs, err := r.ParseMetadata(cmd.Context(), ns)
64+
_, nsMDs := try.To2(r.ParseMetadata(cmd.Context()))
6465

65-
staticCtxType := unpackProtoType(moduleRoot, "/"+nsMDs[ns])
66+
staticCtxType := unpackProtoType(moduleRoot, nsMDs[ns].ContextProto)
6667
ffs, err := r.GetFeatureFiles(cmd.Context(), ns)
6768
if err != nil {
6869
return err
@@ -73,6 +74,9 @@ func genGoCmd() *cobra.Command {
7374
var protoAsByteStrings []string
7475
var codeStrings []string
7576
protoImportSet := make(map[string]*protoImport)
77+
if staticCtxType != nil {
78+
protoImportSet[staticCtxType.ImportPath] = staticCtxType
79+
}
7680
for _, ff := range ffs {
7781
fff, err := os.ReadFile(wd + "/" + ns + "/" + ff.CompiledProtoBinFileName)
7882
if err != nil {
@@ -82,13 +86,13 @@ func genGoCmd() *cobra.Command {
8286
if err := proto.Unmarshal(fff, f); err != nil {
8387
return err
8488
}
85-
codeString, err := genGoForFeature(f, ns)
89+
codeString, err := genGoForFeature(f, ns, staticCtxType)
8690
if err != nil {
8791
return err
8892
}
8993
if f.Type == featurev1beta1.FeatureType_FEATURE_TYPE_PROTO {
9094
protoImport := unpackProtoType(moduleRoot, f.Tree.Default.TypeUrl)
91-
protoImportSet[protoImport.ImportPath] = &protoImport
95+
protoImportSet[protoImport.ImportPath] = protoImport
9296
}
9397
protoAsBytes := fmt.Sprintf("\t\t\"%s\": []byte{", f.Key)
9498
for idx, b := range fff {
@@ -173,7 +177,6 @@ var StaticConfig = map[string]map[string][]byte{
173177
"--include-imports",
174178
wd) // #nosec G204
175179
pCmd.Dir = "."
176-
fmt.Println("executing in working dir: " + wd + " command: " + pCmd.String())
177180
if out, err := pCmd.CombinedOutput(); err != nil {
178181
fmt.Println("this is the error probably")
179182
fmt.Println(string(out))
@@ -217,16 +220,16 @@ var genCmd = &cobra.Command{
217220
Short: "generate library code from configs",
218221
}
219222

220-
func genGoForFeature(f *featurev1beta1.Feature, ns string) (string, error) {
223+
func genGoForFeature(f *featurev1beta1.Feature, ns string, staticCtxType *protoImport) (string, error) {
221224
const defaultTemplateBody = `// {{$.Description}}
222225
func (c *LekkoClient) {{$.FuncName}}(ctx context.Context) ({{$.RetType}}, error) {
223226
return c.{{$.GetFunction}}(ctx, "{{$.Namespace}}", "{{$.Key}}")
224227
}
225228
226229
// {{$.Description}}
227-
func (c *SafeLekkoClient) {{$.FuncName}}(ctx context.Context) {{$.RetType}} {
228-
{{if $.NaturalLanguage}}{{range $.NaturalLanguage}}{{ . }}
229-
{{end}}{{else}}
230+
{{if $.NaturalLanguage}}func (c *SafeLekkoClient) {{$.FuncName}}(ctx *{{$.StaticType}}) {{$.RetType}} {
231+
{{range $.NaturalLanguage}}{{ . }}
232+
{{end}}{{else}}func (c *SafeLekkoClient) {{$.FuncName}}(ctx context.Context) {{$.RetType}} {
230233
return c.{{$.GetFunction}}(ctx, "{{$.Namespace}}", "{{$.Key}}")
231234
{{end}}}`
232235

@@ -264,6 +267,7 @@ func (c *SafeLekkoClient) {{$.FuncName}}(ctx context.Context, result interface{}
264267
var getFunction string
265268
templateBody := defaultTemplateBody
266269
var natty []string
270+
267271
switch f.Type {
268272
case 1:
269273
retType = "bool"
@@ -298,6 +302,7 @@ func (c *SafeLekkoClient) {{$.FuncName}}(ctx context.Context, result interface{}
298302
Namespace string
299303
Key string
300304
NaturalLanguage []string
305+
StaticType string
301306
}{
302307
f.Description,
303308
funcName,
@@ -306,6 +311,7 @@ func (c *SafeLekkoClient) {{$.FuncName}}(ctx context.Context, result interface{}
306311
ns,
307312
f.Key,
308313
natty,
314+
fmt.Sprintf("%s.%s", staticCtxType.PackageAlias, staticCtxType.Type),
309315
}
310316
templ, err := template.New("go func").Parse(templateBody)
311317
if err != nil {
@@ -322,28 +328,41 @@ type protoImport struct {
322328
Type string
323329
}
324330

325-
func unpackProtoType(moduleRoot string, typeURL string) protoImport {
331+
// This function handles both the google.protobuf.Any.TypeURL variable
332+
// which has the format of `types.googleapis.com/fully.qualified.Proto`
333+
// and purely `fully.qualified.Proto`
334+
//
335+
// return nil if typeURL is empty. Panics on any problems like the rest of the file.
336+
func unpackProtoType(moduleRoot string, typeURL string) *protoImport {
337+
if typeURL == "" {
338+
return nil
339+
}
326340
anyURLSplit := strings.Split(typeURL, "/")
327-
if anyURLSplit[0] != "type.googleapis.com" {
328-
panic("invalid any type url: " + typeURL)
341+
fqType := anyURLSplit[0]
342+
if len(anyURLSplit) > 1 {
343+
if anyURLSplit[0] != "type.googleapis.com" {
344+
panic("invalid any type url: " + typeURL)
345+
}
346+
fqType = anyURLSplit[1]
329347
}
348+
330349
// turn default.config.v1beta1.DBConfig into:
331350
// moduleRoot/internal/lekko/proto/default/config/v1beta1
332-
typeParts := strings.Split(anyURLSplit[1], ".")
351+
typeParts := strings.Split(fqType, ".")
333352

334353
importPath := strings.Join(append([]string{moduleRoot + "/internal/lekko/proto"}, typeParts[:len(typeParts)-1]...), "/")
335354

336355
prefix := fmt.Sprintf(`%s%s`, typeParts[len(typeParts)-3], typeParts[len(typeParts)-2])
337356

338357
// TODO do google.protobuf.X
339-
switch anyURLSplit[1] {
358+
switch fqType {
340359
case "google.protobuf.Duration":
341360
importPath = "google.golang.org/protobuf/types/known/durationpb"
342361
prefix = "durationpb"
343362
default:
344363
}
345364

346-
return protoImport{PackageAlias: prefix, ImportPath: importPath, Type: typeParts[len(typeParts)-1]}
365+
return &protoImport{PackageAlias: prefix, ImportPath: importPath, Type: typeParts[len(typeParts)-1]}
347366
}
348367

349368
func translateFeature(f *featurev1beta1.Feature) []string {
@@ -355,7 +374,9 @@ func translateFeature(f *featurev1beta1.Feature) []string {
355374
}
356375
rule := translateRule(constraint.GetRuleAstNew())
357376
buffer = append(buffer, fmt.Sprintf("\t%s %s {", ifToken, rule))
377+
358378
// TODO this doesn't work for proto, but let's try
379+
359380
buffer = append(buffer, fmt.Sprintf("\t\treturn %s", try.To1(protojson.Marshal(try.To1(constraint.Value.UnmarshalNew())))))
360381
}
361382
if len(f.Tree.Constraints) > 0 {
@@ -377,7 +398,7 @@ func translateRule(rule *rulesv1beta3.Rule) string {
377398
if err != nil {
378399
panic(err)
379400
}
380-
return fmt.Sprintf("%s == %s", v.Atom.ContextKey, string(b))
401+
return fmt.Sprintf("ctx.%s == %s", strcase.UpperCamelCase(v.Atom.ContextKey), string(b))
381402
case rulesv1beta3.ComparisonOperator_COMPARISON_OPERATOR_CONTAINED_WITHIN:
382403
// TODO, probably logical to have this here but we need slice syntax, use slices as of golang 1.21
383404
}

go.mod

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ require (
1919
github.com/mitchellh/go-homedir v1.1.0
2020
github.com/olekukonko/tablewriter v0.0.5
2121
github.com/spf13/cobra v1.5.0
22+
github.com/stoewer/go-strcase v1.2.0
2223
github.com/stretchr/testify v1.8.0
2324
github.com/whilp/git-urls v1.0.0
2425
golang.org/x/mod v0.8.0

go.sum

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,7 @@ github.com/spf13/cobra v1.5.0 h1:X+jTBEBqF0bHN+9cSMgmfuvv2VHJ9ezmFNf9Y/XstYU=
210210
github.com/spf13/cobra v1.5.0/go.mod h1:dWXEIy2H428czQCjInthrTRUg7yKbok+2Qi/yBIJoUM=
211211
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
212212
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
213+
github.com/stoewer/go-strcase v1.2.0 h1:Z2iHWqGXH00XYgqDmNgQbIBxf3wrNq0F3feEy0ainaU=
213214
github.com/stoewer/go-strcase v1.2.0/go.mod h1:IBiWB2sKIp3wVVQ3Y035++gc+knqhUQag1KpM8ahLw8=
214215
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
215216
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=

pkg/repo/feature.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -448,7 +448,6 @@ func (r *repository) Compile(ctx context.Context, req *CompileRequest) ([]*Featu
448448
nsContextTypes[ns] = ct
449449
}
450450
}
451-
r.Logf("%#v\n", nsContextTypes)
452451

453452
// Step 1: collect. Find all features
454453
vffs, numNamespaces, err := r.findVersionedFeatureFiles(ctx, req.NamespaceFilter, req.FeatureFilter, req.Verify)

0 commit comments

Comments
 (0)