Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Paramgen: generate constants for each specification parameter #60

Merged
merged 3 commits into from
Jun 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@ linters-settings:
allow-unused: false # report any unused nolint directives
require-explanation: true # require an explanation for nolint directives
require-specific: true # require nolint directives to mention the specific linter being suppressed
gocyclo:
min-complexity: 20
goconst:
ignore-tests: true
goheader:
Expand Down
55 changes: 55 additions & 0 deletions paramgen/internal/integration_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// Copyright © 2024 Meroxa, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package internal

import (
"os"
"testing"

"github.com/google/go-cmp/cmp"
"github.com/matryer/is"
)

func TestIntegration(t *testing.T) {
testCases := []struct {
havePath string
structName string
wantPath string
}{{
havePath: "./testdata/basic",
structName: "SourceConfig",
wantPath: "./testdata/basic/want.go",
}, {
havePath: "./testdata/complex",
structName: "SourceConfig",
wantPath: "./testdata/complex/want.go",
}, {
havePath: "./testdata/tags",
structName: "Config",
wantPath: "./testdata/tags/want.go",
}}

for _, tc := range testCases {
t.Run(tc.havePath, func(t *testing.T) {
is := is.New(t)
params, pkg, err := ParseParameters(tc.havePath, tc.structName)
is.NoErr(err)
want, err := os.ReadFile(tc.wantPath)
is.NoErr(err)
got := GenerateCode(params, pkg, tc.structName)
is.Equal("", cmp.Diff(string(want), got))
})
}
}
66 changes: 54 additions & 12 deletions paramgen/internal/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"log"
"reflect"
"strconv"
"strings"
"text/template"

"github.com/conduitio/conduit-commons/config"
Expand All @@ -39,10 +40,16 @@ import (
"github.com/conduitio/conduit-commons/config"
)

const (
{{- range $name, $parameter := $.Parameters }}
{{ $.Constant $name }} = {{ $.Quote $name }}
{{- end }}
)

func ({{ $.Struct }}) Parameters() map[string]config.Parameter {
return map[string]config.Parameter{
{{- range $name, $parameter := .Parameters }}
{{ $.Quote $name }}: {
{{ $.Constant $name }}: {
Default: {{ $.Quote .Default }},
Description: {{ $.Quote .Description }},
Type: config.{{ .GetTypeConstant }},
Expand All @@ -68,6 +75,52 @@ func (templateData) Quote(s string) string {
return strconv.Quote(s)
}

func (t templateData) Constant(s string) string {
key := toCamelCase(s)
return t.Struct + key
}

func (t templateData) HasRegex() bool {
for _, p := range t.Parameters {
for _, v := range p.Validations {
if _, ok := v.(config.ValidationRegex); ok {
return true
}
}
}
return false
}

func toCamelCase(s string) string {
s = strings.TrimSpace(s)
if s == "" {
return s
}

n := strings.Builder{}
n.Grow(len(s))
capNext := true // cap first letter
for _, v := range []byte(s) {
vIsCap := v >= 'A' && v <= 'Z'
vIsLow := v >= 'a' && v <= 'z'
if capNext && vIsLow {
v += 'A'
v -= 'a'
}

if vIsCap || vIsLow {
n.WriteByte(v)
capNext = false
} else if vIsNum := v >= '0' && v <= '9'; vIsNum {
n.WriteByte(v)
capNext = true
} else {
capNext = v == '_' || v == ' ' || v == '-' || v == '.'
}
}
return n.String()
}

var parameterTypeConstantMapping = map[config.ParameterType]string{
config.ParameterTypeString: "ParameterTypeString",
config.ParameterTypeInt: "ParameterTypeInt",
Expand Down Expand Up @@ -97,17 +150,6 @@ func (p parameter) GetValidation(index int) string {
return fmt.Sprintf("%s{%s}", validationType, validationParameters)
}

func (t templateData) HasRegex() bool {
for _, p := range t.Parameters {
for _, v := range p.Validations {
if _, ok := v.(config.ValidationRegex); ok {
return true
}
}
}
return false
}

func GenerateCode(parameters map[string]config.Parameter, packageName string, structName string) string {
// create the go template
t := template.Must(template.New("").Parse(tmpl))
Expand Down
26 changes: 19 additions & 7 deletions paramgen/internal/template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
"testing"

"github.com/conduitio/conduit-commons/config"
"github.com/google/go-cmp/cmp"
"github.com/matryer/is"
)

Expand Down Expand Up @@ -61,17 +62,23 @@ import (
"github.com/conduitio/conduit-commons/config"
)
const (
SourceConfigBoolParam = "bool.param"
SourceConfigIntParam = "int.param"
SourceConfigStringParam = "string.param"
)
func (SourceConfig) Parameters() map[string]config.Parameter {
return map[string]config.Parameter{
"bool.param": {
SourceConfigBoolParam: {
Default: "true",
Description: "my bool param",
Type: config.ParameterTypeBool,
Validations: []config.Validation{
config.ValidationRegex{Regex: regexp.MustCompile(".*")},
},
},
"int.param": {
SourceConfigIntParam: {
Default: "1",
Description: "my int param with \"quotes\"",
Type: config.ParameterTypeInt,
Expand All @@ -82,7 +89,7 @@ func (SourceConfig) Parameters() map[string]config.Parameter {
config.ValidationLessThan{V: 3},
},
},
"string.param": {
SourceConfigStringParam: {
Default: "",
Description: "simple string param",
Type: config.ParameterTypeString,
Expand All @@ -91,7 +98,7 @@ func (SourceConfig) Parameters() map[string]config.Parameter {
}
}
`
is.Equal(got, want)
is.Equal("", cmp.Diff(got, want))
}

func TestGenerateCodeWithoutRegex(t *testing.T) {
Expand Down Expand Up @@ -122,17 +129,22 @@ import (
"github.com/conduitio/conduit-commons/config"
)
const (
ConfigDurationParam = "duration.param"
ConfigIntParam = "int.param"
)
func (Config) Parameters() map[string]config.Parameter {
return map[string]config.Parameter{
"duration.param": {
ConfigDurationParam: {
Default: "1s",
Description: "my duration param",
Type: config.ParameterTypeDuration,
Validations: []config.Validation{
config.ValidationInclusion{List: []string{"1s", "2s", "3s"}},
},
},
"int.param": {
ConfigIntParam: {
Default: "1",
Description: "my int param",
Type: config.ParameterTypeInt,
Expand All @@ -141,5 +153,5 @@ func (Config) Parameters() map[string]config.Parameter {
}
}
`
is.Equal(got, want)
is.Equal("", cmp.Diff(got, want))
}
10 changes: 9 additions & 1 deletion paramgen/internal/testdata/basic/go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
module example.com/test

go 1.18
go 1.22.3

require github.com/conduitio/conduit-commons v0.2.0

require (
github.com/goccy/go-json v0.10.2 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
google.golang.org/protobuf v1.33.0 // indirect
)
12 changes: 12 additions & 0 deletions paramgen/internal/testdata/basic/go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
github.com/conduitio/conduit-commons v0.2.0 h1:TMpVGXi0Wski537qLAyQWdGjuGHEhaZxOS5L90pZJSQ=
github.com/conduitio/conduit-commons v0.2.0/go.mod h1:i7Q2jm7FBSi2zj1/4MCsFD1hIKAbvamlNtSQfkhUTiY=
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/matryer/is v1.4.1 h1:55ehd8zaGABKLXQUe2awZ99BD/PTc2ls+KV/dXphgEQ=
github.com/matryer/is v1.4.1/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI=
google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
Loading
Loading