Skip to content

Commit

Permalink
chore(*): cleanup unnecessary pointers to slices (#66)
Browse files Browse the repository at this point in the history
  • Loading branch information
Tieske authored Jul 6, 2023
1 parent 1563410 commit b425220
Show file tree
Hide file tree
Showing 15 changed files with 90 additions and 91 deletions.
3 changes: 1 addition & 2 deletions cmd/addplugins.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,7 @@ func executeAddPlugins(cmd *cobra.Command, cfgFiles []string) error {
return fmt.Errorf("failed getting cli argument 'config'; %w", err)
}
for _, strConfig := range strConfigs {
temp := []byte(strConfig)
pluginConfig, err := filebasics.Deserialize(&temp)
pluginConfig, err := filebasics.Deserialize([]byte(strConfig))
if err != nil {
return fmt.Errorf("failed to deserialize plugin config '%s'; %w", strConfig, err)
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/listtags.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ func executeListTags(cmd *cobra.Command, _ []string) error {
if outputFormat == "PLAIN" {
// return as a plain text format, unix style; line separated
result := []byte(strings.Join(list, "\n"))
return filebasics.WriteFile(outputFilename, &result)
return filebasics.WriteFile(outputFilename, result)
}
// return as yaml/json, create an object containing only a tags-array
result := make(map[string]interface{})
Expand Down
6 changes: 3 additions & 3 deletions cmd/openapi2kong.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,14 @@ func executeOpenapi2Kong(cmd *cobra.Command, _ []string) error {
return fmt.Errorf("failed getting cli argument 'uuid-base'; %w", err)
}

var entityTags *[]string
var entityTags []string
{
tags, err := cmd.Flags().GetStringSlice("select-tag")
if err != nil {
return fmt.Errorf("failed getting cli argument 'select-tag'; %w", err)
}
entityTags = &tags
if len(*entityTags) == 0 {
entityTags = tags
if len(entityTags) == 0 {
entityTags = nil
}
}
Expand Down
12 changes: 6 additions & 6 deletions deckformat/dbless_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,11 @@ var _ = Describe("deckformat", func() {
}
]
}`)
deckdata, err := ConvertDBless(MustDeserialize(&jsonData))
deckdata, err := ConvertDBless(MustDeserialize(jsonData))
Expect(err).To(BeNil())

jsonDeck := MustSerialize(deckdata, OutputFormatJSON)
Expect(*jsonDeck).Should(MatchJSON(`{
Expect(jsonDeck).Should(MatchJSON(`{
"consumer_groups": [
{
"name": "A-team",
Expand Down Expand Up @@ -148,11 +148,11 @@ var _ = Describe("deckformat", func() {
}
]
}`)
deckdata, err := ConvertDBless(MustDeserialize(&jsonData))
deckdata, err := ConvertDBless(MustDeserialize(jsonData))
Expect(err).To(BeNil())

jsonDeck := MustSerialize(deckdata, OutputFormatJSON)
Expect(*jsonDeck).Should(MatchJSON(`{
Expect(jsonDeck).Should(MatchJSON(`{
"consumer_groups": [
{
"name": "A-team",
Expand Down Expand Up @@ -203,7 +203,7 @@ var _ = Describe("deckformat", func() {
},
]
}`)
_, err := ConvertDBless(MustDeserialize(&jsonData))
_, err := ConvertDBless(MustDeserialize(jsonData))
Expect(err.Error()).To(ContainSubstring(
"entry 'consumer_groups[0]' contains both 'consumer_group_plugins' and 'plugins'"))
})
Expand All @@ -218,7 +218,7 @@ var _ = Describe("deckformat", func() {
}
]
}`)
_, err := ConvertDBless(MustDeserialize(&jsonData))
_, err := ConvertDBless(MustDeserialize(jsonData))
Expect(err.Error()).To(ContainSubstring(
"consumer_group 'A-team' referenced by 'consumer_group_plugins[0]' not found"))
})
Expand Down
2 changes: 1 addition & 1 deletion deckformat/deckformat.go
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ func HistoryGet(filedata map[string]interface{}) (historyArray []interface{}) {
}

// Return a copy
return *jsonbasics.DeepCopyArray(&trackInfo)
return jsonbasics.DeepCopyArray(trackInfo)
}

// HistorySet sets the history info array. Setting to nil will delete the history.
Expand Down
26 changes: 13 additions & 13 deletions filebasics/filebasics.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const (

// ReadFile reads file contents.
// Reads from stdin if filename == "-"
func ReadFile(filename string) (*[]byte, error) {
func ReadFile(filename string) ([]byte, error) {
var (
body []byte
err error
Expand All @@ -35,12 +35,12 @@ func ReadFile(filename string) (*[]byte, error) {
if err != nil {
return nil, err
}
return &body, nil
return body, nil
}

// MustReadFile reads file contents. Will panic if reading fails.
// Reads from stdin if filename == "-"
func MustReadFile(filename string) *[]byte {
func MustReadFile(filename string) []byte {
body, err := ReadFile(filename)
if err != nil {
log.Fatalf("unable to read file: %v", err)
Expand All @@ -51,7 +51,7 @@ func MustReadFile(filename string) *[]byte {

// WriteFile writes the output to a file.
// Writes to stdout if filename == "-"
func WriteFile(filename string, content *[]byte) error {
func WriteFile(filename string, content []byte) error {
var f *os.File
var err error

Expand All @@ -66,7 +66,7 @@ func WriteFile(filename string, content *[]byte) error {
// writing to stdout
f = os.Stdout
}
_, err = f.Write(*content)
_, err = f.Write(content)
if err != nil {
return fmt.Errorf("failed to write to output file '%s'; %w", filename, err)
}
Expand All @@ -75,15 +75,15 @@ func WriteFile(filename string, content *[]byte) error {

// MustWriteFile writes the output to a file. Will panic if writing fails.
// Writes to stdout if filename == "-"
func MustWriteFile(filename string, content *[]byte) {
func MustWriteFile(filename string, content []byte) {
err := WriteFile(filename, content)
if err != nil {
panic(err)
}
}

// Serialize will serialize the result as a JSON/YAML.
func Serialize(content map[string]interface{}, format string) (*[]byte, error) {
func Serialize(content map[string]interface{}, format string) ([]byte, error) {
var (
str []byte
err error
Expand All @@ -105,12 +105,12 @@ func Serialize(content map[string]interface{}, format string) (*[]byte, error) {
strings.ToLower(OutputFormatYaml), strings.ToLower(OutputFormatJSON), format)
}

return &str, nil
return str, nil
}

// MustSerialize will serialize the result as a JSON/YAML. Will panic
// if serializing fails.
func MustSerialize(content map[string]interface{}, format string) *[]byte {
func MustSerialize(content map[string]interface{}, format string) []byte {
result, err := Serialize(content, format)
if err != nil {
panic(err)
Expand All @@ -120,12 +120,12 @@ func MustSerialize(content map[string]interface{}, format string) *[]byte {

// Deserialize will deserialize data as a JSON or YAML object. Will return an error
// if deserializing fails or if it isn't an object.
func Deserialize(data *[]byte) (map[string]interface{}, error) {
func Deserialize(data []byte) (map[string]interface{}, error) {
var output interface{}

err1 := json.Unmarshal(*data, &output)
err1 := json.Unmarshal(data, &output)
if err1 != nil {
err2 := yaml.Unmarshal(*data, &output)
err2 := yaml.Unmarshal(data, &output)
if err2 != nil {
return nil, errors.New("failed deserializing data as JSON and as YAML")
}
Expand All @@ -141,7 +141,7 @@ func Deserialize(data *[]byte) (map[string]interface{}, error) {

// MustDeserialize will deserialize data as a JSON or YAML object. Will panic
// if deserializing fails or if it isn't an object. Will never return nil.
func MustDeserialize(data *[]byte) map[string]interface{} {
func MustDeserialize(data []byte) map[string]interface{} {
jsondata, err := Deserialize(data)
if err != nil {
log.Fatal("%w", err)
Expand Down
8 changes: 4 additions & 4 deletions jsonbasics/jsonbasics.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,19 +191,19 @@ func GetBoolIndex(arr []interface{}, index int) (bool, error) {
}

// DeepCopyObject implements a poor man's deepcopy by jsonify/de-jsonify
func DeepCopyObject(data *map[string]interface{}) *map[string]interface{} {
func DeepCopyObject(data map[string]interface{}) map[string]interface{} {
var dataCopy map[string]interface{}
serialized, _ := json.Marshal(data)
_ = json.Unmarshal(serialized, &dataCopy)
return &dataCopy
return dataCopy
}

// DeepCopyArray implements a poor man's deepcopy by jsonify/de-jsonify
func DeepCopyArray(data *[]interface{}) *[]interface{} {
func DeepCopyArray(data []interface{}) []interface{} {
var dataCopy []interface{}
serialized, _ := json.Marshal(data)
_ = json.Unmarshal(serialized, &dataCopy)
return &dataCopy
return dataCopy
}

//
Expand Down
12 changes: 6 additions & 6 deletions jsonbasics/jsonbasics_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ var _ = Describe("jsonbasics", func() {
{ "name": "two" }
]
}`)
objArr, err := GetObjectArrayField(MustDeserialize(&data), "myArray")
objArr, err := GetObjectArrayField(MustDeserialize(data), "myArray")

Expect(err).To(BeNil())
Expect(objArr).To(BeEquivalentTo([]map[string]interface{}{
Expand All @@ -87,7 +87,7 @@ var _ = Describe("jsonbasics", func() {
[1,2,3]
]
}`)
objArr, err := GetObjectArrayField(MustDeserialize(&data), "myArray")
objArr, err := GetObjectArrayField(MustDeserialize(data), "myArray")

Expect(err).To(BeNil())
Expect(objArr).To(BeEquivalentTo([]map[string]interface{}{
Expand All @@ -102,7 +102,7 @@ var _ = Describe("jsonbasics", func() {

It("returns an empty array if the field doesn't exist", func() {
data := []byte(`{}`)
objArr, err := GetObjectArrayField(MustDeserialize(&data), "myArray")
objArr, err := GetObjectArrayField(MustDeserialize(data), "myArray")

Expect(err).To(BeNil())
Expect(objArr).To(BeEquivalentTo([]map[string]interface{}{}))
Expand All @@ -116,7 +116,7 @@ var _ = Describe("jsonbasics", func() {
[1,2,3]
]
}`)
objArr, err := GetObjectArrayField(MustDeserialize(&data), "myArray")
objArr, err := GetObjectArrayField(MustDeserialize(data), "myArray")

Expect(err).To(BeNil())
Expect(objArr).To(BeEquivalentTo([]map[string]interface{}{}))
Expand All @@ -126,7 +126,7 @@ var _ = Describe("jsonbasics", func() {
data := []byte(`{
"myArray": "it's a string"
}`)
objArr, err := GetObjectArrayField(MustDeserialize(&data), "myArray")
objArr, err := GetObjectArrayField(MustDeserialize(data), "myArray")

Expect(err).To(MatchError("not an array, but %!t(string=it's a string)"))
Expect(objArr).To(BeNil())
Expand All @@ -140,7 +140,7 @@ var _ = Describe("jsonbasics", func() {
{ "name": "one" }
]
}`)
obj := MustDeserialize(&data)
obj := MustDeserialize(data)
objArr, err := GetObjectArrayField(obj, "myArray")
Expect(err).To(BeNil())
Expect(objArr[0]["name"]).To(Equal("one"))
Expand Down
4 changes: 2 additions & 2 deletions merge/merge_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ var _ = Describe("Merge", func() {
MustWriteSerializedFile("./merge_testfiles/"+
strings.Replace(expected, "_expected.", "_generated.", -1), res, OutputFormatJSON)

Expect(*result).To(MatchJSON(*expectedResult))
Expect(result).To(MatchJSON(expectedResult))
}
}

Expand Down Expand Up @@ -133,7 +133,7 @@ var _ = Describe("Merge", func() {
result := MustSerialize(res, OutputFormatJSON)
expected := MustReadFile(expectedFile)

Expect(*result).To(MatchJSON(*expected))
Expect(result).To(MatchJSON(expected))
})

It("throws error on bad files", func() {
Expand Down
14 changes: 7 additions & 7 deletions openapi2kong/openapi2kong.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const (

// O2KOptions defines the options for an O2K conversion operation
type O2kOptions struct {
Tags *[]string // Array of tags to mark all generated entities with, taken from 'x-kong-tags' if omitted.
Tags []string // Array of tags to mark all generated entities with, taken from 'x-kong-tags' if omitted.
DocName string // Base document name, will be taken from x-kong-name, or info.title (for UUID generation!)
UUIDNamespace uuid.UUID // Namespace for UUID generation, defaults to DNS namespace for UUID v5
}
Expand Down Expand Up @@ -60,10 +60,10 @@ func sanitizeRegexCapture(varName string) string {
// getKongTags returns the provided tags or if nil, then the `x-kong-tags` property,
// validated to be a string array. If there is no error, then there will always be
// an array returned for safe access later in the process.
func getKongTags(doc *openapi3.T, tagsProvided *[]string) ([]string, error) {
func getKongTags(doc *openapi3.T, tagsProvided []string) ([]string, error) {
if tagsProvided != nil {
// the provided tags take precedence, return them
return *tagsProvided, nil
return tagsProvided, nil
}

if doc.ExtensionProps.Extensions == nil || doc.ExtensionProps.Extensions["x-kong-tags"] == nil {
Expand Down Expand Up @@ -240,7 +240,7 @@ func getPluginsList(
if pluginsToInclude != nil {
for _, config := range *pluginsToInclude {
pluginName := (*config)["name"].(string) // safe because it was previously parsed
configCopy := *(jsonbasics.DeepCopyObject(config))
configCopy := jsonbasics.DeepCopyObject(*config)

// generate a new ID, for a new plugin, based on new basename
configCopy["id"] = createPluginID(uuidNamespace, baseName, configCopy)
Expand Down Expand Up @@ -383,7 +383,7 @@ func getForeignKeyPlugins(
}

// MustConvert is the same as Convert, but will panic if an error is returned.
func MustConvert(content *[]byte, opts O2kOptions) map[string]interface{} {
func MustConvert(content []byte, opts O2kOptions) map[string]interface{} {
result, err := Convert(content, opts)
if err != nil {
log.Fatal(err)
Expand All @@ -392,7 +392,7 @@ func MustConvert(content *[]byte, opts O2kOptions) map[string]interface{} {
}

// Convert converts an OpenAPI spec to a Kong declarative file.
func Convert(content *[]byte, opts O2kOptions) (map[string]interface{}, error) {
func Convert(content []byte, opts O2kOptions) (map[string]interface{}, error) {
opts.setDefaults()
logbasics.Debug("received OpenAPI2Kong options", "options", opts)

Expand Down Expand Up @@ -442,7 +442,7 @@ func Convert(content *[]byte, opts O2kOptions) (map[string]interface{}, error) {

// Load and parse the OAS file
loader := openapi3.NewLoader()
doc, err = loader.LoadFromData(*content)
doc, err = loader.LoadFromData(content)
if err != nil {
return nil, fmt.Errorf("error parsing OAS3 file: [%w]", err)
}
Expand Down
4 changes: 2 additions & 2 deletions openapi2kong/openapi2kong_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ func Test_Openapi2kong(t *testing.T) {
fileNameExpected := strings.TrimSuffix(fileNameIn, ".yaml") + ".expected.json"
fileNameOut := strings.TrimSuffix(fileNameIn, ".yaml") + ".generated.json"
dataIn, _ := os.ReadFile(fixturePath + fileNameIn)
dataOut, err := Convert(&dataIn, O2kOptions{
Tags: &[]string{"OAS3_import", "OAS3file_" + fileNameIn},
dataOut, err := Convert(dataIn, O2kOptions{
Tags: []string{"OAS3_import", "OAS3file_" + fileNameIn},
})
if err != nil {
t.Error(fmt.Sprintf("'%s' didn't expect error: %%w", fixturePath+fileNameIn), err)
Expand Down
8 changes: 4 additions & 4 deletions openapi2kong/validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ func getDefaultParamStyle(givenStyle string, paramType string) string {
// generateParameterSchema returns the given schema if there is one, a generated
// schema if it was specified, or nil if there is none.
// Parameters include path, query, and headers
func generateParameterSchema(operation *openapi3.Operation) *[]map[string]interface{} {
func generateParameterSchema(operation *openapi3.Operation) []map[string]interface{} {
parameters := operation.Parameters
if parameters == nil {
return nil
Expand Down Expand Up @@ -76,7 +76,7 @@ func generateParameterSchema(operation *openapi3.Operation) *[]map[string]interf
}
}

return &result
return result
}

// generateBodySchema returns the given schema if there is one, a generated
Expand Down Expand Up @@ -108,7 +108,7 @@ func generateBodySchema(operation *openapi3.Operation) string {

// generateContentTypes returns an array of allowed content types. nil if none.
// Returned array will be sorted by name for deterministic comparisons.
func generateContentTypes(operation *openapi3.Operation) *[]string {
func generateContentTypes(operation *openapi3.Operation) []string {
requestBody := operation.RequestBody
if requestBody == nil {
return nil
Expand Down Expand Up @@ -136,7 +136,7 @@ func generateContentTypes(operation *openapi3.Operation) *[]string {
}
sort.Strings(list)

return &list
return list
}

// generateValidatorPlugin generates the validator plugin configuration, based
Expand Down
Loading

0 comments on commit b425220

Please sign in to comment.