Skip to content

Commit

Permalink
feat: Add support for writing out models as yaml files
Browse files Browse the repository at this point in the history
  • Loading branch information
humblenginr committed Jul 7, 2024
1 parent 348f281 commit b09de1b
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
14 changes: 11 additions & 3 deletions models/meshmodel/core/v1beta1/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,14 +120,22 @@ func (m *Model) UpdateStatus(db *database.Handler, status entity.EntityStatus) e
return nil
}

func (c Model) WriteModelDefinition(modelDefPath string) error {
// WriteModelDefinition writes out the model to the given `modelDefPath` in the `outputType` format.
// `outputType` can be `yaml` or `json`.
func (c Model) WriteModelDefinition(modelDefPath string, outputType string) error {
err := utils.CreateDirectory(modelDefPath)
if err != nil {
return err
}

modelFilePath := filepath.Join(modelDefPath, "model.json")
var modelFilePath string
if(outputType == "json"){
modelFilePath = filepath.Join(modelDefPath, "model.json")
err = utils.WriteJSONToFile[Model](modelFilePath, c)
}
if(outputType == "yaml"){
modelFilePath = filepath.Join(modelDefPath, "model.yaml")
err = utils.WriteYamlToFile[Model](modelFilePath, c)
}
if err != nil {
return err
}
Expand Down
20 changes: 20 additions & 0 deletions utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
"strings"

log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v3"
)

// transforms the keys of a Map recursively with the given transform function
Expand Down Expand Up @@ -345,6 +346,25 @@ func MergeMaps(mergeInto, toMerge map[string]interface{}) map[string]interface{}
return mergeInto
}

func WriteYamlToFile[K any](outputPath string, data K) error {
byt, err := yaml.Marshal(data)
if err != nil {
// Use a different error code
return ErrMarshal(err)
}

file, err := os.Create(outputPath)
if err != nil {
return ErrCreateFile(err, outputPath)
}

_, err = file.Write(byt)
if err != nil {
return ErrWriteFile(err, outputPath)
}
return nil
}

func WriteJSONToFile[K any](outputPath string, data K) error {
byt, err := json.MarshalIndent(data, " ", " ")
if err != nil {
Expand Down

0 comments on commit b09de1b

Please sign in to comment.