diff --git a/pkg/flags/setjson.go b/pkg/flags/setjson.go new file mode 100644 index 0000000..7ed976f --- /dev/null +++ b/pkg/flags/setjson.go @@ -0,0 +1,56 @@ +// Copyright 2024 Google LLC +// +// 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 flags + +import ( + "encoding/json" + "fmt" + "github.com/go-errors/errors" + "github.com/micovery/apigee-yaml-toolkit/pkg/values" + "strings" +) + +type SetJSON struct { + Data *values.Map +} + +func NewSetJSON(data *values.Map) SetJSON { + return SetJSON{Data: data} +} + +func (v *SetJSON) String() string { + return fmt.Sprintf("%v", v.Data) +} + +func (v *SetJSON) Set(entry string) error { + key, jsonText, found := strings.Cut(entry, "=") + if !found { + return errors.Errorf("missing JSON text in set-json for key=%s", key) + } + + wrappedJSONText := fmt.Sprintf(`{"JSON":%s}`, jsonText) + type Wrapper struct { + JSON any `yaml:"Data"` + } + + wrapper := Wrapper{JSON: nil} + err := json.Unmarshal([]byte(wrappedJSONText), &wrapper) + if err != nil { + return errors.New(err) + } + + v.Data.Set(key, wrapper.JSON) + return nil +} diff --git a/pkg/render/render.go b/pkg/render/render.go index 38d0407..9b7dd06 100644 --- a/pkg/render/render.go +++ b/pkg/render/render.go @@ -363,6 +363,7 @@ func GetRenderFlags(printVersion func(), printUsage func()) (*Flags, error) { setOAS := flags.NewSetOAS(rFlags.Values) setGraphQL := flags.NewSetGraphQL(rFlags.Values) setGRPC := flags.NewSetGRPC(rFlags.Values) + setJSON := flags.NewSetJSON(rFlags.Values) flag.BoolVar(&rFlags.Version, "version", false, "(optional) prints version text") flag.BoolVar(&rFlags.Help, "help", false, `(optional) prints additional help text`) @@ -377,6 +378,7 @@ func GetRenderFlags(printVersion func(), printUsage func()) (*Flags, error) { flag.Var(&setOAS, "set-oas", "(optional,0..*) sets context key/value where value is an OpenAPI spec of a file e.g. \"my_oas=petstore.yaml\"") flag.Var(&setGRPC, "set-grpc", "(optional,0..*) sets context key/value where value is a gRPC proto of a file e.g. \"my_proto=greeter.proto\"") flag.Var(&setGraphQL, "set-graphql", "(optional,0..*) sets context key/value where value is a GraphQL schema of a file e.g. \"my_schema=resorts.graphql\"") + flag.Var(&setJSON, "set-json", "(optional,0..*) sets context key/value where value is JSON e.g. 'servers=[\"server1\",\"server2\"]'") flag.Parse()