Skip to content

Commit

Permalink
Merge pull request #530 from humblenginr/nithish/refactor/model_yaml
Browse files Browse the repository at this point in the history
[Feat] Add Support For Writing Out Models as Yaml Files
  • Loading branch information
MUzairS15 authored Jul 8, 2024
2 parents 348f281 + 6ec508a commit b263478
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)
err = utils.WriteJSONToFile[Model](modelFilePath, c)
}
if(outputType == "yaml"){
modelFilePath = filepath.Join(modelDefPath)
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 b263478

Please sign in to comment.