From 81b6e1c47c5f72bf4067f2d3439afb49731803e4 Mon Sep 17 00:00:00 2001 From: Arieh Schneier <15041913+AriehSchneier@users.noreply.github.com> Date: Wed, 21 Aug 2024 17:07:18 +1000 Subject: [PATCH] Remove sourceContext from the json when compact is set (#938) * Remove sourceContext from the json when compact * for loop on 1 line * simplify * keep sourceContext for Imports --- cmd/sysl/cmd_protobuf.go | 41 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/cmd/sysl/cmd_protobuf.go b/cmd/sysl/cmd_protobuf.go index 24200298f..1cd951fbb 100644 --- a/cmd/sysl/cmd_protobuf.go +++ b/cmd/sysl/cmd_protobuf.go @@ -3,6 +3,7 @@ package main import ( "fmt" "os" + "reflect" "strings" "github.com/anz-bank/sysl/pkg/cmdutils" @@ -75,6 +76,10 @@ func (p *protobufCmd) Execute(args cmdutils.ExecuteArgs) error { } if toJSON { + if p.compact { + removeSourceContext(m.Apps) + } + if p.splitappspath != "-" { return pbutil.OutputSplitApplications(m, "json", opt, p.splitappspath, "data.json", args.Filesystem) } else if p.output == "-" { @@ -104,3 +109,39 @@ func (p *protobufCmd) Execute(args cmdutils.ExecuteArgs) error { } return pbutil.GeneratePBBinaryMessageFile(m, p.output, args.Filesystem) } + +func removeSourceContext(target any) { + removeSourceContextImpl(reflect.ValueOf(target)) +} + +func removeSourceContextImpl(v reflect.Value) { + for v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface { + v = v.Elem() + } + switch v.Kind() { + case reflect.Array, reflect.Slice: + for i := 0; i < v.Len(); i++ { + removeSourceContextImpl(v.Index(i)) + } + case reflect.Map: + for iterator := v.MapRange(); iterator.Next(); { + removeSourceContextImpl(iterator.Value()) + } + case reflect.Struct: + t := v.Type() + for i := 0; i < v.NumField(); i++ { + fType := t.Field(i) + if fType.IsExported() == false || fType.Name == "SourceContexts" { + continue + } + + fValue := v.Field(i) + if fType.Name == "SourceContext" { + fValue.Set(reflect.Zero(fType.Type)) + } else { + removeSourceContextImpl(fValue) + } + } + default: + } +}